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": "\": [\n {\n \"name\": {\n \"last\": \"Jones\",\n \"first\": \"Richard\"\n }\n },", "end": 2289, "score": 0.9996662139892578, "start": 2284, "tag": "NAME", "value": "Jones" }, { "context": " {\n \"last\": \"Jones\",\n ...
server/use/dissemin.coffee
leviathanindustries/noddy
2
# at 17/01/2016 dissemin searches crossref, base, sherpa/romeo, zotero primarily, # and arxiv, hal, pmc, openaire, doaj, perse, cairn.info, numdam secondarily via oa-pmh # see http://dissem.in/sources # http://dev.dissem.in/api.html API.use ?= {} API.use.dissemin = {} API.add 'use/dissemin/doi/:doipre/:doipost', get: () -> return API.use.dissemin.doi this.urlParams.doipre + '/' + this.urlParams.doipost API.use.dissemin.doi = (doi) -> url = 'https://dissem.in/api/' + doi API.log 'Using dissemin for ' + url res = API.http.cache doi, 'dissemin_doi' if not res? try res = HTTP.call('GET', url).data.paper res.url = API.http.resolve res.pdf_url API.http.cache doi, 'dissemin_doi', res try res.redirect = API.service.oab.redirect res.url return res API.use.dissemin.status = () -> try h = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47',{timeout: API.settings.use?.dissemin?.timeout ? API.settings.use?._timeout ? 2000}) return if h.data.paper then true else h.data catch err return err.toString() API.use.dissemin.test = (verbose) -> console.log('Starting dissemin test') if API.settings.dev result = {passed:[],failed:[]} tests = [ () -> result.record = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47') result.record = result.record.data.paper if result.record?.data?.paper? return false if not result.record.records? or result.record.records.length is 0 # this list can reasonably change length delete result.record.records return _.isEqual result.record, API.use.dissemin.test._examples.record ] (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose console.log('Ending dissemin test') if API.settings.dev return result API.use.dissemin.test._examples = { record:{ "classification": "OA", "title": "Open Bibliography for Science, Technology, and Medicine", "pdf_url": "http://dx.doi.org/10.1186/1758-2946-3-47", "authors": [ { "name": { "last": "Jones", "first": "Richard" } }, { "name": { "last": "MacGillivray", "first": "Mark" } }, { "orcid": "0000-0003-3386-3972", "name": { "last": "Murray-Rust", "first": "Peter" } }, { "name": { "last": "Pitman", "first": "Jim" } }, { "name": { "last": "Sefton", "first": "Peter" } }, { "name": { "last": "O'Steen", "first": "Ben" } }, { "name": { "last": "Waites", "first": "William" } } ], "date": "2011-01-01", "type": "journal-article" } }
192776
# at 17/01/2016 dissemin searches crossref, base, sherpa/romeo, zotero primarily, # and arxiv, hal, pmc, openaire, doaj, perse, cairn.info, numdam secondarily via oa-pmh # see http://dissem.in/sources # http://dev.dissem.in/api.html API.use ?= {} API.use.dissemin = {} API.add 'use/dissemin/doi/:doipre/:doipost', get: () -> return API.use.dissemin.doi this.urlParams.doipre + '/' + this.urlParams.doipost API.use.dissemin.doi = (doi) -> url = 'https://dissem.in/api/' + doi API.log 'Using dissemin for ' + url res = API.http.cache doi, 'dissemin_doi' if not res? try res = HTTP.call('GET', url).data.paper res.url = API.http.resolve res.pdf_url API.http.cache doi, 'dissemin_doi', res try res.redirect = API.service.oab.redirect res.url return res API.use.dissemin.status = () -> try h = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47',{timeout: API.settings.use?.dissemin?.timeout ? API.settings.use?._timeout ? 2000}) return if h.data.paper then true else h.data catch err return err.toString() API.use.dissemin.test = (verbose) -> console.log('Starting dissemin test') if API.settings.dev result = {passed:[],failed:[]} tests = [ () -> result.record = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47') result.record = result.record.data.paper if result.record?.data?.paper? return false if not result.record.records? or result.record.records.length is 0 # this list can reasonably change length delete result.record.records return _.isEqual result.record, API.use.dissemin.test._examples.record ] (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose console.log('Ending dissemin test') if API.settings.dev return result API.use.dissemin.test._examples = { record:{ "classification": "OA", "title": "Open Bibliography for Science, Technology, and Medicine", "pdf_url": "http://dx.doi.org/10.1186/1758-2946-3-47", "authors": [ { "name": { "last": "<NAME>", "first": "<NAME>" } }, { "name": { "last": "<NAME>", "first": "<NAME>" } }, { "orcid": "0000-0003-3386-3972", "name": { "last": "<NAME>", "first": "<NAME>" } }, { "name": { "last": "<NAME>", "first": "<NAME>" } }, { "name": { "last": "<NAME>", "first": "<NAME>" } }, { "name": { "last": "<NAME>", "first": "<NAME>" } }, { "name": { "last": "<NAME>", "first": "<NAME>" } } ], "date": "2011-01-01", "type": "journal-article" } }
true
# at 17/01/2016 dissemin searches crossref, base, sherpa/romeo, zotero primarily, # and arxiv, hal, pmc, openaire, doaj, perse, cairn.info, numdam secondarily via oa-pmh # see http://dissem.in/sources # http://dev.dissem.in/api.html API.use ?= {} API.use.dissemin = {} API.add 'use/dissemin/doi/:doipre/:doipost', get: () -> return API.use.dissemin.doi this.urlParams.doipre + '/' + this.urlParams.doipost API.use.dissemin.doi = (doi) -> url = 'https://dissem.in/api/' + doi API.log 'Using dissemin for ' + url res = API.http.cache doi, 'dissemin_doi' if not res? try res = HTTP.call('GET', url).data.paper res.url = API.http.resolve res.pdf_url API.http.cache doi, 'dissemin_doi', res try res.redirect = API.service.oab.redirect res.url return res API.use.dissemin.status = () -> try h = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47',{timeout: API.settings.use?.dissemin?.timeout ? API.settings.use?._timeout ? 2000}) return if h.data.paper then true else h.data catch err return err.toString() API.use.dissemin.test = (verbose) -> console.log('Starting dissemin test') if API.settings.dev result = {passed:[],failed:[]} tests = [ () -> result.record = HTTP.call('GET', 'https://dissem.in/api/10.1186/1758-2946-3-47') result.record = result.record.data.paper if result.record?.data?.paper? return false if not result.record.records? or result.record.records.length is 0 # this list can reasonably change length delete result.record.records return _.isEqual result.record, API.use.dissemin.test._examples.record ] (if (try tests[t]()) then (result.passed.push(t) if result.passed isnt false) else result.failed.push(t)) for t of tests result.passed = result.passed.length if result.passed isnt false and result.failed.length is 0 result = {passed:result.passed} if result.failed.length is 0 and not verbose console.log('Ending dissemin test') if API.settings.dev return result API.use.dissemin.test._examples = { record:{ "classification": "OA", "title": "Open Bibliography for Science, Technology, and Medicine", "pdf_url": "http://dx.doi.org/10.1186/1758-2946-3-47", "authors": [ { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "orcid": "0000-0003-3386-3972", "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } }, { "name": { "last": "PI:NAME:<NAME>END_PI", "first": "PI:NAME:<NAME>END_PI" } } ], "date": "2011-01-01", "type": "journal-article" } }
[ { "context": "age = 29\nname = \"Jacob\"\n\nif true\n console.log \"True!\"\nelse\n console.lo", "end": 22, "score": 0.9997655749320984, "start": 17, "tag": "NAME", "value": "Jacob" }, { "context": " constructor: (@name) ->\n\nstudent = new Student(\"Mohammed\")\n\nconsole.log stu...
CoffeeScript/main.coffee
jgphilpott/babel
1
age = 29 name = "Jacob" if true console.log "True!" else console.log "False!" letters = ["a", "b", "c", "d", "e", "f", "g"] for letter in letters console.log letter greet = (message) -> console.log message greet("Hello World!") class Student constructor: (@name) -> student = new Student("Mohammed") console.log student.name
187315
age = 29 name = "<NAME>" if true console.log "True!" else console.log "False!" letters = ["a", "b", "c", "d", "e", "f", "g"] for letter in letters console.log letter greet = (message) -> console.log message greet("Hello World!") class Student constructor: (@name) -> student = new Student("<NAME>") console.log student.name
true
age = 29 name = "PI:NAME:<NAME>END_PI" if true console.log "True!" else console.log "False!" letters = ["a", "b", "c", "d", "e", "f", "g"] for letter in letters console.log letter greet = (message) -> console.log message greet("Hello World!") class Student constructor: (@name) -> student = new Student("PI:NAME:<NAME>END_PI") console.log student.name
[ { "context": " new Vanity(url: \"http://localhost:3003\", token: \"secret\")\n split = vanity.split(\"foo-bar\")\n # Recor", "end": 561, "score": 0.638130247592926, "start": 555, "tag": "PASSWORD", "value": "secret" }, { "context": "\n # Record participants\n Async.forEac...
server/test/api_split_test.coffee
assaf/vanity.js
2
Helper = require("./helper") # must be at top assert = require("assert") Async = require("async") { EventEmitter } = require("events") request = require("request") EventSource = require("./event_source") redis = require("../config/redis") Vanity = require("../../node/vanity") describe "API split test", -> base_url = "http://localhost:3003/v1/split/" before Helper.once before Helper.setup before (done)-> vanity = new Vanity(url: "http://localhost:3003", token: "secret") split = vanity.split("foo-bar") # Record participants Async.forEach ["8c0521ee", "c2659ef8", "be8bb5b1", "f3cb65e5", "6d9d70c5"], (id, done)-> split.show id, done # Records completion , -> Async.forEach ["8c0521ee", "f3cb65e5"], (id, done)-> split.completed id, done , done # -- List tests -- describe "list tests", -> statusCode = null tests = null before (done)-> # Collect the results request.get base_url + "?access_token=secret", (error, response)-> { statusCode, body } = response tests = JSON.parse(response.body).tests if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return array of tests", -> assert.equal tests.length, 1 it "should return identifier for each test", -> assert.equal tests[0].id, "foo-bar" it "should return title for each test", -> assert.equal tests[0].title, "Foo Bar" it "should return created time for each test", -> assert Date.create(tests[0].created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal tests[0].alternatives[0].title, "A" assert.equal tests[0].alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal tests[0].alternatives[0].participants, 2 assert.equal tests[0].alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal tests[0].alternatives[0].completed, 0 assert.equal tests[0].alternatives[1].completed, 2 describe "no token", -> before (done)-> request.get base_url, (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 # -- Retrieving test -- describe "get test", -> statusCode = null test = null describe "no such test", -> before (done)-> request.get base_url + "nosuch?access_token=secret", (_, response)-> { statusCode, body } = response done() it "should return 404", -> assert.equal statusCode, 404 describe "no token", -> before (done)-> request.get base_url + "foo-bar", (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 describe "existing test", -> before (done)-> # Collect the results request.get base_url + "foo-bar?access_token=secret", (error, response)-> { statusCode, body } = response test = JSON.parse(response.body) if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return test identifier", -> assert.equal test.id, "foo-bar" it "should return test title", -> assert.equal test.title, "Foo Bar" it "should return test created time", -> assert Date.create(test.created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal test.alternatives[0].title, "A" assert.equal test.alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal test.alternatives[0].participants, 2 assert.equal test.alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal test.alternatives[0].completed, 0 assert.equal test.alternatives[1].completed, 2 it "should return historical data for each alternative", -> assert a = test.alternatives[0].data assert.equal a.length, 1 assert.equal a[0].participants, 2, "No participants for foo" assert.equal a[0].converted, 0, "No test completed for foo" assert b = test.alternatives[1].data assert.equal b.length, 1 assert.equal b[0].participants, 3, "No participatnts for bar" assert.equal b[0].converted, 2, "No test completed for bar"
68491
Helper = require("./helper") # must be at top assert = require("assert") Async = require("async") { EventEmitter } = require("events") request = require("request") EventSource = require("./event_source") redis = require("../config/redis") Vanity = require("../../node/vanity") describe "API split test", -> base_url = "http://localhost:3003/v1/split/" before Helper.once before Helper.setup before (done)-> vanity = new Vanity(url: "http://localhost:3003", token: "<PASSWORD>") split = vanity.split("foo-bar") # Record participants Async.forEach ["8c0<PASSWORD>21ee", "c<PASSWORD>", "be8bb5b1", "f3cb65e5", "6<PASSWORD>"], (id, done)-> split.show id, done # Records completion , -> Async.forEach ["8c0521ee", "f3cb65e5"], (id, done)-> split.completed id, done , done # -- List tests -- describe "list tests", -> statusCode = null tests = null before (done)-> # Collect the results request.get base_url + "?access_token=secret", (error, response)-> { statusCode, body } = response tests = JSON.parse(response.body).tests if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return array of tests", -> assert.equal tests.length, 1 it "should return identifier for each test", -> assert.equal tests[0].id, "foo-bar" it "should return title for each test", -> assert.equal tests[0].title, "Foo Bar" it "should return created time for each test", -> assert Date.create(tests[0].created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal tests[0].alternatives[0].title, "A" assert.equal tests[0].alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal tests[0].alternatives[0].participants, 2 assert.equal tests[0].alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal tests[0].alternatives[0].completed, 0 assert.equal tests[0].alternatives[1].completed, 2 describe "no token", -> before (done)-> request.get base_url, (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 # -- Retrieving test -- describe "get test", -> statusCode = null test = null describe "no such test", -> before (done)-> request.get base_url + "nosuch?access_token=secret", (_, response)-> { statusCode, body } = response done() it "should return 404", -> assert.equal statusCode, 404 describe "no token", -> before (done)-> request.get base_url + "foo-bar", (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 describe "existing test", -> before (done)-> # Collect the results request.get base_url + "foo-bar?access_token=secret", (error, response)-> { statusCode, body } = response test = JSON.parse(response.body) if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return test identifier", -> assert.equal test.id, "foo-bar" it "should return test title", -> assert.equal test.title, "Foo Bar" it "should return test created time", -> assert Date.create(test.created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal test.alternatives[0].title, "A" assert.equal test.alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal test.alternatives[0].participants, 2 assert.equal test.alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal test.alternatives[0].completed, 0 assert.equal test.alternatives[1].completed, 2 it "should return historical data for each alternative", -> assert a = test.alternatives[0].data assert.equal a.length, 1 assert.equal a[0].participants, 2, "No participants for foo" assert.equal a[0].converted, 0, "No test completed for foo" assert b = test.alternatives[1].data assert.equal b.length, 1 assert.equal b[0].participants, 3, "No participatnts for bar" assert.equal b[0].converted, 2, "No test completed for bar"
true
Helper = require("./helper") # must be at top assert = require("assert") Async = require("async") { EventEmitter } = require("events") request = require("request") EventSource = require("./event_source") redis = require("../config/redis") Vanity = require("../../node/vanity") describe "API split test", -> base_url = "http://localhost:3003/v1/split/" before Helper.once before Helper.setup before (done)-> vanity = new Vanity(url: "http://localhost:3003", token: "PI:PASSWORD:<PASSWORD>END_PI") split = vanity.split("foo-bar") # Record participants Async.forEach ["8c0PI:PASSWORD:<PASSWORD>END_PI21ee", "cPI:PASSWORD:<PASSWORD>END_PI", "be8bb5b1", "f3cb65e5", "6PI:PASSWORD:<PASSWORD>END_PI"], (id, done)-> split.show id, done # Records completion , -> Async.forEach ["8c0521ee", "f3cb65e5"], (id, done)-> split.completed id, done , done # -- List tests -- describe "list tests", -> statusCode = null tests = null before (done)-> # Collect the results request.get base_url + "?access_token=secret", (error, response)-> { statusCode, body } = response tests = JSON.parse(response.body).tests if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return array of tests", -> assert.equal tests.length, 1 it "should return identifier for each test", -> assert.equal tests[0].id, "foo-bar" it "should return title for each test", -> assert.equal tests[0].title, "Foo Bar" it "should return created time for each test", -> assert Date.create(tests[0].created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal tests[0].alternatives[0].title, "A" assert.equal tests[0].alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal tests[0].alternatives[0].participants, 2 assert.equal tests[0].alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal tests[0].alternatives[0].completed, 0 assert.equal tests[0].alternatives[1].completed, 2 describe "no token", -> before (done)-> request.get base_url, (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 # -- Retrieving test -- describe "get test", -> statusCode = null test = null describe "no such test", -> before (done)-> request.get base_url + "nosuch?access_token=secret", (_, response)-> { statusCode, body } = response done() it "should return 404", -> assert.equal statusCode, 404 describe "no token", -> before (done)-> request.get base_url + "foo-bar", (_, response)-> { statusCode, body } = response done() it "should return 401", -> assert.equal statusCode, 401 describe "existing test", -> before (done)-> # Collect the results request.get base_url + "foo-bar?access_token=secret", (error, response)-> { statusCode, body } = response test = JSON.parse(response.body) if statusCode == 200 done() it "should return 200", -> assert.equal statusCode, 200 it "should return test identifier", -> assert.equal test.id, "foo-bar" it "should return test title", -> assert.equal test.title, "Foo Bar" it "should return test created time", -> assert Date.create(test.created) - Date.now() < 1000 it "should return title for each alternative", -> assert.equal test.alternatives[0].title, "A" assert.equal test.alternatives[1].title, "B" it "should return participants for each alternative", -> assert.equal test.alternatives[0].participants, 2 assert.equal test.alternatives[1].participants, 3 it "should return completed for each alternative", -> assert.equal test.alternatives[0].completed, 0 assert.equal test.alternatives[1].completed, 2 it "should return historical data for each alternative", -> assert a = test.alternatives[0].data assert.equal a.length, 1 assert.equal a[0].participants, 2, "No participants for foo" assert.equal a[0].converted, 0, "No test completed for foo" assert b = test.alternatives[1].data assert.equal b.length, 1 assert.equal b[0].participants, 3, "No participatnts for bar" assert.equal b[0].converted, 2, "No test completed for bar"
[ { "context": "(err) if err?\n# \n# data.password = data2.password\n# client.users.redeem data, (err, user) =", "end": 1237, "score": 0.9991844892501831, "start": 1223, "tag": "PASSWORD", "value": "data2.password" }, { "context": " @log('')\n# @l...
lib/app/commands/user.coffee
awesomebox/awesomebox
1
{chalk} = require 'commandment' errors = require '../errors' # exports.reserve = (cb) -> # @prompt.get # properties: # email: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.reserve data, (err, user) => # return cb(err) if err? # @log('') # @log "Awesome! We've reserved you a spot." # @log "Sit tight and we'll send you an email when awesomebox is ready to go!" # cb() # # exports.redeem = (cb) -> # @prompt.get # properties: # email: # required: true # reservation: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.redeem data, (err, user) => # return cb(err) if err? and err.body?.error isnt 'Required field: password' # # @log('') # @log "Great! We found your reservation." # @log "You'll have to create a password now." # @log('') # # @prompt.get # properties: # password: # required: true # hidden: true # , (err, data2) => # return cb(err) if err? # # data.password = data2.password # client.users.redeem data, (err, user) => # return cb(err) if err? # # @log('') # @log 'Splendiforous!' # @log "Well isn't this wonderful news! We invited you in and you came. Oh happy day!" # @log('') # @log 'Welcome to ' + chalk.blue.bold('awesomebox') + '!!!' # @log('') # @log "Now that you're a user, why don't you try creating a new box." # @log "Just type #{chalk.cyan('awesomebox save')} from your project folder to get started." # @log('') # @log chalk.cyan('awesomebox save') + chalk.gray(" will create a new box on awesomebox.es and save") # @log chalk.gray("your current work on the server.") # # @login(user) # # cb() exports.me = -> client = @client.keyed() throw errors.unauthorized() unless client? client.me.get() .then (user) => @log(JSON.stringify(user, null, 2))
73378
{chalk} = require 'commandment' errors = require '../errors' # exports.reserve = (cb) -> # @prompt.get # properties: # email: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.reserve data, (err, user) => # return cb(err) if err? # @log('') # @log "Awesome! We've reserved you a spot." # @log "Sit tight and we'll send you an email when awesomebox is ready to go!" # cb() # # exports.redeem = (cb) -> # @prompt.get # properties: # email: # required: true # reservation: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.redeem data, (err, user) => # return cb(err) if err? and err.body?.error isnt 'Required field: password' # # @log('') # @log "Great! We found your reservation." # @log "You'll have to create a password now." # @log('') # # @prompt.get # properties: # password: # required: true # hidden: true # , (err, data2) => # return cb(err) if err? # # data.password = <PASSWORD> # client.users.redeem data, (err, user) => # return cb(err) if err? # # @log('') # @log 'Splendiforous!' # @log "Well isn't this wonderful news! We invited you in and you came. Oh happy day!" # @log('') # @log 'Welcome to ' + chalk.blue.bold('awesomebox') + '!!!' # @log('') # @log "Now that you're a user, why don't you try creating a new box." # @log "Just type #{chalk.cyan('awesomebox save')} from your project folder to get started." # @log('') # @log chalk.cyan('awesomebox save') + chalk.gray(" will create a new box on awesomebox.es and save") # @log chalk.gray("your current work on the server.") # # @login(user) # # cb() exports.me = -> client = @client.keyed() throw errors.unauthorized() unless client? client.me.get() .then (user) => @log(JSON.stringify(user, null, 2))
true
{chalk} = require 'commandment' errors = require '../errors' # exports.reserve = (cb) -> # @prompt.get # properties: # email: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.reserve data, (err, user) => # return cb(err) if err? # @log('') # @log "Awesome! We've reserved you a spot." # @log "Sit tight and we'll send you an email when awesomebox is ready to go!" # cb() # # exports.redeem = (cb) -> # @prompt.get # properties: # email: # required: true # reservation: # required: true # , (err, data) => # return cb(err) if err? # # client = @client() # client.users.redeem data, (err, user) => # return cb(err) if err? and err.body?.error isnt 'Required field: password' # # @log('') # @log "Great! We found your reservation." # @log "You'll have to create a password now." # @log('') # # @prompt.get # properties: # password: # required: true # hidden: true # , (err, data2) => # return cb(err) if err? # # data.password = PI:PASSWORD:<PASSWORD>END_PI # client.users.redeem data, (err, user) => # return cb(err) if err? # # @log('') # @log 'Splendiforous!' # @log "Well isn't this wonderful news! We invited you in and you came. Oh happy day!" # @log('') # @log 'Welcome to ' + chalk.blue.bold('awesomebox') + '!!!' # @log('') # @log "Now that you're a user, why don't you try creating a new box." # @log "Just type #{chalk.cyan('awesomebox save')} from your project folder to get started." # @log('') # @log chalk.cyan('awesomebox save') + chalk.gray(" will create a new box on awesomebox.es and save") # @log chalk.gray("your current work on the server.") # # @login(user) # # cb() exports.me = -> client = @client.keyed() throw errors.unauthorized() unless client? client.me.get() .then (user) => @log(JSON.stringify(user, null, 2))
[ { "context": "if value instanceof Date\n full_path_key = \"#{prefix}#{key}\"\n key_to_type[full_path_key] = \"Date\"\n\n ", "end": 835, "score": 0.9872434139251709, "start": 818, "tag": "KEY", "value": "\"#{prefix}#{key}\"" }, { "context": "peof value isnt 'functio...
lib/shared.coffee
gterrono/houston
508
root = exports ? this root.Houston ?= {} Houston._houstonize = (name) -> "_houston_#{name}" Houston._custom_method_name = (collection_name, method_name) -> Houston._houstonize("#{collection_name}/#{method_name}") # change _MAX_DOCS_TO_EXPLORE if you need us to explore more docs Houston._MAX_DOCS_TO_EXPLORE = 100 Houston._get_fields_from_collection = (collection) -> # TODO(AMK) randomly sample the documents in question Houston._get_fields(collection.find().fetch()) Houston._get_fields = (documents, options={}) -> key_to_type = if options.exclude_id? then {} else {_id: 'ObjectId'} find_fields = (document, prefix='') -> for key, value of _.omit(document, '_id') if typeof value is 'object' # handle dates like strings if value instanceof Date full_path_key = "#{prefix}#{key}" key_to_type[full_path_key] = "Date" # recurse into sub documents else find_fields value, "#{prefix}#{key}." else if typeof value isnt 'function' full_path_key = "#{prefix}#{key}" key_to_type[full_path_key] = typeof value for document in documents[..Houston._MAX_DOCS_TO_EXPLORE] find_fields document (name: key, type: value for key, value of key_to_type) Houston._get_field_names = (documents) -> _.pluck(Houston._get_fields(documents), 'name')
51855
root = exports ? this root.Houston ?= {} Houston._houstonize = (name) -> "_houston_#{name}" Houston._custom_method_name = (collection_name, method_name) -> Houston._houstonize("#{collection_name}/#{method_name}") # change _MAX_DOCS_TO_EXPLORE if you need us to explore more docs Houston._MAX_DOCS_TO_EXPLORE = 100 Houston._get_fields_from_collection = (collection) -> # TODO(AMK) randomly sample the documents in question Houston._get_fields(collection.find().fetch()) Houston._get_fields = (documents, options={}) -> key_to_type = if options.exclude_id? then {} else {_id: 'ObjectId'} find_fields = (document, prefix='') -> for key, value of _.omit(document, '_id') if typeof value is 'object' # handle dates like strings if value instanceof Date full_path_key = <KEY> key_to_type[full_path_key] = "Date" # recurse into sub documents else find_fields value, "#{prefix}#{key}." else if typeof value isnt 'function' full_path_key = <KEY> key_to_type[full_path_key] = typeof value for document in documents[..Houston._MAX_DOCS_TO_EXPLORE] find_fields document (name: key, type: value for key, value of key_to_type) Houston._get_field_names = (documents) -> _.pluck(Houston._get_fields(documents), 'name')
true
root = exports ? this root.Houston ?= {} Houston._houstonize = (name) -> "_houston_#{name}" Houston._custom_method_name = (collection_name, method_name) -> Houston._houstonize("#{collection_name}/#{method_name}") # change _MAX_DOCS_TO_EXPLORE if you need us to explore more docs Houston._MAX_DOCS_TO_EXPLORE = 100 Houston._get_fields_from_collection = (collection) -> # TODO(AMK) randomly sample the documents in question Houston._get_fields(collection.find().fetch()) Houston._get_fields = (documents, options={}) -> key_to_type = if options.exclude_id? then {} else {_id: 'ObjectId'} find_fields = (document, prefix='') -> for key, value of _.omit(document, '_id') if typeof value is 'object' # handle dates like strings if value instanceof Date full_path_key = PI:KEY:<KEY>END_PI key_to_type[full_path_key] = "Date" # recurse into sub documents else find_fields value, "#{prefix}#{key}." else if typeof value isnt 'function' full_path_key = PI:KEY:<KEY>END_PI key_to_type[full_path_key] = typeof value for document in documents[..Houston._MAX_DOCS_TO_EXPLORE] find_fields document (name: key, type: value for key, value of key_to_type) Houston._get_field_names = (documents) -> _.pluck(Houston._get_fields(documents), 'name')
[ { "context": "l\"\n input:\n api_key: \"baz\"\n \"first name\": \"baz\"\n last_name: \"foo\"\n array: [\n {\n ", "end": 512, "score": 0.9965750575065613, "start": 509, "tag": "NAME", "value": "baz" }, { "context": "ey: \"baz\"\n \"first name\": \"baz\"\n ...
test/fixtures.coffee
vgrbr/normalize-object
0
fixtures = [] fixtures.push name: "simple (defaults to camel)" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] fixtures.push name: "simple pascal" method: "pascal" input: key_key: [Key: "baz"] output: KeyKey: [Key: "baz"] fixtures.push name: "simple camel" method: "camel" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] # complex fixtures.push name: "complex pascal" method: "pascal" input: api_key: "baz" "first name": "baz" last_name: "foo" array: [ { Name: "baz" } { "names ": [A: 1] } ] output: ApiKey: "baz" FirstName: "baz" LastName: "foo" Array: [ { Name: "baz" } { Names: [A: 1] } ] fixtures.push name: "complex camel" method: "camel" input: api_key: "baz" "first name": "baz" last_name: "foo" array: [ { Name: "baz" } { "names ": [A: 1] } ] output: apiKey: "baz" firstName: "baz" lastName: "foo" array: [ { name: "baz" } { names: [a: 1] } ] module.exports = fixtures
114702
fixtures = [] fixtures.push name: "simple (defaults to camel)" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] fixtures.push name: "simple pascal" method: "pascal" input: key_key: [Key: "baz"] output: KeyKey: [Key: "baz"] fixtures.push name: "simple camel" method: "camel" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] # complex fixtures.push name: "complex pascal" method: "pascal" input: api_key: "baz" "first name": "<NAME>" last_name: "<NAME>" array: [ { Name: "<NAME>" } { "names ": [A: 1] } ] output: ApiKey: "baz" FirstName: "<NAME>" LastName: "<NAME>" Array: [ { Name: "<NAME>" } { Names: [A: 1] } ] fixtures.push name: "complex camel" method: "camel" input: api_key: "baz" "first name": "<NAME>" last_name: "<NAME>" array: [ { Name: "<NAME>" } { "names ": [A: 1] } ] output: apiKey: "baz" firstName: "<NAME>" lastName: "<NAME>" array: [ { name: "<NAME>" } { names: [a: 1] } ] module.exports = fixtures
true
fixtures = [] fixtures.push name: "simple (defaults to camel)" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] fixtures.push name: "simple pascal" method: "pascal" input: key_key: [Key: "baz"] output: KeyKey: [Key: "baz"] fixtures.push name: "simple camel" method: "camel" input: key_key: [Key: "baz"] output: keyKey: [key: "baz"] # complex fixtures.push name: "complex pascal" method: "pascal" input: api_key: "baz" "first name": "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" array: [ { Name: "PI:NAME:<NAME>END_PI" } { "names ": [A: 1] } ] output: ApiKey: "baz" FirstName: "PI:NAME:<NAME>END_PI" LastName: "PI:NAME:<NAME>END_PI" Array: [ { Name: "PI:NAME:<NAME>END_PI" } { Names: [A: 1] } ] fixtures.push name: "complex camel" method: "camel" input: api_key: "baz" "first name": "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" array: [ { Name: "PI:NAME:<NAME>END_PI" } { "names ": [A: 1] } ] output: apiKey: "baz" firstName: "PI:NAME:<NAME>END_PI" lastName: "PI:NAME:<NAME>END_PI" array: [ { name: "PI:NAME:<NAME>END_PI" } { names: [a: 1] } ] module.exports = fixtures
[ { "context": "me comments': null\n group1:\n key1a: '\"value1a\"'\n '# comment': null\n key1b: '1'\n ", "end": 592, "score": 0.9929466247558594, "start": 585, "tag": "KEY", "value": "value1a" }, { "context": "lue1a\"'\n '# comment': null\n key...
packages/core/test/misc.ini/stringify_multi_brackets.coffee
chibanemourad/node-nikita
0
ini = require '../../src/misc/ini' {tags} = require '../test' return unless tags.api describe 'misc.ini stringify_multi_brackets', -> it 'stringify test eol', -> res = ini.stringify_multi_brackets user: preference: color: true group: name: 'us' , eol: '|' res.should.eql '[user]| [[preference]]| color = true|[group]| name = us|' it 'stringify style', -> ini.stringify_multi_brackets '###########################################################################': null '# Some comments': null group1: key1a: '"value1a"' '# comment': null key1b: '1' '# Administrators': null '# ----------------': null group1a1: '## [[[admin1aX]]]': null key1a1: 'value1a1' group1b: '# comment': 'value' '## double comment': 'value' key1b1: 'value1b1' group2: key1: 'value1b' .should.eql """ ########################################################################### # Some comments [group1] key1a = "value1a" # comment key1b = 1 # Administrators # ---------------- [[group1a1]] ## [[[admin1aX]]] key1a1 = value1a1 [[group1b]] # comment = value ## double comment = value key1b1 = value1b1 [group2] key1 = value1b """ it 'stringify simple values before complex values', -> ini.stringify_multi_brackets group1: key1: 'value1' group1b: key1b1: 'value1b1' key2: 'value2' group2: key1: 'value1b' .should.eql """ [group1] key1 = value1 key2 = value2 [[group1b]] key1b1 = value1b1 [group2] key1 = value1b """
28796
ini = require '../../src/misc/ini' {tags} = require '../test' return unless tags.api describe 'misc.ini stringify_multi_brackets', -> it 'stringify test eol', -> res = ini.stringify_multi_brackets user: preference: color: true group: name: 'us' , eol: '|' res.should.eql '[user]| [[preference]]| color = true|[group]| name = us|' it 'stringify style', -> ini.stringify_multi_brackets '###########################################################################': null '# Some comments': null group1: key1a: '"<KEY>"' '# comment': null key1b: '<KEY>' '# Administrators': null '# ----------------': null group1a1: '## [[[admin1aX]]]': null key1a1: '<KEY>' group1b: '# comment': 'value' '## double comment': 'value' key1b1: '<KEY>' group2: key1: '<KEY>' .should.eql """ ########################################################################### # Some comments [group1] key1a = "<KEY>" # comment key1b = <KEY> # Administrators # ---------------- [[group1a1]] ## [[[admin1aX]]] key1a1 = <KEY> [[group1b]] # comment = value ## double comment = value key1b1 = <KEY> [group2] key1 = value<KEY> """ it 'stringify simple values before complex values', -> ini.stringify_multi_brackets group1: key1: '<KEY>' group1b: key1b1: '<KEY>' key2: '<KEY>' group2: key1: '<KEY>' .should.eql """ [group1] key1 = value1 key2 = value2 [[group1b]] key1b1 = value1b1 [group2] key1 = value1b """
true
ini = require '../../src/misc/ini' {tags} = require '../test' return unless tags.api describe 'misc.ini stringify_multi_brackets', -> it 'stringify test eol', -> res = ini.stringify_multi_brackets user: preference: color: true group: name: 'us' , eol: '|' res.should.eql '[user]| [[preference]]| color = true|[group]| name = us|' it 'stringify style', -> ini.stringify_multi_brackets '###########################################################################': null '# Some comments': null group1: key1a: '"PI:KEY:<KEY>END_PI"' '# comment': null key1b: 'PI:KEY:<KEY>END_PI' '# Administrators': null '# ----------------': null group1a1: '## [[[admin1aX]]]': null key1a1: 'PI:KEY:<KEY>END_PI' group1b: '# comment': 'value' '## double comment': 'value' key1b1: 'PI:KEY:<KEY>END_PI' group2: key1: 'PI:KEY:<KEY>END_PI' .should.eql """ ########################################################################### # Some comments [group1] key1a = "PI:KEY:<KEY>END_PI" # comment key1b = PI:KEY:<KEY>END_PI # Administrators # ---------------- [[group1a1]] ## [[[admin1aX]]] key1a1 = PI:KEY:<KEY>END_PI [[group1b]] # comment = value ## double comment = value key1b1 = PI:KEY:<KEY>END_PI [group2] key1 = valuePI:KEY:<KEY>END_PI """ it 'stringify simple values before complex values', -> ini.stringify_multi_brackets group1: key1: 'PI:KEY:<KEY>END_PI' group1b: key1b1: 'PI:KEY:<KEY>END_PI' key2: 'PI:KEY:<KEY>END_PI' group2: key1: 'PI:KEY:<KEY>END_PI' .should.eql """ [group1] key1 = value1 key2 = value2 [[group1b]] key1b1 = value1b1 [group2] key1 = value1b """
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9991855621337891, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-timers-this.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. assert = require("assert") immediateThis = undefined intervalThis = undefined timeoutThis = undefined immediateArgsThis = undefined intervalArgsThis = undefined timeoutArgsThis = undefined immediateHandler = setImmediate(-> immediateThis = this return ) immediateArgsHandler = setImmediate(-> immediateArgsThis = this return , "args ...") intervalHandler = setInterval(-> clearInterval intervalHandler intervalThis = this return ) intervalArgsHandler = setInterval(-> clearInterval intervalArgsHandler intervalArgsThis = this return , 0, "args ...") timeoutHandler = setTimeout(-> timeoutThis = this return ) timeoutArgsHandler = setTimeout(-> timeoutArgsThis = this return , 0, "args ...") process.once "exit", -> assert.strictEqual immediateThis, immediateHandler assert.strictEqual immediateArgsThis, immediateArgsHandler assert.strictEqual intervalThis, intervalHandler assert.strictEqual intervalArgsThis, intervalArgsHandler assert.strictEqual timeoutThis, timeoutHandler assert.strictEqual timeoutArgsThis, timeoutArgsHandler return
159697
# 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. assert = require("assert") immediateThis = undefined intervalThis = undefined timeoutThis = undefined immediateArgsThis = undefined intervalArgsThis = undefined timeoutArgsThis = undefined immediateHandler = setImmediate(-> immediateThis = this return ) immediateArgsHandler = setImmediate(-> immediateArgsThis = this return , "args ...") intervalHandler = setInterval(-> clearInterval intervalHandler intervalThis = this return ) intervalArgsHandler = setInterval(-> clearInterval intervalArgsHandler intervalArgsThis = this return , 0, "args ...") timeoutHandler = setTimeout(-> timeoutThis = this return ) timeoutArgsHandler = setTimeout(-> timeoutArgsThis = this return , 0, "args ...") process.once "exit", -> assert.strictEqual immediateThis, immediateHandler assert.strictEqual immediateArgsThis, immediateArgsHandler assert.strictEqual intervalThis, intervalHandler assert.strictEqual intervalArgsThis, intervalArgsHandler assert.strictEqual timeoutThis, timeoutHandler assert.strictEqual timeoutArgsThis, timeoutArgsHandler 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. assert = require("assert") immediateThis = undefined intervalThis = undefined timeoutThis = undefined immediateArgsThis = undefined intervalArgsThis = undefined timeoutArgsThis = undefined immediateHandler = setImmediate(-> immediateThis = this return ) immediateArgsHandler = setImmediate(-> immediateArgsThis = this return , "args ...") intervalHandler = setInterval(-> clearInterval intervalHandler intervalThis = this return ) intervalArgsHandler = setInterval(-> clearInterval intervalArgsHandler intervalArgsThis = this return , 0, "args ...") timeoutHandler = setTimeout(-> timeoutThis = this return ) timeoutArgsHandler = setTimeout(-> timeoutArgsThis = this return , 0, "args ...") process.once "exit", -> assert.strictEqual immediateThis, immediateHandler assert.strictEqual immediateArgsThis, immediateArgsHandler assert.strictEqual intervalThis, intervalHandler assert.strictEqual intervalArgsThis, intervalArgsHandler assert.strictEqual timeoutThis, timeoutHandler assert.strictEqual timeoutArgsThis, timeoutArgsHandler return
[ { "context": "e'\n\nLayoutCtrl = ($scope) ->\n $scope.albert = \"Albert\"\n\napp.controller('LayoutCtrl', ['$scope', LayoutC", "end": 84, "score": 0.9988563060760498, "start": 78, "tag": "NAME", "value": "Albert" } ]
client/layout/layout.ng.coffee
albertsgrc/cmm-frontend
0
import '/client/app.ng.coffee' LayoutCtrl = ($scope) -> $scope.albert = "Albert" app.controller('LayoutCtrl', ['$scope', LayoutCtrl])
163254
import '/client/app.ng.coffee' LayoutCtrl = ($scope) -> $scope.albert = "<NAME>" app.controller('LayoutCtrl', ['$scope', LayoutCtrl])
true
import '/client/app.ng.coffee' LayoutCtrl = ($scope) -> $scope.albert = "PI:NAME:<NAME>END_PI" app.controller('LayoutCtrl', ['$scope', LayoutCtrl])
[ { "context": "@User = class User extends MockClass\n name: 'default name'\n\nasyncTest 'it should pull in objects for f", "end": 215, "score": 0.8179405927658081, "start": 208, "tag": "NAME", "value": "default" }, { "context": " class User extends MockClass\n name: 'default...
tests/batman/view/formfor_rendering_test.coffee
nickjs/batman
1
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View rendering formfor' setup: -> @User = class User extends MockClass name: 'default name' asyncTest 'it should pull in objects for form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) -> equals $('input', node).val(), "default name" QUnit.start() asyncTest 'it should update objects when form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) => $('input', node).val('new name') # IE8 inserts explicit text nodes childNode = if node[0].childNodes[1].nodeName != '#text' then node[0].childNodes[1] else node[0].childNodes[0] helpers.triggerChange(childNode) delay => equals @User.lastInstance.name, "new name" asyncTest 'it should update the context for the form if the context changes', 2, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = new Batman.Object instanceOfUser: null node = helpers.render source, context, (node) => equals $('input', node).val(), "" context.set 'instanceOfUser', new @User delay => equals $('input', node).val(), "default name"
121970
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View rendering formfor' setup: -> @User = class User extends MockClass name: '<NAME> <PASSWORD>' asyncTest 'it should pull in objects for form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) -> equals $('input', node).val(), "default name" QUnit.start() asyncTest 'it should update objects when form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) => $('input', node).val('new name') # IE8 inserts explicit text nodes childNode = if node[0].childNodes[1].nodeName != '#text' then node[0].childNodes[1] else node[0].childNodes[0] helpers.triggerChange(childNode) delay => equals @User.lastInstance.name, "new name" asyncTest 'it should update the context for the form if the context changes', 2, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = new Batman.Object instanceOfUser: null node = helpers.render source, context, (node) => equals $('input', node).val(), "" context.set 'instanceOfUser', new @User delay => equals $('input', node).val(), "default name"
true
helpers = if typeof require is 'undefined' then window.viewHelpers else require './view_helper' QUnit.module 'Batman.View rendering formfor' setup: -> @User = class User extends MockClass name: 'PI:NAME:<NAME>END_PI PI:PASSWORD:<PASSWORD>END_PI' asyncTest 'it should pull in objects for form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) -> equals $('input', node).val(), "default name" QUnit.start() asyncTest 'it should update objects when form rendering', 1, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = instanceOfUser: new @User node = helpers.render source, context, (node) => $('input', node).val('new name') # IE8 inserts explicit text nodes childNode = if node[0].childNodes[1].nodeName != '#text' then node[0].childNodes[1] else node[0].childNodes[0] helpers.triggerChange(childNode) delay => equals @User.lastInstance.name, "new name" asyncTest 'it should update the context for the form if the context changes', 2, -> source = ''' <form data-formfor-user="instanceOfUser"> <input type="text" data-bind="user.name"> </form> ''' context = new Batman.Object instanceOfUser: null node = helpers.render source, context, (node) => equals $('input', node).val(), "" context.set 'instanceOfUser', new @User delay => equals $('input', node).val(), "default name"
[ { "context": " =\n\t\t\tid: @v1Id\n\t\t\temail: @user.email\n\t\t\tpassword: @user.password\n\t\t\tprofile:\n\t\t\t\tid: @v1Id\n\t\t\t\temail: @user.email\n", "end": 291, "score": 0.999183177947998, "start": 277, "tag": "PASSWORD", "value": "@user.password" }, { "context": " @v1Id\n\...
test/acceptance/coffee/SettingsTests.coffee
shyoshyo/web-sharelatex
1
should = require('chai').should() async = require("async") User = require "./helpers/User" MockV1Api = require './helpers/MockV1Api' describe 'SettingsPage', -> before (done) -> @user = new User() @v1Id = 1234 @v1User = id: @v1Id email: @user.email password: @user.password profile: id: @v1Id email: @user.email async.series [ @user.ensureUserExists.bind(@user) @user.login.bind(@user) (cb) => @user.mongoUpdate {$set: {'overleaf.id': @v1Id}}, cb (cb) => MockV1Api.setUser @v1Id, @v1User cb() @user.activateSudoMode.bind(@user) ], done it 'load settings page', (done) -> @user.getUserSettingsPage (err, statusCode) -> statusCode.should.equal 200 done() it 'update main email address', (done) -> newEmail = 'foo@bar.com' @user.updateSettings email: newEmail, (error) => should.not.exist error @user.get (error, user) -> user.email.should.equal newEmail user.emails.length.should.equal 1 user.emails[0].email.should.equal newEmail done()
118308
should = require('chai').should() async = require("async") User = require "./helpers/User" MockV1Api = require './helpers/MockV1Api' describe 'SettingsPage', -> before (done) -> @user = new User() @v1Id = 1234 @v1User = id: @v1Id email: @user.email password: <PASSWORD> profile: id: @v1Id email: @user.email async.series [ @user.ensureUserExists.bind(@user) @user.login.bind(@user) (cb) => @user.mongoUpdate {$set: {'overleaf.id': @v1Id}}, cb (cb) => MockV1Api.setUser @v1Id, @v1User cb() @user.activateSudoMode.bind(@user) ], done it 'load settings page', (done) -> @user.getUserSettingsPage (err, statusCode) -> statusCode.should.equal 200 done() it 'update main email address', (done) -> newEmail = '<EMAIL>' @user.updateSettings email: newEmail, (error) => should.not.exist error @user.get (error, user) -> user.email.should.equal newEmail user.emails.length.should.equal 1 user.emails[0].email.should.equal newEmail done()
true
should = require('chai').should() async = require("async") User = require "./helpers/User" MockV1Api = require './helpers/MockV1Api' describe 'SettingsPage', -> before (done) -> @user = new User() @v1Id = 1234 @v1User = id: @v1Id email: @user.email password: PI:PASSWORD:<PASSWORD>END_PI profile: id: @v1Id email: @user.email async.series [ @user.ensureUserExists.bind(@user) @user.login.bind(@user) (cb) => @user.mongoUpdate {$set: {'overleaf.id': @v1Id}}, cb (cb) => MockV1Api.setUser @v1Id, @v1User cb() @user.activateSudoMode.bind(@user) ], done it 'load settings page', (done) -> @user.getUserSettingsPage (err, statusCode) -> statusCode.should.equal 200 done() it 'update main email address', (done) -> newEmail = 'PI:EMAIL:<EMAIL>END_PI' @user.updateSettings email: newEmail, (error) => should.not.exist error @user.get (error, user) -> user.email.should.equal newEmail user.emails.length.should.equal 1 user.emails[0].email.should.equal newEmail done()
[ { "context": "# JSControl - User action control class\n# Coded by Hajime Oh-yake 2013.03.29\n#*************************************", "end": 108, "score": 0.9998967051506042, "start": 94, "tag": "NAME", "value": "Hajime Oh-yake" } ]
JSKit/03_JSControl.coffee
digitarhythm/codeJS
0
#***************************************** # JSControl - User action control class # Coded by Hajime Oh-yake 2013.03.29 #***************************************** class JSControl extends JSView constructor:(frame)-> super(frame) @_enable = true addTarget: (@action) -> setEnable:(@_enable)-> if (@_enable == false) @_self.setAlpha(0.2) else @_self.setAlpha(1.0) viewDidAppear:-> super() @setEnable(@_enable) $(@_viewSelector).on 'click', (event)=> if (@action? && @_enable == true && @_userInteractionEnabled == true) event.stopPropagation() @action(@_self)
214925
#***************************************** # JSControl - User action control class # Coded by <NAME> 2013.03.29 #***************************************** class JSControl extends JSView constructor:(frame)-> super(frame) @_enable = true addTarget: (@action) -> setEnable:(@_enable)-> if (@_enable == false) @_self.setAlpha(0.2) else @_self.setAlpha(1.0) viewDidAppear:-> super() @setEnable(@_enable) $(@_viewSelector).on 'click', (event)=> if (@action? && @_enable == true && @_userInteractionEnabled == true) event.stopPropagation() @action(@_self)
true
#***************************************** # JSControl - User action control class # Coded by PI:NAME:<NAME>END_PI 2013.03.29 #***************************************** class JSControl extends JSView constructor:(frame)-> super(frame) @_enable = true addTarget: (@action) -> setEnable:(@_enable)-> if (@_enable == false) @_self.setAlpha(0.2) else @_self.setAlpha(1.0) viewDidAppear:-> super() @setEnable(@_enable) $(@_viewSelector).on 'click', (event)=> if (@action? && @_enable == true && @_userInteractionEnabled == true) event.stopPropagation() @action(@_self)
[ { "context": "creating test users'\n\n users = [\n email: 'admin@example.com'\n password: 'admin'\n name: 'Admin'\n ", "end": 147, "score": 0.9999295473098755, "start": 130, "tag": "EMAIL", "value": "admin@example.com" }, { "context": " email: 'admin@example...
server/app.coffee
mliradelc/peakaboo
7
Meteor.startup -> if Meteor.users.find().fetch().length is 0 console.log 'creating test users' users = [ email: 'admin@example.com' password: 'admin' name: 'Admin' roles: ['admin'] , email: 'view@example.com' password: 'view' name: 'View' roles: ['view-rooms'] , email: 'control@example.com' password: 'control' name: 'Control' roles: ['control-rooms'] , email: 'galicaster@example.com' password: 'galicaster' name: 'Galicaster' roles: ['galicaster'] ] for user in users id = Accounts.createUser email: user.email password: user.password profile: name: user.name Meteor.users.update {_id: id}, {$set: {'emails.0.verified': true}} Roles.addUsersToRoles id, user.roles Accounts.validateNewUser (user) -> try return true if isUserAuthorised Meteor.userId(), ['admin', 'manage-users'] catch throw new Meteor.Error 403, 'Not authorized to create new users' Meteor.setInterval -> now = Meteor.call 'getServerTime' caTimeout = Meteor.settings.caTimeout Rooms.update {heartbeat: {$lt: now - caTimeout}}, {$set: {offline: true}}, {multi: true} , 10000
162276
Meteor.startup -> if Meteor.users.find().fetch().length is 0 console.log 'creating test users' users = [ email: '<EMAIL>' password: '<PASSWORD>' name: 'Admin' roles: ['admin'] , email: '<EMAIL>' password: '<PASSWORD>' name: 'View' roles: ['view-rooms'] , email: '<EMAIL>' password: '<PASSWORD>' name: 'Control' roles: ['control-rooms'] , email: '<EMAIL>' password: '<PASSWORD>' name: 'Galicaster' roles: ['galicaster'] ] for user in users id = Accounts.createUser email: user.email password: <PASSWORD> profile: name: user.name Meteor.users.update {_id: id}, {$set: {'emails.0.verified': true}} Roles.addUsersToRoles id, user.roles Accounts.validateNewUser (user) -> try return true if isUserAuthorised Meteor.userId(), ['admin', 'manage-users'] catch throw new Meteor.Error 403, 'Not authorized to create new users' Meteor.setInterval -> now = Meteor.call 'getServerTime' caTimeout = Meteor.settings.caTimeout Rooms.update {heartbeat: {$lt: now - caTimeout}}, {$set: {offline: true}}, {multi: true} , 10000
true
Meteor.startup -> if Meteor.users.find().fetch().length is 0 console.log 'creating test users' users = [ email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'Admin' roles: ['admin'] , email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'View' roles: ['view-rooms'] , email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'Control' roles: ['control-rooms'] , email: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' name: 'Galicaster' roles: ['galicaster'] ] for user in users id = Accounts.createUser email: user.email password: PI:PASSWORD:<PASSWORD>END_PI profile: name: user.name Meteor.users.update {_id: id}, {$set: {'emails.0.verified': true}} Roles.addUsersToRoles id, user.roles Accounts.validateNewUser (user) -> try return true if isUserAuthorised Meteor.userId(), ['admin', 'manage-users'] catch throw new Meteor.Error 403, 'Not authorized to create new users' Meteor.setInterval -> now = Meteor.call 'getServerTime' caTimeout = Meteor.settings.caTimeout Rooms.update {heartbeat: {$lt: now - caTimeout}}, {$set: {offline: true}}, {multi: true} , 10000
[ { "context": "preter)\n#\n# See README for more information\n#\n# by Pjotr Prins (c) 2013\n\nVERSION = '0.1.2'\n\nprint \"# Heyu-run #{", "end": 143, "score": 0.9998863339424133, "start": 132, "tag": "NAME", "value": "Pjotr Prins" }, { "context": "VERSION = '0.1.2'\n\nprint \"# Heyu-...
bin/heyu-run.coffee
pjotrp/heyu-run
1
# Script for HEYU runner with state machine (target spidermonkey javascript interpreter) # # See README for more information # # by Pjotr Prins (c) 2013 VERSION = '0.1.2' print "# Heyu-run #{VERSION} by Pjotr Prins" time=new Date() print "#",time.toTimeString() local_date = time.toLocaleFormat("%Y-%m-%d") local_time = time.toLocaleFormat("%H:%M:%S") load('lib/util.js') load('lib/statemachine.js') load('lib/timedevent.js') # File names to store state machine and events state_db_fn = 'heyu-run.db' event_db_fn = 'heyu-events.db' # ---- Display help help = () -> print """ Usage: heyu-run [args] --id appl Appliance id --switch ON|OFF Send event to appliance --time Add timed event (format yyyy-mm-dd hh:mm) --state Show state of appliance --exec Execute any queued timed events --replay Replay state machine and timed events --test Run tests --dry-run Do not save state Examples: heyu-run --id light1 --switch on heyu-run --time 2013-04-12 10:45 --id light1 --switch on heyu-run --exec heyu-run --replay """ quit(1) # ---- Parse the command line parse_opts = (set,args) -> if args.length > 0 args2 = switch args[0] when '--help','-h' then help() when '--test' load('test/test.js') run_tests() set.event = "on" set.id = "test" args[1..] when '--time' arg1 = args[1] arg2 = args[2] if not arg2? or arg2[0] == '-' # just time setting set.time = arg1 set.date = local_date args[2..] else set.date = arg1 set.time = arg2 args[3..] when '--id' set.id = args[1] args[2..] when '--switch' set.event = args[1].toUpperCase() args[2..] when '--state' set.display_state = true args[1..] when '--exec' set.exec = true args[1..] when '--replay' set.replay = true args[1..] when '--dry-run' set.dry_run = true args[1..] else throw "Unknown argument #{args[0]}" parse_opts(set,args2) if args2.length > 0 set # ---- Main program, parse command line set = parse_opts({},@arguments) # ---- Fetch state machine appliances = read_json(state_db_fn) # ---- Fetch timed events and update state events = read_events(event_db_fn) # ---- Function for updating the appliances state machine appliances_update = (id,event) -> if appliances[id] appl1 = appliances[id] print "#",id,"is",appl1.currentState() appl1.changeState(appl1.currentState(),event) else print "# new:",event,id appl2 = new HeyuAppliance(id, states: ['OFF', 'ON']) appl2.changeState(appl2.currentState(),event) appliances[appl2.name] = appl2 # ---- Update state machine from command line if set?.id? if set.display_state print "# Display current state of",set.id print appliances[set.id].currentState() if set.event? if not set.time # Force update of appliance now and record setting in timed events appliances_update(set.id,set.event) set.date = local_date set.time = local_time print "# updated",set.id,"at",set.date,set.time events.add_ary [set.date+' '+set.time,set.id,set.event] write_events(event_db_fn,events) if not set.dry_run if set.exec? or set.replay? print "# Executing timed events" state_list = get_last_state(events) for appl,e of state_list print "# Last event for",appl,"is",e.event,e.time appliances_update(e.id,e.event) if set.replay? print "# Replaying state machine" for name,appl of appliances appl.heyu_cli(name,appl.currentState()) # ---- Write state machine to file state_changed = false for name,appl of appliances state_changed = true if appl.changed write_json(state_db_fn,appliances) if state_changed and not set.dry_run
69728
# Script for HEYU runner with state machine (target spidermonkey javascript interpreter) # # See README for more information # # by <NAME> (c) 2013 VERSION = '0.1.2' print "# Heyu-run #{VERSION} by <NAME>" time=new Date() print "#",time.toTimeString() local_date = time.toLocaleFormat("%Y-%m-%d") local_time = time.toLocaleFormat("%H:%M:%S") load('lib/util.js') load('lib/statemachine.js') load('lib/timedevent.js') # File names to store state machine and events state_db_fn = 'heyu-run.db' event_db_fn = 'heyu-events.db' # ---- Display help help = () -> print """ Usage: heyu-run [args] --id appl Appliance id --switch ON|OFF Send event to appliance --time Add timed event (format yyyy-mm-dd hh:mm) --state Show state of appliance --exec Execute any queued timed events --replay Replay state machine and timed events --test Run tests --dry-run Do not save state Examples: heyu-run --id light1 --switch on heyu-run --time 2013-04-12 10:45 --id light1 --switch on heyu-run --exec heyu-run --replay """ quit(1) # ---- Parse the command line parse_opts = (set,args) -> if args.length > 0 args2 = switch args[0] when '--help','-h' then help() when '--test' load('test/test.js') run_tests() set.event = "on" set.id = "test" args[1..] when '--time' arg1 = args[1] arg2 = args[2] if not arg2? or arg2[0] == '-' # just time setting set.time = arg1 set.date = local_date args[2..] else set.date = arg1 set.time = arg2 args[3..] when '--id' set.id = args[1] args[2..] when '--switch' set.event = args[1].toUpperCase() args[2..] when '--state' set.display_state = true args[1..] when '--exec' set.exec = true args[1..] when '--replay' set.replay = true args[1..] when '--dry-run' set.dry_run = true args[1..] else throw "Unknown argument #{args[0]}" parse_opts(set,args2) if args2.length > 0 set # ---- Main program, parse command line set = parse_opts({},@arguments) # ---- Fetch state machine appliances = read_json(state_db_fn) # ---- Fetch timed events and update state events = read_events(event_db_fn) # ---- Function for updating the appliances state machine appliances_update = (id,event) -> if appliances[id] appl1 = appliances[id] print "#",id,"is",appl1.currentState() appl1.changeState(appl1.currentState(),event) else print "# new:",event,id appl2 = new HeyuAppliance(id, states: ['OFF', 'ON']) appl2.changeState(appl2.currentState(),event) appliances[appl2.name] = appl2 # ---- Update state machine from command line if set?.id? if set.display_state print "# Display current state of",set.id print appliances[set.id].currentState() if set.event? if not set.time # Force update of appliance now and record setting in timed events appliances_update(set.id,set.event) set.date = local_date set.time = local_time print "# updated",set.id,"at",set.date,set.time events.add_ary [set.date+' '+set.time,set.id,set.event] write_events(event_db_fn,events) if not set.dry_run if set.exec? or set.replay? print "# Executing timed events" state_list = get_last_state(events) for appl,e of state_list print "# Last event for",appl,"is",e.event,e.time appliances_update(e.id,e.event) if set.replay? print "# Replaying state machine" for name,appl of appliances appl.heyu_cli(name,appl.currentState()) # ---- Write state machine to file state_changed = false for name,appl of appliances state_changed = true if appl.changed write_json(state_db_fn,appliances) if state_changed and not set.dry_run
true
# Script for HEYU runner with state machine (target spidermonkey javascript interpreter) # # See README for more information # # by PI:NAME:<NAME>END_PI (c) 2013 VERSION = '0.1.2' print "# Heyu-run #{VERSION} by PI:NAME:<NAME>END_PI" time=new Date() print "#",time.toTimeString() local_date = time.toLocaleFormat("%Y-%m-%d") local_time = time.toLocaleFormat("%H:%M:%S") load('lib/util.js') load('lib/statemachine.js') load('lib/timedevent.js') # File names to store state machine and events state_db_fn = 'heyu-run.db' event_db_fn = 'heyu-events.db' # ---- Display help help = () -> print """ Usage: heyu-run [args] --id appl Appliance id --switch ON|OFF Send event to appliance --time Add timed event (format yyyy-mm-dd hh:mm) --state Show state of appliance --exec Execute any queued timed events --replay Replay state machine and timed events --test Run tests --dry-run Do not save state Examples: heyu-run --id light1 --switch on heyu-run --time 2013-04-12 10:45 --id light1 --switch on heyu-run --exec heyu-run --replay """ quit(1) # ---- Parse the command line parse_opts = (set,args) -> if args.length > 0 args2 = switch args[0] when '--help','-h' then help() when '--test' load('test/test.js') run_tests() set.event = "on" set.id = "test" args[1..] when '--time' arg1 = args[1] arg2 = args[2] if not arg2? or arg2[0] == '-' # just time setting set.time = arg1 set.date = local_date args[2..] else set.date = arg1 set.time = arg2 args[3..] when '--id' set.id = args[1] args[2..] when '--switch' set.event = args[1].toUpperCase() args[2..] when '--state' set.display_state = true args[1..] when '--exec' set.exec = true args[1..] when '--replay' set.replay = true args[1..] when '--dry-run' set.dry_run = true args[1..] else throw "Unknown argument #{args[0]}" parse_opts(set,args2) if args2.length > 0 set # ---- Main program, parse command line set = parse_opts({},@arguments) # ---- Fetch state machine appliances = read_json(state_db_fn) # ---- Fetch timed events and update state events = read_events(event_db_fn) # ---- Function for updating the appliances state machine appliances_update = (id,event) -> if appliances[id] appl1 = appliances[id] print "#",id,"is",appl1.currentState() appl1.changeState(appl1.currentState(),event) else print "# new:",event,id appl2 = new HeyuAppliance(id, states: ['OFF', 'ON']) appl2.changeState(appl2.currentState(),event) appliances[appl2.name] = appl2 # ---- Update state machine from command line if set?.id? if set.display_state print "# Display current state of",set.id print appliances[set.id].currentState() if set.event? if not set.time # Force update of appliance now and record setting in timed events appliances_update(set.id,set.event) set.date = local_date set.time = local_time print "# updated",set.id,"at",set.date,set.time events.add_ary [set.date+' '+set.time,set.id,set.event] write_events(event_db_fn,events) if not set.dry_run if set.exec? or set.replay? print "# Executing timed events" state_list = get_last_state(events) for appl,e of state_list print "# Last event for",appl,"is",e.event,e.time appliances_update(e.id,e.event) if set.replay? print "# Replaying state machine" for name,appl of appliances appl.heyu_cli(name,appl.currentState()) # ---- Write state machine to file state_changed = false for name,appl of appliances state_changed = true if appl.changed write_json(state_db_fn,appliances) if state_changed and not set.dry_run
[ { "context": " person = @subject.create.call @, 'user', name: 'john'\n person.save().then @async (saved) =>\n saved", "end": 765, "score": 0.9910280704498291, "start": 761, "tag": "NAME", "value": "john" }, { "context": "e().then @async (saved) =>\n saved.set 'name', 'updated...
spec/revs-adapter_spec.coffee
ekrabismi/CRUD-Ember-couchdb
0
Ember.ENV.TESTING = true module 'EmberCouchDBKit.RevsAdapter', setup: -> unless window.testing window.subject = new TestEnv() window.testing = true @subject = window.subject @async = window.async test 'belongsTo relation', 1, -> person = @subject.create.call @, 'user', name: 'name' person.save().then @async (saved) => saved.set 'name', 'updated' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => start() equal history.get('user.id').split('/')[0], person.id, 'history belongsTo user' , 1000 , 1000 test 'hasMany relation', 1, -> person = @subject.create.call @, 'user', name: 'john' person.save().then @async (saved) => saved.set 'name', 'updatedJohn' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => history.get('users') setTimeout => start() console.log(length) equal history.get('users.length'), 2, 'history hasMany users' , 1000 , 1000 , 1000
174891
Ember.ENV.TESTING = true module 'EmberCouchDBKit.RevsAdapter', setup: -> unless window.testing window.subject = new TestEnv() window.testing = true @subject = window.subject @async = window.async test 'belongsTo relation', 1, -> person = @subject.create.call @, 'user', name: 'name' person.save().then @async (saved) => saved.set 'name', 'updated' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => start() equal history.get('user.id').split('/')[0], person.id, 'history belongsTo user' , 1000 , 1000 test 'hasMany relation', 1, -> person = @subject.create.call @, 'user', name: '<NAME>' person.save().then @async (saved) => saved.set 'name', '<NAME>' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => history.get('users') setTimeout => start() console.log(length) equal history.get('users.length'), 2, 'history hasMany users' , 1000 , 1000 , 1000
true
Ember.ENV.TESTING = true module 'EmberCouchDBKit.RevsAdapter', setup: -> unless window.testing window.subject = new TestEnv() window.testing = true @subject = window.subject @async = window.async test 'belongsTo relation', 1, -> person = @subject.create.call @, 'user', name: 'name' person.save().then @async (saved) => saved.set 'name', 'updated' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => start() equal history.get('user.id').split('/')[0], person.id, 'history belongsTo user' , 1000 , 1000 test 'hasMany relation', 1, -> person = @subject.create.call @, 'user', name: 'PI:NAME:<NAME>END_PI' person.save().then @async (saved) => saved.set 'name', 'PI:NAME:<NAME>END_PI' saved.save().then @async (updated) => stop() history = updated.get 'history' setTimeout => history.reload() setTimeout => history.get('users') setTimeout => start() console.log(length) equal history.get('users.length'), 2, 'history hasMany users' , 1000 , 1000 , 1000
[ { "context": "name: 'summon'\ncycleMarkers: [\n\t{\n\t\ttype: 'entity-id'\n\t\tvalu", "end": 10, "score": 0.7640376091003418, "start": 7, "tag": "NAME", "value": "sum" }, { "context": "name: 'summon'\ncycleMarkers: [\n\t{\n\t\ttype: 'entity-id'\n\t\tvalue: ", "end": 13, "scor...
commands/commands/summon.cson
Czaplicki/mcfunction-support-data
0
name: 'summon' cycleMarkers: [ { type: 'entity-id' value: 'name' } { type: 'coord' value: 'x y z' } { type: 'nbt' value: 'nbt' } ]
102842
name: '<NAME>mon' cycleMarkers: [ { type: 'entity-id' value: 'name' } { type: 'coord' value: 'x y z' } { type: 'nbt' value: 'nbt' } ]
true
name: 'PI:NAME:<NAME>END_PImon' cycleMarkers: [ { type: 'entity-id' value: 'name' } { type: 'coord' value: 'x y z' } { type: 'nbt' value: 'nbt' } ]
[ { "context": "o be claimed by the next barista\n#\n#\n# Author:\n# brent@kiratalent.com, Kira Talent Inc.\n\ndateformat = require 'dateform", "end": 831, "score": 0.9999186992645264, "start": 811, "tag": "EMAIL", "value": "brent@kiratalent.com" }, { "context": " msg.send \"A b...
src/coffee.coffee
kiratalent/hubot-coffee
3
# Description # A hubot script for announcing & claiming coffee # # Configuration: # HUBOT_COFFEE_DIBS_LIMIT Set the dibs limit (Default 6) # HUBOT_COFFEE_DIBS_DURATION Set the dibs time limit in seconds (Default 600 seconds (10 minutes)) # # Commands: # hubot brewing - Start a new brewing lineup # hubot fresh pot - Announce that a pot is finished # hubot fp - Alias for: hubot fresh pot # hubot dibs - Reserve your spot in line for a current brew # hubot coffee balance [user] - Check your coffee balance (defaults to you) # hubot coffee top [n] - See the top coffee balances (defaults to 10) # hubot coffee bottom [n] - See the bottom coffee balances (defaults to 10) # hubot coffee bounty <n> - Issue a bounty worth `<n>` :coffee:s to be claimed by the next barista # # # Author: # brent@kiratalent.com, Kira Talent Inc. dateformat = require 'dateformat' dibsLimit = process.env.HUBOT_COFFEE_DIBS_LIMIT || 6 dibsDuration = process.env.HUBOT_COFFEE_DIBS_DURATION || (60 * 10) class StatusEmoji success: [':dancer:', ':relaxed:', ':grin:', ':smile:', ':sunglasses:'], pending: [':worried:', ':see_no_evil:', ':no_mouth:', ':neutral_face:'] failure: [':cry:', ':angry:', ':fearful:', ':sob:', ':disappointed:'] random: (status) -> emojis = @[status] || [] return emojis[Math.floor(Math.random() * emojis.length)] freshPots = [ "http://stream1.gifsoup.com/view6/3131142/chug-coffee-o.gif", "http://a4.files.blazepress.com/image/upload/MTI4OTg3NDE5MTAwODc4MDk4.gif", "http://38.media.tumblr.com/tumblr_m8wmtj5uqw1qzqwamo1_500.gif", "https://images.encyclopediadramatica.se/5/51/I_dont_like_coffee.gif", "http://spoonuniversity.com/wp-content/uploads/2015/07/anigif_enhanced-19737-1400112478-17.gif", "http://i.huffpost.com/gadgets/slideshows/335861/slide_335861_3385763_free.gif", "http://queenmobs.com/wp-content/uploads/2015/07/coffee-sylvester-cat.gif", "http://www.meltingmama.net/.a/6a00d8345190c169e20192aa97b3c0970d-pi", "https://s-media-cache-ak0.pinimg.com/originals/7c/f0/bc/7cf0bc80401a35b6413fcb7685e87bdc.jpg", "http://ak-hdl.buzzfed.com/static/2015-07/7/13/enhanced/webdr12/anigif_enhanced-24754-1436291259-3.gif", "http://i.imgur.com/vnuJQ4S.gif", "http://25.media.tumblr.com/tumblr_m5bndgzQsI1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_m5bnrxFuDj1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_mash62P7pW1ro71p1o1_500.gif", "https://thelordofthenerds.files.wordpress.com/2014/07/colbert-loves-coffee-o.gif", "http://cdn1.theodysseyonline.com/files/2015/06/26/635709513164674737586848637_coffee-talk.gif", "http://cdn1.theodysseyonline.com/files/2015/07/10/635720909538639483647877704_coffee-Elf.gif", "https://media.giphy.com/media/11Lz1Y4n1f2j96/giphy.gif", "http://imagesmtv-a.akamaihd.net/uri/mgid:file:http:shared:mtv.com/news/wp-content/uploads/2015/10/coffee-iv-1443999849.gif", "https://media.giphy.com/media/yLpNlfdHBaXQs/giphy.gif", "http://i.imgur.com/EYRpuaz.gif", "http://i0.kym-cdn.com/photos/images/newsfeed/000/605/727/cae.gif", "http://img.memecdn.com/this-coffee-is-fantastic-now-where-is-your-peroxide_o_588657.gif", "http://img.memecdn.com/le-coffee_o_523768.gif", "https://s-media-cache-ak0.pinimg.com/originals/bb/74/cb/bb74cbbed8dca8ca4e25f8ffa5156620.gif", "http://31.media.tumblr.com/3ae02ce94f54ed9e47a7f214f1e390c2/tumblr_n6mycaAO111somw7ho1_250.gif", "https://ak-hdl.buzzfed.com/static/2015-05/10/20/imagebuzz/webdr11/anigif_optimized-15275-1431304767-6.gif", "https://media.giphy.com/media/iHgMN3wishlde/giphy.gif", "https://media.giphy.com/media/oZEBLugoTthxS/giphy.gif", "https://media.giphy.com/media/3oKIPx16LFvftHPLiM/giphy.gif", "https://media.giphy.com/media/26uffErnoIpeQ3PmU/giphy.gif", "https://media.giphy.com/media/ceeFbVxiZzMBi/giphy.gif", "https://media.giphy.com/media/xThuWjDsB8IbJggCME/giphy.gif", "https://media.giphy.com/media/Rf3rGzWqKXsw8/giphy.gif", "https://media.giphy.com/media/xT5LMT6SSx83oZz464/giphy.gif", "https://media.giphy.com/media/3o85xrFlGdyGk2t9aU/giphy.gif", "https://media.giphy.com/media/3o6Ztfg45ZhI9oagxO/giphy.gif", "https://media.giphy.com/media/l0MYFwjgTKh5X4jew/giphy.gif", ] module.exports = (robot) -> statusEmoji = new StatusEmoji brewing = {} robot.brain.on 'loaded', => robot.brain.data.coffee ?= {brewing: {}} brewing = robot.brain.data.coffee.brewing ?= {} bounty = {} coffeeconomy = new Coffeeconomy robot robot.respond /coffee balance(?:\s+@?([^ ]+)\s*)?$/i, (msg) -> clientName = msg.match[1] || msg.message.user.name matchedClients = robot.brain.usersForFuzzyName(clientName) if matchedClients.length > 1 msg.send "Did you mean: #{matchedClients.join ', '}?" return client = matchedClients[0] if not client msg.send "Sorry, I don't know anyone named #{clientName}! #{statusEmoji.random('failure')}" return if not coffeeconomy.hasAccount client msg.send "#{client.name} hasn't opened an account by `#{robot.alias}brewing` or " + "`#{robot.alias}dibs`ing yet! #{statusEmoji.random('failure')}" return msg.send coffeeconomy.accountFormatter coffeeconomy.account client robot.respond /coffee top(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 count = 1 topList = ( coffeeconomy.topListEntryFormatter count++, account\ for account in coffeeconomy.top limit ) msg.send "These are the top :coffee: accounts:\n #{topList.join('\n')}" robot.respond /coffee bottom(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 total = coffeeconomy.length() bottomList = ( coffeeconomy.topListEntryFormatter total--, account\ for account in coffeeconomy.bottom limit ) msg.send "These are the bottom :coffee: accounts:\n #{bottomList.join('\n')}" robot.respond /brewing\s*$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})! " + "#{statusEmoji.random('failure')}\n" + freeSpots() return createBrew msg robot.respond /coffee bounty\s+(\d+)$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})!" + "#{statusEmoji.random('failure')}\n" + freeSpots() return issuer = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name proposedReward = parseInt msg.match[1]?.trim() || 0 account = coffeeconomy.account issuer if not proposedReward return if not coffeeconomy.hasAccount issuer msg.send "Sorry @#{issuer}, you don't have an account with us! #{statusEmoji.random('failure')}" return if proposedReward > account.balance msg.send "Whoa whoa whoa @#{issuer}, you don't have that many :coffee:s cowboy. #{statusEmoji.random('failure')} \n" + "Your current balance is: \n#{coffeeconomy.accountFormatter account}" return if hasBounty() and proposedReward > bounty.reward if issuer is bounty.issuer msg.send "@#{issuer} has raised the bounty from #{bounty.reward} to #{proposedReward}." else msg.send "@#{issuer} has outbid @#{bounty.issuer}'s bounty of #{bounty.reward} by increasing it to #{proposedReward}." else if hasBounty() and proposedReward <= bounty.reward msg.send "A bounty of #{bounty.reward} by #{issuer} has already been issued. #{statusEmoji.random('failure')}" return else msg.send "@team #{issuer} has issued a bounty of #{proposedReward}." createBounty issuer, proposedReward robot.respond /(fresh[ -]?pot|fp)\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() endBrew msg robot.respond /dibs\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() dibber = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name dib dibber, msg hasBounty = -> bounty.reward > 0 clearBounty = -> bounty = {} createBounty = (issuer, reward) -> bounty = issuer: issuer, reward: reward, dib = (dibber, msg) -> if dibber in brewing.dibs msg.send "Nice try @#{dibber}, you already grabbed a spot! #{statusEmoji.random('failure')}" return if brewing.dibs.length >= dibsLimit msg.send "Sorry! All spots have been claimed. #{statusEmoji.random('failure')}" return brewing.dibs.push(dibber) if hasBounty() and bounty.issuer is dibber threadedMsg(msg).send "@#{dibber} has been automatically granted :coffee: spot ##{brewing.dibs.length} for their _outstanding_ bounty! " + "#{statusEmoji.random('success')}" else threadedMsg(msg).send "Ok @#{dibber}, you grabbed :coffee: ##{brewing.dibs.length}! " + "#{statusEmoji.random('success')}" isBrewing = -> return brewing.dibs? threadedMsg = (msg) -> # Ensure that the vote response sticks to the original thread if using the flowdock adapter if robot.adapterName == 'flowdock' metadata = msg.envelope.metadata || {} metadata.room = brewing.messageMetadata.room if brewing.messageMetadata.room metadata.thread_id = brewing.messageMetadata.thread_id if brewing.messageMetadata.thread_id metadata.message_id = brewing.messageMetadata.message_id if brewing.messageMetadata.message_id msg.envelope.metadata = metadata msg handleNoBrew = (msg) -> msg.send "There is no brew happening! #{statusEmoji.random('failure')}" createBrew = (msg) -> barista = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name if bounty.reward > 0 and barista is bounty.issuer msg.send "Hey @#{bounty.issuer} you can't collect your own bounty! **Your bounty has been cancelled.** #{statusEmoji.random('failure')}" clearBounty() brewing = barista: barista dibs: [barista], messageMetadata: msg.envelope.message?.metadata, robot.brain.save() if hasBounty() msg.send "@team A bountied brew has been started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "@#{brewing.barista} will be rewarded #{bounty.reward} :coffee:s for this brew.\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" dib bounty.issuer, msg else msg.send "@team Brew started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" endBrew = (msg) -> expiry = new Date (new Date()).getTime() + dibsDuration * 1000 claims = [] for i in [1..dibsLimit] dibber = brewing.dibs[i - 1] if dibber client = robot.brain.userForName dibber if dibber == brewing.barista coffeeconomy.deposit client, dibsLimit - 1 if hasBounty() coffeeconomy.withdraw bounty.issuer, bounty.reward, true coffeeconomy.deposit client, bounty.reward, true else coffeeconomy.withdraw client, 1 account = coffeeconomy.account client dibberLabel = "**@#{dibber}**" txIcon = ":chart_with_downwards_trend:" if dibber == brewing.barista txIcon = ":chart_with_upwards_trend:" dibberLabel += " _(barista)_" else if hasBounty() and dibber == bounty.issuer dibberLabel += " _(#{bounty.reward} :coffee:#{if bounty.reward != 1 then 's' else ''} bounty issuer)_" claims.push("#{dibberLabel} #{txIcon} " + "#{coffeeconomy.balanceFormatter account.balance}") else claims.push "_Unclaimed!_" threadMsg = threadedMsg(msg) threadMsg.send "Fresh Pot!!! #{msg.random freshPots} " + ":coffee: Claims (valid until #{dateformat expiry, 'h:MM:ss tt'}):\n" + ("#{(parseInt index) + 1}. #{claim}" for index, claim of claims).join("\n") if claims.length > 1 setTimeout -> threadMsg.send "Claims have expired!" , dibsDuration * 1000 brewing = {} clearBounty() robot.brain.save() freeSpots = -> remaining = dibsLimit - brewing.dibs.length "#{remaining} dib#{if remaining == 1 then '' else 's'}" class Coffeeconomy constructor: (@robot, brain_ns = 'coffeeconomy') -> @brain = @robot.brain @storage = {} @brain.on 'loaded', => @storage = @brain.data[brain_ns] ?= {} @robot.logger.info "Coffeeconomy loaded. #{this.length()} accounts loaded." accountNumber: (client) -> if typeof client is 'string' client = @brain.userForName client return client.id if 'id' of client client: (accountNumber) -> @brain.userForId accountNumber accountFormatter: (account) -> "**#{@clientFormatter account.accountNumber}**: #{@balanceFormatter account.balance} " + "(#{@accountDetailsFormatter account})" shortDateFormatter: (date) -> dateformat date, "mmm d yyyy h:MMtt" longDateFormatter: (date) -> dateformat date, "ddd mmm d yyyy 'at' h:MM:ss tt Z" clientFormatter: (accountNumber) -> "#{(@client accountNumber).name}" balanceFormatter: (balance) -> "#{balance} :coffee:#{unless balance == 1 then 's' else ''}" accountDetailsFormatter: (account) -> if account.totals.rewards rewardsSummary = "(_+#{account.totals.rewards.earned || 0}_ / " + "_-#{account.totals.rewards.paid || 0}_ as/for rewards) " "_+#{account.totals.deposited}_ / _-#{account.totals.withdrawn}_ " + "#{rewardsSummary||''}" + "_Txs:_ #{account.transactions}, _Opened:_ #{@shortDateFormatter account.created}" + " #{if account.updated then ", _Updated:_ #{@longDateFormatter account.updated}" else ""}" topListEntryFormatter: (index, account) -> "_#{index}._ **#{@clientFormatter account.accountNumber}** #{@balanceFormatter account.balance}" deposit: (client, amount, reward = false) -> @transaction client, amount, reward withdraw: (client, amount, reward=false) -> @transaction client, (-1 * amount), reward transaction: (client, amount, reward=false) -> account = @account client account.balance += amount if reward and not account.totals.rewards @initRewards account if amount > 0 account.totals.deposited += amount if reward account.totals.rewards.earned += amount else account.totals.withdrawn -= amount if reward account.totals.rewards.paid -= amount account.transactions++ @saveAccount account txType = if amount > 0 then 'deposited to' else 'withdrawn from' @robot.logger.info "#{amount} :coffee:s #{txType} #{if reward then "reward " else ""}"+ "#{client.name} (#{client.id})" balance: (client) -> (@account client).balance hasAccount: (client) -> (@accountNumber client) of @storage account: (client) -> @storage[@accountNumber client] || @openAccount client openAccount: (client) -> accountNumber: @accountNumber client balance: 0 transactions: 0 totals: deposited: 0 withdrawn: 0 created: new Date() initRewards: (account) -> account.totals.rewards = earned: 0 paid: 0 saveAccount: (account) -> account.updated = new Date() @storage[account.accountNumber] = account @brain.save() orderedAccounts: (descending = true, limit = false) -> accounts = ( { accountNumber: accountNumber, balance: account.balance } for accountNumber, account of @storage ) first = if descending then 1 else 0 second = if descending then 0 else 1 accounts.sort -> arguments[first].balance - arguments[second].balance accounts[...(limit || accounts.length())] top: (limit = 10) -> @orderedAccounts true, limit bottom: (limit = 10) -> @orderedAccounts false, limit length: -> Object.getOwnPropertyNames(@storage).length
147760
# Description # A hubot script for announcing & claiming coffee # # Configuration: # HUBOT_COFFEE_DIBS_LIMIT Set the dibs limit (Default 6) # HUBOT_COFFEE_DIBS_DURATION Set the dibs time limit in seconds (Default 600 seconds (10 minutes)) # # Commands: # hubot brewing - Start a new brewing lineup # hubot fresh pot - Announce that a pot is finished # hubot fp - Alias for: hubot fresh pot # hubot dibs - Reserve your spot in line for a current brew # hubot coffee balance [user] - Check your coffee balance (defaults to you) # hubot coffee top [n] - See the top coffee balances (defaults to 10) # hubot coffee bottom [n] - See the bottom coffee balances (defaults to 10) # hubot coffee bounty <n> - Issue a bounty worth `<n>` :coffee:s to be claimed by the next barista # # # Author: # <EMAIL>, Kira Talent Inc. dateformat = require 'dateformat' dibsLimit = process.env.HUBOT_COFFEE_DIBS_LIMIT || 6 dibsDuration = process.env.HUBOT_COFFEE_DIBS_DURATION || (60 * 10) class StatusEmoji success: [':dancer:', ':relaxed:', ':grin:', ':smile:', ':sunglasses:'], pending: [':worried:', ':see_no_evil:', ':no_mouth:', ':neutral_face:'] failure: [':cry:', ':angry:', ':fearful:', ':sob:', ':disappointed:'] random: (status) -> emojis = @[status] || [] return emojis[Math.floor(Math.random() * emojis.length)] freshPots = [ "http://stream1.gifsoup.com/view6/3131142/chug-coffee-o.gif", "http://a4.files.blazepress.com/image/upload/MTI4OTg3NDE5MTAwODc4MDk4.gif", "http://38.media.tumblr.com/tumblr_m8wmtj5uqw1qzqwamo1_500.gif", "https://images.encyclopediadramatica.se/5/51/I_dont_like_coffee.gif", "http://spoonuniversity.com/wp-content/uploads/2015/07/anigif_enhanced-19737-1400112478-17.gif", "http://i.huffpost.com/gadgets/slideshows/335861/slide_335861_3385763_free.gif", "http://queenmobs.com/wp-content/uploads/2015/07/coffee-sylvester-cat.gif", "http://www.meltingmama.net/.a/6a00d8345190c169e20192aa97b3c0970d-pi", "https://s-media-cache-ak0.pinimg.com/originals/7c/f0/bc/7cf0bc80401a35b6413fcb7685e87bdc.jpg", "http://ak-hdl.buzzfed.com/static/2015-07/7/13/enhanced/webdr12/anigif_enhanced-24754-1436291259-3.gif", "http://i.imgur.com/vnuJQ4S.gif", "http://25.media.tumblr.com/tumblr_m5bndgzQsI1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_m5bnrxFuDj1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_mash62P7pW1ro71p1o1_500.gif", "https://thelordofthenerds.files.wordpress.com/2014/07/colbert-loves-coffee-o.gif", "http://cdn1.theodysseyonline.com/files/2015/06/26/635709513164674737586848637_coffee-talk.gif", "http://cdn1.theodysseyonline.com/files/2015/07/10/635720909538639483647877704_coffee-Elf.gif", "https://media.giphy.com/media/11Lz1Y4n1f2j96/giphy.gif", "http://imagesmtv-a.akamaihd.net/uri/mgid:file:http:shared:mtv.com/news/wp-content/uploads/2015/10/coffee-iv-1443999849.gif", "https://media.giphy.com/media/yLpNlfdHBaXQs/giphy.gif", "http://i.imgur.com/EYRpuaz.gif", "http://i0.kym-cdn.com/photos/images/newsfeed/000/605/727/cae.gif", "http://img.memecdn.com/this-coffee-is-fantastic-now-where-is-your-peroxide_o_588657.gif", "http://img.memecdn.com/le-coffee_o_523768.gif", "https://s-media-cache-ak0.pinimg.com/originals/bb/74/cb/bb74cbbed8dca8ca4e25f8ffa5156620.gif", "http://31.media.tumblr.com/3ae02ce94f54ed9e47a7f214f1e390c2/tumblr_n6mycaAO111somw7ho1_250.gif", "https://ak-hdl.buzzfed.com/static/2015-05/10/20/imagebuzz/webdr11/anigif_optimized-15275-1431304767-6.gif", "https://media.giphy.com/media/iHgMN3wishlde/giphy.gif", "https://media.giphy.com/media/oZEBLugoTthxS/giphy.gif", "https://media.giphy.com/media/3oKIPx16LFvftHPLiM/giphy.gif", "https://media.giphy.com/media/26uffErnoIpeQ3PmU/giphy.gif", "https://media.giphy.com/media/ceeFbVxiZzMBi/giphy.gif", "https://media.giphy.com/media/xThuWjDsB8IbJggCME/giphy.gif", "https://media.giphy.com/media/Rf3rGzWqKXsw8/giphy.gif", "https://media.giphy.com/media/xT5LMT6SSx83oZz464/giphy.gif", "https://media.giphy.com/media/3o85xrFlGdyGk2t9aU/giphy.gif", "https://media.giphy.com/media/3o6Ztfg45ZhI9oagxO/giphy.gif", "https://media.giphy.com/media/l0MYFwjgTKh5X4jew/giphy.gif", ] module.exports = (robot) -> statusEmoji = new StatusEmoji brewing = {} robot.brain.on 'loaded', => robot.brain.data.coffee ?= {brewing: {}} brewing = robot.brain.data.coffee.brewing ?= {} bounty = {} coffeeconomy = new Coffeeconomy robot robot.respond /coffee balance(?:\s+@?([^ ]+)\s*)?$/i, (msg) -> clientName = msg.match[1] || msg.message.user.name matchedClients = robot.brain.usersForFuzzyName(clientName) if matchedClients.length > 1 msg.send "Did you mean: #{matchedClients.join ', '}?" return client = matchedClients[0] if not client msg.send "Sorry, I don't know anyone named #{clientName}! #{statusEmoji.random('failure')}" return if not coffeeconomy.hasAccount client msg.send "#{client.name} hasn't opened an account by `#{robot.alias}brewing` or " + "`#{robot.alias}dibs`ing yet! #{statusEmoji.random('failure')}" return msg.send coffeeconomy.accountFormatter coffeeconomy.account client robot.respond /coffee top(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 count = 1 topList = ( coffeeconomy.topListEntryFormatter count++, account\ for account in coffeeconomy.top limit ) msg.send "These are the top :coffee: accounts:\n #{topList.join('\n')}" robot.respond /coffee bottom(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 total = coffeeconomy.length() bottomList = ( coffeeconomy.topListEntryFormatter total--, account\ for account in coffeeconomy.bottom limit ) msg.send "These are the bottom :coffee: accounts:\n #{bottomList.join('\n')}" robot.respond /brewing\s*$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})! " + "#{statusEmoji.random('failure')}\n" + freeSpots() return createBrew msg robot.respond /coffee bounty\s+(\d+)$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})!" + "#{statusEmoji.random('failure')}\n" + freeSpots() return issuer = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name proposedReward = parseInt msg.match[1]?.trim() || 0 account = coffeeconomy.account issuer if not proposedReward return if not coffeeconomy.hasAccount issuer msg.send "Sorry @#{issuer}, you don't have an account with us! #{statusEmoji.random('failure')}" return if proposedReward > account.balance msg.send "Whoa whoa whoa @#{issuer}, you don't have that many :coffee:s cowboy. #{statusEmoji.random('failure')} \n" + "Your current balance is: \n#{coffeeconomy.accountFormatter account}" return if hasBounty() and proposedReward > bounty.reward if issuer is bounty.issuer msg.send "@#{issuer} has raised the bounty from #{bounty.reward} to #{proposedReward}." else msg.send "@#{issuer} has outbid @#{bounty.issuer}'s bounty of #{bounty.reward} by increasing it to #{proposedReward}." else if hasBounty() and proposedReward <= bounty.reward msg.send "A bounty of #{bounty.reward} by #{issuer} has already been issued. #{statusEmoji.random('failure')}" return else msg.send "@team #{issuer} has issued a bounty of #{proposedReward}." createBounty issuer, proposedReward robot.respond /(fresh[ -]?pot|fp)\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() endBrew msg robot.respond /dibs\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() dibber = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name dib dibber, msg hasBounty = -> bounty.reward > 0 clearBounty = -> bounty = {} createBounty = (issuer, reward) -> bounty = issuer: issuer, reward: reward, dib = (dibber, msg) -> if dibber in brewing.dibs msg.send "Nice try @#{dibber}, you already grabbed a spot! #{statusEmoji.random('failure')}" return if brewing.dibs.length >= dibsLimit msg.send "Sorry! All spots have been claimed. #{statusEmoji.random('failure')}" return brewing.dibs.push(dibber) if hasBounty() and bounty.issuer is dibber threadedMsg(msg).send "@#{dibber} has been automatically granted :coffee: spot ##{brewing.dibs.length} for their _outstanding_ bounty! " + "#{statusEmoji.random('success')}" else threadedMsg(msg).send "Ok @#{dibber}, you grabbed :coffee: ##{brewing.dibs.length}! " + "#{statusEmoji.random('success')}" isBrewing = -> return brewing.dibs? threadedMsg = (msg) -> # Ensure that the vote response sticks to the original thread if using the flowdock adapter if robot.adapterName == 'flowdock' metadata = msg.envelope.metadata || {} metadata.room = brewing.messageMetadata.room if brewing.messageMetadata.room metadata.thread_id = brewing.messageMetadata.thread_id if brewing.messageMetadata.thread_id metadata.message_id = brewing.messageMetadata.message_id if brewing.messageMetadata.message_id msg.envelope.metadata = metadata msg handleNoBrew = (msg) -> msg.send "There is no brew happening! #{statusEmoji.random('failure')}" createBrew = (msg) -> barista = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name if bounty.reward > 0 and barista is bounty.issuer msg.send "Hey @#{bounty.issuer} you can't collect your own bounty! **Your bounty has been cancelled.** #{statusEmoji.random('failure')}" clearBounty() brewing = barista: barista dibs: [barista], messageMetadata: msg.envelope.message?.metadata, robot.brain.save() if hasBounty() msg.send "@team A bountied brew has been started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "@#{brewing.barista} will be rewarded #{bounty.reward} :coffee:s for this brew.\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" dib bounty.issuer, msg else msg.send "@team Brew started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" endBrew = (msg) -> expiry = new Date (new Date()).getTime() + dibsDuration * 1000 claims = [] for i in [1..dibsLimit] dibber = brewing.dibs[i - 1] if dibber client = robot.brain.userForName dibber if dibber == brewing.barista coffeeconomy.deposit client, dibsLimit - 1 if hasBounty() coffeeconomy.withdraw bounty.issuer, bounty.reward, true coffeeconomy.deposit client, bounty.reward, true else coffeeconomy.withdraw client, 1 account = coffeeconomy.account client dibberLabel = "**@#{dibber}**" txIcon = ":chart_with_downwards_trend:" if dibber == brewing.barista txIcon = ":chart_with_upwards_trend:" dibberLabel += " _(barista)_" else if hasBounty() and dibber == bounty.issuer dibberLabel += " _(#{bounty.reward} :coffee:#{if bounty.reward != 1 then 's' else ''} bounty issuer)_" claims.push("#{dibberLabel} #{txIcon} " + "#{coffeeconomy.balanceFormatter account.balance}") else claims.push "_Unclaimed!_" threadMsg = threadedMsg(msg) threadMsg.send "Fresh Pot!!! #{msg.random freshPots} " + ":coffee: Claims (valid until #{dateformat expiry, 'h:MM:ss tt'}):\n" + ("#{(parseInt index) + 1}. #{claim}" for index, claim of claims).join("\n") if claims.length > 1 setTimeout -> threadMsg.send "Claims have expired!" , dibsDuration * 1000 brewing = {} clearBounty() robot.brain.save() freeSpots = -> remaining = dibsLimit - brewing.dibs.length "#{remaining} dib#{if remaining == 1 then '' else 's'}" class Coffeeconomy constructor: (@robot, brain_ns = 'coffeeconomy') -> @brain = @robot.brain @storage = {} @brain.on 'loaded', => @storage = @brain.data[brain_ns] ?= {} @robot.logger.info "Coffeeconomy loaded. #{this.length()} accounts loaded." accountNumber: (client) -> if typeof client is 'string' client = @brain.userForName client return client.id if 'id' of client client: (accountNumber) -> @brain.userForId accountNumber accountFormatter: (account) -> "**#{@clientFormatter account.accountNumber}**: #{@balanceFormatter account.balance} " + "(#{@accountDetailsFormatter account})" shortDateFormatter: (date) -> dateformat date, "mmm d yyyy h:MMtt" longDateFormatter: (date) -> dateformat date, "ddd mmm d yyyy 'at' h:MM:ss tt Z" clientFormatter: (accountNumber) -> "#{(@client accountNumber).name}" balanceFormatter: (balance) -> "#{balance} :coffee:#{unless balance == 1 then 's' else ''}" accountDetailsFormatter: (account) -> if account.totals.rewards rewardsSummary = "(_+#{account.totals.rewards.earned || 0}_ / " + "_-#{account.totals.rewards.paid || 0}_ as/for rewards) " "_+#{account.totals.deposited}_ / _-#{account.totals.withdrawn}_ " + "#{rewardsSummary||''}" + "_Txs:_ #{account.transactions}, _Opened:_ #{@shortDateFormatter account.created}" + " #{if account.updated then ", _Updated:_ #{@longDateFormatter account.updated}" else ""}" topListEntryFormatter: (index, account) -> "_#{index}._ **#{@clientFormatter account.accountNumber}** #{@balanceFormatter account.balance}" deposit: (client, amount, reward = false) -> @transaction client, amount, reward withdraw: (client, amount, reward=false) -> @transaction client, (-1 * amount), reward transaction: (client, amount, reward=false) -> account = @account client account.balance += amount if reward and not account.totals.rewards @initRewards account if amount > 0 account.totals.deposited += amount if reward account.totals.rewards.earned += amount else account.totals.withdrawn -= amount if reward account.totals.rewards.paid -= amount account.transactions++ @saveAccount account txType = if amount > 0 then 'deposited to' else 'withdrawn from' @robot.logger.info "#{amount} :coffee:s #{txType} #{if reward then "reward " else ""}"+ "#{client.name} (#{client.id})" balance: (client) -> (@account client).balance hasAccount: (client) -> (@accountNumber client) of @storage account: (client) -> @storage[@accountNumber client] || @openAccount client openAccount: (client) -> accountNumber: @accountNumber client balance: 0 transactions: 0 totals: deposited: 0 withdrawn: 0 created: new Date() initRewards: (account) -> account.totals.rewards = earned: 0 paid: 0 saveAccount: (account) -> account.updated = new Date() @storage[account.accountNumber] = account @brain.save() orderedAccounts: (descending = true, limit = false) -> accounts = ( { accountNumber: accountNumber, balance: account.balance } for accountNumber, account of @storage ) first = if descending then 1 else 0 second = if descending then 0 else 1 accounts.sort -> arguments[first].balance - arguments[second].balance accounts[...(limit || accounts.length())] top: (limit = 10) -> @orderedAccounts true, limit bottom: (limit = 10) -> @orderedAccounts false, limit length: -> Object.getOwnPropertyNames(@storage).length
true
# Description # A hubot script for announcing & claiming coffee # # Configuration: # HUBOT_COFFEE_DIBS_LIMIT Set the dibs limit (Default 6) # HUBOT_COFFEE_DIBS_DURATION Set the dibs time limit in seconds (Default 600 seconds (10 minutes)) # # Commands: # hubot brewing - Start a new brewing lineup # hubot fresh pot - Announce that a pot is finished # hubot fp - Alias for: hubot fresh pot # hubot dibs - Reserve your spot in line for a current brew # hubot coffee balance [user] - Check your coffee balance (defaults to you) # hubot coffee top [n] - See the top coffee balances (defaults to 10) # hubot coffee bottom [n] - See the bottom coffee balances (defaults to 10) # hubot coffee bounty <n> - Issue a bounty worth `<n>` :coffee:s to be claimed by the next barista # # # Author: # PI:EMAIL:<EMAIL>END_PI, Kira Talent Inc. dateformat = require 'dateformat' dibsLimit = process.env.HUBOT_COFFEE_DIBS_LIMIT || 6 dibsDuration = process.env.HUBOT_COFFEE_DIBS_DURATION || (60 * 10) class StatusEmoji success: [':dancer:', ':relaxed:', ':grin:', ':smile:', ':sunglasses:'], pending: [':worried:', ':see_no_evil:', ':no_mouth:', ':neutral_face:'] failure: [':cry:', ':angry:', ':fearful:', ':sob:', ':disappointed:'] random: (status) -> emojis = @[status] || [] return emojis[Math.floor(Math.random() * emojis.length)] freshPots = [ "http://stream1.gifsoup.com/view6/3131142/chug-coffee-o.gif", "http://a4.files.blazepress.com/image/upload/MTI4OTg3NDE5MTAwODc4MDk4.gif", "http://38.media.tumblr.com/tumblr_m8wmtj5uqw1qzqwamo1_500.gif", "https://images.encyclopediadramatica.se/5/51/I_dont_like_coffee.gif", "http://spoonuniversity.com/wp-content/uploads/2015/07/anigif_enhanced-19737-1400112478-17.gif", "http://i.huffpost.com/gadgets/slideshows/335861/slide_335861_3385763_free.gif", "http://queenmobs.com/wp-content/uploads/2015/07/coffee-sylvester-cat.gif", "http://www.meltingmama.net/.a/6a00d8345190c169e20192aa97b3c0970d-pi", "https://s-media-cache-ak0.pinimg.com/originals/7c/f0/bc/7cf0bc80401a35b6413fcb7685e87bdc.jpg", "http://ak-hdl.buzzfed.com/static/2015-07/7/13/enhanced/webdr12/anigif_enhanced-24754-1436291259-3.gif", "http://i.imgur.com/vnuJQ4S.gif", "http://25.media.tumblr.com/tumblr_m5bndgzQsI1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_m5bnrxFuDj1qic1zfo1_500.gif", "https://38.media.tumblr.com/tumblr_mash62P7pW1ro71p1o1_500.gif", "https://thelordofthenerds.files.wordpress.com/2014/07/colbert-loves-coffee-o.gif", "http://cdn1.theodysseyonline.com/files/2015/06/26/635709513164674737586848637_coffee-talk.gif", "http://cdn1.theodysseyonline.com/files/2015/07/10/635720909538639483647877704_coffee-Elf.gif", "https://media.giphy.com/media/11Lz1Y4n1f2j96/giphy.gif", "http://imagesmtv-a.akamaihd.net/uri/mgid:file:http:shared:mtv.com/news/wp-content/uploads/2015/10/coffee-iv-1443999849.gif", "https://media.giphy.com/media/yLpNlfdHBaXQs/giphy.gif", "http://i.imgur.com/EYRpuaz.gif", "http://i0.kym-cdn.com/photos/images/newsfeed/000/605/727/cae.gif", "http://img.memecdn.com/this-coffee-is-fantastic-now-where-is-your-peroxide_o_588657.gif", "http://img.memecdn.com/le-coffee_o_523768.gif", "https://s-media-cache-ak0.pinimg.com/originals/bb/74/cb/bb74cbbed8dca8ca4e25f8ffa5156620.gif", "http://31.media.tumblr.com/3ae02ce94f54ed9e47a7f214f1e390c2/tumblr_n6mycaAO111somw7ho1_250.gif", "https://ak-hdl.buzzfed.com/static/2015-05/10/20/imagebuzz/webdr11/anigif_optimized-15275-1431304767-6.gif", "https://media.giphy.com/media/iHgMN3wishlde/giphy.gif", "https://media.giphy.com/media/oZEBLugoTthxS/giphy.gif", "https://media.giphy.com/media/3oKIPx16LFvftHPLiM/giphy.gif", "https://media.giphy.com/media/26uffErnoIpeQ3PmU/giphy.gif", "https://media.giphy.com/media/ceeFbVxiZzMBi/giphy.gif", "https://media.giphy.com/media/xThuWjDsB8IbJggCME/giphy.gif", "https://media.giphy.com/media/Rf3rGzWqKXsw8/giphy.gif", "https://media.giphy.com/media/xT5LMT6SSx83oZz464/giphy.gif", "https://media.giphy.com/media/3o85xrFlGdyGk2t9aU/giphy.gif", "https://media.giphy.com/media/3o6Ztfg45ZhI9oagxO/giphy.gif", "https://media.giphy.com/media/l0MYFwjgTKh5X4jew/giphy.gif", ] module.exports = (robot) -> statusEmoji = new StatusEmoji brewing = {} robot.brain.on 'loaded', => robot.brain.data.coffee ?= {brewing: {}} brewing = robot.brain.data.coffee.brewing ?= {} bounty = {} coffeeconomy = new Coffeeconomy robot robot.respond /coffee balance(?:\s+@?([^ ]+)\s*)?$/i, (msg) -> clientName = msg.match[1] || msg.message.user.name matchedClients = robot.brain.usersForFuzzyName(clientName) if matchedClients.length > 1 msg.send "Did you mean: #{matchedClients.join ', '}?" return client = matchedClients[0] if not client msg.send "Sorry, I don't know anyone named #{clientName}! #{statusEmoji.random('failure')}" return if not coffeeconomy.hasAccount client msg.send "#{client.name} hasn't opened an account by `#{robot.alias}brewing` or " + "`#{robot.alias}dibs`ing yet! #{statusEmoji.random('failure')}" return msg.send coffeeconomy.accountFormatter coffeeconomy.account client robot.respond /coffee top(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 count = 1 topList = ( coffeeconomy.topListEntryFormatter count++, account\ for account in coffeeconomy.top limit ) msg.send "These are the top :coffee: accounts:\n #{topList.join('\n')}" robot.respond /coffee bottom(?:\s+(\d+))?$/i, (msg) -> limit = parseInt msg.match[1]?.trim() || 10 total = coffeeconomy.length() bottomList = ( coffeeconomy.topListEntryFormatter total--, account\ for account in coffeeconomy.bottom limit ) msg.send "These are the bottom :coffee: accounts:\n #{bottomList.join('\n')}" robot.respond /brewing\s*$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})! " + "#{statusEmoji.random('failure')}\n" + freeSpots() return createBrew msg robot.respond /coffee bounty\s+(\d+)$/i, (msg) -> if isBrewing() msg.send "A brew is already underway by (@#{brewing.barista})!" + "#{statusEmoji.random('failure')}\n" + freeSpots() return issuer = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name proposedReward = parseInt msg.match[1]?.trim() || 0 account = coffeeconomy.account issuer if not proposedReward return if not coffeeconomy.hasAccount issuer msg.send "Sorry @#{issuer}, you don't have an account with us! #{statusEmoji.random('failure')}" return if proposedReward > account.balance msg.send "Whoa whoa whoa @#{issuer}, you don't have that many :coffee:s cowboy. #{statusEmoji.random('failure')} \n" + "Your current balance is: \n#{coffeeconomy.accountFormatter account}" return if hasBounty() and proposedReward > bounty.reward if issuer is bounty.issuer msg.send "@#{issuer} has raised the bounty from #{bounty.reward} to #{proposedReward}." else msg.send "@#{issuer} has outbid @#{bounty.issuer}'s bounty of #{bounty.reward} by increasing it to #{proposedReward}." else if hasBounty() and proposedReward <= bounty.reward msg.send "A bounty of #{bounty.reward} by #{issuer} has already been issued. #{statusEmoji.random('failure')}" return else msg.send "@team #{issuer} has issued a bounty of #{proposedReward}." createBounty issuer, proposedReward robot.respond /(fresh[ -]?pot|fp)\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() endBrew msg robot.respond /dibs\s*$/i, (msg) -> return handleNoBrew msg if not isBrewing() dibber = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name dib dibber, msg hasBounty = -> bounty.reward > 0 clearBounty = -> bounty = {} createBounty = (issuer, reward) -> bounty = issuer: issuer, reward: reward, dib = (dibber, msg) -> if dibber in brewing.dibs msg.send "Nice try @#{dibber}, you already grabbed a spot! #{statusEmoji.random('failure')}" return if brewing.dibs.length >= dibsLimit msg.send "Sorry! All spots have been claimed. #{statusEmoji.random('failure')}" return brewing.dibs.push(dibber) if hasBounty() and bounty.issuer is dibber threadedMsg(msg).send "@#{dibber} has been automatically granted :coffee: spot ##{brewing.dibs.length} for their _outstanding_ bounty! " + "#{statusEmoji.random('success')}" else threadedMsg(msg).send "Ok @#{dibber}, you grabbed :coffee: ##{brewing.dibs.length}! " + "#{statusEmoji.random('success')}" isBrewing = -> return brewing.dibs? threadedMsg = (msg) -> # Ensure that the vote response sticks to the original thread if using the flowdock adapter if robot.adapterName == 'flowdock' metadata = msg.envelope.metadata || {} metadata.room = brewing.messageMetadata.room if brewing.messageMetadata.room metadata.thread_id = brewing.messageMetadata.thread_id if brewing.messageMetadata.thread_id metadata.message_id = brewing.messageMetadata.message_id if brewing.messageMetadata.message_id msg.envelope.metadata = metadata msg handleNoBrew = (msg) -> msg.send "There is no brew happening! #{statusEmoji.random('failure')}" createBrew = (msg) -> barista = robot.brain.usersForFuzzyName(msg.message.user['name'])[0].name if bounty.reward > 0 and barista is bounty.issuer msg.send "Hey @#{bounty.issuer} you can't collect your own bounty! **Your bounty has been cancelled.** #{statusEmoji.random('failure')}" clearBounty() brewing = barista: barista dibs: [barista], messageMetadata: msg.envelope.message?.metadata, robot.brain.save() if hasBounty() msg.send "@team A bountied brew has been started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "@#{brewing.barista} will be rewarded #{bounty.reward} :coffee:s for this brew.\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" dib bounty.issuer, msg else msg.send "@team Brew started by @#{brewing.barista}! #{statusEmoji.random('success')}\n" + "To grab a spot use: `#{robot.alias}dibs`\n" + "To end the brew use: `#{robot.alias}fresh pot`" endBrew = (msg) -> expiry = new Date (new Date()).getTime() + dibsDuration * 1000 claims = [] for i in [1..dibsLimit] dibber = brewing.dibs[i - 1] if dibber client = robot.brain.userForName dibber if dibber == brewing.barista coffeeconomy.deposit client, dibsLimit - 1 if hasBounty() coffeeconomy.withdraw bounty.issuer, bounty.reward, true coffeeconomy.deposit client, bounty.reward, true else coffeeconomy.withdraw client, 1 account = coffeeconomy.account client dibberLabel = "**@#{dibber}**" txIcon = ":chart_with_downwards_trend:" if dibber == brewing.barista txIcon = ":chart_with_upwards_trend:" dibberLabel += " _(barista)_" else if hasBounty() and dibber == bounty.issuer dibberLabel += " _(#{bounty.reward} :coffee:#{if bounty.reward != 1 then 's' else ''} bounty issuer)_" claims.push("#{dibberLabel} #{txIcon} " + "#{coffeeconomy.balanceFormatter account.balance}") else claims.push "_Unclaimed!_" threadMsg = threadedMsg(msg) threadMsg.send "Fresh Pot!!! #{msg.random freshPots} " + ":coffee: Claims (valid until #{dateformat expiry, 'h:MM:ss tt'}):\n" + ("#{(parseInt index) + 1}. #{claim}" for index, claim of claims).join("\n") if claims.length > 1 setTimeout -> threadMsg.send "Claims have expired!" , dibsDuration * 1000 brewing = {} clearBounty() robot.brain.save() freeSpots = -> remaining = dibsLimit - brewing.dibs.length "#{remaining} dib#{if remaining == 1 then '' else 's'}" class Coffeeconomy constructor: (@robot, brain_ns = 'coffeeconomy') -> @brain = @robot.brain @storage = {} @brain.on 'loaded', => @storage = @brain.data[brain_ns] ?= {} @robot.logger.info "Coffeeconomy loaded. #{this.length()} accounts loaded." accountNumber: (client) -> if typeof client is 'string' client = @brain.userForName client return client.id if 'id' of client client: (accountNumber) -> @brain.userForId accountNumber accountFormatter: (account) -> "**#{@clientFormatter account.accountNumber}**: #{@balanceFormatter account.balance} " + "(#{@accountDetailsFormatter account})" shortDateFormatter: (date) -> dateformat date, "mmm d yyyy h:MMtt" longDateFormatter: (date) -> dateformat date, "ddd mmm d yyyy 'at' h:MM:ss tt Z" clientFormatter: (accountNumber) -> "#{(@client accountNumber).name}" balanceFormatter: (balance) -> "#{balance} :coffee:#{unless balance == 1 then 's' else ''}" accountDetailsFormatter: (account) -> if account.totals.rewards rewardsSummary = "(_+#{account.totals.rewards.earned || 0}_ / " + "_-#{account.totals.rewards.paid || 0}_ as/for rewards) " "_+#{account.totals.deposited}_ / _-#{account.totals.withdrawn}_ " + "#{rewardsSummary||''}" + "_Txs:_ #{account.transactions}, _Opened:_ #{@shortDateFormatter account.created}" + " #{if account.updated then ", _Updated:_ #{@longDateFormatter account.updated}" else ""}" topListEntryFormatter: (index, account) -> "_#{index}._ **#{@clientFormatter account.accountNumber}** #{@balanceFormatter account.balance}" deposit: (client, amount, reward = false) -> @transaction client, amount, reward withdraw: (client, amount, reward=false) -> @transaction client, (-1 * amount), reward transaction: (client, amount, reward=false) -> account = @account client account.balance += amount if reward and not account.totals.rewards @initRewards account if amount > 0 account.totals.deposited += amount if reward account.totals.rewards.earned += amount else account.totals.withdrawn -= amount if reward account.totals.rewards.paid -= amount account.transactions++ @saveAccount account txType = if amount > 0 then 'deposited to' else 'withdrawn from' @robot.logger.info "#{amount} :coffee:s #{txType} #{if reward then "reward " else ""}"+ "#{client.name} (#{client.id})" balance: (client) -> (@account client).balance hasAccount: (client) -> (@accountNumber client) of @storage account: (client) -> @storage[@accountNumber client] || @openAccount client openAccount: (client) -> accountNumber: @accountNumber client balance: 0 transactions: 0 totals: deposited: 0 withdrawn: 0 created: new Date() initRewards: (account) -> account.totals.rewards = earned: 0 paid: 0 saveAccount: (account) -> account.updated = new Date() @storage[account.accountNumber] = account @brain.save() orderedAccounts: (descending = true, limit = false) -> accounts = ( { accountNumber: accountNumber, balance: account.balance } for accountNumber, account of @storage ) first = if descending then 1 else 0 second = if descending then 0 else 1 accounts.sort -> arguments[first].balance - arguments[second].balance accounts[...(limit || accounts.length())] top: (limit = 10) -> @orderedAccounts true, limit bottom: (limit = 10) -> @orderedAccounts false, limit length: -> Object.getOwnPropertyNames(@storage).length
[ { "context": "#\t> File Name: Gruntfile.coffee\n#\t> Author: LY\n#\t> Mail: ly.franky@gmail.com\n#\t> Created Time: S", "end": 46, "score": 0.9987780451774597, "start": 44, "tag": "USERNAME", "value": "LY" }, { "context": "le Name: Gruntfile.coffee\n#\t> Author: LY\n#\t> Mail: ly.fra...
rdir/generateHTML/Gruntfile.coffee
laiy/rdir
6
# > File Name: Gruntfile.coffee # > Author: LY # > Mail: ly.franky@gmail.com # > Created Time: Sunday, November 23, 2014 AM10:42:51 CST module.exports = (grunt)-> grunt.initConfig watch: compile: files: [ 'src/coffee/**/*.coffee' 'src/sass/**/*.sass' ] options: spawn: false tasks: ['coffee', 'sass'] coffee: glob_to_multiple: expand: true, flatten: true, cwd: 'src/coffee', src: ['**/*.coffee'] dest: 'bin/js', ext: '.js' sass: dist: files: [ expand: true cwd: 'src/sass/' src: '**/*.sass' dest: 'bin/css' ext: '.css' ] grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-sass' grunt.registerTask 'default', 'watch'
189362
# > File Name: Gruntfile.coffee # > Author: LY # > Mail: <EMAIL> # > Created Time: Sunday, November 23, 2014 AM10:42:51 CST module.exports = (grunt)-> grunt.initConfig watch: compile: files: [ 'src/coffee/**/*.coffee' 'src/sass/**/*.sass' ] options: spawn: false tasks: ['coffee', 'sass'] coffee: glob_to_multiple: expand: true, flatten: true, cwd: 'src/coffee', src: ['**/*.coffee'] dest: 'bin/js', ext: '.js' sass: dist: files: [ expand: true cwd: 'src/sass/' src: '**/*.sass' dest: 'bin/css' ext: '.css' ] grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-sass' grunt.registerTask 'default', 'watch'
true
# > File Name: Gruntfile.coffee # > Author: LY # > Mail: PI:EMAIL:<EMAIL>END_PI # > Created Time: Sunday, November 23, 2014 AM10:42:51 CST module.exports = (grunt)-> grunt.initConfig watch: compile: files: [ 'src/coffee/**/*.coffee' 'src/sass/**/*.sass' ] options: spawn: false tasks: ['coffee', 'sass'] coffee: glob_to_multiple: expand: true, flatten: true, cwd: 'src/coffee', src: ['**/*.coffee'] dest: 'bin/js', ext: '.js' sass: dist: files: [ expand: true cwd: 'src/sass/' src: '**/*.sass' dest: 'bin/css' ext: '.css' ] grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.loadNpmTasks 'grunt-contrib-watch' grunt.loadNpmTasks 'grunt-contrib-sass' grunt.registerTask 'default', 'watch'
[ { "context": " class=\"btn btn-default\" cradmin-legacy-use-this=\"Peter Pan\" cradmin-legacy-fieldid=\"id_name\">\n Use th", "end": 728, "score": 0.9997124671936035, "start": 719, "tag": "NAME", "value": "Peter Pan" } ]
cradmin_legacy/static/cradmin_legacy/src/lib/forms/usethisbutton.coffee
appressoas/cradmin_legacy
0
angular.module('cradminLegacy.forms.usethisbutton', []) .directive('cradminLegacyUseThis', [ '$window' ($window) -> ### The cradmin-legacy-use-this directive is used to select elements for the ``cradmin-legacy-model-choice-field`` directive. You add this directive to a button or a-element within an iframe, and this directive will use ``window.postMessage`` to send the needed information to the ``cradmin-legacy-model-choice-field-wrapper``. You may also use this if you create your own custom iframe communication receiver directive where a "use this" button within an iframe is needed. Example ======= ``` <a class="btn btn-default" cradmin-legacy-use-this="Peter Pan" cradmin-legacy-fieldid="id_name"> Use this </a> ``` How it works ============ When the user clicks an element with this directive, the click is captured, the default action is prevented, and we decode the given JSON encoded value and add ``postmessageid='cradmin-legacy-use-this'`` to the object making it look something like this:: ``` { postmessageid: 'cradmin-legacy-use-this', value: '<the value provided via the cradmin-legacy attribute>', fieldid: '<the fieldid provided via the cradmin-legacy-fieldid attribute>', preview: '<the preview HTML>' } ``` We assume there is a event listener listening for the ``message`` event on the message in the parent of the iframe where this was clicked, but no checks ensuring this is made. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThis' } link: (scope, element, attrs) -> element.on 'click', (e) -> e.preventDefault() data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ]) .directive('cradminLegacyUseThisHidden', [ '$window' ($window) -> ### Works just like the ``cradmin-legacy-use-this`` directive, except this is intended to be triggered on load. The intended use-case is to trigger the same action as clicking a ``cradmin-legacy-use-this``-button but on load, typically after creating/adding a new item that the user wants to be selected without any further manual input. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThisHidden' } link: (scope, element, attrs) -> data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ])
55359
angular.module('cradminLegacy.forms.usethisbutton', []) .directive('cradminLegacyUseThis', [ '$window' ($window) -> ### The cradmin-legacy-use-this directive is used to select elements for the ``cradmin-legacy-model-choice-field`` directive. You add this directive to a button or a-element within an iframe, and this directive will use ``window.postMessage`` to send the needed information to the ``cradmin-legacy-model-choice-field-wrapper``. You may also use this if you create your own custom iframe communication receiver directive where a "use this" button within an iframe is needed. Example ======= ``` <a class="btn btn-default" cradmin-legacy-use-this="<NAME>" cradmin-legacy-fieldid="id_name"> Use this </a> ``` How it works ============ When the user clicks an element with this directive, the click is captured, the default action is prevented, and we decode the given JSON encoded value and add ``postmessageid='cradmin-legacy-use-this'`` to the object making it look something like this:: ``` { postmessageid: 'cradmin-legacy-use-this', value: '<the value provided via the cradmin-legacy attribute>', fieldid: '<the fieldid provided via the cradmin-legacy-fieldid attribute>', preview: '<the preview HTML>' } ``` We assume there is a event listener listening for the ``message`` event on the message in the parent of the iframe where this was clicked, but no checks ensuring this is made. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThis' } link: (scope, element, attrs) -> element.on 'click', (e) -> e.preventDefault() data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ]) .directive('cradminLegacyUseThisHidden', [ '$window' ($window) -> ### Works just like the ``cradmin-legacy-use-this`` directive, except this is intended to be triggered on load. The intended use-case is to trigger the same action as clicking a ``cradmin-legacy-use-this``-button but on load, typically after creating/adding a new item that the user wants to be selected without any further manual input. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThisHidden' } link: (scope, element, attrs) -> data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ])
true
angular.module('cradminLegacy.forms.usethisbutton', []) .directive('cradminLegacyUseThis', [ '$window' ($window) -> ### The cradmin-legacy-use-this directive is used to select elements for the ``cradmin-legacy-model-choice-field`` directive. You add this directive to a button or a-element within an iframe, and this directive will use ``window.postMessage`` to send the needed information to the ``cradmin-legacy-model-choice-field-wrapper``. You may also use this if you create your own custom iframe communication receiver directive where a "use this" button within an iframe is needed. Example ======= ``` <a class="btn btn-default" cradmin-legacy-use-this="PI:NAME:<NAME>END_PI" cradmin-legacy-fieldid="id_name"> Use this </a> ``` How it works ============ When the user clicks an element with this directive, the click is captured, the default action is prevented, and we decode the given JSON encoded value and add ``postmessageid='cradmin-legacy-use-this'`` to the object making it look something like this:: ``` { postmessageid: 'cradmin-legacy-use-this', value: '<the value provided via the cradmin-legacy attribute>', fieldid: '<the fieldid provided via the cradmin-legacy-fieldid attribute>', preview: '<the preview HTML>' } ``` We assume there is a event listener listening for the ``message`` event on the message in the parent of the iframe where this was clicked, but no checks ensuring this is made. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThis' } link: (scope, element, attrs) -> element.on 'click', (e) -> e.preventDefault() data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ]) .directive('cradminLegacyUseThisHidden', [ '$window' ($window) -> ### Works just like the ``cradmin-legacy-use-this`` directive, except this is intended to be triggered on load. The intended use-case is to trigger the same action as clicking a ``cradmin-legacy-use-this``-button but on load, typically after creating/adding a new item that the user wants to be selected without any further manual input. ### return { restrict: 'A' scope: { data: '@cradminLegacyUseThisHidden' } link: (scope, element, attrs) -> data = angular.fromJson(scope.data) data.postmessageid = 'cradmin-legacy-use-this' $window.parent.postMessage( angular.toJson(data), window.parent.location.href) return } ])
[ { "context": " '.' + options.suffix\n token = new Token('link_open', 'a', 1)\n token.attrs = [ [\n 'href'\n ", "end": 761, "score": 0.4660593867301941, "start": 757, "tag": "PASSWORD", "value": "open" } ]
index.coffee
DavidParkin/markdown-it-vimwiki
0
'use strict' _ = undefined vimwikiReplace = undefined _ = require('underscore') vimwikiReplace = (md, options, Token) -> arrayReplaceAt = undefined createTokens = undefined defaults = undefined pattern = undefined splitTextToken = undefined arrayReplaceAt = md.utils.arrayReplaceAt defaults = suffix: 'wiki' options = _.extend(defaults, options) pattern = /\[\[([A-Za-z1-9\- ]+)?\|?(\w+)?\]\](.*)/ createTokens = (linkUrl, linkText, remainder, Token) -> nodes = undefined token = undefined fullUrl = undefined nodes = [] urlText = linkUrl if typeof linkText != 'undefined' urlText = linkText else urlText = linkUrl fullUrl = './' + linkUrl + '.' + options.suffix token = new Token('link_open', 'a', 1) token.attrs = [ [ 'href' fullUrl ] ] #token.level = level++; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = urlText #token.level = level; nodes.push token token = new Token('link_close', 'a', -1) #token.level = --level; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = remainder #token.level = level; nodes.push token nodes splitTextToken = (original, Token) -> linkUrl = undefined matches = undefined text = undefined linkText = undefined remainder = undefined text = original.content matches = text.match(pattern) if matches == null return original linkUrl = matches[1] linkText = matches[2] remainder = matches[3] createTokens linkUrl, linkText, remainder, Token (state) -> blockTokens = undefined i = undefined j = undefined l = undefined token = undefined tokens = undefined blockTokens = state.tokens j = 0 l = blockTokens.length while j < l if blockTokens[j].type != 'inline' j++ continue tokens = blockTokens[j].children i = tokens.length - 1 while i >= 0 token = tokens[i] if token.type != 'code_inline' blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, splitTextToken(token, state.Token)) i-- j++ return ###global module ### module.exports = (md, options) -> md.core.ruler.push 'vimwiki', vimwikiReplace(md, options) return
142093
'use strict' _ = undefined vimwikiReplace = undefined _ = require('underscore') vimwikiReplace = (md, options, Token) -> arrayReplaceAt = undefined createTokens = undefined defaults = undefined pattern = undefined splitTextToken = undefined arrayReplaceAt = md.utils.arrayReplaceAt defaults = suffix: 'wiki' options = _.extend(defaults, options) pattern = /\[\[([A-Za-z1-9\- ]+)?\|?(\w+)?\]\](.*)/ createTokens = (linkUrl, linkText, remainder, Token) -> nodes = undefined token = undefined fullUrl = undefined nodes = [] urlText = linkUrl if typeof linkText != 'undefined' urlText = linkText else urlText = linkUrl fullUrl = './' + linkUrl + '.' + options.suffix token = new Token('link_<PASSWORD>', 'a', 1) token.attrs = [ [ 'href' fullUrl ] ] #token.level = level++; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = urlText #token.level = level; nodes.push token token = new Token('link_close', 'a', -1) #token.level = --level; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = remainder #token.level = level; nodes.push token nodes splitTextToken = (original, Token) -> linkUrl = undefined matches = undefined text = undefined linkText = undefined remainder = undefined text = original.content matches = text.match(pattern) if matches == null return original linkUrl = matches[1] linkText = matches[2] remainder = matches[3] createTokens linkUrl, linkText, remainder, Token (state) -> blockTokens = undefined i = undefined j = undefined l = undefined token = undefined tokens = undefined blockTokens = state.tokens j = 0 l = blockTokens.length while j < l if blockTokens[j].type != 'inline' j++ continue tokens = blockTokens[j].children i = tokens.length - 1 while i >= 0 token = tokens[i] if token.type != 'code_inline' blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, splitTextToken(token, state.Token)) i-- j++ return ###global module ### module.exports = (md, options) -> md.core.ruler.push 'vimwiki', vimwikiReplace(md, options) return
true
'use strict' _ = undefined vimwikiReplace = undefined _ = require('underscore') vimwikiReplace = (md, options, Token) -> arrayReplaceAt = undefined createTokens = undefined defaults = undefined pattern = undefined splitTextToken = undefined arrayReplaceAt = md.utils.arrayReplaceAt defaults = suffix: 'wiki' options = _.extend(defaults, options) pattern = /\[\[([A-Za-z1-9\- ]+)?\|?(\w+)?\]\](.*)/ createTokens = (linkUrl, linkText, remainder, Token) -> nodes = undefined token = undefined fullUrl = undefined nodes = [] urlText = linkUrl if typeof linkText != 'undefined' urlText = linkText else urlText = linkUrl fullUrl = './' + linkUrl + '.' + options.suffix token = new Token('link_PI:PASSWORD:<PASSWORD>END_PI', 'a', 1) token.attrs = [ [ 'href' fullUrl ] ] #token.level = level++; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = urlText #token.level = level; nodes.push token token = new Token('link_close', 'a', -1) #token.level = --level; token.markup = 'linkify' token.info = 'auto' nodes.push token token = new Token('text', '', 0) token.content = remainder #token.level = level; nodes.push token nodes splitTextToken = (original, Token) -> linkUrl = undefined matches = undefined text = undefined linkText = undefined remainder = undefined text = original.content matches = text.match(pattern) if matches == null return original linkUrl = matches[1] linkText = matches[2] remainder = matches[3] createTokens linkUrl, linkText, remainder, Token (state) -> blockTokens = undefined i = undefined j = undefined l = undefined token = undefined tokens = undefined blockTokens = state.tokens j = 0 l = blockTokens.length while j < l if blockTokens[j].type != 'inline' j++ continue tokens = blockTokens[j].children i = tokens.length - 1 while i >= 0 token = tokens[i] if token.type != 'code_inline' blockTokens[j].children = tokens = arrayReplaceAt(tokens, i, splitTextToken(token, state.Token)) i-- j++ return ###global module ### module.exports = (md, options) -> md.core.ruler.push 'vimwiki', vimwikiReplace(md, options) return
[ { "context": "fileoverview Tests for no-return-assign.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------", "end": 71, "score": 0.9997806549072266, "start": 59, "tag": "NAME", "value": "Ilya Volodin" } ]
src/tests/rules/no-return-assign.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-return-assign. # @author Ilya Volodin ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-return-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ error = message: 'Return statement should not contain assignment.' type: 'ReturnStatement' implicitError = message: 'Implicit return statement should not contain assignment.' type: 'AssignmentExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-return-assign', rule, valid: [ "module.exports = {'a': 1}" 'result = a * b' ''' -> result = a * b return result ''' '-> return (result = a * b)' , code: ''' -> result = a * b return result ''' options: ['except-parens'] , code: '-> return (result = a * b)' options: ['except-parens'] , code: '-> (result = a * b)' options: ['except-parens'] , code: ''' -> result = a * b return result ''' options: ['always'] , code: ''' -> return -> result = a * b null ''' options: ['always'] , code: '=> return (result = a * b)' options: ['except-parens'] , code: ''' => result = a * b null ''' options: ['except-parens'] , ''' -> while yes return a if b c = d ''' ''' -> for a in b return c d = e ''' ''' class A constructor: -> @a = 1 ''' ] invalid: [ code: '-> return result = a * b' errors: [error] , code: '-> result = a * b' errors: [implicitError] , code: '-> return result = (a * b)' errors: [error] , code: '-> return result = a * b' options: ['except-parens'] errors: [error] , code: '-> return result = (a * b)' options: ['except-parens'] errors: [error] , code: '=> return result = a * b' errors: [error] , code: '=> result = a * b' errors: ['Implicit return statement should not contain assignment.'] , code: '-> return result = a * b' options: ['always'] errors: [error] , code: '-> return (result = a * b)' options: ['always'] errors: [error] , code: '-> (result = a * b)' options: ['always'] errors: [implicitError] , code: '-> return result || (result = a * b)' options: ['always'] errors: [error] , code: '-> result || (result = a * b)' options: ['always'] errors: [{...implicitError, type: 'LogicalExpression'}] ]
88039
###* # @fileoverview Tests for no-return-assign. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-return-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ error = message: 'Return statement should not contain assignment.' type: 'ReturnStatement' implicitError = message: 'Implicit return statement should not contain assignment.' type: 'AssignmentExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-return-assign', rule, valid: [ "module.exports = {'a': 1}" 'result = a * b' ''' -> result = a * b return result ''' '-> return (result = a * b)' , code: ''' -> result = a * b return result ''' options: ['except-parens'] , code: '-> return (result = a * b)' options: ['except-parens'] , code: '-> (result = a * b)' options: ['except-parens'] , code: ''' -> result = a * b return result ''' options: ['always'] , code: ''' -> return -> result = a * b null ''' options: ['always'] , code: '=> return (result = a * b)' options: ['except-parens'] , code: ''' => result = a * b null ''' options: ['except-parens'] , ''' -> while yes return a if b c = d ''' ''' -> for a in b return c d = e ''' ''' class A constructor: -> @a = 1 ''' ] invalid: [ code: '-> return result = a * b' errors: [error] , code: '-> result = a * b' errors: [implicitError] , code: '-> return result = (a * b)' errors: [error] , code: '-> return result = a * b' options: ['except-parens'] errors: [error] , code: '-> return result = (a * b)' options: ['except-parens'] errors: [error] , code: '=> return result = a * b' errors: [error] , code: '=> result = a * b' errors: ['Implicit return statement should not contain assignment.'] , code: '-> return result = a * b' options: ['always'] errors: [error] , code: '-> return (result = a * b)' options: ['always'] errors: [error] , code: '-> (result = a * b)' options: ['always'] errors: [implicitError] , code: '-> return result || (result = a * b)' options: ['always'] errors: [error] , code: '-> result || (result = a * b)' options: ['always'] errors: [{...implicitError, type: 'LogicalExpression'}] ]
true
###* # @fileoverview Tests for no-return-assign. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-return-assign' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ error = message: 'Return statement should not contain assignment.' type: 'ReturnStatement' implicitError = message: 'Implicit return statement should not contain assignment.' type: 'AssignmentExpression' ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-return-assign', rule, valid: [ "module.exports = {'a': 1}" 'result = a * b' ''' -> result = a * b return result ''' '-> return (result = a * b)' , code: ''' -> result = a * b return result ''' options: ['except-parens'] , code: '-> return (result = a * b)' options: ['except-parens'] , code: '-> (result = a * b)' options: ['except-parens'] , code: ''' -> result = a * b return result ''' options: ['always'] , code: ''' -> return -> result = a * b null ''' options: ['always'] , code: '=> return (result = a * b)' options: ['except-parens'] , code: ''' => result = a * b null ''' options: ['except-parens'] , ''' -> while yes return a if b c = d ''' ''' -> for a in b return c d = e ''' ''' class A constructor: -> @a = 1 ''' ] invalid: [ code: '-> return result = a * b' errors: [error] , code: '-> result = a * b' errors: [implicitError] , code: '-> return result = (a * b)' errors: [error] , code: '-> return result = a * b' options: ['except-parens'] errors: [error] , code: '-> return result = (a * b)' options: ['except-parens'] errors: [error] , code: '=> return result = a * b' errors: [error] , code: '=> result = a * b' errors: ['Implicit return statement should not contain assignment.'] , code: '-> return result = a * b' options: ['always'] errors: [error] , code: '-> return (result = a * b)' options: ['always'] errors: [error] , code: '-> (result = a * b)' options: ['always'] errors: [implicitError] , code: '-> return result || (result = a * b)' options: ['always'] errors: [error] , code: '-> result || (result = a * b)' options: ['always'] errors: [{...implicitError, type: 'LogicalExpression'}] ]
[ { "context": "### Author James \"The Jamesernator\" Browning\n 2016\n###\n\"use str", "end": 16, "score": 0.9990818500518799, "start": 11, "tag": "NAME", "value": "James" }, { "context": "### Author James \"The Jamesernator\" Browning\n 2016\n###\n\"use strict\"\nGeneratorFunc"...
async.coffee
Jamesernator/simple-async
0
### Author James "The Jamesernator" Browning 2016 ### "use strict" GeneratorFunction = Object.getPrototypeOf(-> yield return).constructor async = (genFunc) -> ### async converts a GeneratorFunction into a ES7 async function ### unless genFunc instanceof GeneratorFunction # If we don't have a generator stop and don't proceed throw new Error("Passed non-generator to async") return spawn = (args...) -> # This spawn function is the spawn function defined here: # https://tc39.github.io/ecmascript-asyncawait/#desugaring return new Promise (resolve, reject) => # Initialize gen with the correct scope of this and pass in the # arguments given gen = genFunc.apply(this, args) step = (nextFunc) -> # This function will be called whenever a promise returned # from gen.next(...) resolves try # Find out if passing the value back into the generator # succeeds next = nextFunc() catch err # If it threw an error then we're done so reject with # that error reject(err) return if next.done # If the generator is done then this is the return value # so just resolve our promise to it resolve(next.value) return # Take the value yielded and treat it as a promise Promise.resolve(next.value).then (val) -> # If there's a value then step again with a function # that tries to pass it to the generator step -> return gen.next(val) , (err) -> # But if there's an error than try throwing it to the # generator step -> return gen.throw(err) step -> # Start our generator return gen.next(undefined) async.run = (func, errCallback=console.log) -> ### This tries running the async function given and if it fails it calls the errCallback with the error given by the async function ### do async -> try yield async(func)() catch err errCallback(err) async.main = (func) -> ### Although async.run has errCallback as console.log we'll just print the stack ### async.run func, (err) -> console.log err.stack async.from = (iterable) -> ### Creates a async function from an existing iterable ### genFunc = -> yield from iterable return async(genFunc) async.do = async.run Object.defineProperty(async, "name", value: "async") if module? module.exports = async else window.async = async
222565
### Author <NAME> "<NAME>" <NAME> 2016 ### "use strict" GeneratorFunction = Object.getPrototypeOf(-> yield return).constructor async = (genFunc) -> ### async converts a GeneratorFunction into a ES7 async function ### unless genFunc instanceof GeneratorFunction # If we don't have a generator stop and don't proceed throw new Error("Passed non-generator to async") return spawn = (args...) -> # This spawn function is the spawn function defined here: # https://tc39.github.io/ecmascript-asyncawait/#desugaring return new Promise (resolve, reject) => # Initialize gen with the correct scope of this and pass in the # arguments given gen = genFunc.apply(this, args) step = (nextFunc) -> # This function will be called whenever a promise returned # from gen.next(...) resolves try # Find out if passing the value back into the generator # succeeds next = nextFunc() catch err # If it threw an error then we're done so reject with # that error reject(err) return if next.done # If the generator is done then this is the return value # so just resolve our promise to it resolve(next.value) return # Take the value yielded and treat it as a promise Promise.resolve(next.value).then (val) -> # If there's a value then step again with a function # that tries to pass it to the generator step -> return gen.next(val) , (err) -> # But if there's an error than try throwing it to the # generator step -> return gen.throw(err) step -> # Start our generator return gen.next(undefined) async.run = (func, errCallback=console.log) -> ### This tries running the async function given and if it fails it calls the errCallback with the error given by the async function ### do async -> try yield async(func)() catch err errCallback(err) async.main = (func) -> ### Although async.run has errCallback as console.log we'll just print the stack ### async.run func, (err) -> console.log err.stack async.from = (iterable) -> ### Creates a async function from an existing iterable ### genFunc = -> yield from iterable return async(genFunc) async.do = async.run Object.defineProperty(async, "name", value: "async") if module? module.exports = async else window.async = async
true
### Author PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI 2016 ### "use strict" GeneratorFunction = Object.getPrototypeOf(-> yield return).constructor async = (genFunc) -> ### async converts a GeneratorFunction into a ES7 async function ### unless genFunc instanceof GeneratorFunction # If we don't have a generator stop and don't proceed throw new Error("Passed non-generator to async") return spawn = (args...) -> # This spawn function is the spawn function defined here: # https://tc39.github.io/ecmascript-asyncawait/#desugaring return new Promise (resolve, reject) => # Initialize gen with the correct scope of this and pass in the # arguments given gen = genFunc.apply(this, args) step = (nextFunc) -> # This function will be called whenever a promise returned # from gen.next(...) resolves try # Find out if passing the value back into the generator # succeeds next = nextFunc() catch err # If it threw an error then we're done so reject with # that error reject(err) return if next.done # If the generator is done then this is the return value # so just resolve our promise to it resolve(next.value) return # Take the value yielded and treat it as a promise Promise.resolve(next.value).then (val) -> # If there's a value then step again with a function # that tries to pass it to the generator step -> return gen.next(val) , (err) -> # But if there's an error than try throwing it to the # generator step -> return gen.throw(err) step -> # Start our generator return gen.next(undefined) async.run = (func, errCallback=console.log) -> ### This tries running the async function given and if it fails it calls the errCallback with the error given by the async function ### do async -> try yield async(func)() catch err errCallback(err) async.main = (func) -> ### Although async.run has errCallback as console.log we'll just print the stack ### async.run func, (err) -> console.log err.stack async.from = (iterable) -> ### Creates a async function from an existing iterable ### genFunc = -> yield from iterable return async(genFunc) async.do = async.run Object.defineProperty(async, "name", value: "async") if module? module.exports = async else window.async = async
[ { "context": " \"undefined\")\n bot.replyPromisified(\"My name is bob\", \"Hello, Bob.\")\n .then ->\n bot.uservar(\"name", "end": 1440, "score": 0.9835101962089539, "start": 1437, "tag": "NAME", "value": "bob" }, { "context": " bot.replyPromisified(\"My name is bob\", \"He...
test/test-promises-begin.coffee
rundexter/rivescript-js
1
TestCase = require("./test-promises-base") ################################################################################ # BEGIN Block Tests ################################################################################ exports.test_no_begin_block = (test) -> bot = new TestCase(test, """ + hello bot - Hello human. """) bot.replyPromisified("Hello bot", "Hello human.").then -> test.done() exports.test_simple_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - {ok} < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> test.done() exports.test_blocked_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Nope.").then -> test.done() exports.test_conditional_begin_block = (test) -> bot = new TestCase(test, """ > begin + request * <get met> == undefined => <set met=true>{ok} * <get name> != undefined => <get name>: {ok} - {ok} < begin + hello bot - Hello human. + my name is * - <set name=<formal>>Hello, <get name>. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> bot.uservar("met", "true") bot.uservar("name", "undefined") bot.replyPromisified("My name is bob", "Hello, Bob.") .then -> bot.uservar("name", "Bob") bot.replyPromisified("Hello Bot", "Bob: Hello human.") .then -> test.done() exports.test_skip_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.rs.replyPromisified(bot.username, "Hello bot.", null, true).then (reply) -> test.equal(reply, "Hello human.") test.done() exports.test_redirects_in_begin = (test) -> bot = new TestCase(test, """ > begin + request * <get welcomed> == undefined => {@ hello} * <get welcomed> == 1 => {ok} - {ok} < begin + hello - <set welcomed=1>Hello human. + * - Hi Again """) bot.replyPromisified("I'm not welcomed yet", "Hello human.") .then (reply) -> bot.replyPromisified("Now I am welcomed", "Hi Again") .then -> bot = new TestCase(test, """ > begin + request * <get welcomed> != 1 => {topic=intro}{ok} - {ok} < begin > topic intro + hello - <set welcomed=1>hi{topic=next} + * - not here < topic > topic next + next - in next + * - nope < topic """, "debug":true) bot.replyPromisified("hello", "hi") .then -> bot.replyPromisified("next", "in next") .then -> test.done()
27128
TestCase = require("./test-promises-base") ################################################################################ # BEGIN Block Tests ################################################################################ exports.test_no_begin_block = (test) -> bot = new TestCase(test, """ + hello bot - Hello human. """) bot.replyPromisified("Hello bot", "Hello human.").then -> test.done() exports.test_simple_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - {ok} < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> test.done() exports.test_blocked_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Nope.").then -> test.done() exports.test_conditional_begin_block = (test) -> bot = new TestCase(test, """ > begin + request * <get met> == undefined => <set met=true>{ok} * <get name> != undefined => <get name>: {ok} - {ok} < begin + hello bot - Hello human. + my name is * - <set name=<formal>>Hello, <get name>. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> bot.uservar("met", "true") bot.uservar("name", "undefined") bot.replyPromisified("My name is <NAME>", "Hello, <NAME>.") .then -> bot.uservar("name", "<NAME>") bot.replyPromisified("Hello Bot", "Bob: Hello human.") .then -> test.done() exports.test_skip_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.rs.replyPromisified(bot.username, "Hello bot.", null, true).then (reply) -> test.equal(reply, "Hello human.") test.done() exports.test_redirects_in_begin = (test) -> bot = new TestCase(test, """ > begin + request * <get welcomed> == undefined => {@ hello} * <get welcomed> == 1 => {ok} - {ok} < begin + hello - <set welcomed=1>Hello human. + * - Hi Again """) bot.replyPromisified("I'm not welcomed yet", "Hello human.") .then (reply) -> bot.replyPromisified("Now I am welcomed", "Hi Again") .then -> bot = new TestCase(test, """ > begin + request * <get welcomed> != 1 => {topic=intro}{ok} - {ok} < begin > topic intro + hello - <set welcomed=1>hi{topic=next} + * - not here < topic > topic next + next - in next + * - nope < topic """, "debug":true) bot.replyPromisified("hello", "hi") .then -> bot.replyPromisified("next", "in next") .then -> test.done()
true
TestCase = require("./test-promises-base") ################################################################################ # BEGIN Block Tests ################################################################################ exports.test_no_begin_block = (test) -> bot = new TestCase(test, """ + hello bot - Hello human. """) bot.replyPromisified("Hello bot", "Hello human.").then -> test.done() exports.test_simple_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - {ok} < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> test.done() exports.test_blocked_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.replyPromisified("Hello bot.", "Nope.").then -> test.done() exports.test_conditional_begin_block = (test) -> bot = new TestCase(test, """ > begin + request * <get met> == undefined => <set met=true>{ok} * <get name> != undefined => <get name>: {ok} - {ok} < begin + hello bot - Hello human. + my name is * - <set name=<formal>>Hello, <get name>. """) bot.replyPromisified("Hello bot.", "Hello human.").then -> bot.uservar("met", "true") bot.uservar("name", "undefined") bot.replyPromisified("My name is PI:NAME:<NAME>END_PI", "Hello, PI:NAME:<NAME>END_PI.") .then -> bot.uservar("name", "PI:NAME:<NAME>END_PI") bot.replyPromisified("Hello Bot", "Bob: Hello human.") .then -> test.done() exports.test_skip_begin_block = (test) -> bot = new TestCase(test, """ > begin + request - Nope. < begin + hello bot - Hello human. """) bot.rs.replyPromisified(bot.username, "Hello bot.", null, true).then (reply) -> test.equal(reply, "Hello human.") test.done() exports.test_redirects_in_begin = (test) -> bot = new TestCase(test, """ > begin + request * <get welcomed> == undefined => {@ hello} * <get welcomed> == 1 => {ok} - {ok} < begin + hello - <set welcomed=1>Hello human. + * - Hi Again """) bot.replyPromisified("I'm not welcomed yet", "Hello human.") .then (reply) -> bot.replyPromisified("Now I am welcomed", "Hi Again") .then -> bot = new TestCase(test, """ > begin + request * <get welcomed> != 1 => {topic=intro}{ok} - {ok} < begin > topic intro + hello - <set welcomed=1>hi{topic=next} + * - not here < topic > topic next + next - in next + * - nope < topic """, "debug":true) bot.replyPromisified("hello", "hi") .then -> bot.replyPromisified("next", "in next") .then -> test.done()
[ { "context": "# name: coffeescript.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈", "end": 39, "score": 0.9998928904533386, "start": 36, "tag": "NAME", "value": "沈维忠" }, { "context": "# name: coffeescript.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n...
dev/splited_tasks_for_gulp/coffeescript.coffee
gitter-badger/is-object-brace
0
# name: coffeescript.js # # author: 沈维忠 ( Shen Weizhong / Tony Stark ) # # Last Update: 沈维忠 ( Shen Weizhong / Tony Stark ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() clp = require './clp' lazypipe = require 'lazypipe' _coffeelint = lazypipe() .pipe $.coffeelint, 'coffeelint.json' .pipe $.coffeelint.reporter _cs = lazypipe() .pipe -> $.if clp.coffeelint, _coffeelint() .pipe $.coffee, cfg.cs_opts gulp.task 'coffeescript', -> iob_src = gulp.src cfg.path.dev + 'is.object.brace.coffee' test_src = gulp.src cfg.path.dev + 'test.coffee' gulpfile_src = gulp.src cfg.path.dev + 'gulpfile.coffee' iob_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe $.rename dirname: '' basename: 'index' extname: '.js' .pipe gulp.dest cfg.path.project_root test_src.pipe $.changed cfg.path.test .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.test gulpfile_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.project_root return
203289
# name: coffeescript.js # # author: <NAME> ( <NAME> / <NAME> ) # # Last Update: <NAME> ( <NAME> / <NAME> ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() clp = require './clp' lazypipe = require 'lazypipe' _coffeelint = lazypipe() .pipe $.coffeelint, 'coffeelint.json' .pipe $.coffeelint.reporter _cs = lazypipe() .pipe -> $.if clp.coffeelint, _coffeelint() .pipe $.coffee, cfg.cs_opts gulp.task 'coffeescript', -> iob_src = gulp.src cfg.path.dev + 'is.object.brace.coffee' test_src = gulp.src cfg.path.dev + 'test.coffee' gulpfile_src = gulp.src cfg.path.dev + 'gulpfile.coffee' iob_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe $.rename dirname: '' basename: 'index' extname: '.js' .pipe gulp.dest cfg.path.project_root test_src.pipe $.changed cfg.path.test .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.test gulpfile_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.project_root return
true
# name: coffeescript.js # # author: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) # # Last Update: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI ) 'use strict' cfg = require '../config.json' gulp = require 'gulp' $ = require('gulp-load-plugins')() clp = require './clp' lazypipe = require 'lazypipe' _coffeelint = lazypipe() .pipe $.coffeelint, 'coffeelint.json' .pipe $.coffeelint.reporter _cs = lazypipe() .pipe -> $.if clp.coffeelint, _coffeelint() .pipe $.coffee, cfg.cs_opts gulp.task 'coffeescript', -> iob_src = gulp.src cfg.path.dev + 'is.object.brace.coffee' test_src = gulp.src cfg.path.dev + 'test.coffee' gulpfile_src = gulp.src cfg.path.dev + 'gulpfile.coffee' iob_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe $.rename dirname: '' basename: 'index' extname: '.js' .pipe gulp.dest cfg.path.project_root test_src.pipe $.changed cfg.path.test .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.test gulpfile_src.pipe $.changed cfg.path.project_root .pipe $.plumber() .pipe _cs() .pipe gulp.dest cfg.path.project_root return
[ { "context": "el: '#emailAddressFieldLabel'\n passwordField: '#passwordField'\n passwordFieldLabel: '#passwordFieldLabel'\n", "end": 1051, "score": 0.9978083968162537, "start": 1036, "tag": "PASSWORD", "value": "'#passwordField" }, { "context": "dField: '#passwordField'\n ...
src/app/controller/Account.coffee
Purple-Services/app
2
Ext.define 'Purple.controller.Account', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountForm: 'accountform' vehicles: 'vehicles' orders: 'orders' # LoginForm elements loginForm: 'loginform' loginButtonContainer: '#loginButtonContainer' registerButtonContainer: '#registerButtonContainer' forgotPasswordButtonContainer: '#forgotPasswordButtonContainer' createAccountButtonContainer: '#createAccountButtonContainer' termsMessage: '#termsMessage' showRegisterButtonContainer: '#showRegisterButtonContainer' showLoginButtonContainer: '#showLoginButtonContainer' purpleLoginLogo: '#purpleLoginLogo' finalStepText: '#finalStepText' alternativeLoginOptionsText: '#alternativeLoginOptionsText' alternativeLoginOptions: '#alternativeLoginOptions' emailAddressField: '#emailAddressField' emailAddressFieldLabel: '#emailAddressFieldLabel' passwordField: '#passwordField' passwordFieldLabel: '#passwordFieldLabel' nameField: '#nameField' nameFieldLabel: '#nameFieldLabel' phoneNumberField: '#phoneNumberField' phoneNumberFieldLabel: '#phoneNumberFieldLabel' googleLoginButton: '#googleLoginButton' # AccountForm elements accountNameField: '#accountNameField' accountPhoneNumberField: '#accountPhoneNumberField' accountEmailField: '#accountEmailField' accountPaymentMethodField: '#accountPaymentMethodField' accountHorizontalRuleAbovePaymentMethod: '[ctype=accountHorizontalRuleAbovePaymentMethod]' accountTabContainer: '#accountTabContainer' editAccountForm: 'editaccountform' control: loginForm: nativeLogin: 'nativeLogin' nativeRegister: 'nativeRegister' createAccount: 'createAccount' # for adding phone and name to account resetPassword: 'resetPassword' facebookLogin: 'facebookLogin' googleLogin: 'googleLogin' showRegisterButtonTap: 'showRegisterForm' showLoginButtonTap: 'showLoginForm' showForgotPasswordButtonTap: 'showForgotPasswordForm' accountNameField: initialize: 'initAccountNameField' accountPhoneNumberField: initialize: 'initAccountPhoneNumberField' accountEmailField: initialize: 'initAccountEmailField' editAccountForm: saveChanges: 'saveChanges' accountForm: logoutButtonTap: 'logout' launch: -> @callParent arguments nativeRegister: -> vals = @getLoginForm().getValues() @registerUser vals['email_address'], vals['password'] # only for users of type = 'native' # for other users (google / fb) should just use authorizeUser() # regardless of whether or not they already exist in our db # # so, platformId is always email address # and, authKey is always password registerUser: (platformId, authKey) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/register" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: platformId auth_key: authKey headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> # this will be treated the same as authorizeUser # because they are automatically logged in after creating # their account Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleToken'] = response.token # they don't have any vehicles or orders yet. util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() @accountSetup() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' nativeLogin: -> vals = @getLoginForm().getValues() @authorizeUser 'native', vals['email_address'], vals['password'] # handles native users as a login # handles fb and google users as a login or register # (depending on whether or not they exist in our db) authorizeUser: (type, platformId, authKey, emailOverride = null) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/login" params: Ext.JSON.encode version: util.VERSION_NUMBER os: Ext.os.name type: type platform_id: platformId auth_key: authKey email_override: emailOverride headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserName'] = response.user.name localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserAccountManagerId'] = response.user.account_manager_id localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleUserHasPushNotificationsSetUp'] = response.user.has_push_notifications_set_up localStorage['purpleToken'] = response.token localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId delete localStorage['purpleDefaultPaymentMethodId'] for c, card of response.cards if card.default localStorage['purpleDefaultPaymentMethodId'] = card.id localStorage['purpleDefaultPaymentMethodDisplayText'] = """ #{card.brand} *#{card.last4} """ util.ctl('PaymentMethods').paymentMethods = response.cards util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = response.orders util.ctl('Orders').loadOrdersList() analytics?.identify localStorage['purpleUserId'] if response.account_complete? and not response.account_complete @accountSetup() else util.ctl('Menu').adjustForAppLoginState() if @isCourier() # a courier account, go to Orders page # may want to go to Tanks page in future when we use that util.ctl('Menu').selectOption 3 util.ctl('Main').setUpPushNotifications() else # a normal user, go to Request Gas page util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' facebookLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Facebook Login Pressed' analytics?.track 'Facebook Login Pressed' facebookConnectPlugin.getLoginStatus( ((result) => if result['status'] is 'connected' # they've done this before, just renew *our* 'purpleToken' @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) else # they haven't logged into our fb app yet (or they removed it) facebookConnectPlugin.login( ["email"], (Ext.bind @facebookLoginSuccess, this), (Ext.bind @facebookLoginFailure, this) ) ), (-> Ext.Viewport.setMasked false console.log 'error', arguments) ) facebookLoginSuccess: (result) -> @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) facebookLoginFailure: (error) -> Ext.Viewport.setMasked false alert "Facebook login error. Please make sure your Facebook app is logged in correctly." console.log 'Facebook login error: ' + JSON.stringify(error) googleLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Google Login Pressed' analytics?.track 'Google Login Pressed' window.plugins.googleplus.login( (if Ext.os.name is "iOS" { 'scopes': 'profile email' } else # Android { 'scopes': 'profile email' 'webClientId': '727391770434-33032g56t6p38uh9sj9dqtst53eipaka.apps.googleusercontent.com' 'offline': true }), (Ext.bind @googleLoginSuccess, this), (-> Ext.Viewport.setMasked false analytics?.track 'Google Login Error', platform: Ext.os.name errorId: arguments[0] util.alert "Something went wrong. Please use Facebook Login or register a Purple Account. Or, email us at support@purpleapp.com.", "Error", (->) console.log 'error', arguments) ) googleLoginSuccess: (result) -> if VERSION isnt "PROD" console.log JSON.stringify(result) @authorizeUser( 'google', result['userId'], (if Ext.os.name is "iOS" result['accessToken'] else # Android result['idToken']) ) accountSetup: -> @showAccountSetupForm() createAccount: -> # for adding phone and name to account that was just created in db name = @getNameField().getValue() phoneNumber = @getPhoneNumberField().getValue().replace(/[^\d]/gi, '') Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: name: name phone_number: phoneNumber headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes ga_storage._trackEvent 'main', 'Account Created' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' showAccountSetupForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getEmailAddressField().hide() @getEmailAddressFieldLabel().hide() @getPasswordField().hide() @getPasswordFieldLabel().hide() @getAlternativeLoginOptions().hide() @getAlternativeLoginOptionsText().hide() @getPurpleLoginLogo().hide() @getFinalStepText().show() @getNameField().show() @getNameFieldLabel().show() @getPhoneNumberField().show() @getPhoneNumberFieldLabel().show() @getCreateAccountButtonContainer().show() @getTermsMessage().show() # populate with any info we might have (depending on user type) if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getNameField().setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' @getPhoneNumberField().setValue localStorage['purpleUserPhoneNumber'] showRegisterForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getRegisterButtonContainer().show() showLoginForm: -> @getFinalStepText().hide() @getNameField().hide() @getNameFieldLabel().hide() @getPhoneNumberField().hide() @getPhoneNumberFieldLabel().hide() @getCreateAccountButtonContainer().hide() @getTermsMessage().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getForgotPasswordButtonContainer().hide() @getEmailAddressField().show() @getEmailAddressFieldLabel().show() @getAlternativeLoginOptions().show() @getAlternativeLoginOptionsText().show() @getPurpleLoginLogo().show() @getPasswordField().show() @getPasswordFieldLabel().show() @getLoginButtonContainer().show() @getShowRegisterButtonContainer().show() if Ext.os.name is "iOS" @getGoogleLoginButton().hide() window.plugins?.googleplus?.isAvailable (available) => if available then @getGoogleLoginButton().show() else @getGoogleLoginButton().show() if not facebookConnectPlugin? @getAlternativeLoginOptionsText().hide() @getAlternativeLoginOptions().hide() showForgotPasswordForm: -> @getPasswordField().hide() @getPasswordFieldLabel().hide() @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getForgotPasswordButtonContainer().show() logout: -> # send ajax to kill session? delete localStorage['purpleUserType'] delete localStorage['purpleUserId'] delete localStorage['purpleUserName'] delete localStorage['purpleUserPhoneNumber'] delete localStorage['purpleUserEmail'] delete localStorage['purpleDefaultPaymentMethodId'] delete localStorage['purpleDefaultPaymentMethodDisplayText'] delete localStorage['purpleToken'] delete localStorage['purpleUserIsCourier'] delete localStorage['purpleUserAccountManagerId'] delete localStorage['purpleCourierGallons87'] delete localStorage['purpleCourierGallons91'] delete localStorage['purpleUserHasPushNotificationsSetUp'] delete localStorage['purpleUserReferralCode'] delete localStorage['purpleUserReferralGallons'] delete localStorage['purpleReferralReferredValue'] delete localStorage['purpleReferralReferrerGallons'] delete localStorage['purpleSubscriptionId'] delete localStorage['purpleSubscriptionExpirationTime'] delete localStorage['purpleSubscriptionAutoRenew'] delete localStorage['purpleSubscriptionPeriodStartTime'] delete localStorage['purpleSubscriptionName'] delete localStorage['specialInstructions'] delete localStorage['courierOnDuty'] # clear out some lists from any old logins util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('Main').killCourierPing() util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 1 Ext.get(document.getElementsByTagName('body')[0]).removeCls 'courier-app' ga_storage._trackEvent 'main', 'Logged Out' isUserLoggedIn: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' # of course, this is spoofable by changing localStorage manually isCompleteAccount: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' and localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' and localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' and localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' hasDefaultPaymentMethod: -> localStorage['purpleDefaultPaymentMethodId']? and localStorage['purpleDefaultPaymentMethodId'] isnt '' isCourier: -> # note that 'true' is in quotes intentionally localStorage['purpleUserIsCourier']? and localStorage['purpleUserIsCourier'] is 'true' isManagedAccount: -> localStorage['purpleUserAccountManagerId']? and ("" + localStorage['purpleUserAccountManagerId']) isnt "" hasPushNotificationsSetup: -> localStorage['purpleUserHasPushNotificationsSetUp']? and localStorage['purpleUserHasPushNotificationsSetUp'] is 'true' # only for users of type = 'native' resetPassword: -> vals = @getLoginForm().getValues() emailAddress = vals['email_address'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/forgot-password" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: emailAddress headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() @showLoginForm() util.alert response.message, "Success!", (->) ga_storage._trackEvent 'main', 'Password Reset Initiated' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'forgot password ajax error' populateAccountForm: -> if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getAccountNameField()?.setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' phone = localStorage['purpleUserPhoneNumber'] @getAccountPhoneNumberField()?.setValue switch when phone.length < 10 then phone when phone.length is 10 then "(#{phone.slice 0, 3}) #{phone.slice 3, 6} #{phone.slice 6}" else countryCodeLength = phone.length - 10 "+#{phone.slice 0, countryCodeLength} (#{phone.slice countryCodeLength, (countryCodeLength + 3)}) #{phone.slice (countryCodeLength + 3), (countryCodeLength + 6)}-#{phone.slice (countryCodeLength + 6)}" if localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' @getAccountEmailField()?.setValue localStorage['purpleUserEmail'] if @isCourier() @getAccountPaymentMethodField()?.hide() @getAccountHorizontalRuleAbovePaymentMethod()?.hide() # TODO (is this todo still relevant?) #@getAccountPaymentMethodField().setValue '' initAccountNameField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountPhoneNumberField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountEmailField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this showEditAccountForm: -> @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.EditAccountForm' ) @getEditAccountForm().setValues @getAccountForm().getValues() util.ctl('Menu').pushOntoBackButton => # back to Account page @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) saveChanges: -> user = @getEditAccountForm().getValues() user.phone_number = user.phone_number.replace /[^\d]/gi, '' Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: user headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name # back to Account page @populateAccountForm() @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) util.ctl('Menu').popOffBackButtonWithoutAction() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
22658
Ext.define 'Purple.controller.Account', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountForm: 'accountform' vehicles: 'vehicles' orders: 'orders' # LoginForm elements loginForm: 'loginform' loginButtonContainer: '#loginButtonContainer' registerButtonContainer: '#registerButtonContainer' forgotPasswordButtonContainer: '#forgotPasswordButtonContainer' createAccountButtonContainer: '#createAccountButtonContainer' termsMessage: '#termsMessage' showRegisterButtonContainer: '#showRegisterButtonContainer' showLoginButtonContainer: '#showLoginButtonContainer' purpleLoginLogo: '#purpleLoginLogo' finalStepText: '#finalStepText' alternativeLoginOptionsText: '#alternativeLoginOptionsText' alternativeLoginOptions: '#alternativeLoginOptions' emailAddressField: '#emailAddressField' emailAddressFieldLabel: '#emailAddressFieldLabel' passwordField: <PASSWORD>' passwordFieldLabel: <PASSWORD>' nameField: '#nameField' nameFieldLabel: '#nameFieldLabel' phoneNumberField: '#phoneNumberField' phoneNumberFieldLabel: '#phoneNumberFieldLabel' googleLoginButton: '#googleLoginButton' # AccountForm elements accountNameField: '#accountNameField' accountPhoneNumberField: '#accountPhoneNumberField' accountEmailField: '#accountEmailField' accountPaymentMethodField: '#accountPaymentMethodField' accountHorizontalRuleAbovePaymentMethod: '[ctype=accountHorizontalRuleAbovePaymentMethod]' accountTabContainer: '#accountTabContainer' editAccountForm: 'editaccountform' control: loginForm: nativeLogin: 'nativeLogin' nativeRegister: 'nativeRegister' createAccount: 'createAccount' # for adding phone and name to account resetPassword: '<PASSWORD>' facebookLogin: 'facebookLogin' googleLogin: 'googleLogin' showRegisterButtonTap: 'showRegisterForm' showLoginButtonTap: 'showLoginForm' showForgotPasswordButtonTap: 'showForgotPasswordForm' accountNameField: initialize: 'initAccountNameField' accountPhoneNumberField: initialize: 'initAccountPhoneNumberField' accountEmailField: initialize: 'initAccountEmailField' editAccountForm: saveChanges: 'saveChanges' accountForm: logoutButtonTap: 'logout' launch: -> @callParent arguments nativeRegister: -> vals = @getLoginForm().getValues() @registerUser vals['email_address'], vals['password'] # only for users of type = 'native' # for other users (google / fb) should just use authorizeUser() # regardless of whether or not they already exist in our db # # so, platformId is always email address # and, authKey is always password registerUser: (platformId, authKey) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/register" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: platformId auth_key: authKey headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> # this will be treated the same as authorizeUser # because they are automatically logged in after creating # their account Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleToken'] = response.token # they don't have any vehicles or orders yet. util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() @accountSetup() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' nativeLogin: -> vals = @getLoginForm().getValues() @authorizeUser 'native', vals['email_address'], vals['password'] # handles native users as a login # handles fb and google users as a login or register # (depending on whether or not they exist in our db) authorizeUser: (type, platformId, authKey, emailOverride = null) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/login" params: Ext.JSON.encode version: util.VERSION_NUMBER os: Ext.os.name type: type platform_id: platformId auth_key: authKey email_override: emailOverride headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserName'] = response.user.name localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserAccountManagerId'] = response.user.account_manager_id localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleUserHasPushNotificationsSetUp'] = response.user.has_push_notifications_set_up localStorage['purpleToken'] = response.token localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId delete localStorage['purpleDefaultPaymentMethodId'] for c, card of response.cards if card.default localStorage['purpleDefaultPaymentMethodId'] = card.id localStorage['purpleDefaultPaymentMethodDisplayText'] = """ #{card.brand} *#{card.last4} """ util.ctl('PaymentMethods').paymentMethods = response.cards util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = response.orders util.ctl('Orders').loadOrdersList() analytics?.identify localStorage['purpleUserId'] if response.account_complete? and not response.account_complete @accountSetup() else util.ctl('Menu').adjustForAppLoginState() if @isCourier() # a courier account, go to Orders page # may want to go to Tanks page in future when we use that util.ctl('Menu').selectOption 3 util.ctl('Main').setUpPushNotifications() else # a normal user, go to Request Gas page util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' facebookLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Facebook Login Pressed' analytics?.track 'Facebook Login Pressed' facebookConnectPlugin.getLoginStatus( ((result) => if result['status'] is 'connected' # they've done this before, just renew *our* 'purpleToken' @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) else # they haven't logged into our fb app yet (or they removed it) facebookConnectPlugin.login( ["email"], (Ext.bind @facebookLoginSuccess, this), (Ext.bind @facebookLoginFailure, this) ) ), (-> Ext.Viewport.setMasked false console.log 'error', arguments) ) facebookLoginSuccess: (result) -> @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) facebookLoginFailure: (error) -> Ext.Viewport.setMasked false alert "Facebook login error. Please make sure your Facebook app is logged in correctly." console.log 'Facebook login error: ' + JSON.stringify(error) googleLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Google Login Pressed' analytics?.track 'Google Login Pressed' window.plugins.googleplus.login( (if Ext.os.name is "iOS" { 'scopes': 'profile email' } else # Android { 'scopes': 'profile email' 'webClientId': '727391770434-33032g56t6p38uh9sj9dqtst53eipaka.apps.googleusercontent.com' 'offline': true }), (Ext.bind @googleLoginSuccess, this), (-> Ext.Viewport.setMasked false analytics?.track 'Google Login Error', platform: Ext.os.name errorId: arguments[0] util.alert "Something went wrong. Please use Facebook Login or register a Purple Account. Or, email us at <EMAIL>.", "Error", (->) console.log 'error', arguments) ) googleLoginSuccess: (result) -> if VERSION isnt "PROD" console.log JSON.stringify(result) @authorizeUser( 'google', result['userId'], (if Ext.os.name is "iOS" result['accessToken'] else # Android result['idToken']) ) accountSetup: -> @showAccountSetupForm() createAccount: -> # for adding phone and name to account that was just created in db name = @getNameField().getValue() phoneNumber = @getPhoneNumberField().getValue().replace(/[^\d]/gi, '') Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: name: <NAME> phone_number: phoneNumber headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes ga_storage._trackEvent 'main', 'Account Created' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' showAccountSetupForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getEmailAddressField().hide() @getEmailAddressFieldLabel().hide() @getPasswordField().hide() @getPasswordFieldLabel().hide() @getAlternativeLoginOptions().hide() @getAlternativeLoginOptionsText().hide() @getPurpleLoginLogo().hide() @getFinalStepText().show() @getNameField().show() @getNameFieldLabel().show() @getPhoneNumberField().show() @getPhoneNumberFieldLabel().show() @getCreateAccountButtonContainer().show() @getTermsMessage().show() # populate with any info we might have (depending on user type) if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getNameField().setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' @getPhoneNumberField().setValue localStorage['purpleUserPhoneNumber'] showRegisterForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getRegisterButtonContainer().show() showLoginForm: -> @getFinalStepText().hide() @getNameField().hide() @getNameFieldLabel().hide() @getPhoneNumberField().hide() @getPhoneNumberFieldLabel().hide() @getCreateAccountButtonContainer().hide() @getTermsMessage().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getForgotPasswordButtonContainer().hide() @getEmailAddressField().show() @getEmailAddressFieldLabel().show() @getAlternativeLoginOptions().show() @getAlternativeLoginOptionsText().show() @getPurpleLoginLogo().show() @getPasswordField().show() @getPasswordFieldLabel().show() @getLoginButtonContainer().show() @getShowRegisterButtonContainer().show() if Ext.os.name is "iOS" @getGoogleLoginButton().hide() window.plugins?.googleplus?.isAvailable (available) => if available then @getGoogleLoginButton().show() else @getGoogleLoginButton().show() if not facebookConnectPlugin? @getAlternativeLoginOptionsText().hide() @getAlternativeLoginOptions().hide() showForgotPasswordForm: -> @getPasswordField().hide() @getPasswordFieldLabel().hide() @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getForgotPasswordButtonContainer().show() logout: -> # send ajax to kill session? delete localStorage['purpleUserType'] delete localStorage['purpleUserId'] delete localStorage['purpleUserName'] delete localStorage['purpleUserPhoneNumber'] delete localStorage['purpleUserEmail'] delete localStorage['purpleDefaultPaymentMethodId'] delete localStorage['purpleDefaultPaymentMethodDisplayText'] delete localStorage['purpleToken'] delete localStorage['purpleUserIsCourier'] delete localStorage['purpleUserAccountManagerId'] delete localStorage['purpleCourierGallons87'] delete localStorage['purpleCourierGallons91'] delete localStorage['purpleUserHasPushNotificationsSetUp'] delete localStorage['purpleUserReferralCode'] delete localStorage['purpleUserReferralGallons'] delete localStorage['purpleReferralReferredValue'] delete localStorage['purpleReferralReferrerGallons'] delete localStorage['purpleSubscriptionId'] delete localStorage['purpleSubscriptionExpirationTime'] delete localStorage['purpleSubscriptionAutoRenew'] delete localStorage['purpleSubscriptionPeriodStartTime'] delete localStorage['purpleSubscriptionName'] delete localStorage['specialInstructions'] delete localStorage['courierOnDuty'] # clear out some lists from any old logins util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('Main').killCourierPing() util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 1 Ext.get(document.getElementsByTagName('body')[0]).removeCls 'courier-app' ga_storage._trackEvent 'main', 'Logged Out' isUserLoggedIn: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' # of course, this is spoofable by changing localStorage manually isCompleteAccount: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' and localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' and localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' and localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' hasDefaultPaymentMethod: -> localStorage['purpleDefaultPaymentMethodId']? and localStorage['purpleDefaultPaymentMethodId'] isnt '' isCourier: -> # note that 'true' is in quotes intentionally localStorage['purpleUserIsCourier']? and localStorage['purpleUserIsCourier'] is 'true' isManagedAccount: -> localStorage['purpleUserAccountManagerId']? and ("" + localStorage['purpleUserAccountManagerId']) isnt "" hasPushNotificationsSetup: -> localStorage['purpleUserHasPushNotificationsSetUp']? and localStorage['purpleUserHasPushNotificationsSetUp'] is 'true' # only for users of type = 'native' resetPassword: -> vals = @getLoginForm().getValues() emailAddress = vals['email_address'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/forgot-password" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: emailAddress headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() @showLoginForm() util.alert response.message, "Success!", (->) ga_storage._trackEvent 'main', 'Password Reset Initiated' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'forgot password ajax error' populateAccountForm: -> if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getAccountNameField()?.setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' phone = localStorage['purpleUserPhoneNumber'] @getAccountPhoneNumberField()?.setValue switch when phone.length < 10 then phone when phone.length is 10 then "(#{phone.slice 0, 3}) #{phone.slice 3, 6} #{phone.slice 6}" else countryCodeLength = phone.length - 10 "+#{phone.slice 0, countryCodeLength} (#{phone.slice countryCodeLength, (countryCodeLength + 3)}) #{phone.slice (countryCodeLength + 3), (countryCodeLength + 6)}-#{phone.slice (countryCodeLength + 6)}" if localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' @getAccountEmailField()?.setValue localStorage['purpleUserEmail'] if @isCourier() @getAccountPaymentMethodField()?.hide() @getAccountHorizontalRuleAbovePaymentMethod()?.hide() # TODO (is this todo still relevant?) #@getAccountPaymentMethodField().setValue '' initAccountNameField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountPhoneNumberField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountEmailField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this showEditAccountForm: -> @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.EditAccountForm' ) @getEditAccountForm().setValues @getAccountForm().getValues() util.ctl('Menu').pushOntoBackButton => # back to Account page @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) saveChanges: -> user = @getEditAccountForm().getValues() user.phone_number = user.phone_number.replace /[^\d]/gi, '' Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: user headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name # back to Account page @populateAccountForm() @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) util.ctl('Menu').popOffBackButtonWithoutAction() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
true
Ext.define 'Purple.controller.Account', extend: 'Ext.app.Controller' config: refs: mainContainer: 'maincontainer' topToolbar: 'toptoolbar' accountForm: 'accountform' vehicles: 'vehicles' orders: 'orders' # LoginForm elements loginForm: 'loginform' loginButtonContainer: '#loginButtonContainer' registerButtonContainer: '#registerButtonContainer' forgotPasswordButtonContainer: '#forgotPasswordButtonContainer' createAccountButtonContainer: '#createAccountButtonContainer' termsMessage: '#termsMessage' showRegisterButtonContainer: '#showRegisterButtonContainer' showLoginButtonContainer: '#showLoginButtonContainer' purpleLoginLogo: '#purpleLoginLogo' finalStepText: '#finalStepText' alternativeLoginOptionsText: '#alternativeLoginOptionsText' alternativeLoginOptions: '#alternativeLoginOptions' emailAddressField: '#emailAddressField' emailAddressFieldLabel: '#emailAddressFieldLabel' passwordField: PI:PASSWORD:<PASSWORD>END_PI' passwordFieldLabel: PI:PASSWORD:<PASSWORD>END_PI' nameField: '#nameField' nameFieldLabel: '#nameFieldLabel' phoneNumberField: '#phoneNumberField' phoneNumberFieldLabel: '#phoneNumberFieldLabel' googleLoginButton: '#googleLoginButton' # AccountForm elements accountNameField: '#accountNameField' accountPhoneNumberField: '#accountPhoneNumberField' accountEmailField: '#accountEmailField' accountPaymentMethodField: '#accountPaymentMethodField' accountHorizontalRuleAbovePaymentMethod: '[ctype=accountHorizontalRuleAbovePaymentMethod]' accountTabContainer: '#accountTabContainer' editAccountForm: 'editaccountform' control: loginForm: nativeLogin: 'nativeLogin' nativeRegister: 'nativeRegister' createAccount: 'createAccount' # for adding phone and name to account resetPassword: 'PI:PASSWORD:<PASSWORD>END_PI' facebookLogin: 'facebookLogin' googleLogin: 'googleLogin' showRegisterButtonTap: 'showRegisterForm' showLoginButtonTap: 'showLoginForm' showForgotPasswordButtonTap: 'showForgotPasswordForm' accountNameField: initialize: 'initAccountNameField' accountPhoneNumberField: initialize: 'initAccountPhoneNumberField' accountEmailField: initialize: 'initAccountEmailField' editAccountForm: saveChanges: 'saveChanges' accountForm: logoutButtonTap: 'logout' launch: -> @callParent arguments nativeRegister: -> vals = @getLoginForm().getValues() @registerUser vals['email_address'], vals['password'] # only for users of type = 'native' # for other users (google / fb) should just use authorizeUser() # regardless of whether or not they already exist in our db # # so, platformId is always email address # and, authKey is always password registerUser: (platformId, authKey) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/register" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: platformId auth_key: authKey headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> # this will be treated the same as authorizeUser # because they are automatically logged in after creating # their account Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleToken'] = response.token # they don't have any vehicles or orders yet. util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() @accountSetup() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' nativeLogin: -> vals = @getLoginForm().getValues() @authorizeUser 'native', vals['email_address'], vals['password'] # handles native users as a login # handles fb and google users as a login or register # (depending on whether or not they exist in our db) authorizeUser: (type, platformId, authKey, emailOverride = null) -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/login" params: Ext.JSON.encode version: util.VERSION_NUMBER os: Ext.os.name type: type platform_id: platformId auth_key: authKey email_override: emailOverride headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserType'] = response.user.type localStorage['purpleUserId'] = response.user.id localStorage['purpleUserName'] = response.user.name localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserIsCourier'] = response.user.is_courier localStorage['purpleUserAccountManagerId'] = response.user.account_manager_id localStorage['purpleUserReferralCode'] = response.user.referral_code localStorage['purpleUserReferralGallons'] = "" + response.user.referral_gallons util.ctl('Subscriptions').updateSubscriptionRelatedData response localStorage['purpleUserHasPushNotificationsSetUp'] = response.user.has_push_notifications_set_up localStorage['purpleToken'] = response.token localStorage['purpleUserHomeLocationName'] = response.saved_locations.home.displayText localStorage['purpleUserHomePlaceId'] = response.saved_locations.home.googlePlaceId localStorage['purpleUserWorkLocationName'] = response.saved_locations.work.displayText localStorage['purpleUserWorkPlaceId'] = response.saved_locations.work.googlePlaceId delete localStorage['purpleDefaultPaymentMethodId'] for c, card of response.cards if card.default localStorage['purpleDefaultPaymentMethodId'] = card.id localStorage['purpleDefaultPaymentMethodDisplayText'] = """ #{card.brand} *#{card.last4} """ util.ctl('PaymentMethods').paymentMethods = response.cards util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('PaymentMethods').refreshPaymentMethodField() util.ctl('Vehicles').vehicles = response.vehicles util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = response.orders util.ctl('Orders').loadOrdersList() analytics?.identify localStorage['purpleUserId'] if response.account_complete? and not response.account_complete @accountSetup() else util.ctl('Menu').adjustForAppLoginState() if @isCourier() # a courier account, go to Orders page # may want to go to Tanks page in future when we use that util.ctl('Menu').selectOption 3 util.ctl('Main').setUpPushNotifications() else # a normal user, go to Request Gas page util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' facebookLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Facebook Login Pressed' analytics?.track 'Facebook Login Pressed' facebookConnectPlugin.getLoginStatus( ((result) => if result['status'] is 'connected' # they've done this before, just renew *our* 'purpleToken' @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) else # they haven't logged into our fb app yet (or they removed it) facebookConnectPlugin.login( ["email"], (Ext.bind @facebookLoginSuccess, this), (Ext.bind @facebookLoginFailure, this) ) ), (-> Ext.Viewport.setMasked false console.log 'error', arguments) ) facebookLoginSuccess: (result) -> @authorizeUser( 'facebook', result['authResponse']['userID'], result['authResponse']['accessToken'] ) facebookLoginFailure: (error) -> Ext.Viewport.setMasked false alert "Facebook login error. Please make sure your Facebook app is logged in correctly." console.log 'Facebook login error: ' + JSON.stringify(error) googleLogin: -> Ext.Viewport.setMasked xtype: 'loadmask' message: '' ga_storage._trackEvent 'ui', 'Google Login Pressed' analytics?.track 'Google Login Pressed' window.plugins.googleplus.login( (if Ext.os.name is "iOS" { 'scopes': 'profile email' } else # Android { 'scopes': 'profile email' 'webClientId': '727391770434-33032g56t6p38uh9sj9dqtst53eipaka.apps.googleusercontent.com' 'offline': true }), (Ext.bind @googleLoginSuccess, this), (-> Ext.Viewport.setMasked false analytics?.track 'Google Login Error', platform: Ext.os.name errorId: arguments[0] util.alert "Something went wrong. Please use Facebook Login or register a Purple Account. Or, email us at PI:EMAIL:<EMAIL>END_PI.", "Error", (->) console.log 'error', arguments) ) googleLoginSuccess: (result) -> if VERSION isnt "PROD" console.log JSON.stringify(result) @authorizeUser( 'google', result['userId'], (if Ext.os.name is "iOS" result['accessToken'] else # Android result['idToken']) ) accountSetup: -> @showAccountSetupForm() createAccount: -> # for adding phone and name to account that was just created in db name = @getNameField().getValue() phoneNumber = @getPhoneNumberField().getValue().replace(/[^\d]/gi, '') Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: name: PI:NAME:<NAME>END_PI phone_number: phoneNumber headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 0 util.ctl('Main').setUpPushNotifications() @showLoginForm() # to prepare for next logout, if it comes ga_storage._trackEvent 'main', 'Account Created' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'login error' showAccountSetupForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getEmailAddressField().hide() @getEmailAddressFieldLabel().hide() @getPasswordField().hide() @getPasswordFieldLabel().hide() @getAlternativeLoginOptions().hide() @getAlternativeLoginOptionsText().hide() @getPurpleLoginLogo().hide() @getFinalStepText().show() @getNameField().show() @getNameFieldLabel().show() @getPhoneNumberField().show() @getPhoneNumberFieldLabel().show() @getCreateAccountButtonContainer().show() @getTermsMessage().show() # populate with any info we might have (depending on user type) if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getNameField().setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' @getPhoneNumberField().setValue localStorage['purpleUserPhoneNumber'] showRegisterForm: -> @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getRegisterButtonContainer().show() showLoginForm: -> @getFinalStepText().hide() @getNameField().hide() @getNameFieldLabel().hide() @getPhoneNumberField().hide() @getPhoneNumberFieldLabel().hide() @getCreateAccountButtonContainer().hide() @getTermsMessage().hide() @getShowLoginButtonContainer().hide() @getRegisterButtonContainer().hide() @getForgotPasswordButtonContainer().hide() @getEmailAddressField().show() @getEmailAddressFieldLabel().show() @getAlternativeLoginOptions().show() @getAlternativeLoginOptionsText().show() @getPurpleLoginLogo().show() @getPasswordField().show() @getPasswordFieldLabel().show() @getLoginButtonContainer().show() @getShowRegisterButtonContainer().show() if Ext.os.name is "iOS" @getGoogleLoginButton().hide() window.plugins?.googleplus?.isAvailable (available) => if available then @getGoogleLoginButton().show() else @getGoogleLoginButton().show() if not facebookConnectPlugin? @getAlternativeLoginOptionsText().hide() @getAlternativeLoginOptions().hide() showForgotPasswordForm: -> @getPasswordField().hide() @getPasswordFieldLabel().hide() @getLoginButtonContainer().hide() @getShowRegisterButtonContainer().hide() @getShowLoginButtonContainer().show() @getForgotPasswordButtonContainer().show() logout: -> # send ajax to kill session? delete localStorage['purpleUserType'] delete localStorage['purpleUserId'] delete localStorage['purpleUserName'] delete localStorage['purpleUserPhoneNumber'] delete localStorage['purpleUserEmail'] delete localStorage['purpleDefaultPaymentMethodId'] delete localStorage['purpleDefaultPaymentMethodDisplayText'] delete localStorage['purpleToken'] delete localStorage['purpleUserIsCourier'] delete localStorage['purpleUserAccountManagerId'] delete localStorage['purpleCourierGallons87'] delete localStorage['purpleCourierGallons91'] delete localStorage['purpleUserHasPushNotificationsSetUp'] delete localStorage['purpleUserReferralCode'] delete localStorage['purpleUserReferralGallons'] delete localStorage['purpleReferralReferredValue'] delete localStorage['purpleReferralReferrerGallons'] delete localStorage['purpleSubscriptionId'] delete localStorage['purpleSubscriptionExpirationTime'] delete localStorage['purpleSubscriptionAutoRenew'] delete localStorage['purpleSubscriptionPeriodStartTime'] delete localStorage['purpleSubscriptionName'] delete localStorage['specialInstructions'] delete localStorage['courierOnDuty'] # clear out some lists from any old logins util.ctl('Vehicles').vehicles = [] util.ctl('Vehicles').loadVehiclesList() util.ctl('Orders').orders = [] util.ctl('Orders').loadOrdersList() util.ctl('PaymentMethods').paymentMethods = [] util.ctl('PaymentMethods').loadPaymentMethodsList() util.ctl('Main').killCourierPing() util.ctl('Menu').adjustForAppLoginState() util.ctl('Menu').selectOption 1 Ext.get(document.getElementsByTagName('body')[0]).removeCls 'courier-app' ga_storage._trackEvent 'main', 'Logged Out' isUserLoggedIn: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' # of course, this is spoofable by changing localStorage manually isCompleteAccount: -> localStorage['purpleUserId']? and localStorage['purpleUserId'] isnt '' and localStorage['purpleToken']? and localStorage['purpleToken'] isnt '' and localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' and localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' and localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' hasDefaultPaymentMethod: -> localStorage['purpleDefaultPaymentMethodId']? and localStorage['purpleDefaultPaymentMethodId'] isnt '' isCourier: -> # note that 'true' is in quotes intentionally localStorage['purpleUserIsCourier']? and localStorage['purpleUserIsCourier'] is 'true' isManagedAccount: -> localStorage['purpleUserAccountManagerId']? and ("" + localStorage['purpleUserAccountManagerId']) isnt "" hasPushNotificationsSetup: -> localStorage['purpleUserHasPushNotificationsSetUp']? and localStorage['purpleUserHasPushNotificationsSetUp'] is 'true' # only for users of type = 'native' resetPassword: -> vals = @getLoginForm().getValues() emailAddress = vals['email_address'] Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/forgot-password" params: Ext.JSON.encode version: util.VERSION_NUMBER platform_id: emailAddress headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success @getLoginForm().reset() @showLoginForm() util.alert response.message, "Success!", (->) ga_storage._trackEvent 'main', 'Password Reset Initiated' else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response console.log 'forgot password ajax error' populateAccountForm: -> if localStorage['purpleUserName']? and localStorage['purpleUserName'] isnt '' @getAccountNameField()?.setValue localStorage['purpleUserName'] if localStorage['purpleUserPhoneNumber']? and localStorage['purpleUserPhoneNumber'] isnt '' phone = localStorage['purpleUserPhoneNumber'] @getAccountPhoneNumberField()?.setValue switch when phone.length < 10 then phone when phone.length is 10 then "(#{phone.slice 0, 3}) #{phone.slice 3, 6} #{phone.slice 6}" else countryCodeLength = phone.length - 10 "+#{phone.slice 0, countryCodeLength} (#{phone.slice countryCodeLength, (countryCodeLength + 3)}) #{phone.slice (countryCodeLength + 3), (countryCodeLength + 6)}-#{phone.slice (countryCodeLength + 6)}" if localStorage['purpleUserEmail']? and localStorage['purpleUserEmail'] isnt '' @getAccountEmailField()?.setValue localStorage['purpleUserEmail'] if @isCourier() @getAccountPaymentMethodField()?.hide() @getAccountHorizontalRuleAbovePaymentMethod()?.hide() # TODO (is this todo still relevant?) #@getAccountPaymentMethodField().setValue '' initAccountNameField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountPhoneNumberField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this initAccountEmailField: (field) -> field.element.on 'tap', Ext.bind @showEditAccountForm, this showEditAccountForm: -> @getAccountTabContainer().setActiveItem( Ext.create 'Purple.view.EditAccountForm' ) @getEditAccountForm().setValues @getAccountForm().getValues() util.ctl('Menu').pushOntoBackButton => # back to Account page @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) saveChanges: -> user = @getEditAccountForm().getValues() user.phone_number = user.phone_number.replace /[^\d]/gi, '' Ext.Viewport.setMasked xtype: 'loadmask' message: '' Ext.Ajax.request url: "#{util.WEB_SERVICE_BASE_URL}user/edit" params: Ext.JSON.encode version: util.VERSION_NUMBER user_id: localStorage['purpleUserId'] token: localStorage['purpleToken'] user: user headers: 'Content-Type': 'application/json' timeout: 30000 method: 'POST' scope: this success: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText if response.success localStorage['purpleUserEmail'] = response.user.email localStorage['purpleUserPhoneNumber'] = response.user.phone_number localStorage['purpleUserName'] = response.user.name # back to Account page @populateAccountForm() @getAccountTabContainer().setActiveItem @getAccountForm() @getAccountTabContainer().remove( @getEditAccountForm(), yes ) util.ctl('Menu').popOffBackButtonWithoutAction() else util.alert response.message, "Error", (->) failure: (response_obj) -> Ext.Viewport.setMasked false response = Ext.JSON.decode response_obj.responseText console.log response
[ { "context": ">\n nikita\n $templated: true\n key_1: 'value 1'\n key_2: 'value 2 and {{config.key_1}}'\n ", "end": 197, "score": 0.9426977038383484, "start": 190, "tag": "KEY", "value": "value 1" }, { "context": "d: true\n key_1: 'value 1'\n key_2: 'val...
packages/core/test/plugins/templated.coffee
shivaylamba/meilisearch-gatsby-plugin-guide
31
{tags} = require '../test' nikita = require '../../src' describe 'plugins.templated', -> return unless tags.api it 'access config', -> nikita $templated: true key_1: 'value 1' key_2: 'value 2 and {{config.key_1}}' $handler: ({config}) -> config .should.be.finally.containEql key_1: 'value 1' key_2: 'value 2 and value 1' it 'access parent', -> nikita $templated: true key: 'value' , -> @call key: "get {{parent.config.key}} from parent" , ({config}) -> config .should.be.finally.containEql key: 'get value from parent' describe 'disabled with value `false`', -> it 'access value in metadata', -> nikita.call $templated: false , ({metadata: {templated}}) -> templated.should.be.false() it 'disabled in current', -> nikita $templated: false key_1: 'value 1' key_2: 'value 2 and {{config.key_1}}' , ({config}) -> config .should.be.finally.containEql key_1: 'value 1' key_2: 'value 2 and {{config.key_1}}' it 'disabled from parent', -> nikita $templated: true , -> @call $templated: false , -> @call -> @call -> key_1: 'value 1' key_2: 'value 2 and {{config.key_1}}' handler: ({config}) -> config .should.be.finally.containEql key_1: 'value 1' key_2: 'value 2 and {{config.key_1}}'
158112
{tags} = require '../test' nikita = require '../../src' describe 'plugins.templated', -> return unless tags.api it 'access config', -> nikita $templated: true key_1: '<KEY>' key_2: 'value <KEY> and {{config.key_1}}' $handler: ({config}) -> config .should.be.finally.containEql key_1: '<KEY>' key_2: '<KEY> and value <KEY>' it 'access parent', -> nikita $templated: true key: 'value' , -> @call key: "get {{parent.config.key}} from parent" , ({config}) -> config .should.be.finally.containEql key: 'get value from parent' describe 'disabled with value `false`', -> it 'access value in metadata', -> nikita.call $templated: false , ({metadata: {templated}}) -> templated.should.be.false() it 'disabled in current', -> nikita $templated: false key_1: '<KEY>' key_2: 'value <KEY> and {{config.key_1}}' , ({config}) -> config .should.be.finally.containEql key_1: 'value <KEY>' key_2: 'value <KEY> and {{config.key_1}}' it 'disabled from parent', -> nikita $templated: true , -> @call $templated: false , -> @call -> @call -> key_1: '<KEY>' key_2: 'value <KEY> and {{config.key_1}}' handler: ({config}) -> config .should.be.finally.containEql key_1: 'value <KEY>' key_2: 'value <KEY> and {{config.key_1}}'
true
{tags} = require '../test' nikita = require '../../src' describe 'plugins.templated', -> return unless tags.api it 'access config', -> nikita $templated: true key_1: 'PI:KEY:<KEY>END_PI' key_2: 'value PI:KEY:<KEY>END_PI and {{config.key_1}}' $handler: ({config}) -> config .should.be.finally.containEql key_1: 'PI:KEY:<KEY>END_PI' key_2: 'PI:KEY:<KEY>END_PI and value PI:KEY:<KEY>END_PI' it 'access parent', -> nikita $templated: true key: 'value' , -> @call key: "get {{parent.config.key}} from parent" , ({config}) -> config .should.be.finally.containEql key: 'get value from parent' describe 'disabled with value `false`', -> it 'access value in metadata', -> nikita.call $templated: false , ({metadata: {templated}}) -> templated.should.be.false() it 'disabled in current', -> nikita $templated: false key_1: 'PI:KEY:<KEY>END_PI' key_2: 'value PI:KEY:<KEY>END_PI and {{config.key_1}}' , ({config}) -> config .should.be.finally.containEql key_1: 'value PI:KEY:<KEY>END_PI' key_2: 'value PI:KEY:<KEY>END_PI and {{config.key_1}}' it 'disabled from parent', -> nikita $templated: true , -> @call $templated: false , -> @call -> @call -> key_1: 'PI:KEY:<KEY>END_PI' key_2: 'value PI:KEY:<KEY>END_PI and {{config.key_1}}' handler: ({config}) -> config .should.be.finally.containEql key_1: 'value PI:KEY:<KEY>END_PI' key_2: 'value PI:KEY:<KEY>END_PI and {{config.key_1}}'
[ { "context": "js\n // version: <%= pkg.version %> \n // author: Arturo Castillo Delgado \n // license: MIT \n // https://github.com/acs", "end": 105, "score": 0.9998966455459595, "start": 82, "tag": "NAME", "value": "Arturo Castillo Delgado" }, { "context": "ado \n // licens...
node_modules/alerts/Gruntfile.coffee
kathleenfrench/target
1
bannerGlobal = """ // alerts.js // version: <%= pkg.version %> // author: Arturo Castillo Delgado // license: MIT // https://github.com/acstll/alerts (function () {\n\n """ bannerAMD = """ // alerts.js // version: <%= pkg.version %> // author: Arturo Castillo Delgado // license: MIT // https://github.com/acstll/alerts\n\n """ module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON 'package.json' concat: global: options: banner: bannerGlobal, footer: '\n\n}());', process: true src: './index.js' dest: 'dist/<%= pkg.name %>.js' amd: options: banner: bannerAMD, process: false src: 'dist/<%= pkg.name %>-amd-pre.js' dest: 'dist/<%= pkg.name %>-amd.js' amdwrap: main: src: './index.js' dest: 'dist/<%= pkg.name %>-amd-pre.js' clean: ['dist/<%= pkg.name %>-amd-pre.js'] jshint: options: laxbreak: true index: './index.js', # tests: ['test/*.js'] grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-amd-wrap' grunt.registerTask 'lint', ['jshint'] grunt.registerTask 'build', ['concat:global', 'amdwrap:main', 'concat:amd', 'clean']
56694
bannerGlobal = """ // alerts.js // version: <%= pkg.version %> // author: <NAME> // license: MIT // https://github.com/acstll/alerts (function () {\n\n """ bannerAMD = """ // alerts.js // version: <%= pkg.version %> // author: <NAME> // license: MIT // https://github.com/acstll/alerts\n\n """ module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON 'package.json' concat: global: options: banner: bannerGlobal, footer: '\n\n}());', process: true src: './index.js' dest: 'dist/<%= pkg.name %>.js' amd: options: banner: bannerAMD, process: false src: 'dist/<%= pkg.name %>-amd-pre.js' dest: 'dist/<%= pkg.name %>-amd.js' amdwrap: main: src: './index.js' dest: 'dist/<%= pkg.name %>-amd-pre.js' clean: ['dist/<%= pkg.name %>-amd-pre.js'] jshint: options: laxbreak: true index: './index.js', # tests: ['test/*.js'] grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-amd-wrap' grunt.registerTask 'lint', ['jshint'] grunt.registerTask 'build', ['concat:global', 'amdwrap:main', 'concat:amd', 'clean']
true
bannerGlobal = """ // alerts.js // version: <%= pkg.version %> // author: PI:NAME:<NAME>END_PI // license: MIT // https://github.com/acstll/alerts (function () {\n\n """ bannerAMD = """ // alerts.js // version: <%= pkg.version %> // author: PI:NAME:<NAME>END_PI // license: MIT // https://github.com/acstll/alerts\n\n """ module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON 'package.json' concat: global: options: banner: bannerGlobal, footer: '\n\n}());', process: true src: './index.js' dest: 'dist/<%= pkg.name %>.js' amd: options: banner: bannerAMD, process: false src: 'dist/<%= pkg.name %>-amd-pre.js' dest: 'dist/<%= pkg.name %>-amd.js' amdwrap: main: src: './index.js' dest: 'dist/<%= pkg.name %>-amd-pre.js' clean: ['dist/<%= pkg.name %>-amd-pre.js'] jshint: options: laxbreak: true index: './index.js', # tests: ['test/*.js'] grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-concat' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-amd-wrap' grunt.registerTask 'lint', ['jshint'] grunt.registerTask 'build', ['concat:global', 'amdwrap:main', 'concat:amd', 'clean']
[ { "context": "don't know yet what this should be\n author: 'aulast' # author should actually be au, but aulast works", "end": 18769, "score": 0.9445488452911377, "start": 18763, "tag": "USERNAME", "value": "aulast" }, { "context": "lank\">[2]</a>' if this.config.terms\n p...
static/embed/oab_embed.coffee
bit2u/website-12
0
# start with a simple set of helper functions @_L = api: 'https://api.lvatn.com' _L.gebi = (id) -> return document.getElementById id.replace('#','') _L.gebc = (cls) -> return document.getElementsByClassName cls.replace('.','') _L.gebn = (n) -> r = document.getElementsByTagName n.replace('<','').replace('>','') # e.g. by the element name, like "div" return if r? then r else document.getElementsByName n # otherwise by the "name" attribute matching n _L.each = (elems, key, val) -> if typeof elems is 'string' if elems.startsWith '#' elems = [_L.gebi elems] else if elems.startsWith '.' elems = _L.gebc elems else elems = _L.gebn elems else if typeof elems is 'object' elems = [elems] if not Array.isArray elems if elems? for elem in elems if elem? if typeof key is 'function' then key(elem) else _L.set elem, key, val _L.listen = (action, els, fn) -> _L.each els, (el) -> if action is 'enter' action = 'keyup' wfn = (e) -> fn(e) if e.keyCode is 13 else wfn = fn if not _L.has el, 'listen_'+action _L.class el, 'listen_'+action el.addEventListener action, (e) -> wfn(e) _L.show = (els, html, append) -> _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html was = _L.get el, '_l_display' was = (if el.tagName is 'DIV' then 'block' else 'inline') if typeof was isnt 'string' or was is 'none' # TODO should be inline in which cases... el.style.display = was _L.hide = (els) -> _L.each els, (el) -> if el.style.display isnt 'none' _L.set el, '_l_display', el.style.display el.style.display = 'none' _L.get = (els, attr) -> res = undefined _L.each els, (el) -> if not attr? try res = el.value res = undefined if typeof res is 'string' and not res.length try res ?= el.getAttribute attr return res _L.set = (els, attr, val) -> _L.each els, (el) -> # TODO handle dot notation keys e.g if attr is style.display if not val? or attr is 'value' or attr is 'val' try el.value = if not val? then attr else val else try el.setAttribute attr, val _L.checked = (els) -> res = true _L.each els, (el) -> res = el.checked return res _L.html = (els, html, append, show) -> rs = [] _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html rs.push el.innerHTML _L.show(el) if show return if rs.length is 1 then (rs[0] ? '') else if rs.length then rs else '' _L.append = (els, html) -> _L.html els, html, true _L.remove = (els) -> _L.each els, (el) -> el.parentNode.removeChild el _L.class = (el, cls) -> rs = [] classes = el.getAttribute 'class' classes ?= '' if typeof cls is 'string' if classes.indexOf(cls) is -1 classes += ' ' if classes.length classes += cls else classes = classes.replace(cls,'').trim().replace(/ /g,' ') el.setAttribute 'class', classes for c in classes.split ' ' rs.push(c) if c not in rs return rs _L.classes = (els) -> return _L.class els _L.has = (el, cls) -> classes = _L.classes el cls = cls.replace('.') if cls.startsWith '.' if cls in classes return true else return if el.getAttribute(cls) then true else false _L.css = (els, key, val) -> _L.each els, (el) -> s = _L.get(el, 'style') ? '' style = {} for p in s.split ';' ps = p.split ':' style[ps[0].trim()] = ps[1].trim() if ps.length is 2 style[key] = val if val? ss = '' for k of style ss += ';' if ss isnt '' ss += k + ':' + style[k] _L.set el, 'style', ss _L.jx = (route, q, success, error, api, method, data, headers) -> # add auth options to this api ?= _L.api if route.startsWith 'http' url = route else url = api + if api.endsWith('/') then '' else '/' url += (if route.startsWith('/') then route.replace('/','') else route) if route if typeof q is 'string' url += (if url.indexOf('?') is -1 then '?' else '&') + (if q.indexOf('=') is -1 then 'q=' else '') + q else if typeof q is 'object' url += '?' if url.indexOf('?') is -1 url += p + '=' + q[p] + '&' for p of q xhr = new XMLHttpRequest() xhr.open (method ? 'GET'), url xhr.setRequestHeader(h, headers[h]) for h of headers ? {} xhr.send data xhr.onload = () -> if xhr.status isnt 200 try error xhr else try success JSON.parse(xhr.response), xhr catch err console.log err try success xhr catch try error xhr _L.loaded(xhr) if typeof _L.loaded is 'function' xhr.onerror = (err) -> try error(err) _L.post = (route, data, success, error, api, headers) -> headers ?= {} if typeof data is 'object' if typeof data.append isnt 'function' # a FormData object will have an append function, a normal json object will not. FormData should be POSTable by xhr as-is data = JSON.stringify data # disabled sending the correct header to avoid waiting for an OPTIONS check #headers['Content-type'] ?= 'application/json' #route += (if route.indexOf('?') is -1 then '?' else '&') + '_=' + Date.now() # set a random header to try to break any possible caching _L.jx route, undefined, success, error, api, 'POST', data, headers # ============================================================================== _oab = (opts) -> try opts ?= {} # can pass demo true here as well, to control demo output, stopping submit from POSTing this[o] = opts[o] for o of opts this.uid ?= 'anonymous' this.api ?= if window.location.host.indexOf('dev.openaccessbutton.org') isnt -1 then 'https://dev.api.cottagelabs.com/service/oab' else 'https://api.openaccessbutton.org' this.plugin ?= 'instantill' # has to be defined at startup, as either instantill or shareyourpaper this.element ?= '#' + this.plugin this.pushstate ?= true # if true, the embed will try to add page state changes to the browser state manager this.local ?= true # local storage of config turned off by default for now this.config ?= {} this.data ?= {} # the data obj to send to backend this.f ?= {} # the result of the find/ill/permission request to the backend this.template ?= _oab[this.plugin + '_template'] # template or css can be passed in or are as defined below this.css ?= _oab.css this._loading = false # tracks when loads are occurring this.submit_after_metadata = false # used by instantill to track if metadata has been provided by user this.file = false # used by syp to store the file for sending to backend this.demo ?= window.location.href.indexOf('/demo') isnt -1 and (window.location.href.indexOf('openaccessbutton.') isnt -1 or window.location.href.indexOf('shareyourpaper.') isnt -1 or window.location.href.indexOf('instantill.') isnt -1) _L.loaded = this.loaded if this.loaded? # if this is set to a function, it will be passed to _leviathan loaded, which gets run after every ajax call completes. It is also called directly after every configure if window.location.search.indexOf('clear=') isnt -1 localStorage.removeItem '_oab_config_' + this.plugin if window.location.search.indexOf('local=') isnt -1 this.local = if window.location.search.indexOf('local=true') isnt -1 then true else false if window.location.search.indexOf('config=') isnt -1 try this.config = JSON.parse window.location.search.split('config=')[1].split('&')[0].split('#')[0] if window.location.search.indexOf('config.') isnt -1 configs = window.location.search.split 'config.' configs.shift() for c in configs cs = c.split '=' if cs.length is 2 csk = cs[0].trim() csv = cs[1].split('&')[0].split('#')[0].trim() this.configure csk, csv, false setTimeout (() => this.configure()), 1 if not this.config.autorun_off ap = if typeof this.config.autorunparams is 'string' then this.config.autorunparams.split(',') else if typeof this.config.autorunparams is 'object' then this.config.autorunparams else ['doi','title','url','atitle','rft_id','journal','issn','year','author'] ap = ap.replace(/"/g,'').replace(/'/g,'').split(',') if typeof ap is 'string' for o in ap o = o.split('=')[0].trim() eq = o.split('=')[1].trim() if o.indexOf('=') isnt -1 this.data[eq ? o] = decodeURIComponent(window.location.search.replace('?','&').split('&'+o+'=')[1].split('&')[0].replace(/\+/g,' ')) if (window.location.search.replace('?','&').indexOf('&'+o+'=') isnt -1) if not this.data.doi and window.location.href.split('?')[0].indexOf('/10.') isnt -1 and window.location.href.split('?')[0].split('/10.')[1].indexOf('/') > 1 and window.location.href.split('?')[0].split('/10.')[1].trim().split('/').length > 1 this.data.doi = '10.' + window.location.href.split('?')[0].split('/10.')[1].replace(/\/$/,'') if window.location.search.indexOf('email=') isnt -1 this.data.email = window.location.search.split('email=')[1].split('&')[0].split('#')[0] _L.remove '#_oab_collect_email' if window.location.search.indexOf('confirmed=') isnt -1 this.data.confirmed = window.location.search.split('confirmed=')[1].split('&')[0].split('#')[0] this.find() if this.data.doi or (this.plugin is 'instantill' and (this.data.title or this.data.url)) window.addEventListener "popstate", (pe) => this.state(pe) return this catch this.ping 'instantill_or_shareyourpaper_try_initialise_catch' _oab.prototype.cml = () -> return this.config.problem ? this.config.owner ? this.config.email ? '' _oab.prototype.contact = () -> return 'Please try ' + (if this.cml() then '<a id="_oab_contact_library" href="mailto:' + this.cml() + '">contacting your library</a>' else 'contacting your library') + ' directly' _oab.prototype.loading = (load) -> _L.hide '#_oab_error' if load isnt true and (this._loading or load is false) try clearInterval this._loading this._loading = false _L.each '._oab_loading', (el) => if _L.has el, '_oab_continue' el.innerHTML = 'Continue' else if _L.has el, '_oab_submit' el.innerHTML = 'Complete request' else if _L.has el, '_oab_deposit' el.innerHTML = 'Deposit' else if _L.has el, '_oab_find' el.innerHTML = 'Next' else if _L.has el, '_oab_confirm' el.innerHTML = '<b>My upload was an accepted manuscript</b>' else el.innerHTML = 'Find ' + if this.config.say_paper then 'paper' else 'article' # this would only happen on instantill, as "Next" above is the default for syp else _L.html '._oab_find', 'Searching .' _L.html '._oab_submit', 'Submitting .' _L.html '._oab_deposit', 'Depositing .' _L.html '._oab_confirm', 'Depositing .' this._loading = setInterval (() -> for button in _L.gebc '._oab_loading' dots = button.innerHTML.split '.' if dots.length >= 4 button.innerHTML = dots[0] else button.innerHTML = button.innerHTML + ' .' ), 700 _oab.prototype.state = (pop) -> if this.pushstate try u = window.location.pathname if not pop? if window.location.href.indexOf('shareyourpaper.org') isnt -1 and this.data.doi? u = window.location.href.split('10.')[0] + this.data.doi + window.location.search + window.location.hash else if window.location.href.indexOf('/setup') is -1 and window.location.href.indexOf('/demo') is -1 if this.data.doi? or this.data.title? or this.data.url? k = if this.data.doi then 'doi' else if this.data.title then 'title' else 'url' u += window.location.search.split('?' + k + '=')[0].split('&' + k + '=')[0] u += if u.indexOf('?') is -1 then '?' else '&' u += k + '=' + this.data[k] + window.location.hash window.history.pushState "", (if pop? then "search" else "find"), u if pop? # what to do with the pop event? for now just triggers a restart if user # tries to go back, unless called with a boolean from the restart event this.restart() if typeof pop isnt 'boolean' _oab.prototype.restart = (e, val) -> try e.preventDefault() if e.target.parentElement.id isnt '_oab_permissionemail' this.data = {} this.f = {} this.loading false this.file = false gf.value = '' if gf = _L.gebi "_oab_file" _L.hide '._oab_panel' _L.show '#_oab_inputs' this.configure() this.state true if val _L.set '#_oab_input', val this.find() else _L.set '#_oab_input', '' _oab.prototype.ping = (what) -> try if what.indexOf(this.plugin) is -1 what = '_' + what if not what.startsWith '_' what = this.plugin + what url = if this.api.indexOf('dev.') isnt -1 then 'https://dev.api.cottagelabs.com' else 'https://api.cottagelabs.com' url += '/ping.png?service=openaccessbutton&action=' + what + '&from=' + this.uid + '&url=' + encodeURIComponent window.location.href url += '&pilot=' + this.config.pilot if this.config.pilot url += '&live=' + this.config.live if this.config.live _L.jx url _oab.prototype.panel = (panel, section) -> if he = _L.gebi '_oab_' + (if panel.startsWith('_oab_') then panel.replace('_oab_','') else panel) _L.hide '._oab_panel' _L.show he this.section(section) if section _oab.prototype.section = (section) -> # useful for demo/test, just shows a specific section within a panel fe = _L.gebi '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) fe = _L.gebc '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) if not fe? if fe _L.hide '._oab_section' _L.show fe _oab.prototype.submit = (e) -> # only used by instantill try try e.preventDefault() if not this.openurl() and not this.data.email and _L.gebi '#_oab_email' this.validate() else if JSON.stringify(this.f) is '{}' or (not this.f.metadata?.title or not this.f.metadata?.journal or not this.f.metadata?.year) if this.submit_after_metadata this.done false else this.submit_after_metadata = true this.metadata() else this.loading() data = {match: this.f.input, email:this.data.email, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} for k in ['title','journal','year','doi'] data.metadata[k] = this.data[k] if not data.metadata[k] and this.data[k] if data.metadata.doi and data.metadata.doi.indexOf('http') is 0 data.metadata.url = data.metadata.doi delete data.metadata.doi nfield = if this.config.notes then this.config.notes else 'notes' data[nfield] = 'The user provided some metadata. ' if this.data.usermetadata data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f?.ill?.subscription or this.f?.url if typeof data[nfield] isnt 'string' then data[nfield] = '' else data[nfield] += ' ' if this.f.ill?.subscription data[nfield] += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.metadata? data[nfield] += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' ou = this.openurl() if ou and not data.email data.forwarded = true if this.demo is true console.log 'Not POSTing ILL and not forwarding to ' + ou + ' for demo purposes' console.log data else _L.post( this.api+'/ill' data (res) => this.done res () => this.done false ) catch this.ping 'instantill_try_submit_catch' _oab.prototype.validate = () -> if this.config.terms and not _L.checked '#_oab_read_terms' # instantill terms _L.show '#_oab_error', '<p>Please agree to the terms first.</p>' else email = (_L.get('#_oab_email') ? '').trim() if not email.length _L.show '#_oab_error', '<p>Please provide your university email address.</p>' _L.css '#_oab_email', 'border-color', '#f04717' _L.gebi('#_oab_email').focus() else this.loading() _L.post( this.api + '/validate?uid=' + this.uid + '&email=' + email this.config (res) => this.loading false if res is true this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() else if res is 'baddomain' _L.show '#_oab_error', '<p>Please try again with your university email address.</p>' else _L.show '#_oab_error', '<p>Sorry, your email does not look right. ' + (if res isnt false then 'Did you mean ' + res + '? ' else '') + 'Please check and try again.</p>' () => this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() ) _oab.prototype.metadata = (submitafter) -> # only used by instantill for m in ['title','year','journal','doi'] if this.f?.metadata?[m]? or this.data[m]? _L.set '#_oab_'+m, (this.f.metadata ? this.data)[m].split('(')[0].trim() #if this.f?.doi_not_in_crossref # _L.html '#_oab_bad_doi', this.f.doi_not_in_crossref # _L.show '#_oab_doi_not_in_crossref' _L.hide '._oab_panel' _L.show '#_oab_metadata' _oab.prototype.openurl = () -> # only used by instantill if this.f.ill?.openurl try nf = this.config.notes ? 'notes' if this.f.ill.openurl.indexOf(nf+'=') is -1 notes = if this.data?.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? this.f.ill.openurl += '&' if not this.f.ill.openurl.endsWith '&' this.f.ill.openurl += nf + '=' + notes return this.f.ill.openurl else if not this.config.ill_form return '' else config = JSON.parse JSON.stringify this.config defaults = sid: 'sid' title: 'atitle' # this is what iupui needs (title is also acceptable, but would clash with using title for journal title, which we set below, as iupui do that doi: 'rft_id' # don't know yet what this should be author: 'aulast' # author should actually be au, but aulast works even if contains the whole author, using aufirst just concatenates journal: 'title' # this is what iupui needs page: 'pages' # iupui uses the spage and epage for start and end pages, but pages is allowed in openurl, check if this will work for iupui published: 'date' # this is what iupui needs, but in format 1991-07-01 - date format may be a problem year: 'rft.year' # this is what IUPUI uses for d of defaults config[d] = defaults[d] if not config[d] url = config.ill_form url += if url.indexOf('?') is -1 then '?' else '&' url += config.ill_added_params.replace('?','') + '&' if config.ill_added_params url += config.sid + '=InstantILL&' for k of this.f.metadata ? {} v = false if k is 'author' if typeof this.f.metadata.author is 'string' v = this.f.metadata.author else if Array.isArray this.f.metadata.author v = '' for author in this.f.metadata.author try v += ', ' if v.length v += if typeof author is 'string' then author else if typeof author is 'object' and author.family then (author.family + if author.given then ', ' + author.given else '') else JSON.stringify author else if k in ['doi','pmid','pmc','pmcid','url','journal','title','year','issn','volume','issue','page','crossref_type','publisher','published','notes'] v = this.f.metadata[k] url += (config[k] ? k) + '=' + encodeURIComponent(v) + '&' if v notes = if this.data.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? url += '&' + (this.config.notes ? 'notes') + '=' + notes if notes return url.replace '/&&/g', '&' _oab.prototype.done = (res, msg) -> this.loading false if ou = this.openurl() window.location = ou else _L.hide '._oab_panel' _L.hide '._oab_done' if typeof res is 'string' and _L.gebi '_oab_' + res _L.show '#_oab_' + res # various done states for shareyourpaper if res is 'confirm' _L.hide '#_oab_done_restart' else _L.show '#_oab_done_restart' else if res _L.html '#_oab_done_header', '<h3>Thanks! Your request has been received</h3><p>Your confirmation code is: ' + res + ', this will not be emailed to you. The ' + (if this.config.say_paper then 'paper' else 'article') + ' will be sent to ' + this.data.email + ' as soon as possible.</p>' else # only instantill falls through to here _L.html '#_oab_done_header', '<h3>Sorry, we were not able to create an Interlibrary Loan request for you.</h3><p>' + this.contact() + '</p>' _L.html '#_oab_done_restart', 'Try again' this.ping msg ? 'instantill_couldnt_submit_ill' setTimeout (() => this.restart()), 6000 _L.show '#_oab_done' this.after() if typeof this.after is 'function' _oab.prototype.deposit = (e) -> # only used by shareyourpaper try try e.preventDefault() if not this.data.email and _L.gebi '#_oab_email' this.validate() else if this.demo is true and this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 if this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 and this.data.doi isnt '10.1234/oab-syp-confirm' # demo successful deposit info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info _L.set '#_oab_zenodo_url', 'https://zenodo.org/record/3703317' this.done 'zenodo' else # demo something wrong, please confirm this.done 'confirm' this.loaded() if typeof this.loaded is 'function' else fl = _L.gebi '#_oab_file' if fl? and fl.files? and fl.files.length this.file = new FormData() this.file.append 'file', fl.files[0] else if this.file isnt true # can be set to true when dark deposit is being followed - no file required. Or a demo may set it to true _L.show '#_oab_error', '<p>Whoops, you need to give us a file! Check it\'s uploaded.</p>' _L.css '#_oab_file', 'border-color','#f04717' return this.loading() # this could be just an email for a dark deposit, or a file for actual deposit # if the file is acceptable and can go in zenodo then we don't bother getting the email address data = {from: this.uid, plugin: this.plugin, embedded:window.location.href, metadata: this.f?.metadata } data.demo = true if this.demo is true data.config = this.config data.email = this.data.email if this.data.email data.confirmed = this.data.confirmed if this.data.confirmed data.redeposit = this.f.url if typeof this.f?.url is 'string' data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if typeof this.file isnt 'boolean' for d of data if d is 'metadata' for md of data[d] this.file.append(md,data[d][md]) if (typeof data[d][md] is 'string' or typeof data[d][md] is 'number') else this.file.append d,data[d] data = this.file _L.post( this.api+'/deposit', # + (this.f.catalogue ? '') data (res) => this.loading false if typeof this.file isnt 'boolean' if res.zenodo?.already or (this.data.confirmed and not res.zenodo?.url) #or not this.f?.permissions?.file?.archivable this.done 'check' else if res.error # if we should be able to deposit but can't, we stick to the positive response and the file will be manually checked this.done 'partial' else if res.zenodo?.url # deposit was possible, show the user a congrats page with a link to the item in zenodo _L.set '#_oab_zenodo_url', res.zenodo.url if res.embargo info = '<p>You\'ve done your part for now. Unfortunately, ' + (this.f?.metadata?.journal_short ? this.f?.metadata?.journal ? 'the journal') + ' won\'t let us make it public until ' info += if res.embargo_UI then res.embargo_UI else res.embargo info += '. After release, you\'ll find your paper on ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science.</p>' info += '<h3>Your paper will be freely available at this link:</h3>' else info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info this.done 'zenodo' else # if the file given is not a version that is allowed, show a page saying something looks wrong # also the backend should create a dark deposit in this case, but delay it by six hours, and cancel if received in the meantime this.done 'confirm' else if res.type is 'redeposit' this.done 'redeposit' else this.done 'success' () => this.loading false _L.show '#_oab_error', '<p>Sorry, we were not able to deposit this paper for you. ' + this.contact() + '</p><p><a href="#" class="_oab_restart" id="_oab_sorry_try_again"><b>Try again</b></a></p>' this.ping('shareyourpaper_couldnt_submit_deposit') ) catch this.ping 'shareyourpaper_try_deposit_catch' _oab.prototype.permissions = (data) -> # only used by shareyourpaper try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.permissions()), 100 else this.loading false if this.f?.doi_not_in_crossref this.f = {} _L.show '#_oab_error', '<p>Double check your DOI, that doesn\'t look right to us.</p>' _L.gebi('_oab_input').focus() else if this.f?.metadata?.crossref_type? and this.f.metadata.crossref_type not in ['journal-article', 'proceedings-article'] _L.gebi('_oab_input').focus() nj = '<p>Sorry, right now this only works with academic journal articles.' if this.cml() nj += ' To get help with depositing, <a href="' nj += if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml() nj += "?subject=Help%20depositing%20&body=Hi%2C%0D%0A%0D%0AI'd%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C" + '">click here</a>' _L.show '#_oab_error', nj + '.</p>' else if not this.f?.metadata?.title? _L.show '#_oab_error', '<h3>Unknown paper</h3><p>Sorry, we cannot find this paper or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' else _L.hide '._oab_panel' _L.hide '._oab_section' _L.show '#_oab_permissions' this.loading false tcs = 'terms <a id="_oab_terms" href="https://openaccessbutton.org/terms" target="_blank">[1]</a>' tcs += ' <a id="_oab_config_terms" href="' + this.config.terms + '" target="_blank">[2]</a>' if this.config.terms ph = 'your.name@institution.edu'; if this.config.email_domains? and this.config.email_domains.length this.config.email_domains = this.config.email_domains.split(',') if typeof this.config.email_domains is 'string' ph = this.config.email_domains[0] ph = ph.split('@')[1] if ph.indexOf('@') isnt -1 ph = ph.split('//')[1] if ph.indexOf('//') isnt -1 ph = ph.toLowerCase().replace('www.','') ph = 'your.name@institution.edu' if not ph? or ph.length < 3 ph = 'your.name@' + ph if ph.indexOf('@') is -1 if this.data.email _L.hide '._oab_get_email' else _L.show '._oab_get_email' _L.set '#_oab_email', 'placeholder', ph _L.html '._oab_terms', tcs refs = '' for p of this.f?.permissions?.permissions?.policy_full_text ? [] refs += ' <a id="_oab_policy_text" target="_blank" href="' + this.f.permissions.permissions.policy_full_text[p] + '">[' + (parseInt(p)+1) + ']</a>' _L.html '._oab_refs', refs paper = if this.f?.metadata?.doi then '<a id="_oab_your_paper" target="_blank" href="https://doi.org/' + this.f.metadata.doi + '"><u>your paper</u></a>' else 'your paper' _L.html '._oab_your_paper', (if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' then 'the publisher pdf of ' else '') + paper _L.html '._oab_journal', this.f?.metadata?.journal_short ? 'the journal' # set config by this.config.repo_name put name in ._oab_repo if this.f.url # it is already OA, depending on settings can deposit another copy _L.set '._oab_oa_url', 'href', this.f.url if this.config.oa_deposit_off _L.hide '._oab_get_email' _L.show '._oab_oa' else this.file = true # no file required for oa deposit... _L.show '._oab_oa_deposit' else if this.f?.permissions?.permissions?.archiving_allowed # can be shared, depending on permissions info _L.hide('#_oab_not_pdf') if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' if typeof this.f?.permissions?.permissions?.licence_required is 'string' and this.f.permissions.permissions.licence_required.indexOf('other-') is 0 _L.html '._oab_licence', 'under the publisher terms' + refs else _L.html '._oab_licence', this.f?.permissions?.permissions?.licence_required ? 'CC-BY' _L.show '._oab_archivable' else if this.config.dark_deposit_off # permission must be requested first rm = 'mailto:' + (this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact ? this.config.deposit_help ? this.cml()) + '?' rm += 'cc=' + (this.config.deposit_help ? this.cml()) + '&' if this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact rm += 'subject=Request%20to%20self%20archive%20' + (this.f.metadata?.doi ? '') + '&body='; rm += encodeURIComponent 'To whom it may concern,\n\n' rm += encodeURIComponent 'I am writing to request permission to deposit the full text of my paper "' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" ' rm += encodeURIComponent 'published in "' + this.f.metadata.journal + '"' if this.f.metadata?.journal rm += encodeURIComponent '\n\nI would like to archive the final pdf. If that is not possible, I would like to archive the accepted manuscript. Ideally, I would like to do so immediately but will respect a reasonable embargo if requested.\n\n' if this.config.repo_name rm += encodeURIComponent 'I plan to deposit it into "' + this.config.repo_name + '", a not-for-profit, digital, publicly accessible repository for scholarly work created for researchers ' + (if this.config.institution_name then 'at ' + this.config.institution_name else '') + '. It helps make research available to a wider audience, get citations for the original article, and assure its long-term preservation. The deposit will include a complete citation of the published version, and a link to it.\n\n' rm += encodeURIComponent 'Thank you for your attention and I look forward to hearing from you.' _L.set '#_oab_reviewemail', 'href', rm # or to confirm permission has been received pm = 'mailto:' + (this.config.deposit_help ? this.cml()) + '?subject=Permission%20Given%20to%20Deposit%20' + (this.f.metadata?.doi ? '') + '&body=' pm += encodeURIComponent 'To whom it may concern,\n\nAttached is written confirmation of permission I\'ve been given to deposit, and the permitted version of my paper: ' pm += encodeURIComponent '"' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" \n\nCan you please deposit it into the repository on my behalf? \n\nSincerely, ' _L.set '#_oab_permissionemail', 'href', pm _L.hide '._oab_get_email' _L.show '._oab_permission_required' else # can't be directly shared but can be passed to library for dark deposit this.file = true _L.hide '#_oab_file' _L.show '._oab_dark_deposit' catch this.ping 'shareyourpaper_try_permissions_catch' _oab.prototype.findings = (data) -> # only used by instantill try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.findings()), 100 else if ct = this.f.metadata?.crossref_type if ct not in ['journal-article','proceedings-article','posted-content'] if ct in ['book-section','book-part','book-chapter'] err = '<p>Please make your request through our ' + (if this.config.book then '<a id="_oab_book_form" href="' + this.config.book + '">book form</a>' else 'book form') else err = '<p>We can only process academic journal articles, please use another form.' _L.show '#_oab_error', err + '</p>' return _L.hide '._oab_panel' _L.hide '._oab_section' this.loading false if this.config.resolver # new setting to act as a link resolver, try to pass through immediately if sub url, OA url, or lib openurl are available # TODO confirm if this should send an ILL to the backend first, as a record, or maybe just a pinger # also check if could forward the user to the new page before the send to backend succeeds / errors data = {match: this.f.input, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f.ill?.subscription?.url data.resolved = 'subscription' else if this.f.url data.resolved = 'open' else if ou = this.openurl() data.resolved = 'library' if data.resolved? data.url = this.f.ill?.subscription?.url ? this.f.url ? ou _L.post(this.api+'/ill', data, (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou), (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou)) _L.show '#_oab_findings' if this.f.ill?.error _L.show '#_oab_error', '<p>Please note, we encountered errors querying the following subscription services: ' + this.f.ill.error.join(', ') + '</p>' if this.f.metadata?.title? citation = '<h2>' + this.f.metadata.title + '</h2>' if this.f.metadata.year or this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue citation += '<p><i>' citation += (this.f.metadata.year ? '') + (if this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue then ', ' else '') if this.f.metadata.year if this.f.metadata.journal citation += this.f.metadata.journal else citation += 'vol. ' + this.f.metadata.volume if this.f.metadata.volume citation += (if this.f.metadata.volume then ', ' else '') + 'issue ' + this.f.metadata.issue if this.f.metadata.issue citation += '</i></p>' _L.html '#_oab_citation', citation hassub = false hasoa = false if this.f.ill?.subscription?.journal or this.f.ill?.subscription?.url hassub = true # if sub url show the url link, else show the "should be able to access on pub site _L.set('#_oab_sub_url', 'href', this.f.ill.subscription.url) if this.f.ill.subscription.url? _L.show '#_oab_sub_available' else if this.f.url hasoa = true _L.set '#_oab_url', 'href', this.f.url _L.show '#_oab_oa_available' if this.f.ill? and not ((this.config.ill_if_sub_off and hassub) or (this.config.ill_if_oa_off and hasoa)) _L.html '#_oab_cost_time', '<p>It ' + (if this.config.cost then 'costs ' + this.config.cost else 'is free to you,') + ' and we\'ll usually email the link within ' + (this.config.time ? '24 hours') + '.<br></p>' if not this.data.email if this.openurl() _L.hide '#_oab_collect_email' else if this.config.terms _L.show '#_oab_terms_note' _L.set '#_oab_terms_link', 'href', this.config.terms else _L.hide '#_oab_terms_note' _L.show '#_oab_ask_library' else if this.data.usermetadata _L.html '#_oab_citation', '<h3>Unknown ' + (if this.config.say_paper then 'paper' else 'article') + '</h3><p>Sorry, we can\'t find this ' + (if this.config.say_paper then 'paper' else 'article') + ' or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' setTimeout (() => this.restart()), 6000 else this.metadata() catch this.ping 'instantill_try_findings_catch' _oab.prototype.find = (e) -> try try e.preventDefault() if JSON.stringify(this.f) isnt '{}' for k in ['title','journal','year','doi'] if v = _L.get '#_oab_' + k if this.data[k] isnt v this.data[k] = v this.data.usermetadata = true if this.data.year and this.data.year.length isnt 4 delete this.data.year _L.show '#_oab_error', '<p>Please provide the full year e.g 2019</p>' return if not this.data.title or not this.data.journal or not this.data.year _L.show '#_oab_error', '<p>Please complete all required fields</p>' return if this.submit_after_metadata this.submit() return this.data.title ?= this.data.atitle if this.data.atitle this.data.doi ?= this.data.rft_id if this.data.rft_id if this.data.doi and this.data.doi.indexOf('10.') isnt -1 and (this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('http') is 0) this.data.url = this.data.doi delete this.data.doi if val = _L.get('#_oab_input') val = val.trim().replace(/\.$/,'') if val.length if val.indexOf('doi.org/') isnt -1 this.data.url = val this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('10.') isnt -1 this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('http') is 0 or val.indexOf('www.') isnt -1 this.data.url = val else if val.toLowerCase().replace('pmc','').replace('pmid','').replace(':','').replace(/[0-9]/g,'').length is 0 this.data.id = val else this.data.title = val else if this.data.doi or this.data.title or this.data.url or this.data.id _L.set '#_oab_input', this.data.doi ? this.data.title ? this.data.url ? this.data.id if this.plugin is 'instantill' and not this.data.doi and not this.f?.metadata?.journal and this.data.title and this.data.title.length < 30 and this.data.title.split(' ').length < 3 this.metadata() # need more metadata for short titles else if not this.data.doi and (this.plugin is 'shareyourpaper' or (not this.data.url and not this.data.pmid and not this.data.pmcid and not this.data.title and not this.data.id)) if this.plugin is 'shareyourpaper' delete this.data.title delete this.data.url delete this.data.id _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else _L.show '#_oab_error', '<p><span>&#10060;</span> Sorry please provide the full DOI, title, citation, PMID or PMC ID.</p>' else if this.data.doi and this.plugin is 'shareyourpaper' and (this.data.doi.indexOf('10') isnt 0 or this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('.') is -1 or this.data.doi.length < 8) delete this.data.doi _L.set '#_oab_input', '' _L.gebi('_oab_input').focus() _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else this.state() this.loading() this.data.config = this.config this.data.from ?= this.uid this.data.plugin ?= this.plugin this.data.embedded ?= window.location.href this.data.pilot ?= this.config.pilot if this.config.pilot this.data.live ?= this.config.live if this.config.live if this.demo is true and (this.data.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or this.data.doi is '10.1234/567890' or (this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp') is 0)) data = {metadata: {title: 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL', year: '2019', crossref_type: 'journal-article', doi: this.data.doi ? '10.1234/oab-syp-aam'}} data.metadata.journal = 'Proceedings of the 16th IFLA ILDS conference: Beyond the paywall - Resource sharing in a disruptive ecosystem' data.metadata.author = [{given: 'Mike', family: 'Paxton'}, {given: 'Gary', family: 'Maixner III'}, {given: 'Joseph', family: 'McArthur'}, {given: 'Tina', family: 'Baich'}] data.ill = {subscription: {findings:{}, uid: this.uid, lookups:[], error:[], url: 'https://scholarworks.iupui.edu/bitstream/handle/1805/20422/07-PAXTON.pdf?sequence=1&isAllowed=y'}} data.permissions = { permissions: { archiving_allowed: if this.data.doi is '10.1234/oab-syp-aam' then true else false, version_allowed: if this.data.doi is '10.1234/oab-syp-aam' then "postprint" else undefined }, file: {archivable: true, archivable_reason: "Demo acceptance", version: "postprint", licence: "cc-by", same_paper: true, name: "example.pdf", format: "pdf", checksum: "example-checksum"}} if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) else _L.post( this.api+'/find' this.data (data) => if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) () => _L.show '#_oab_error', '<p>Oh dear, the service is down! We\'re aware, and working to fix the problem. ' + this.contact() + '</p>' ) catch this.ping this.plugin + '_try_find_catch' _oab.css = ' <style> ._oab_form { display: inline-block; width: 100%; height: 34px; padding: 6px 12px; font-size: 1em; line-height: 1.428571429; color: #555555; vertical-align: middle; background-color: #ffffff; background-image: none; border: 1px solid #cccccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; } ._oab_button { display: table-cell; height:34px; padding: 6px 3px; margin-bottom: 0; font-size: 1em; font-weight: normal; line-height: 1.428571429; text-decoration: none; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: #ffffff; background-color: #428bca; border-color: #357ebd; } </style>' _oab.instantill_template = ' <div class="_oab_panel" id="_oab_inputs"> <p id="_oab_intro"> If you need <span class="_oab_paper">an article</span> you can request it from any library in the world through Interlibrary loan. <br>Start by entering a full <span class="_oab_paper">article</span> title, citation, DOI or URL:<br> </p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. World Scientists Warning of a Climate Emergency" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" id="_oab_find" href="#" aria-label="Search" style="min-width:140px;">Find <span class="_oab_paper">article</span></a></p> <div id="_oab_book_or_other"></div> <div id="_oab_advanced_account_info"></div> </div> <div class="_oab_panel" id="_oab_findings" style="display:none;"> <div id="_oab_citation"><h2>A title</h2><p><b>And citation string, OR demo title OR Unknown <span class="_oab_paper">article</span> and refer to library</b></p></div> <p id="_oab_wrong_paper"><a class="_oab_wrong" href="#"><b>This is not the <span class="_oab_paper">article</span> I searched</b></a></p> <div class="_oab_section" id="_oab_sub_available"> <h3>We have an online copy instantly available</h3> <p>You should be able to access it on the publisher\'s website.</p> <p><a target="_blank" id="_oab_sub_url" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_oa_available"> <h3><br>There is a free, instantly accessible copy online</h3> <p>It may not be the final published version and may lack graphs or figures making it unsuitable for citations.</p> <p><a id="_oab_url" target="_blank" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_ask_library"> <h3><br>Ask the library to digitally send you the published full-text via Interlibrary Loan</h3> <div id="_oab_cost_time"><p>It is free to you, and we\'ll usually email the link within 24 hours.<br></p></div> <div id="_oab_collect_email"> <p id="_oab_terms_note"><input type="checkbox" id="_oab_read_terms"> I have read the <a id="_oab_terms_link" target="_blank" href="#">terms and conditions</a></p> <p><input placeholder="Your university email address" id="_oab_email" type="text" class="_oab_form"></p> </div> <p><a class="_oab_submit btn-iu _oab_button _oab_loading" href="#" id="_oab_submit" style="min-width:140px;">Complete request</a></p> </div> </div> <div class="_oab_panel" id="_oab_metadata" style="display:none;"> <h2>Sorry we didn\'t find that!</h2> <p id="_oab_doi_not_in_crossref" style="display:none;">The DOI <span id="_oab_bad_doi">you entered</span> does not appear in Crossref</p> <p>Please provide or amend the <span class="_oab_paper">article</span> details.</p> <p><span class="_oab_paper">Article</span> title (required)<br><input class="_oab_form" id="_oab_title" type="text" placeholder="e.g The State of OA: A large-scale analysis of Open Access"></p> <p>Journal title (required)<br><input class="_oab_form" id="_oab_journal" type="text" placeholder="e.g. Nature"></p> <p>Year of publication (required)<br><input class="_oab_form" id="_oab_year" type="text" placeholder="e.g 1992"></p> <p><span class="_oab_paper">Article</span> DOI or URL<br><input class="_oab_form" id="_oab_doi" type="text" placeholder="e.g 10.1126/scitranslmed.3008973"></p> <p><a href="#" class="_oab_find btn-iu _oab_button _oab_loading _oab_continue" id="_oab_continue" style="min-width:140px;">Continue</a></p> <p> <a href="#" class="_oab_restart" id="_oab_try_again"><b>Try again</b></a> <span id="_oab_advanced_ill_form" style="display:none;"></span> </p> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div id="_oab_done_header"> <h2>Thanks! Your request has been received.</h2> <p>And confirmation code and tell we will email soon - OR sorry we could not create an ILL, and refer back to library if possible.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" id="_oab_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' _oab.shareyourpaper_template = ' <div class="_oab_panel" id="_oab_inputs"> <h2>Make your research visible and see 30% more citations</h2> <p><span id="_oab_lib_info">We can help you make your paper Open Access, for free, wherever you publish. It\'s legal and takes just minutes.</span> Join millions of researchers sharing their papers freely with colleagues and the public.</p> <h3>Start by entering the DOI of your paper</h3> <p>We\'ll gather information about your paper and find the easiest way to share it.</p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. 10.1126/scitranslmed.3001922" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" href="#" id="_oab_find" aria-label="Search" style="min-width:140px;">Next</a></p> <p><a id="_oab_nodoi" href="mailto:help@openaccessbutton.org?subject=Help%20depositing%20my%20paper&body=Hi%2C%0D%0A%0D%0AI\'d%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C"><b>My paper doesn\'t have a DOI</b></a></p> </div> <div class="_oab_panel" id="_oab_permissions" style="display:none;"> <div class="_oab_section _oab_oa" id="_oab_oa"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared it.</p> <p><a target="_blank" href="#" class="_oab_oa_url btn-iu _oab_button" style="min-width:140px;">See free version</a></p> <p><a href="#" class="_oab_restart" id="_oab_restart"><b>Do another</b></a></p> </div> <div class="_oab_section _oab_permission_required" id="_oab_permission_required"> <h2>You may share your paper if you ask the journal</h2> <p>Unlike most, <span class="_oab_journal">the journal</span> requires that you ask them before you share your paper freely. Asking only takes a moment as we find out who to contact and have drafted an email for you.</p> <p><a target="_blank" id="_oab_reviewemail" href="#" class="btn-iu _oab_button" style="min-width:140px;">Review Email</a></p> <p><a target="_blank" id="_oab_permissionemail" class="_oab_restart" href="#"><b>I\'ve got permission now!</b></a></p> </div> <div class="_oab_section _oab_oa_deposit" id="_oab_oa_deposit"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared a <a class="_oab_oa_url" id="_oab_goto_oa_url" target="_blank" href="#">freely available copy</a>.</p> <h3 class="_oab_section _oab_get_email">Give us your email to confirm deposit</h3> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable"> <h2>You can freely share your paper now!</h2> <p><span class="_oab_library">The library has</span> checked and <span class="_oab_journal">the journal</span> encourages you to freely share <span class="_oab_your_paper">your paper</span> so colleagues and the public can freely read and cite it. <span class="_oab_refs"></span></p> <div id="_oab_not_pdf"> <h3><span>&#10003;</span> Find the manuscript the journal accepted. It\'s not a PDF from the journal site</h3> <p>This is the only version you\'re able to share legally. The accepted manuscript is the word file or Latex export you sent the publisher after peer-review and before formatting (publisher proofs).</p> <h3><span>&#10003;</span> Check there aren\'t publisher logos or formatting</h3> <p>It\'s normal to share accepted manuscripts as the research is the same. It\'s fine to save your file as a pdf, make small edits to formatting, fix typos, remove comments, and arrange figures.</p> </div> <h3 class="_oab_section _oab_get_email"><span>&#10003;</span> Tell us your email</h3> </div> <div class="_oab_section _oab_dark_deposit" id="_oab_dark_deposit"> <h2>You can share your paper!</h2> <p>We checked and unfortunately <span class="_oab_journal">the journal</span> won\'t let you share <span class="_oab_your_paper">your paper</span> freely with everyone. <span class="_oab_refs"></span><br><br> The good news is the library can still legally make your paper much easier to find and access. We\'ll put the publisher PDF in <span class="_oab_repo">ScholarWorks</span> and then share it on your behalf whenever it is requested.</p> <h3 class="_oab_section _oab_get_email">All we need is your email</h3> </div> <div class="_oab_section _oab_get_email" id="_oab_get_email"> <p><input class="_oab_form" type="text" id="_oab_email" placeholder="" aria-label="Enter your email" style="box-shadow:none;"></input></p> <p class="_oab_section _oab_oa_deposit">We\'ll use this to send you a link. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> <p class="_oab_section _oab_archivable">We\'ll only use this if something goes wrong.<br> <p class="_oab_section _oab_dark_deposit">We\'ll only use this to send you a link to your paper when it is in <span class="_oab_repo">ScholarWorks</span>. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable_file"> <h3>We\'ll check it\'s legal, then promote, and preserve your work</h3> <p><input type="file" name="file" id="_oab_file" class="_oab_form"></p> <p>By depositing you\'re agreeing to the <span class="_oab_terms">terms</span> and to license your work <span class="_oab_licence">CC-BY</span>.</p> </div> <div class="_oab_section _oab_oa_deposit _oab_archivable _oab_dark_deposit" id="_oab_deposits"> <p><a href="#" class="_oab_deposit btn-iu _oab_button _oab_loading" style="min-width:140px;" id="_oab_deposit">Deposit</a></p> </div> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div class="_oab_done" id="_oab_confirm"> <h2>Hmmm, something looks wrong</h2> <p>You\'re nearly done. It looks like what you uploaded is a publisher\'s PDF which your journal prohibits legally sharing.<!-- It can only be shared on a limited basis.--><br><br> We just need the version accepted by the journal to make your work available to everyone.</p> <p><a href="#" class="_oab_reload btn-iu _oab_button" id="_oab_upload_again" style="min-width:140px;">Try uploading again</a></p> <p><a href="#" class="_oab_confirm _oab_loading" id="_oab_upload_accept"><b>My upload was an accepted manuscript</b></a></p> </div> <div class="_oab_done" id="_oab_check"> <h2>We\'ll double check your paper</h2> <p>You\'ve done your part for now. Hopefully, we\'ll send you a link soon. First, we\'ll check in the next working day to make sure it\'s legal to share.</p> </div> <div class="_oab_done" id="_oab_partial"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_zenodo"> <h2>Congrats! Your paper will be available to everyone, forever!</h2> <div id="_oab_zenodo_embargo"></div> <p><input id="_oab_zenodo_url" class="_oab_form" type="text" style="box-shadow:none;" value=""></input></p> <p>You can now put the link on your website, CV, any profiles, and ResearchGate.</p> </div> <div class="_oab_done" id="_oab_redeposit"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_success"> <h2>Hurray, you\'re done!</h2> <p>We\'ll email you a link to your paper in <span class="_oab_repo">ScholarWorks</span> soon. Next time, before you publish check to see if your journal allows you to have the most impact by making your research available to everyone, for free.</p> </div> <div class="_oab_done" id="_oab_review"> <h2>You\'ve done your part</h2> <p>All that\'s left to do is wait. Once the journal gives you permission to share, come back and we\'ll help you finish the job.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' # can pass in a key/value pair, or key can be a config object, in which case val can optionally be a user ID string, # or key can be a user ID string and val must be empty, or key and val can both be empty and config will attempt # to be retrieved from setup, or localstorage and/or from the API if a user ID is available from setup _oab.prototype.configure = (key, val, build, preview) -> if typeof key is 'string' and not val? and key.startsWith '{' try key = JSON.parse key if typeof key is 'string' and not val? and (not this.uid? or this.uid is 'anonymous') this.uid = key key = undefined if ((typeof key is 'string' and val?) or (not key? and not val?)) and JSON.stringify(this.config) is '{}' try if this.local isnt false # can be disabled if desired, by setting local to false at setup or in url param lc = JSON.parse localStorage.getItem '_oab_config_' + this.plugin if typeof lc is 'object' and lc isnt null console.log 'Config retrieved from local storage' this.config = lc if this.remote isnt false and this.uid and this.uid isnt 'anonymous' and JSON.stringify(this.config) is '{}' # should a remote call always be made to check for superseded config if one is not provided at startup? _L.jx this.api + '/' + (if this.plugin is 'instantill' then 'ill' else 'deposit') + '/config?uid='+this.uid, undefined, (res) => console.log 'Config retrieved from API' this.configure res if this.local is false return # stop here, once the retrieve from remote works, the rest will run if typeof key is 'object' this.uid = val if typeof val is 'string' for d of key if not this.config[d]? or (this.config[d] isnt key[d] and val is true) # val true allows overwrite present values build = true if build isnt false this.config[d] = if key[d] is 'true' then true else if key[d] is 'false' then false else key[d] if val is true for cd of this.config delete this.config[cd] if cd isnt 'owner' and not key[cd]? else if key? and val? this.config[key] = if val is 'true' then true else if val is 'false' then false else val # make a "writable" config without unecessary params, such as those setting false etc # keep separate from this.config so that additional calls to configure take account of false if they do exist though this.config.pilot = Date.now() if this.config.pilot is true this.config.live = Date.now() if this.config.live is true for k of wc = JSON.parse JSON.stringify this.config delete wc[k] if not wc[k]? or wc[k] is false or ((typeof wc[k] is 'string' or Array.isArray(wc[k])) and wc[k].length is 0) try localStorage.setItem('_oab_config_' + this.plugin, JSON.stringify wc) if JSON.stringify(wc) isnt '{}' and this.local isnt false if this.css isnt false and this.config.css_off this.css = false build = true if this.bootstrap isnt false and this.config.bootstrap_off this.bootstrap = false build = true this.element ?= '#' + this.plugin _whenready = () => if _L.gebi this.element if build isnt false console.log 'Building embed' #_L.append('body', '<div id="' + this.element + '"></div>') if not _L.gebi this.element _L.html this.element, '' if not this.bootstrap? # hack test for bootstrap calls or classes in page doc dstr = document.documentElement.innerHTML this.bootstrap = dstr.indexOf('bootstrap/') isnt -1 or dstr.indexOf('/bootstrap') isnt -1 or dstr.indexOf('bootstrap.css') isnt -1 or dstr.indexOf('bootstrap.min.css') isnt -1 or dstr.indexOf('btn-') isnt -1 console.log('Found bootstrap indicators in the doc') if this.bootstrap is true if this.bootstrap is true if this.template.indexOf('btn-primary') is -1 this.template = this.template.replace(/_oab_button/g,'_oab_button btn btn-primary').replace(/_oab_form/g,'_oab_form form-control') else if this.template.indexOf('btn-primary') isnt -1 this.template = this.template.replace(/ btn btn-primary/g,'').replace(/ form-control/g,'') if typeof this.css is 'string' and this.css isnt 'false' and this.bootstrap isnt true #this.bootstrap is false this.css = '<div id="_oab_css"><style>' + this.css + '</style></div>' if not this.css.startsWith '<style>' _L.append this.element, this.css _L.append this.element, this.template _L.each '._oab_paper', (el) => cs = el.innerHTML if this.config.say_paper if cs.indexOf('aper') is -1 el.innerHTML = (if cs is 'an article' then 'a paper' else if cs is 'article' then 'paper' else 'Paper') else if cs.indexOf('aper') isnt -1 el.innerHTML = (if cs is 'a paper' then 'an article' else if cs is 'paper' then 'article' else 'Article') if this.config.pilot pilot = '<p><br>Notice a change? We\'re testing a simpler and faster way to ' + (if this.plugin is 'instantill' then 'get' else 'deposit') + ' your ' + (if this.config.say_paper then 'paper' else 'article') + (if this.plugin is 'instantill' then '' else 's') + '. You can ' pilot += '<a href="mailto:' + this.cml() + '">give feedback</a> or ' if this.plugin is 'instantill' pilot += '<a class="_oab_ping" message="instantill_use_the_old_form" target="_blank" href="' + (if this.config.advanced_ill_form then this.config.advanced_ill_form else if this.config.ill_form then this.config.ill_form else 'mailto:'+this.cml()) + '">use the old form</a>.</p>' else pilot += '<a class="_oab_ping" message="shareyourpaper_use_the_old_form" target="_blank" href="' + (if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml()) + '">use the old way</a>.</p>' _L.html '#_oab_pilot', pilot else _L.html '#_oab_pilot', '' # shareyourpaper exclusive configs if this.plugin is 'shareyourpaper' if this.cml()? and el = _L.gebi '_oab_nodoi' el.setAttribute 'href', el.getAttribute('href').replace('help@openaccessbutton.org', this.cml()) if this.config.not_library _L.html '._oab_library', 'We have' else _L.html '#_oab_lib_info', 'Share your paper with help from the library in ' + (this.config.repo_name ? 'ScholarWorks') + '. Legally, for free, in minutes. ' else if this.plugin is 'instantill' if this.config.book or this.config.other boro = '<p>Need ' boro += 'a <a href="' + this.config.book + '">book chapter</a>' if this.config.book boro += (if this.config.book then ' or ' else ' ') + '<a href="' + this.config.other + '">something else</a>' if this.config.other _L.html '#_oab_book_or_other', boro + '?</p>' else _L.html '#_oab_book_or_other', '' if this.config.intro_off _L.hide '#_oab_intro' if this.config.advanced_ill_form or this.config.account or this.config.ill_info aai = '<p>Or ' if this.config.advanced_ill_form _L.show '#_oab_advanced_ill_form', ' or <a href="' + this.config.advanced_ill_form + '">use full request form</a>' aai += '<a href="' + this.config.advanced_ill_form + '">use full request form</a>' if this.config.account and this.config.ill_info aai += ', ' else if this.config.account or this.config.ill_info aai += ' and ' if this.config.account aai += '<a href="' + this.config.account + '">view account</a>' aai += ' and ' if this.config.ill_info aai += '<a href="' + this.config.ill_info + '">learn about Interlibrary Loan</a>' if this.config.ill_info _L.html '#_oab_advanced_account_info', aai + '</p>' else _L.html '#_oab_advanced_account_info', '' _L.hide '#_oab_advanced_ill_form' # would be better to make _L handle the bind so that this.find works rather than having to wrap it in a function that passes context _L.listen 'enter', '#_oab_input', (e) => this.find(e) _L.listen 'enter', '#_oab_email', (e) => this.validate(e) _L.listen 'click', '._oab_find', (e) => this.find(e) _L.listen 'click', '._oab_submit', (e) => this.submit(e) _L.listen 'click', '._oab_restart', (e) => this.restart(e) _L.listen 'click', '._oab_ping', (e) => this.ping(_L.get e.target, 'message') _L.listen 'click', '._oab_wrong', (e) => e.preventDefault() this.ping '_wrong_article' this.metadata() _L.listen 'click', '._oab_reload', (e) => e.preventDefault() gf.value = '' if gf = _L.gebi "_oab_file" this.file = false this.permissions() _L.listen 'click', '._oab_confirm', (e) => e.preventDefault(); this.data.confirmed = true; this.deposit() _L.listen 'click','#_oab_reviewemail', (e) => this.done 'review' _L.listen 'click','._oab_deposit', (e) => this.deposit(e) if el = _L.gebi '_oab_config' ncwc = JSON.parse JSON.stringify wc nk = ill_institution: 'institution' # translate instantill old config keys ill_redirect_base_url: 'ill_form' ill_redirect_params: 'ill_added_params' deposit_terms: 'terms' problem_email: 'problem' viewaccount: 'account' autorun: 'autorun_off' intropara: 'intro_off' norequests: 'requests_off' illinfo: 'ill_info' noillifoa: 'ill_if_oa_off' noillifsub: 'ill_if_sub_off' saypaper: 'say_paper' advancedform: 'advanced_ill_form' deposit_date: 'depositdate' # and shareyourpaper keys deposit_terms: 'terms' allow_oa_deposit: 'oa_deposit_off' ROR_ID: 'ror' not_a_library: 'not_library' adminemail: 'email' css: 'css_off' bootstrap: 'bootstrap_off' for k of nk if ncwc[k]? ncwc[nk[k]] = ncwc[k] delete ncwc[k] el.innerHTML = JSON.stringify ncwc if window.location.search.indexOf('panel=') isnt -1 this.panel window.location.search.split('panel=')[1].split('&')[0].split('#')[0], (if window.location.search.indexOf('section=') isnt -1 then window.location.search.split('section=')[1].split('&')[0].split('#')[0] else undefined) if preview preview = this.config.val if typeof preview isnt 'string' or (typeof this.config.val is 'string' and this.config.val.length) this.data = {} this.f = {} this.loading false gf.value = '' if gf = _L.gebi "_oab_file" this.file = false _L.hide '._oab_panel' _L.show '#_oab_inputs' _L.set '#_oab_input', preview setTimeout (() => this.find()), 1 this.loaded() if typeof this.loaded is 'function' else console.log 'waiting for ' + this.element setTimeout (() => _whenready()), 100 _whenready() return wc @shareyourpaper = (opts) -> opts ?= {}; opts.plugin = 'shareyourpaper'; return new _oab(opts); @instantill = (opts) -> opts ?= {}; opts.plugin = 'instantill'; return new _oab(opts);
11432
# start with a simple set of helper functions @_L = api: 'https://api.lvatn.com' _L.gebi = (id) -> return document.getElementById id.replace('#','') _L.gebc = (cls) -> return document.getElementsByClassName cls.replace('.','') _L.gebn = (n) -> r = document.getElementsByTagName n.replace('<','').replace('>','') # e.g. by the element name, like "div" return if r? then r else document.getElementsByName n # otherwise by the "name" attribute matching n _L.each = (elems, key, val) -> if typeof elems is 'string' if elems.startsWith '#' elems = [_L.gebi elems] else if elems.startsWith '.' elems = _L.gebc elems else elems = _L.gebn elems else if typeof elems is 'object' elems = [elems] if not Array.isArray elems if elems? for elem in elems if elem? if typeof key is 'function' then key(elem) else _L.set elem, key, val _L.listen = (action, els, fn) -> _L.each els, (el) -> if action is 'enter' action = 'keyup' wfn = (e) -> fn(e) if e.keyCode is 13 else wfn = fn if not _L.has el, 'listen_'+action _L.class el, 'listen_'+action el.addEventListener action, (e) -> wfn(e) _L.show = (els, html, append) -> _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html was = _L.get el, '_l_display' was = (if el.tagName is 'DIV' then 'block' else 'inline') if typeof was isnt 'string' or was is 'none' # TODO should be inline in which cases... el.style.display = was _L.hide = (els) -> _L.each els, (el) -> if el.style.display isnt 'none' _L.set el, '_l_display', el.style.display el.style.display = 'none' _L.get = (els, attr) -> res = undefined _L.each els, (el) -> if not attr? try res = el.value res = undefined if typeof res is 'string' and not res.length try res ?= el.getAttribute attr return res _L.set = (els, attr, val) -> _L.each els, (el) -> # TODO handle dot notation keys e.g if attr is style.display if not val? or attr is 'value' or attr is 'val' try el.value = if not val? then attr else val else try el.setAttribute attr, val _L.checked = (els) -> res = true _L.each els, (el) -> res = el.checked return res _L.html = (els, html, append, show) -> rs = [] _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html rs.push el.innerHTML _L.show(el) if show return if rs.length is 1 then (rs[0] ? '') else if rs.length then rs else '' _L.append = (els, html) -> _L.html els, html, true _L.remove = (els) -> _L.each els, (el) -> el.parentNode.removeChild el _L.class = (el, cls) -> rs = [] classes = el.getAttribute 'class' classes ?= '' if typeof cls is 'string' if classes.indexOf(cls) is -1 classes += ' ' if classes.length classes += cls else classes = classes.replace(cls,'').trim().replace(/ /g,' ') el.setAttribute 'class', classes for c in classes.split ' ' rs.push(c) if c not in rs return rs _L.classes = (els) -> return _L.class els _L.has = (el, cls) -> classes = _L.classes el cls = cls.replace('.') if cls.startsWith '.' if cls in classes return true else return if el.getAttribute(cls) then true else false _L.css = (els, key, val) -> _L.each els, (el) -> s = _L.get(el, 'style') ? '' style = {} for p in s.split ';' ps = p.split ':' style[ps[0].trim()] = ps[1].trim() if ps.length is 2 style[key] = val if val? ss = '' for k of style ss += ';' if ss isnt '' ss += k + ':' + style[k] _L.set el, 'style', ss _L.jx = (route, q, success, error, api, method, data, headers) -> # add auth options to this api ?= _L.api if route.startsWith 'http' url = route else url = api + if api.endsWith('/') then '' else '/' url += (if route.startsWith('/') then route.replace('/','') else route) if route if typeof q is 'string' url += (if url.indexOf('?') is -1 then '?' else '&') + (if q.indexOf('=') is -1 then 'q=' else '') + q else if typeof q is 'object' url += '?' if url.indexOf('?') is -1 url += p + '=' + q[p] + '&' for p of q xhr = new XMLHttpRequest() xhr.open (method ? 'GET'), url xhr.setRequestHeader(h, headers[h]) for h of headers ? {} xhr.send data xhr.onload = () -> if xhr.status isnt 200 try error xhr else try success JSON.parse(xhr.response), xhr catch err console.log err try success xhr catch try error xhr _L.loaded(xhr) if typeof _L.loaded is 'function' xhr.onerror = (err) -> try error(err) _L.post = (route, data, success, error, api, headers) -> headers ?= {} if typeof data is 'object' if typeof data.append isnt 'function' # a FormData object will have an append function, a normal json object will not. FormData should be POSTable by xhr as-is data = JSON.stringify data # disabled sending the correct header to avoid waiting for an OPTIONS check #headers['Content-type'] ?= 'application/json' #route += (if route.indexOf('?') is -1 then '?' else '&') + '_=' + Date.now() # set a random header to try to break any possible caching _L.jx route, undefined, success, error, api, 'POST', data, headers # ============================================================================== _oab = (opts) -> try opts ?= {} # can pass demo true here as well, to control demo output, stopping submit from POSTing this[o] = opts[o] for o of opts this.uid ?= 'anonymous' this.api ?= if window.location.host.indexOf('dev.openaccessbutton.org') isnt -1 then 'https://dev.api.cottagelabs.com/service/oab' else 'https://api.openaccessbutton.org' this.plugin ?= 'instantill' # has to be defined at startup, as either instantill or shareyourpaper this.element ?= '#' + this.plugin this.pushstate ?= true # if true, the embed will try to add page state changes to the browser state manager this.local ?= true # local storage of config turned off by default for now this.config ?= {} this.data ?= {} # the data obj to send to backend this.f ?= {} # the result of the find/ill/permission request to the backend this.template ?= _oab[this.plugin + '_template'] # template or css can be passed in or are as defined below this.css ?= _oab.css this._loading = false # tracks when loads are occurring this.submit_after_metadata = false # used by instantill to track if metadata has been provided by user this.file = false # used by syp to store the file for sending to backend this.demo ?= window.location.href.indexOf('/demo') isnt -1 and (window.location.href.indexOf('openaccessbutton.') isnt -1 or window.location.href.indexOf('shareyourpaper.') isnt -1 or window.location.href.indexOf('instantill.') isnt -1) _L.loaded = this.loaded if this.loaded? # if this is set to a function, it will be passed to _leviathan loaded, which gets run after every ajax call completes. It is also called directly after every configure if window.location.search.indexOf('clear=') isnt -1 localStorage.removeItem '_oab_config_' + this.plugin if window.location.search.indexOf('local=') isnt -1 this.local = if window.location.search.indexOf('local=true') isnt -1 then true else false if window.location.search.indexOf('config=') isnt -1 try this.config = JSON.parse window.location.search.split('config=')[1].split('&')[0].split('#')[0] if window.location.search.indexOf('config.') isnt -1 configs = window.location.search.split 'config.' configs.shift() for c in configs cs = c.split '=' if cs.length is 2 csk = cs[0].trim() csv = cs[1].split('&')[0].split('#')[0].trim() this.configure csk, csv, false setTimeout (() => this.configure()), 1 if not this.config.autorun_off ap = if typeof this.config.autorunparams is 'string' then this.config.autorunparams.split(',') else if typeof this.config.autorunparams is 'object' then this.config.autorunparams else ['doi','title','url','atitle','rft_id','journal','issn','year','author'] ap = ap.replace(/"/g,'').replace(/'/g,'').split(',') if typeof ap is 'string' for o in ap o = o.split('=')[0].trim() eq = o.split('=')[1].trim() if o.indexOf('=') isnt -1 this.data[eq ? o] = decodeURIComponent(window.location.search.replace('?','&').split('&'+o+'=')[1].split('&')[0].replace(/\+/g,' ')) if (window.location.search.replace('?','&').indexOf('&'+o+'=') isnt -1) if not this.data.doi and window.location.href.split('?')[0].indexOf('/10.') isnt -1 and window.location.href.split('?')[0].split('/10.')[1].indexOf('/') > 1 and window.location.href.split('?')[0].split('/10.')[1].trim().split('/').length > 1 this.data.doi = '10.' + window.location.href.split('?')[0].split('/10.')[1].replace(/\/$/,'') if window.location.search.indexOf('email=') isnt -1 this.data.email = window.location.search.split('email=')[1].split('&')[0].split('#')[0] _L.remove '#_oab_collect_email' if window.location.search.indexOf('confirmed=') isnt -1 this.data.confirmed = window.location.search.split('confirmed=')[1].split('&')[0].split('#')[0] this.find() if this.data.doi or (this.plugin is 'instantill' and (this.data.title or this.data.url)) window.addEventListener "popstate", (pe) => this.state(pe) return this catch this.ping 'instantill_or_shareyourpaper_try_initialise_catch' _oab.prototype.cml = () -> return this.config.problem ? this.config.owner ? this.config.email ? '' _oab.prototype.contact = () -> return 'Please try ' + (if this.cml() then '<a id="_oab_contact_library" href="mailto:' + this.cml() + '">contacting your library</a>' else 'contacting your library') + ' directly' _oab.prototype.loading = (load) -> _L.hide '#_oab_error' if load isnt true and (this._loading or load is false) try clearInterval this._loading this._loading = false _L.each '._oab_loading', (el) => if _L.has el, '_oab_continue' el.innerHTML = 'Continue' else if _L.has el, '_oab_submit' el.innerHTML = 'Complete request' else if _L.has el, '_oab_deposit' el.innerHTML = 'Deposit' else if _L.has el, '_oab_find' el.innerHTML = 'Next' else if _L.has el, '_oab_confirm' el.innerHTML = '<b>My upload was an accepted manuscript</b>' else el.innerHTML = 'Find ' + if this.config.say_paper then 'paper' else 'article' # this would only happen on instantill, as "Next" above is the default for syp else _L.html '._oab_find', 'Searching .' _L.html '._oab_submit', 'Submitting .' _L.html '._oab_deposit', 'Depositing .' _L.html '._oab_confirm', 'Depositing .' this._loading = setInterval (() -> for button in _L.gebc '._oab_loading' dots = button.innerHTML.split '.' if dots.length >= 4 button.innerHTML = dots[0] else button.innerHTML = button.innerHTML + ' .' ), 700 _oab.prototype.state = (pop) -> if this.pushstate try u = window.location.pathname if not pop? if window.location.href.indexOf('shareyourpaper.org') isnt -1 and this.data.doi? u = window.location.href.split('10.')[0] + this.data.doi + window.location.search + window.location.hash else if window.location.href.indexOf('/setup') is -1 and window.location.href.indexOf('/demo') is -1 if this.data.doi? or this.data.title? or this.data.url? k = if this.data.doi then 'doi' else if this.data.title then 'title' else 'url' u += window.location.search.split('?' + k + '=')[0].split('&' + k + '=')[0] u += if u.indexOf('?') is -1 then '?' else '&' u += k + '=' + this.data[k] + window.location.hash window.history.pushState "", (if pop? then "search" else "find"), u if pop? # what to do with the pop event? for now just triggers a restart if user # tries to go back, unless called with a boolean from the restart event this.restart() if typeof pop isnt 'boolean' _oab.prototype.restart = (e, val) -> try e.preventDefault() if e.target.parentElement.id isnt '_oab_permissionemail' this.data = {} this.f = {} this.loading false this.file = false gf.value = '' if gf = _L.gebi "_oab_file" _L.hide '._oab_panel' _L.show '#_oab_inputs' this.configure() this.state true if val _L.set '#_oab_input', val this.find() else _L.set '#_oab_input', '' _oab.prototype.ping = (what) -> try if what.indexOf(this.plugin) is -1 what = '_' + what if not what.startsWith '_' what = this.plugin + what url = if this.api.indexOf('dev.') isnt -1 then 'https://dev.api.cottagelabs.com' else 'https://api.cottagelabs.com' url += '/ping.png?service=openaccessbutton&action=' + what + '&from=' + this.uid + '&url=' + encodeURIComponent window.location.href url += '&pilot=' + this.config.pilot if this.config.pilot url += '&live=' + this.config.live if this.config.live _L.jx url _oab.prototype.panel = (panel, section) -> if he = _L.gebi '_oab_' + (if panel.startsWith('_oab_') then panel.replace('_oab_','') else panel) _L.hide '._oab_panel' _L.show he this.section(section) if section _oab.prototype.section = (section) -> # useful for demo/test, just shows a specific section within a panel fe = _L.gebi '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) fe = _L.gebc '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) if not fe? if fe _L.hide '._oab_section' _L.show fe _oab.prototype.submit = (e) -> # only used by instantill try try e.preventDefault() if not this.openurl() and not this.data.email and _L.gebi '#_oab_email' this.validate() else if JSON.stringify(this.f) is '{}' or (not this.f.metadata?.title or not this.f.metadata?.journal or not this.f.metadata?.year) if this.submit_after_metadata this.done false else this.submit_after_metadata = true this.metadata() else this.loading() data = {match: this.f.input, email:this.data.email, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} for k in ['title','journal','year','doi'] data.metadata[k] = this.data[k] if not data.metadata[k] and this.data[k] if data.metadata.doi and data.metadata.doi.indexOf('http') is 0 data.metadata.url = data.metadata.doi delete data.metadata.doi nfield = if this.config.notes then this.config.notes else 'notes' data[nfield] = 'The user provided some metadata. ' if this.data.usermetadata data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f?.ill?.subscription or this.f?.url if typeof data[nfield] isnt 'string' then data[nfield] = '' else data[nfield] += ' ' if this.f.ill?.subscription data[nfield] += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.metadata? data[nfield] += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' ou = this.openurl() if ou and not data.email data.forwarded = true if this.demo is true console.log 'Not POSTing ILL and not forwarding to ' + ou + ' for demo purposes' console.log data else _L.post( this.api+'/ill' data (res) => this.done res () => this.done false ) catch this.ping 'instantill_try_submit_catch' _oab.prototype.validate = () -> if this.config.terms and not _L.checked '#_oab_read_terms' # instantill terms _L.show '#_oab_error', '<p>Please agree to the terms first.</p>' else email = (_L.get('#_oab_email') ? '').trim() if not email.length _L.show '#_oab_error', '<p>Please provide your university email address.</p>' _L.css '#_oab_email', 'border-color', '#f04717' _L.gebi('#_oab_email').focus() else this.loading() _L.post( this.api + '/validate?uid=' + this.uid + '&email=' + email this.config (res) => this.loading false if res is true this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() else if res is 'baddomain' _L.show '#_oab_error', '<p>Please try again with your university email address.</p>' else _L.show '#_oab_error', '<p>Sorry, your email does not look right. ' + (if res isnt false then 'Did you mean ' + res + '? ' else '') + 'Please check and try again.</p>' () => this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() ) _oab.prototype.metadata = (submitafter) -> # only used by instantill for m in ['title','year','journal','doi'] if this.f?.metadata?[m]? or this.data[m]? _L.set '#_oab_'+m, (this.f.metadata ? this.data)[m].split('(')[0].trim() #if this.f?.doi_not_in_crossref # _L.html '#_oab_bad_doi', this.f.doi_not_in_crossref # _L.show '#_oab_doi_not_in_crossref' _L.hide '._oab_panel' _L.show '#_oab_metadata' _oab.prototype.openurl = () -> # only used by instantill if this.f.ill?.openurl try nf = this.config.notes ? 'notes' if this.f.ill.openurl.indexOf(nf+'=') is -1 notes = if this.data?.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? this.f.ill.openurl += '&' if not this.f.ill.openurl.endsWith '&' this.f.ill.openurl += nf + '=' + notes return this.f.ill.openurl else if not this.config.ill_form return '' else config = JSON.parse JSON.stringify this.config defaults = sid: 'sid' title: 'atitle' # this is what iupui needs (title is also acceptable, but would clash with using title for journal title, which we set below, as iupui do that doi: 'rft_id' # don't know yet what this should be author: 'aulast' # author should actually be au, but aulast works even if contains the whole author, using aufirst just concatenates journal: 'title' # this is what iupui needs page: 'pages' # iupui uses the spage and epage for start and end pages, but pages is allowed in openurl, check if this will work for iupui published: 'date' # this is what iupui needs, but in format 1991-07-01 - date format may be a problem year: 'rft.year' # this is what IUPUI uses for d of defaults config[d] = defaults[d] if not config[d] url = config.ill_form url += if url.indexOf('?') is -1 then '?' else '&' url += config.ill_added_params.replace('?','') + '&' if config.ill_added_params url += config.sid + '=InstantILL&' for k of this.f.metadata ? {} v = false if k is 'author' if typeof this.f.metadata.author is 'string' v = this.f.metadata.author else if Array.isArray this.f.metadata.author v = '' for author in this.f.metadata.author try v += ', ' if v.length v += if typeof author is 'string' then author else if typeof author is 'object' and author.family then (author.family + if author.given then ', ' + author.given else '') else JSON.stringify author else if k in ['doi','pmid','pmc','pmcid','url','journal','title','year','issn','volume','issue','page','crossref_type','publisher','published','notes'] v = this.f.metadata[k] url += (config[k] ? k) + '=' + encodeURIComponent(v) + '&' if v notes = if this.data.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? url += '&' + (this.config.notes ? 'notes') + '=' + notes if notes return url.replace '/&&/g', '&' _oab.prototype.done = (res, msg) -> this.loading false if ou = this.openurl() window.location = ou else _L.hide '._oab_panel' _L.hide '._oab_done' if typeof res is 'string' and _L.gebi '_oab_' + res _L.show '#_oab_' + res # various done states for shareyourpaper if res is 'confirm' _L.hide '#_oab_done_restart' else _L.show '#_oab_done_restart' else if res _L.html '#_oab_done_header', '<h3>Thanks! Your request has been received</h3><p>Your confirmation code is: ' + res + ', this will not be emailed to you. The ' + (if this.config.say_paper then 'paper' else 'article') + ' will be sent to ' + this.data.email + ' as soon as possible.</p>' else # only instantill falls through to here _L.html '#_oab_done_header', '<h3>Sorry, we were not able to create an Interlibrary Loan request for you.</h3><p>' + this.contact() + '</p>' _L.html '#_oab_done_restart', 'Try again' this.ping msg ? 'instantill_couldnt_submit_ill' setTimeout (() => this.restart()), 6000 _L.show '#_oab_done' this.after() if typeof this.after is 'function' _oab.prototype.deposit = (e) -> # only used by shareyourpaper try try e.preventDefault() if not this.data.email and _L.gebi '#_oab_email' this.validate() else if this.demo is true and this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 if this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 and this.data.doi isnt '10.1234/oab-syp-confirm' # demo successful deposit info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info _L.set '#_oab_zenodo_url', 'https://zenodo.org/record/3703317' this.done 'zenodo' else # demo something wrong, please confirm this.done 'confirm' this.loaded() if typeof this.loaded is 'function' else fl = _L.gebi '#_oab_file' if fl? and fl.files? and fl.files.length this.file = new FormData() this.file.append 'file', fl.files[0] else if this.file isnt true # can be set to true when dark deposit is being followed - no file required. Or a demo may set it to true _L.show '#_oab_error', '<p>Whoops, you need to give us a file! Check it\'s uploaded.</p>' _L.css '#_oab_file', 'border-color','#f04717' return this.loading() # this could be just an email for a dark deposit, or a file for actual deposit # if the file is acceptable and can go in zenodo then we don't bother getting the email address data = {from: this.uid, plugin: this.plugin, embedded:window.location.href, metadata: this.f?.metadata } data.demo = true if this.demo is true data.config = this.config data.email = this.data.email if this.data.email data.confirmed = this.data.confirmed if this.data.confirmed data.redeposit = this.f.url if typeof this.f?.url is 'string' data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if typeof this.file isnt 'boolean' for d of data if d is 'metadata' for md of data[d] this.file.append(md,data[d][md]) if (typeof data[d][md] is 'string' or typeof data[d][md] is 'number') else this.file.append d,data[d] data = this.file _L.post( this.api+'/deposit', # + (this.f.catalogue ? '') data (res) => this.loading false if typeof this.file isnt 'boolean' if res.zenodo?.already or (this.data.confirmed and not res.zenodo?.url) #or not this.f?.permissions?.file?.archivable this.done 'check' else if res.error # if we should be able to deposit but can't, we stick to the positive response and the file will be manually checked this.done 'partial' else if res.zenodo?.url # deposit was possible, show the user a congrats page with a link to the item in zenodo _L.set '#_oab_zenodo_url', res.zenodo.url if res.embargo info = '<p>You\'ve done your part for now. Unfortunately, ' + (this.f?.metadata?.journal_short ? this.f?.metadata?.journal ? 'the journal') + ' won\'t let us make it public until ' info += if res.embargo_UI then res.embargo_UI else res.embargo info += '. After release, you\'ll find your paper on ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science.</p>' info += '<h3>Your paper will be freely available at this link:</h3>' else info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info this.done 'zenodo' else # if the file given is not a version that is allowed, show a page saying something looks wrong # also the backend should create a dark deposit in this case, but delay it by six hours, and cancel if received in the meantime this.done 'confirm' else if res.type is 'redeposit' this.done 'redeposit' else this.done 'success' () => this.loading false _L.show '#_oab_error', '<p>Sorry, we were not able to deposit this paper for you. ' + this.contact() + '</p><p><a href="#" class="_oab_restart" id="_oab_sorry_try_again"><b>Try again</b></a></p>' this.ping('shareyourpaper_couldnt_submit_deposit') ) catch this.ping 'shareyourpaper_try_deposit_catch' _oab.prototype.permissions = (data) -> # only used by shareyourpaper try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.permissions()), 100 else this.loading false if this.f?.doi_not_in_crossref this.f = {} _L.show '#_oab_error', '<p>Double check your DOI, that doesn\'t look right to us.</p>' _L.gebi('_oab_input').focus() else if this.f?.metadata?.crossref_type? and this.f.metadata.crossref_type not in ['journal-article', 'proceedings-article'] _L.gebi('_oab_input').focus() nj = '<p>Sorry, right now this only works with academic journal articles.' if this.cml() nj += ' To get help with depositing, <a href="' nj += if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml() nj += "?subject=Help%20depositing%20&body=Hi%2C%0D%0A%0D%0AI'd%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C" + '">click here</a>' _L.show '#_oab_error', nj + '.</p>' else if not this.f?.metadata?.title? _L.show '#_oab_error', '<h3>Unknown paper</h3><p>Sorry, we cannot find this paper or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' else _L.hide '._oab_panel' _L.hide '._oab_section' _L.show '#_oab_permissions' this.loading false tcs = 'terms <a id="_oab_terms" href="https://openaccessbutton.org/terms" target="_blank">[1]</a>' tcs += ' <a id="_oab_config_terms" href="' + this.config.terms + '" target="_blank">[2]</a>' if this.config.terms ph = '<EMAIL>'; if this.config.email_domains? and this.config.email_domains.length this.config.email_domains = this.config.email_domains.split(',') if typeof this.config.email_domains is 'string' ph = this.config.email_domains[0] ph = ph.split('@')[1] if ph.indexOf('@') isnt -1 ph = ph.split('//')[1] if ph.indexOf('//') isnt -1 ph = ph.toLowerCase().replace('www.','') ph = '<EMAIL>' if not ph? or ph.length < 3 ph = '<EMAIL>@' + ph if ph.indexOf('@') is -1 if this.data.email _L.hide '._oab_get_email' else _L.show '._oab_get_email' _L.set '#_oab_email', 'placeholder', ph _L.html '._oab_terms', tcs refs = '' for p of this.f?.permissions?.permissions?.policy_full_text ? [] refs += ' <a id="_oab_policy_text" target="_blank" href="' + this.f.permissions.permissions.policy_full_text[p] + '">[' + (parseInt(p)+1) + ']</a>' _L.html '._oab_refs', refs paper = if this.f?.metadata?.doi then '<a id="_oab_your_paper" target="_blank" href="https://doi.org/' + this.f.metadata.doi + '"><u>your paper</u></a>' else 'your paper' _L.html '._oab_your_paper', (if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' then 'the publisher pdf of ' else '') + paper _L.html '._oab_journal', this.f?.metadata?.journal_short ? 'the journal' # set config by this.config.repo_name put name in ._oab_repo if this.f.url # it is already OA, depending on settings can deposit another copy _L.set '._oab_oa_url', 'href', this.f.url if this.config.oa_deposit_off _L.hide '._oab_get_email' _L.show '._oab_oa' else this.file = true # no file required for oa deposit... _L.show '._oab_oa_deposit' else if this.f?.permissions?.permissions?.archiving_allowed # can be shared, depending on permissions info _L.hide('#_oab_not_pdf') if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' if typeof this.f?.permissions?.permissions?.licence_required is 'string' and this.f.permissions.permissions.licence_required.indexOf('other-') is 0 _L.html '._oab_licence', 'under the publisher terms' + refs else _L.html '._oab_licence', this.f?.permissions?.permissions?.licence_required ? 'CC-BY' _L.show '._oab_archivable' else if this.config.dark_deposit_off # permission must be requested first rm = 'mailto:' + (this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact ? this.config.deposit_help ? this.cml()) + '?' rm += 'cc=' + (this.config.deposit_help ? this.cml()) + '&' if this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact rm += 'subject=Request%20to%20self%20archive%20' + (this.f.metadata?.doi ? '') + '&body='; rm += encodeURIComponent 'To whom it may concern,\n\n' rm += encodeURIComponent 'I am writing to request permission to deposit the full text of my paper "' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" ' rm += encodeURIComponent 'published in "' + this.f.metadata.journal + '"' if this.f.metadata?.journal rm += encodeURIComponent '\n\nI would like to archive the final pdf. If that is not possible, I would like to archive the accepted manuscript. Ideally, I would like to do so immediately but will respect a reasonable embargo if requested.\n\n' if this.config.repo_name rm += encodeURIComponent 'I plan to deposit it into "' + this.config.repo_name + '", a not-for-profit, digital, publicly accessible repository for scholarly work created for researchers ' + (if this.config.institution_name then 'at ' + this.config.institution_name else '') + '. It helps make research available to a wider audience, get citations for the original article, and assure its long-term preservation. The deposit will include a complete citation of the published version, and a link to it.\n\n' rm += encodeURIComponent 'Thank you for your attention and I look forward to hearing from you.' _L.set '#_oab_reviewemail', 'href', rm # or to confirm permission has been received pm = 'mailto:' + (this.config.deposit_help ? this.cml()) + '?subject=Permission%20Given%20to%20Deposit%20' + (this.f.metadata?.doi ? '') + '&body=' pm += encodeURIComponent 'To whom it may concern,\n\nAttached is written confirmation of permission I\'ve been given to deposit, and the permitted version of my paper: ' pm += encodeURIComponent '"' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" \n\nCan you please deposit it into the repository on my behalf? \n\nSincerely, ' _L.set '#_oab_permissionemail', 'href', pm _L.hide '._oab_get_email' _L.show '._oab_permission_required' else # can't be directly shared but can be passed to library for dark deposit this.file = true _L.hide '#_oab_file' _L.show '._oab_dark_deposit' catch this.ping 'shareyourpaper_try_permissions_catch' _oab.prototype.findings = (data) -> # only used by instantill try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.findings()), 100 else if ct = this.f.metadata?.crossref_type if ct not in ['journal-article','proceedings-article','posted-content'] if ct in ['book-section','book-part','book-chapter'] err = '<p>Please make your request through our ' + (if this.config.book then '<a id="_oab_book_form" href="' + this.config.book + '">book form</a>' else 'book form') else err = '<p>We can only process academic journal articles, please use another form.' _L.show '#_oab_error', err + '</p>' return _L.hide '._oab_panel' _L.hide '._oab_section' this.loading false if this.config.resolver # new setting to act as a link resolver, try to pass through immediately if sub url, OA url, or lib openurl are available # TODO confirm if this should send an ILL to the backend first, as a record, or maybe just a pinger # also check if could forward the user to the new page before the send to backend succeeds / errors data = {match: this.f.input, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f.ill?.subscription?.url data.resolved = 'subscription' else if this.f.url data.resolved = 'open' else if ou = this.openurl() data.resolved = 'library' if data.resolved? data.url = this.f.ill?.subscription?.url ? this.f.url ? ou _L.post(this.api+'/ill', data, (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou), (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou)) _L.show '#_oab_findings' if this.f.ill?.error _L.show '#_oab_error', '<p>Please note, we encountered errors querying the following subscription services: ' + this.f.ill.error.join(', ') + '</p>' if this.f.metadata?.title? citation = '<h2>' + this.f.metadata.title + '</h2>' if this.f.metadata.year or this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue citation += '<p><i>' citation += (this.f.metadata.year ? '') + (if this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue then ', ' else '') if this.f.metadata.year if this.f.metadata.journal citation += this.f.metadata.journal else citation += 'vol. ' + this.f.metadata.volume if this.f.metadata.volume citation += (if this.f.metadata.volume then ', ' else '') + 'issue ' + this.f.metadata.issue if this.f.metadata.issue citation += '</i></p>' _L.html '#_oab_citation', citation hassub = false hasoa = false if this.f.ill?.subscription?.journal or this.f.ill?.subscription?.url hassub = true # if sub url show the url link, else show the "should be able to access on pub site _L.set('#_oab_sub_url', 'href', this.f.ill.subscription.url) if this.f.ill.subscription.url? _L.show '#_oab_sub_available' else if this.f.url hasoa = true _L.set '#_oab_url', 'href', this.f.url _L.show '#_oab_oa_available' if this.f.ill? and not ((this.config.ill_if_sub_off and hassub) or (this.config.ill_if_oa_off and hasoa)) _L.html '#_oab_cost_time', '<p>It ' + (if this.config.cost then 'costs ' + this.config.cost else 'is free to you,') + ' and we\'ll usually email the link within ' + (this.config.time ? '24 hours') + '.<br></p>' if not this.data.email if this.openurl() _L.hide '#_oab_collect_email' else if this.config.terms _L.show '#_oab_terms_note' _L.set '#_oab_terms_link', 'href', this.config.terms else _L.hide '#_oab_terms_note' _L.show '#_oab_ask_library' else if this.data.usermetadata _L.html '#_oab_citation', '<h3>Unknown ' + (if this.config.say_paper then 'paper' else 'article') + '</h3><p>Sorry, we can\'t find this ' + (if this.config.say_paper then 'paper' else 'article') + ' or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' setTimeout (() => this.restart()), 6000 else this.metadata() catch this.ping 'instantill_try_findings_catch' _oab.prototype.find = (e) -> try try e.preventDefault() if JSON.stringify(this.f) isnt '{}' for k in ['title','journal','year','doi'] if v = _L.get '#_oab_' + k if this.data[k] isnt v this.data[k] = v this.data.usermetadata = true if this.data.year and this.data.year.length isnt 4 delete this.data.year _L.show '#_oab_error', '<p>Please provide the full year e.g 2019</p>' return if not this.data.title or not this.data.journal or not this.data.year _L.show '#_oab_error', '<p>Please complete all required fields</p>' return if this.submit_after_metadata this.submit() return this.data.title ?= this.data.atitle if this.data.atitle this.data.doi ?= this.data.rft_id if this.data.rft_id if this.data.doi and this.data.doi.indexOf('10.') isnt -1 and (this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('http') is 0) this.data.url = this.data.doi delete this.data.doi if val = _L.get('#_oab_input') val = val.trim().replace(/\.$/,'') if val.length if val.indexOf('doi.org/') isnt -1 this.data.url = val this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('10.') isnt -1 this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('http') is 0 or val.indexOf('www.') isnt -1 this.data.url = val else if val.toLowerCase().replace('pmc','').replace('pmid','').replace(':','').replace(/[0-9]/g,'').length is 0 this.data.id = val else this.data.title = val else if this.data.doi or this.data.title or this.data.url or this.data.id _L.set '#_oab_input', this.data.doi ? this.data.title ? this.data.url ? this.data.id if this.plugin is 'instantill' and not this.data.doi and not this.f?.metadata?.journal and this.data.title and this.data.title.length < 30 and this.data.title.split(' ').length < 3 this.metadata() # need more metadata for short titles else if not this.data.doi and (this.plugin is 'shareyourpaper' or (not this.data.url and not this.data.pmid and not this.data.pmcid and not this.data.title and not this.data.id)) if this.plugin is 'shareyourpaper' delete this.data.title delete this.data.url delete this.data.id _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else _L.show '#_oab_error', '<p><span>&#10060;</span> Sorry please provide the full DOI, title, citation, PMID or PMC ID.</p>' else if this.data.doi and this.plugin is 'shareyourpaper' and (this.data.doi.indexOf('10') isnt 0 or this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('.') is -1 or this.data.doi.length < 8) delete this.data.doi _L.set '#_oab_input', '' _L.gebi('_oab_input').focus() _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else this.state() this.loading() this.data.config = this.config this.data.from ?= this.uid this.data.plugin ?= this.plugin this.data.embedded ?= window.location.href this.data.pilot ?= this.config.pilot if this.config.pilot this.data.live ?= this.config.live if this.config.live if this.demo is true and (this.data.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or this.data.doi is '10.1234/567890' or (this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp') is 0)) data = {metadata: {title: 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL', year: '2019', crossref_type: 'journal-article', doi: this.data.doi ? '10.1234/oab-syp-aam'}} data.metadata.journal = 'Proceedings of the 16th IFLA ILDS conference: Beyond the paywall - Resource sharing in a disruptive ecosystem' data.metadata.author = [{given: '<NAME>', family: '<NAME>'}, {given: '<NAME>', family: '<NAME>'}, {given: '<NAME>', family: '<NAME>'}, {given: '<NAME>', family: '<NAME>'}] data.ill = {subscription: {findings:{}, uid: this.uid, lookups:[], error:[], url: 'https://scholarworks.iupui.edu/bitstream/handle/1805/20422/07-PAXTON.pdf?sequence=1&isAllowed=y'}} data.permissions = { permissions: { archiving_allowed: if this.data.doi is '10.1234/oab-syp-aam' then true else false, version_allowed: if this.data.doi is '10.1234/oab-syp-aam' then "postprint" else undefined }, file: {archivable: true, archivable_reason: "Demo acceptance", version: "postprint", licence: "cc-by", same_paper: true, name: "example.pdf", format: "pdf", checksum: "example-checksum"}} if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) else _L.post( this.api+'/find' this.data (data) => if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) () => _L.show '#_oab_error', '<p>Oh dear, the service is down! We\'re aware, and working to fix the problem. ' + this.contact() + '</p>' ) catch this.ping this.plugin + '_try_find_catch' _oab.css = ' <style> ._oab_form { display: inline-block; width: 100%; height: 34px; padding: 6px 12px; font-size: 1em; line-height: 1.428571429; color: #555555; vertical-align: middle; background-color: #ffffff; background-image: none; border: 1px solid #cccccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; } ._oab_button { display: table-cell; height:34px; padding: 6px 3px; margin-bottom: 0; font-size: 1em; font-weight: normal; line-height: 1.428571429; text-decoration: none; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: #ffffff; background-color: #428bca; border-color: #357ebd; } </style>' _oab.instantill_template = ' <div class="_oab_panel" id="_oab_inputs"> <p id="_oab_intro"> If you need <span class="_oab_paper">an article</span> you can request it from any library in the world through Interlibrary loan. <br>Start by entering a full <span class="_oab_paper">article</span> title, citation, DOI or URL:<br> </p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. World Scientists Warning of a Climate Emergency" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" id="_oab_find" href="#" aria-label="Search" style="min-width:140px;">Find <span class="_oab_paper">article</span></a></p> <div id="_oab_book_or_other"></div> <div id="_oab_advanced_account_info"></div> </div> <div class="_oab_panel" id="_oab_findings" style="display:none;"> <div id="_oab_citation"><h2>A title</h2><p><b>And citation string, OR demo title OR Unknown <span class="_oab_paper">article</span> and refer to library</b></p></div> <p id="_oab_wrong_paper"><a class="_oab_wrong" href="#"><b>This is not the <span class="_oab_paper">article</span> I searched</b></a></p> <div class="_oab_section" id="_oab_sub_available"> <h3>We have an online copy instantly available</h3> <p>You should be able to access it on the publisher\'s website.</p> <p><a target="_blank" id="_oab_sub_url" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_oa_available"> <h3><br>There is a free, instantly accessible copy online</h3> <p>It may not be the final published version and may lack graphs or figures making it unsuitable for citations.</p> <p><a id="_oab_url" target="_blank" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_ask_library"> <h3><br>Ask the library to digitally send you the published full-text via Interlibrary Loan</h3> <div id="_oab_cost_time"><p>It is free to you, and we\'ll usually email the link within 24 hours.<br></p></div> <div id="_oab_collect_email"> <p id="_oab_terms_note"><input type="checkbox" id="_oab_read_terms"> I have read the <a id="_oab_terms_link" target="_blank" href="#">terms and conditions</a></p> <p><input placeholder="Your university email address" id="_oab_email" type="text" class="_oab_form"></p> </div> <p><a class="_oab_submit btn-iu _oab_button _oab_loading" href="#" id="_oab_submit" style="min-width:140px;">Complete request</a></p> </div> </div> <div class="_oab_panel" id="_oab_metadata" style="display:none;"> <h2>Sorry we didn\'t find that!</h2> <p id="_oab_doi_not_in_crossref" style="display:none;">The DOI <span id="_oab_bad_doi">you entered</span> does not appear in Crossref</p> <p>Please provide or amend the <span class="_oab_paper">article</span> details.</p> <p><span class="_oab_paper">Article</span> title (required)<br><input class="_oab_form" id="_oab_title" type="text" placeholder="e.g The State of OA: A large-scale analysis of Open Access"></p> <p>Journal title (required)<br><input class="_oab_form" id="_oab_journal" type="text" placeholder="e.g. Nature"></p> <p>Year of publication (required)<br><input class="_oab_form" id="_oab_year" type="text" placeholder="e.g 1992"></p> <p><span class="_oab_paper">Article</span> DOI or URL<br><input class="_oab_form" id="_oab_doi" type="text" placeholder="e.g 10.1126/scitranslmed.3008973"></p> <p><a href="#" class="_oab_find btn-iu _oab_button _oab_loading _oab_continue" id="_oab_continue" style="min-width:140px;">Continue</a></p> <p> <a href="#" class="_oab_restart" id="_oab_try_again"><b>Try again</b></a> <span id="_oab_advanced_ill_form" style="display:none;"></span> </p> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div id="_oab_done_header"> <h2>Thanks! Your request has been received.</h2> <p>And confirmation code and tell we will email soon - OR sorry we could not create an ILL, and refer back to library if possible.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" id="_oab_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' _oab.shareyourpaper_template = ' <div class="_oab_panel" id="_oab_inputs"> <h2>Make your research visible and see 30% more citations</h2> <p><span id="_oab_lib_info">We can help you make your paper Open Access, for free, wherever you publish. It\'s legal and takes just minutes.</span> Join millions of researchers sharing their papers freely with colleagues and the public.</p> <h3>Start by entering the DOI of your paper</h3> <p>We\'ll gather information about your paper and find the easiest way to share it.</p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. 10.1126/scitranslmed.3001922" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" href="#" id="_oab_find" aria-label="Search" style="min-width:140px;">Next</a></p> <p><a id="_oab_nodoi" href="mailto:<EMAIL>?subject=Help%20depositing%20my%20paper&body=Hi%2C%0D%0A%0D%0AI\'d%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C"><b>My paper doesn\'t have a DOI</b></a></p> </div> <div class="_oab_panel" id="_oab_permissions" style="display:none;"> <div class="_oab_section _oab_oa" id="_oab_oa"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared it.</p> <p><a target="_blank" href="#" class="_oab_oa_url btn-iu _oab_button" style="min-width:140px;">See free version</a></p> <p><a href="#" class="_oab_restart" id="_oab_restart"><b>Do another</b></a></p> </div> <div class="_oab_section _oab_permission_required" id="_oab_permission_required"> <h2>You may share your paper if you ask the journal</h2> <p>Unlike most, <span class="_oab_journal">the journal</span> requires that you ask them before you share your paper freely. Asking only takes a moment as we find out who to contact and have drafted an email for you.</p> <p><a target="_blank" id="_oab_reviewemail" href="#" class="btn-iu _oab_button" style="min-width:140px;">Review Email</a></p> <p><a target="_blank" id="_oab_permissionemail" class="_oab_restart" href="#"><b>I\'ve got permission now!</b></a></p> </div> <div class="_oab_section _oab_oa_deposit" id="_oab_oa_deposit"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared a <a class="_oab_oa_url" id="_oab_goto_oa_url" target="_blank" href="#">freely available copy</a>.</p> <h3 class="_oab_section _oab_get_email">Give us your email to confirm deposit</h3> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable"> <h2>You can freely share your paper now!</h2> <p><span class="_oab_library">The library has</span> checked and <span class="_oab_journal">the journal</span> encourages you to freely share <span class="_oab_your_paper">your paper</span> so colleagues and the public can freely read and cite it. <span class="_oab_refs"></span></p> <div id="_oab_not_pdf"> <h3><span>&#10003;</span> Find the manuscript the journal accepted. It\'s not a PDF from the journal site</h3> <p>This is the only version you\'re able to share legally. The accepted manuscript is the word file or Latex export you sent the publisher after peer-review and before formatting (publisher proofs).</p> <h3><span>&#10003;</span> Check there aren\'t publisher logos or formatting</h3> <p>It\'s normal to share accepted manuscripts as the research is the same. It\'s fine to save your file as a pdf, make small edits to formatting, fix typos, remove comments, and arrange figures.</p> </div> <h3 class="_oab_section _oab_get_email"><span>&#10003;</span> Tell us your email</h3> </div> <div class="_oab_section _oab_dark_deposit" id="_oab_dark_deposit"> <h2>You can share your paper!</h2> <p>We checked and unfortunately <span class="_oab_journal">the journal</span> won\'t let you share <span class="_oab_your_paper">your paper</span> freely with everyone. <span class="_oab_refs"></span><br><br> The good news is the library can still legally make your paper much easier to find and access. We\'ll put the publisher PDF in <span class="_oab_repo">ScholarWorks</span> and then share it on your behalf whenever it is requested.</p> <h3 class="_oab_section _oab_get_email">All we need is your email</h3> </div> <div class="_oab_section _oab_get_email" id="_oab_get_email"> <p><input class="_oab_form" type="text" id="_oab_email" placeholder="" aria-label="Enter your email" style="box-shadow:none;"></input></p> <p class="_oab_section _oab_oa_deposit">We\'ll use this to send you a link. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> <p class="_oab_section _oab_archivable">We\'ll only use this if something goes wrong.<br> <p class="_oab_section _oab_dark_deposit">We\'ll only use this to send you a link to your paper when it is in <span class="_oab_repo">ScholarWorks</span>. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable_file"> <h3>We\'ll check it\'s legal, then promote, and preserve your work</h3> <p><input type="file" name="file" id="_oab_file" class="_oab_form"></p> <p>By depositing you\'re agreeing to the <span class="_oab_terms">terms</span> and to license your work <span class="_oab_licence">CC-BY</span>.</p> </div> <div class="_oab_section _oab_oa_deposit _oab_archivable _oab_dark_deposit" id="_oab_deposits"> <p><a href="#" class="_oab_deposit btn-iu _oab_button _oab_loading" style="min-width:140px;" id="_oab_deposit">Deposit</a></p> </div> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div class="_oab_done" id="_oab_confirm"> <h2>Hmmm, something looks wrong</h2> <p>You\'re nearly done. It looks like what you uploaded is a publisher\'s PDF which your journal prohibits legally sharing.<!-- It can only be shared on a limited basis.--><br><br> We just need the version accepted by the journal to make your work available to everyone.</p> <p><a href="#" class="_oab_reload btn-iu _oab_button" id="_oab_upload_again" style="min-width:140px;">Try uploading again</a></p> <p><a href="#" class="_oab_confirm _oab_loading" id="_oab_upload_accept"><b>My upload was an accepted manuscript</b></a></p> </div> <div class="_oab_done" id="_oab_check"> <h2>We\'ll double check your paper</h2> <p>You\'ve done your part for now. Hopefully, we\'ll send you a link soon. First, we\'ll check in the next working day to make sure it\'s legal to share.</p> </div> <div class="_oab_done" id="_oab_partial"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_zenodo"> <h2>Congrats! Your paper will be available to everyone, forever!</h2> <div id="_oab_zenodo_embargo"></div> <p><input id="_oab_zenodo_url" class="_oab_form" type="text" style="box-shadow:none;" value=""></input></p> <p>You can now put the link on your website, CV, any profiles, and ResearchGate.</p> </div> <div class="_oab_done" id="_oab_redeposit"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_success"> <h2>H<NAME>, you\'re done!</h2> <p>We\'ll email you a link to your paper in <span class="_oab_repo">ScholarWorks</span> soon. Next time, before you publish check to see if your journal allows you to have the most impact by making your research available to everyone, for free.</p> </div> <div class="_oab_done" id="_oab_review"> <h2>You\'ve done your part</h2> <p>All that\'s left to do is wait. Once the journal gives you permission to share, come back and we\'ll help you finish the job.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' # can pass in a key/value pair, or key can be a config object, in which case val can optionally be a user ID string, # or key can be a user ID string and val must be empty, or key and val can both be empty and config will attempt # to be retrieved from setup, or localstorage and/or from the API if a user ID is available from setup _oab.prototype.configure = (key, val, build, preview) -> if typeof key is 'string' and not val? and key.startsWith '{' try key = JSON.parse key if typeof key is 'string' and not val? and (not this.uid? or this.uid is 'anonymous') this.uid = key key = undefined if ((typeof key is 'string' and val?) or (not key? and not val?)) and JSON.stringify(this.config) is '{}' try if this.local isnt false # can be disabled if desired, by setting local to false at setup or in url param lc = JSON.parse localStorage.getItem '_oab_config_' + this.plugin if typeof lc is 'object' and lc isnt null console.log 'Config retrieved from local storage' this.config = lc if this.remote isnt false and this.uid and this.uid isnt 'anonymous' and JSON.stringify(this.config) is '{}' # should a remote call always be made to check for superseded config if one is not provided at startup? _L.jx this.api + '/' + (if this.plugin is 'instantill' then 'ill' else 'deposit') + '/config?uid='+this.uid, undefined, (res) => console.log 'Config retrieved from API' this.configure res if this.local is false return # stop here, once the retrieve from remote works, the rest will run if typeof key is 'object' this.uid = val if typeof val is 'string' for d of key if not this.config[d]? or (this.config[d] isnt key[d] and val is true) # val true allows overwrite present values build = true if build isnt false this.config[d] = if key[d] is 'true' then true else if key[d] is 'false' then false else key[d] if val is true for cd of this.config delete this.config[cd] if cd isnt 'owner' and not key[cd]? else if key? and val? this.config[key] = if val is 'true' then true else if val is 'false' then false else val # make a "writable" config without unecessary params, such as those setting false etc # keep separate from this.config so that additional calls to configure take account of false if they do exist though this.config.pilot = Date.now() if this.config.pilot is true this.config.live = Date.now() if this.config.live is true for k of wc = JSON.parse JSON.stringify this.config delete wc[k] if not wc[k]? or wc[k] is false or ((typeof wc[k] is 'string' or Array.isArray(wc[k])) and wc[k].length is 0) try localStorage.setItem('_oab_config_' + this.plugin, JSON.stringify wc) if JSON.stringify(wc) isnt '{}' and this.local isnt false if this.css isnt false and this.config.css_off this.css = false build = true if this.bootstrap isnt false and this.config.bootstrap_off this.bootstrap = false build = true this.element ?= '#' + this.plugin _whenready = () => if _L.gebi this.element if build isnt false console.log 'Building embed' #_L.append('body', '<div id="' + this.element + '"></div>') if not _L.gebi this.element _L.html this.element, '' if not this.bootstrap? # hack test for bootstrap calls or classes in page doc dstr = document.documentElement.innerHTML this.bootstrap = dstr.indexOf('bootstrap/') isnt -1 or dstr.indexOf('/bootstrap') isnt -1 or dstr.indexOf('bootstrap.css') isnt -1 or dstr.indexOf('bootstrap.min.css') isnt -1 or dstr.indexOf('btn-') isnt -1 console.log('Found bootstrap indicators in the doc') if this.bootstrap is true if this.bootstrap is true if this.template.indexOf('btn-primary') is -1 this.template = this.template.replace(/_oab_button/g,'_oab_button btn btn-primary').replace(/_oab_form/g,'_oab_form form-control') else if this.template.indexOf('btn-primary') isnt -1 this.template = this.template.replace(/ btn btn-primary/g,'').replace(/ form-control/g,'') if typeof this.css is 'string' and this.css isnt 'false' and this.bootstrap isnt true #this.bootstrap is false this.css = '<div id="_oab_css"><style>' + this.css + '</style></div>' if not this.css.startsWith '<style>' _L.append this.element, this.css _L.append this.element, this.template _L.each '._oab_paper', (el) => cs = el.innerHTML if this.config.say_paper if cs.indexOf('aper') is -1 el.innerHTML = (if cs is 'an article' then 'a paper' else if cs is 'article' then 'paper' else 'Paper') else if cs.indexOf('aper') isnt -1 el.innerHTML = (if cs is 'a paper' then 'an article' else if cs is 'paper' then 'article' else 'Article') if this.config.pilot pilot = '<p><br>Notice a change? We\'re testing a simpler and faster way to ' + (if this.plugin is 'instantill' then 'get' else 'deposit') + ' your ' + (if this.config.say_paper then 'paper' else 'article') + (if this.plugin is 'instantill' then '' else 's') + '. You can ' pilot += '<a href="mailto:' + this.cml() + '">give feedback</a> or ' if this.plugin is 'instantill' pilot += '<a class="_oab_ping" message="instantill_use_the_old_form" target="_blank" href="' + (if this.config.advanced_ill_form then this.config.advanced_ill_form else if this.config.ill_form then this.config.ill_form else 'mailto:'+this.cml()) + '">use the old form</a>.</p>' else pilot += '<a class="_oab_ping" message="shareyourpaper_use_the_old_form" target="_blank" href="' + (if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml()) + '">use the old way</a>.</p>' _L.html '#_oab_pilot', pilot else _L.html '#_oab_pilot', '' # shareyourpaper exclusive configs if this.plugin is 'shareyourpaper' if this.cml()? and el = _L.gebi '_oab_nodoi' el.setAttribute 'href', el.getAttribute('href').replace('<EMAIL>', this.cml()) if this.config.not_library _L.html '._oab_library', 'We have' else _L.html '#_oab_lib_info', 'Share your paper with help from the library in ' + (this.config.repo_name ? 'ScholarWorks') + '. Legally, for free, in minutes. ' else if this.plugin is 'instantill' if this.config.book or this.config.other boro = '<p>Need ' boro += 'a <a href="' + this.config.book + '">book chapter</a>' if this.config.book boro += (if this.config.book then ' or ' else ' ') + '<a href="' + this.config.other + '">something else</a>' if this.config.other _L.html '#_oab_book_or_other', boro + '?</p>' else _L.html '#_oab_book_or_other', '' if this.config.intro_off _L.hide '#_oab_intro' if this.config.advanced_ill_form or this.config.account or this.config.ill_info aai = '<p>Or ' if this.config.advanced_ill_form _L.show '#_oab_advanced_ill_form', ' or <a href="' + this.config.advanced_ill_form + '">use full request form</a>' aai += '<a href="' + this.config.advanced_ill_form + '">use full request form</a>' if this.config.account and this.config.ill_info aai += ', ' else if this.config.account or this.config.ill_info aai += ' and ' if this.config.account aai += '<a href="' + this.config.account + '">view account</a>' aai += ' and ' if this.config.ill_info aai += '<a href="' + this.config.ill_info + '">learn about Interlibrary Loan</a>' if this.config.ill_info _L.html '#_oab_advanced_account_info', aai + '</p>' else _L.html '#_oab_advanced_account_info', '' _L.hide '#_oab_advanced_ill_form' # would be better to make _L handle the bind so that this.find works rather than having to wrap it in a function that passes context _L.listen 'enter', '#_oab_input', (e) => this.find(e) _L.listen 'enter', '#_oab_email', (e) => this.validate(e) _L.listen 'click', '._oab_find', (e) => this.find(e) _L.listen 'click', '._oab_submit', (e) => this.submit(e) _L.listen 'click', '._oab_restart', (e) => this.restart(e) _L.listen 'click', '._oab_ping', (e) => this.ping(_L.get e.target, 'message') _L.listen 'click', '._oab_wrong', (e) => e.preventDefault() this.ping '_wrong_article' this.metadata() _L.listen 'click', '._oab_reload', (e) => e.preventDefault() gf.value = '' if gf = _L.gebi "_oab_file" this.file = false this.permissions() _L.listen 'click', '._oab_confirm', (e) => e.preventDefault(); this.data.confirmed = true; this.deposit() _L.listen 'click','#_oab_reviewemail', (e) => this.done 'review' _L.listen 'click','._oab_deposit', (e) => this.deposit(e) if el = _L.gebi '_oab_config' ncwc = JSON.parse JSON.stringify wc nk = ill_institution: 'institution' # translate instantill old config keys ill_redirect_base_url: 'ill_form' ill_redirect_params: 'ill_added_params' deposit_terms: 'terms' problem_email: 'problem' viewaccount: 'account' autorun: 'autorun_off' intropara: 'intro_off' norequests: 'requests_off' illinfo: 'ill_info' noillifoa: 'ill_if_oa_off' noillifsub: 'ill_if_sub_off' saypaper: 'say_paper' advancedform: 'advanced_ill_form' deposit_date: 'depositdate' # and shareyourpaper keys deposit_terms: 'terms' allow_oa_deposit: 'oa_deposit_off' ROR_ID: 'ror' not_a_library: 'not_library' adminemail: 'email' css: 'css_off' bootstrap: 'bootstrap_off' for k of nk if ncwc[k]? ncwc[nk[k]] = ncwc[k] delete ncwc[k] el.innerHTML = JSON.stringify ncwc if window.location.search.indexOf('panel=') isnt -1 this.panel window.location.search.split('panel=')[1].split('&')[0].split('#')[0], (if window.location.search.indexOf('section=') isnt -1 then window.location.search.split('section=')[1].split('&')[0].split('#')[0] else undefined) if preview preview = this.config.val if typeof preview isnt 'string' or (typeof this.config.val is 'string' and this.config.val.length) this.data = {} this.f = {} this.loading false gf.value = '' if gf = _L.gebi "_oab_file" this.file = false _L.hide '._oab_panel' _L.show '#_oab_inputs' _L.set '#_oab_input', preview setTimeout (() => this.find()), 1 this.loaded() if typeof this.loaded is 'function' else console.log 'waiting for ' + this.element setTimeout (() => _whenready()), 100 _whenready() return wc @shareyourpaper = (opts) -> opts ?= {}; opts.plugin = 'shareyourpaper'; return new _oab(opts); @instantill = (opts) -> opts ?= {}; opts.plugin = 'instantill'; return new _oab(opts);
true
# start with a simple set of helper functions @_L = api: 'https://api.lvatn.com' _L.gebi = (id) -> return document.getElementById id.replace('#','') _L.gebc = (cls) -> return document.getElementsByClassName cls.replace('.','') _L.gebn = (n) -> r = document.getElementsByTagName n.replace('<','').replace('>','') # e.g. by the element name, like "div" return if r? then r else document.getElementsByName n # otherwise by the "name" attribute matching n _L.each = (elems, key, val) -> if typeof elems is 'string' if elems.startsWith '#' elems = [_L.gebi elems] else if elems.startsWith '.' elems = _L.gebc elems else elems = _L.gebn elems else if typeof elems is 'object' elems = [elems] if not Array.isArray elems if elems? for elem in elems if elem? if typeof key is 'function' then key(elem) else _L.set elem, key, val _L.listen = (action, els, fn) -> _L.each els, (el) -> if action is 'enter' action = 'keyup' wfn = (e) -> fn(e) if e.keyCode is 13 else wfn = fn if not _L.has el, 'listen_'+action _L.class el, 'listen_'+action el.addEventListener action, (e) -> wfn(e) _L.show = (els, html, append) -> _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html was = _L.get el, '_l_display' was = (if el.tagName is 'DIV' then 'block' else 'inline') if typeof was isnt 'string' or was is 'none' # TODO should be inline in which cases... el.style.display = was _L.hide = (els) -> _L.each els, (el) -> if el.style.display isnt 'none' _L.set el, '_l_display', el.style.display el.style.display = 'none' _L.get = (els, attr) -> res = undefined _L.each els, (el) -> if not attr? try res = el.value res = undefined if typeof res is 'string' and not res.length try res ?= el.getAttribute attr return res _L.set = (els, attr, val) -> _L.each els, (el) -> # TODO handle dot notation keys e.g if attr is style.display if not val? or attr is 'value' or attr is 'val' try el.value = if not val? then attr else val else try el.setAttribute attr, val _L.checked = (els) -> res = true _L.each els, (el) -> res = el.checked return res _L.html = (els, html, append, show) -> rs = [] _L.each els, (el) -> if typeof html is 'string' el.innerHTML = (if append then el.innerHTML else '') + html rs.push el.innerHTML _L.show(el) if show return if rs.length is 1 then (rs[0] ? '') else if rs.length then rs else '' _L.append = (els, html) -> _L.html els, html, true _L.remove = (els) -> _L.each els, (el) -> el.parentNode.removeChild el _L.class = (el, cls) -> rs = [] classes = el.getAttribute 'class' classes ?= '' if typeof cls is 'string' if classes.indexOf(cls) is -1 classes += ' ' if classes.length classes += cls else classes = classes.replace(cls,'').trim().replace(/ /g,' ') el.setAttribute 'class', classes for c in classes.split ' ' rs.push(c) if c not in rs return rs _L.classes = (els) -> return _L.class els _L.has = (el, cls) -> classes = _L.classes el cls = cls.replace('.') if cls.startsWith '.' if cls in classes return true else return if el.getAttribute(cls) then true else false _L.css = (els, key, val) -> _L.each els, (el) -> s = _L.get(el, 'style') ? '' style = {} for p in s.split ';' ps = p.split ':' style[ps[0].trim()] = ps[1].trim() if ps.length is 2 style[key] = val if val? ss = '' for k of style ss += ';' if ss isnt '' ss += k + ':' + style[k] _L.set el, 'style', ss _L.jx = (route, q, success, error, api, method, data, headers) -> # add auth options to this api ?= _L.api if route.startsWith 'http' url = route else url = api + if api.endsWith('/') then '' else '/' url += (if route.startsWith('/') then route.replace('/','') else route) if route if typeof q is 'string' url += (if url.indexOf('?') is -1 then '?' else '&') + (if q.indexOf('=') is -1 then 'q=' else '') + q else if typeof q is 'object' url += '?' if url.indexOf('?') is -1 url += p + '=' + q[p] + '&' for p of q xhr = new XMLHttpRequest() xhr.open (method ? 'GET'), url xhr.setRequestHeader(h, headers[h]) for h of headers ? {} xhr.send data xhr.onload = () -> if xhr.status isnt 200 try error xhr else try success JSON.parse(xhr.response), xhr catch err console.log err try success xhr catch try error xhr _L.loaded(xhr) if typeof _L.loaded is 'function' xhr.onerror = (err) -> try error(err) _L.post = (route, data, success, error, api, headers) -> headers ?= {} if typeof data is 'object' if typeof data.append isnt 'function' # a FormData object will have an append function, a normal json object will not. FormData should be POSTable by xhr as-is data = JSON.stringify data # disabled sending the correct header to avoid waiting for an OPTIONS check #headers['Content-type'] ?= 'application/json' #route += (if route.indexOf('?') is -1 then '?' else '&') + '_=' + Date.now() # set a random header to try to break any possible caching _L.jx route, undefined, success, error, api, 'POST', data, headers # ============================================================================== _oab = (opts) -> try opts ?= {} # can pass demo true here as well, to control demo output, stopping submit from POSTing this[o] = opts[o] for o of opts this.uid ?= 'anonymous' this.api ?= if window.location.host.indexOf('dev.openaccessbutton.org') isnt -1 then 'https://dev.api.cottagelabs.com/service/oab' else 'https://api.openaccessbutton.org' this.plugin ?= 'instantill' # has to be defined at startup, as either instantill or shareyourpaper this.element ?= '#' + this.plugin this.pushstate ?= true # if true, the embed will try to add page state changes to the browser state manager this.local ?= true # local storage of config turned off by default for now this.config ?= {} this.data ?= {} # the data obj to send to backend this.f ?= {} # the result of the find/ill/permission request to the backend this.template ?= _oab[this.plugin + '_template'] # template or css can be passed in or are as defined below this.css ?= _oab.css this._loading = false # tracks when loads are occurring this.submit_after_metadata = false # used by instantill to track if metadata has been provided by user this.file = false # used by syp to store the file for sending to backend this.demo ?= window.location.href.indexOf('/demo') isnt -1 and (window.location.href.indexOf('openaccessbutton.') isnt -1 or window.location.href.indexOf('shareyourpaper.') isnt -1 or window.location.href.indexOf('instantill.') isnt -1) _L.loaded = this.loaded if this.loaded? # if this is set to a function, it will be passed to _leviathan loaded, which gets run after every ajax call completes. It is also called directly after every configure if window.location.search.indexOf('clear=') isnt -1 localStorage.removeItem '_oab_config_' + this.plugin if window.location.search.indexOf('local=') isnt -1 this.local = if window.location.search.indexOf('local=true') isnt -1 then true else false if window.location.search.indexOf('config=') isnt -1 try this.config = JSON.parse window.location.search.split('config=')[1].split('&')[0].split('#')[0] if window.location.search.indexOf('config.') isnt -1 configs = window.location.search.split 'config.' configs.shift() for c in configs cs = c.split '=' if cs.length is 2 csk = cs[0].trim() csv = cs[1].split('&')[0].split('#')[0].trim() this.configure csk, csv, false setTimeout (() => this.configure()), 1 if not this.config.autorun_off ap = if typeof this.config.autorunparams is 'string' then this.config.autorunparams.split(',') else if typeof this.config.autorunparams is 'object' then this.config.autorunparams else ['doi','title','url','atitle','rft_id','journal','issn','year','author'] ap = ap.replace(/"/g,'').replace(/'/g,'').split(',') if typeof ap is 'string' for o in ap o = o.split('=')[0].trim() eq = o.split('=')[1].trim() if o.indexOf('=') isnt -1 this.data[eq ? o] = decodeURIComponent(window.location.search.replace('?','&').split('&'+o+'=')[1].split('&')[0].replace(/\+/g,' ')) if (window.location.search.replace('?','&').indexOf('&'+o+'=') isnt -1) if not this.data.doi and window.location.href.split('?')[0].indexOf('/10.') isnt -1 and window.location.href.split('?')[0].split('/10.')[1].indexOf('/') > 1 and window.location.href.split('?')[0].split('/10.')[1].trim().split('/').length > 1 this.data.doi = '10.' + window.location.href.split('?')[0].split('/10.')[1].replace(/\/$/,'') if window.location.search.indexOf('email=') isnt -1 this.data.email = window.location.search.split('email=')[1].split('&')[0].split('#')[0] _L.remove '#_oab_collect_email' if window.location.search.indexOf('confirmed=') isnt -1 this.data.confirmed = window.location.search.split('confirmed=')[1].split('&')[0].split('#')[0] this.find() if this.data.doi or (this.plugin is 'instantill' and (this.data.title or this.data.url)) window.addEventListener "popstate", (pe) => this.state(pe) return this catch this.ping 'instantill_or_shareyourpaper_try_initialise_catch' _oab.prototype.cml = () -> return this.config.problem ? this.config.owner ? this.config.email ? '' _oab.prototype.contact = () -> return 'Please try ' + (if this.cml() then '<a id="_oab_contact_library" href="mailto:' + this.cml() + '">contacting your library</a>' else 'contacting your library') + ' directly' _oab.prototype.loading = (load) -> _L.hide '#_oab_error' if load isnt true and (this._loading or load is false) try clearInterval this._loading this._loading = false _L.each '._oab_loading', (el) => if _L.has el, '_oab_continue' el.innerHTML = 'Continue' else if _L.has el, '_oab_submit' el.innerHTML = 'Complete request' else if _L.has el, '_oab_deposit' el.innerHTML = 'Deposit' else if _L.has el, '_oab_find' el.innerHTML = 'Next' else if _L.has el, '_oab_confirm' el.innerHTML = '<b>My upload was an accepted manuscript</b>' else el.innerHTML = 'Find ' + if this.config.say_paper then 'paper' else 'article' # this would only happen on instantill, as "Next" above is the default for syp else _L.html '._oab_find', 'Searching .' _L.html '._oab_submit', 'Submitting .' _L.html '._oab_deposit', 'Depositing .' _L.html '._oab_confirm', 'Depositing .' this._loading = setInterval (() -> for button in _L.gebc '._oab_loading' dots = button.innerHTML.split '.' if dots.length >= 4 button.innerHTML = dots[0] else button.innerHTML = button.innerHTML + ' .' ), 700 _oab.prototype.state = (pop) -> if this.pushstate try u = window.location.pathname if not pop? if window.location.href.indexOf('shareyourpaper.org') isnt -1 and this.data.doi? u = window.location.href.split('10.')[0] + this.data.doi + window.location.search + window.location.hash else if window.location.href.indexOf('/setup') is -1 and window.location.href.indexOf('/demo') is -1 if this.data.doi? or this.data.title? or this.data.url? k = if this.data.doi then 'doi' else if this.data.title then 'title' else 'url' u += window.location.search.split('?' + k + '=')[0].split('&' + k + '=')[0] u += if u.indexOf('?') is -1 then '?' else '&' u += k + '=' + this.data[k] + window.location.hash window.history.pushState "", (if pop? then "search" else "find"), u if pop? # what to do with the pop event? for now just triggers a restart if user # tries to go back, unless called with a boolean from the restart event this.restart() if typeof pop isnt 'boolean' _oab.prototype.restart = (e, val) -> try e.preventDefault() if e.target.parentElement.id isnt '_oab_permissionemail' this.data = {} this.f = {} this.loading false this.file = false gf.value = '' if gf = _L.gebi "_oab_file" _L.hide '._oab_panel' _L.show '#_oab_inputs' this.configure() this.state true if val _L.set '#_oab_input', val this.find() else _L.set '#_oab_input', '' _oab.prototype.ping = (what) -> try if what.indexOf(this.plugin) is -1 what = '_' + what if not what.startsWith '_' what = this.plugin + what url = if this.api.indexOf('dev.') isnt -1 then 'https://dev.api.cottagelabs.com' else 'https://api.cottagelabs.com' url += '/ping.png?service=openaccessbutton&action=' + what + '&from=' + this.uid + '&url=' + encodeURIComponent window.location.href url += '&pilot=' + this.config.pilot if this.config.pilot url += '&live=' + this.config.live if this.config.live _L.jx url _oab.prototype.panel = (panel, section) -> if he = _L.gebi '_oab_' + (if panel.startsWith('_oab_') then panel.replace('_oab_','') else panel) _L.hide '._oab_panel' _L.show he this.section(section) if section _oab.prototype.section = (section) -> # useful for demo/test, just shows a specific section within a panel fe = _L.gebi '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) fe = _L.gebc '_oab_' + (if section.startsWith('_oab_') then section.replace('_oab_','') else section) if not fe? if fe _L.hide '._oab_section' _L.show fe _oab.prototype.submit = (e) -> # only used by instantill try try e.preventDefault() if not this.openurl() and not this.data.email and _L.gebi '#_oab_email' this.validate() else if JSON.stringify(this.f) is '{}' or (not this.f.metadata?.title or not this.f.metadata?.journal or not this.f.metadata?.year) if this.submit_after_metadata this.done false else this.submit_after_metadata = true this.metadata() else this.loading() data = {match: this.f.input, email:this.data.email, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} for k in ['title','journal','year','doi'] data.metadata[k] = this.data[k] if not data.metadata[k] and this.data[k] if data.metadata.doi and data.metadata.doi.indexOf('http') is 0 data.metadata.url = data.metadata.doi delete data.metadata.doi nfield = if this.config.notes then this.config.notes else 'notes' data[nfield] = 'The user provided some metadata. ' if this.data.usermetadata data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f?.ill?.subscription or this.f?.url if typeof data[nfield] isnt 'string' then data[nfield] = '' else data[nfield] += ' ' if this.f.ill?.subscription data[nfield] += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.metadata? data[nfield] += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' ou = this.openurl() if ou and not data.email data.forwarded = true if this.demo is true console.log 'Not POSTing ILL and not forwarding to ' + ou + ' for demo purposes' console.log data else _L.post( this.api+'/ill' data (res) => this.done res () => this.done false ) catch this.ping 'instantill_try_submit_catch' _oab.prototype.validate = () -> if this.config.terms and not _L.checked '#_oab_read_terms' # instantill terms _L.show '#_oab_error', '<p>Please agree to the terms first.</p>' else email = (_L.get('#_oab_email') ? '').trim() if not email.length _L.show '#_oab_error', '<p>Please provide your university email address.</p>' _L.css '#_oab_email', 'border-color', '#f04717' _L.gebi('#_oab_email').focus() else this.loading() _L.post( this.api + '/validate?uid=' + this.uid + '&email=' + email this.config (res) => this.loading false if res is true this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() else if res is 'baddomain' _L.show '#_oab_error', '<p>Please try again with your university email address.</p>' else _L.show '#_oab_error', '<p>Sorry, your email does not look right. ' + (if res isnt false then 'Did you mean ' + res + '? ' else '') + 'Please check and try again.</p>' () => this.data.email = _L.get('#_oab_email').trim() if this.plugin is 'instantill' then this.submit() else this.deposit() ) _oab.prototype.metadata = (submitafter) -> # only used by instantill for m in ['title','year','journal','doi'] if this.f?.metadata?[m]? or this.data[m]? _L.set '#_oab_'+m, (this.f.metadata ? this.data)[m].split('(')[0].trim() #if this.f?.doi_not_in_crossref # _L.html '#_oab_bad_doi', this.f.doi_not_in_crossref # _L.show '#_oab_doi_not_in_crossref' _L.hide '._oab_panel' _L.show '#_oab_metadata' _oab.prototype.openurl = () -> # only used by instantill if this.f.ill?.openurl try nf = this.config.notes ? 'notes' if this.f.ill.openurl.indexOf(nf+'=') is -1 notes = if this.data?.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? this.f.ill.openurl += '&' if not this.f.ill.openurl.endsWith '&' this.f.ill.openurl += nf + '=' + notes return this.f.ill.openurl else if not this.config.ill_form return '' else config = JSON.parse JSON.stringify this.config defaults = sid: 'sid' title: 'atitle' # this is what iupui needs (title is also acceptable, but would clash with using title for journal title, which we set below, as iupui do that doi: 'rft_id' # don't know yet what this should be author: 'aulast' # author should actually be au, but aulast works even if contains the whole author, using aufirst just concatenates journal: 'title' # this is what iupui needs page: 'pages' # iupui uses the spage and epage for start and end pages, but pages is allowed in openurl, check if this will work for iupui published: 'date' # this is what iupui needs, but in format 1991-07-01 - date format may be a problem year: 'rft.year' # this is what IUPUI uses for d of defaults config[d] = defaults[d] if not config[d] url = config.ill_form url += if url.indexOf('?') is -1 then '?' else '&' url += config.ill_added_params.replace('?','') + '&' if config.ill_added_params url += config.sid + '=InstantILL&' for k of this.f.metadata ? {} v = false if k is 'author' if typeof this.f.metadata.author is 'string' v = this.f.metadata.author else if Array.isArray this.f.metadata.author v = '' for author in this.f.metadata.author try v += ', ' if v.length v += if typeof author is 'string' then author else if typeof author is 'object' and author.family then (author.family + if author.given then ', ' + author.given else '') else JSON.stringify author else if k in ['doi','pmid','pmc','pmcid','url','journal','title','year','issn','volume','issue','page','crossref_type','publisher','published','notes'] v = this.f.metadata[k] url += (config[k] ? k) + '=' + encodeURIComponent(v) + '&' if v notes = if this.data.usermetadata then 'The user provided some metadata. ' else '' notes += 'Subscription check done, found ' + (this.f.ill.subscription.url ? (if this.f.ill.subscription.journal then 'journal' else 'nothing')) + '. ' if this.f.ill?.subscription notes += 'OA availability check done, found ' + (this.f.url ? 'nothing') + '. ' if this.f.metadata? url += '&' + (this.config.notes ? 'notes') + '=' + notes if notes return url.replace '/&&/g', '&' _oab.prototype.done = (res, msg) -> this.loading false if ou = this.openurl() window.location = ou else _L.hide '._oab_panel' _L.hide '._oab_done' if typeof res is 'string' and _L.gebi '_oab_' + res _L.show '#_oab_' + res # various done states for shareyourpaper if res is 'confirm' _L.hide '#_oab_done_restart' else _L.show '#_oab_done_restart' else if res _L.html '#_oab_done_header', '<h3>Thanks! Your request has been received</h3><p>Your confirmation code is: ' + res + ', this will not be emailed to you. The ' + (if this.config.say_paper then 'paper' else 'article') + ' will be sent to ' + this.data.email + ' as soon as possible.</p>' else # only instantill falls through to here _L.html '#_oab_done_header', '<h3>Sorry, we were not able to create an Interlibrary Loan request for you.</h3><p>' + this.contact() + '</p>' _L.html '#_oab_done_restart', 'Try again' this.ping msg ? 'instantill_couldnt_submit_ill' setTimeout (() => this.restart()), 6000 _L.show '#_oab_done' this.after() if typeof this.after is 'function' _oab.prototype.deposit = (e) -> # only used by shareyourpaper try try e.preventDefault() if not this.data.email and _L.gebi '#_oab_email' this.validate() else if this.demo is true and this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 if this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp-') is 0 and this.data.doi isnt '10.1234/oab-syp-confirm' # demo successful deposit info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info _L.set '#_oab_zenodo_url', 'https://zenodo.org/record/3703317' this.done 'zenodo' else # demo something wrong, please confirm this.done 'confirm' this.loaded() if typeof this.loaded is 'function' else fl = _L.gebi '#_oab_file' if fl? and fl.files? and fl.files.length this.file = new FormData() this.file.append 'file', fl.files[0] else if this.file isnt true # can be set to true when dark deposit is being followed - no file required. Or a demo may set it to true _L.show '#_oab_error', '<p>Whoops, you need to give us a file! Check it\'s uploaded.</p>' _L.css '#_oab_file', 'border-color','#f04717' return this.loading() # this could be just an email for a dark deposit, or a file for actual deposit # if the file is acceptable and can go in zenodo then we don't bother getting the email address data = {from: this.uid, plugin: this.plugin, embedded:window.location.href, metadata: this.f?.metadata } data.demo = true if this.demo is true data.config = this.config data.email = this.data.email if this.data.email data.confirmed = this.data.confirmed if this.data.confirmed data.redeposit = this.f.url if typeof this.f?.url is 'string' data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if typeof this.file isnt 'boolean' for d of data if d is 'metadata' for md of data[d] this.file.append(md,data[d][md]) if (typeof data[d][md] is 'string' or typeof data[d][md] is 'number') else this.file.append d,data[d] data = this.file _L.post( this.api+'/deposit', # + (this.f.catalogue ? '') data (res) => this.loading false if typeof this.file isnt 'boolean' if res.zenodo?.already or (this.data.confirmed and not res.zenodo?.url) #or not this.f?.permissions?.file?.archivable this.done 'check' else if res.error # if we should be able to deposit but can't, we stick to the positive response and the file will be manually checked this.done 'partial' else if res.zenodo?.url # deposit was possible, show the user a congrats page with a link to the item in zenodo _L.set '#_oab_zenodo_url', res.zenodo.url if res.embargo info = '<p>You\'ve done your part for now. Unfortunately, ' + (this.f?.metadata?.journal_short ? this.f?.metadata?.journal ? 'the journal') + ' won\'t let us make it public until ' info += if res.embargo_UI then res.embargo_UI else res.embargo info += '. After release, you\'ll find your paper on ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science.</p>' info += '<h3>Your paper will be freely available at this link:</h3>' else info = '<p>You\'ll soon find your paper freely available in ' + (this.config.repo_name ? 'ScholarWorks') + ', Google Scholar, Web of Science, and other popular tools.' info += '<h3>Your paper is now freely available at this link:</h3>' _L.html '#_oab_zenodo_embargo', info this.done 'zenodo' else # if the file given is not a version that is allowed, show a page saying something looks wrong # also the backend should create a dark deposit in this case, but delay it by six hours, and cancel if received in the meantime this.done 'confirm' else if res.type is 'redeposit' this.done 'redeposit' else this.done 'success' () => this.loading false _L.show '#_oab_error', '<p>Sorry, we were not able to deposit this paper for you. ' + this.contact() + '</p><p><a href="#" class="_oab_restart" id="_oab_sorry_try_again"><b>Try again</b></a></p>' this.ping('shareyourpaper_couldnt_submit_deposit') ) catch this.ping 'shareyourpaper_try_deposit_catch' _oab.prototype.permissions = (data) -> # only used by shareyourpaper try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.permissions()), 100 else this.loading false if this.f?.doi_not_in_crossref this.f = {} _L.show '#_oab_error', '<p>Double check your DOI, that doesn\'t look right to us.</p>' _L.gebi('_oab_input').focus() else if this.f?.metadata?.crossref_type? and this.f.metadata.crossref_type not in ['journal-article', 'proceedings-article'] _L.gebi('_oab_input').focus() nj = '<p>Sorry, right now this only works with academic journal articles.' if this.cml() nj += ' To get help with depositing, <a href="' nj += if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml() nj += "?subject=Help%20depositing%20&body=Hi%2C%0D%0A%0D%0AI'd%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C" + '">click here</a>' _L.show '#_oab_error', nj + '.</p>' else if not this.f?.metadata?.title? _L.show '#_oab_error', '<h3>Unknown paper</h3><p>Sorry, we cannot find this paper or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' else _L.hide '._oab_panel' _L.hide '._oab_section' _L.show '#_oab_permissions' this.loading false tcs = 'terms <a id="_oab_terms" href="https://openaccessbutton.org/terms" target="_blank">[1]</a>' tcs += ' <a id="_oab_config_terms" href="' + this.config.terms + '" target="_blank">[2]</a>' if this.config.terms ph = 'PI:EMAIL:<EMAIL>END_PI'; if this.config.email_domains? and this.config.email_domains.length this.config.email_domains = this.config.email_domains.split(',') if typeof this.config.email_domains is 'string' ph = this.config.email_domains[0] ph = ph.split('@')[1] if ph.indexOf('@') isnt -1 ph = ph.split('//')[1] if ph.indexOf('//') isnt -1 ph = ph.toLowerCase().replace('www.','') ph = 'PI:EMAIL:<EMAIL>END_PI' if not ph? or ph.length < 3 ph = 'PI:EMAIL:<EMAIL>END_PI@' + ph if ph.indexOf('@') is -1 if this.data.email _L.hide '._oab_get_email' else _L.show '._oab_get_email' _L.set '#_oab_email', 'placeholder', ph _L.html '._oab_terms', tcs refs = '' for p of this.f?.permissions?.permissions?.policy_full_text ? [] refs += ' <a id="_oab_policy_text" target="_blank" href="' + this.f.permissions.permissions.policy_full_text[p] + '">[' + (parseInt(p)+1) + ']</a>' _L.html '._oab_refs', refs paper = if this.f?.metadata?.doi then '<a id="_oab_your_paper" target="_blank" href="https://doi.org/' + this.f.metadata.doi + '"><u>your paper</u></a>' else 'your paper' _L.html '._oab_your_paper', (if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' then 'the publisher pdf of ' else '') + paper _L.html '._oab_journal', this.f?.metadata?.journal_short ? 'the journal' # set config by this.config.repo_name put name in ._oab_repo if this.f.url # it is already OA, depending on settings can deposit another copy _L.set '._oab_oa_url', 'href', this.f.url if this.config.oa_deposit_off _L.hide '._oab_get_email' _L.show '._oab_oa' else this.file = true # no file required for oa deposit... _L.show '._oab_oa_deposit' else if this.f?.permissions?.permissions?.archiving_allowed # can be shared, depending on permissions info _L.hide('#_oab_not_pdf') if this.f?.permissions?.permissions?.version_allowed is 'publisher pdf' if typeof this.f?.permissions?.permissions?.licence_required is 'string' and this.f.permissions.permissions.licence_required.indexOf('other-') is 0 _L.html '._oab_licence', 'under the publisher terms' + refs else _L.html '._oab_licence', this.f?.permissions?.permissions?.licence_required ? 'CC-BY' _L.show '._oab_archivable' else if this.config.dark_deposit_off # permission must be requested first rm = 'mailto:' + (this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact ? this.config.deposit_help ? this.cml()) + '?' rm += 'cc=' + (this.config.deposit_help ? this.cml()) + '&' if this.f.permissions?.ricks?.application?.can_archive_conditions?.permission_required_contact rm += 'subject=Request%20to%20self%20archive%20' + (this.f.metadata?.doi ? '') + '&body='; rm += encodeURIComponent 'To whom it may concern,\n\n' rm += encodeURIComponent 'I am writing to request permission to deposit the full text of my paper "' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" ' rm += encodeURIComponent 'published in "' + this.f.metadata.journal + '"' if this.f.metadata?.journal rm += encodeURIComponent '\n\nI would like to archive the final pdf. If that is not possible, I would like to archive the accepted manuscript. Ideally, I would like to do so immediately but will respect a reasonable embargo if requested.\n\n' if this.config.repo_name rm += encodeURIComponent 'I plan to deposit it into "' + this.config.repo_name + '", a not-for-profit, digital, publicly accessible repository for scholarly work created for researchers ' + (if this.config.institution_name then 'at ' + this.config.institution_name else '') + '. It helps make research available to a wider audience, get citations for the original article, and assure its long-term preservation. The deposit will include a complete citation of the published version, and a link to it.\n\n' rm += encodeURIComponent 'Thank you for your attention and I look forward to hearing from you.' _L.set '#_oab_reviewemail', 'href', rm # or to confirm permission has been received pm = 'mailto:' + (this.config.deposit_help ? this.cml()) + '?subject=Permission%20Given%20to%20Deposit%20' + (this.f.metadata?.doi ? '') + '&body=' pm += encodeURIComponent 'To whom it may concern,\n\nAttached is written confirmation of permission I\'ve been given to deposit, and the permitted version of my paper: ' pm += encodeURIComponent '"' + (this.f.metadata?.title ? this.f.metadata?.doi ? 'Untitled paper') + '" \n\nCan you please deposit it into the repository on my behalf? \n\nSincerely, ' _L.set '#_oab_permissionemail', 'href', pm _L.hide '._oab_get_email' _L.show '._oab_permission_required' else # can't be directly shared but can be passed to library for dark deposit this.file = true _L.hide '#_oab_file' _L.show '._oab_dark_deposit' catch this.ping 'shareyourpaper_try_permissions_catch' _oab.prototype.findings = (data) -> # only used by instantill try this.f = data if data? if not _L.gebi this.element setTimeout (() => this.findings()), 100 else if ct = this.f.metadata?.crossref_type if ct not in ['journal-article','proceedings-article','posted-content'] if ct in ['book-section','book-part','book-chapter'] err = '<p>Please make your request through our ' + (if this.config.book then '<a id="_oab_book_form" href="' + this.config.book + '">book form</a>' else 'book form') else err = '<p>We can only process academic journal articles, please use another form.' _L.show '#_oab_error', err + '</p>' return _L.hide '._oab_panel' _L.hide '._oab_section' this.loading false if this.config.resolver # new setting to act as a link resolver, try to pass through immediately if sub url, OA url, or lib openurl are available # TODO confirm if this should send an ILL to the backend first, as a record, or maybe just a pinger # also check if could forward the user to the new page before the send to backend succeeds / errors data = {match: this.f.input, from: this.uid, plugin: this.plugin, embedded: window.location.href} data.config = this.config data.metadata = this.f.metadata ? {} data.pilot = this.config.pilot if this.config.pilot data.live = this.config.live if this.config.live if this.f.ill?.subscription?.url data.resolved = 'subscription' else if this.f.url data.resolved = 'open' else if ou = this.openurl() data.resolved = 'library' if data.resolved? data.url = this.f.ill?.subscription?.url ? this.f.url ? ou _L.post(this.api+'/ill', data, (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou), (() => window.location = this.f.ill?.subscription?.url ? this.f.url ? ou)) _L.show '#_oab_findings' if this.f.ill?.error _L.show '#_oab_error', '<p>Please note, we encountered errors querying the following subscription services: ' + this.f.ill.error.join(', ') + '</p>' if this.f.metadata?.title? citation = '<h2>' + this.f.metadata.title + '</h2>' if this.f.metadata.year or this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue citation += '<p><i>' citation += (this.f.metadata.year ? '') + (if this.f.metadata.journal or this.f.metadata.volume or this.f.metadata.issue then ', ' else '') if this.f.metadata.year if this.f.metadata.journal citation += this.f.metadata.journal else citation += 'vol. ' + this.f.metadata.volume if this.f.metadata.volume citation += (if this.f.metadata.volume then ', ' else '') + 'issue ' + this.f.metadata.issue if this.f.metadata.issue citation += '</i></p>' _L.html '#_oab_citation', citation hassub = false hasoa = false if this.f.ill?.subscription?.journal or this.f.ill?.subscription?.url hassub = true # if sub url show the url link, else show the "should be able to access on pub site _L.set('#_oab_sub_url', 'href', this.f.ill.subscription.url) if this.f.ill.subscription.url? _L.show '#_oab_sub_available' else if this.f.url hasoa = true _L.set '#_oab_url', 'href', this.f.url _L.show '#_oab_oa_available' if this.f.ill? and not ((this.config.ill_if_sub_off and hassub) or (this.config.ill_if_oa_off and hasoa)) _L.html '#_oab_cost_time', '<p>It ' + (if this.config.cost then 'costs ' + this.config.cost else 'is free to you,') + ' and we\'ll usually email the link within ' + (this.config.time ? '24 hours') + '.<br></p>' if not this.data.email if this.openurl() _L.hide '#_oab_collect_email' else if this.config.terms _L.show '#_oab_terms_note' _L.set '#_oab_terms_link', 'href', this.config.terms else _L.hide '#_oab_terms_note' _L.show '#_oab_ask_library' else if this.data.usermetadata _L.html '#_oab_citation', '<h3>Unknown ' + (if this.config.say_paper then 'paper' else 'article') + '</h3><p>Sorry, we can\'t find this ' + (if this.config.say_paper then 'paper' else 'article') + ' or sufficient metadata. ' + this.contact() + '</p>' this.ping 'shareyourpaper_unknown_article' setTimeout (() => this.restart()), 6000 else this.metadata() catch this.ping 'instantill_try_findings_catch' _oab.prototype.find = (e) -> try try e.preventDefault() if JSON.stringify(this.f) isnt '{}' for k in ['title','journal','year','doi'] if v = _L.get '#_oab_' + k if this.data[k] isnt v this.data[k] = v this.data.usermetadata = true if this.data.year and this.data.year.length isnt 4 delete this.data.year _L.show '#_oab_error', '<p>Please provide the full year e.g 2019</p>' return if not this.data.title or not this.data.journal or not this.data.year _L.show '#_oab_error', '<p>Please complete all required fields</p>' return if this.submit_after_metadata this.submit() return this.data.title ?= this.data.atitle if this.data.atitle this.data.doi ?= this.data.rft_id if this.data.rft_id if this.data.doi and this.data.doi.indexOf('10.') isnt -1 and (this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('http') is 0) this.data.url = this.data.doi delete this.data.doi if val = _L.get('#_oab_input') val = val.trim().replace(/\.$/,'') if val.length if val.indexOf('doi.org/') isnt -1 this.data.url = val this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('10.') isnt -1 this.data.doi = '10.' + val.split('10.')[1].split(' ')[0] else if val.indexOf('http') is 0 or val.indexOf('www.') isnt -1 this.data.url = val else if val.toLowerCase().replace('pmc','').replace('pmid','').replace(':','').replace(/[0-9]/g,'').length is 0 this.data.id = val else this.data.title = val else if this.data.doi or this.data.title or this.data.url or this.data.id _L.set '#_oab_input', this.data.doi ? this.data.title ? this.data.url ? this.data.id if this.plugin is 'instantill' and not this.data.doi and not this.f?.metadata?.journal and this.data.title and this.data.title.length < 30 and this.data.title.split(' ').length < 3 this.metadata() # need more metadata for short titles else if not this.data.doi and (this.plugin is 'shareyourpaper' or (not this.data.url and not this.data.pmid and not this.data.pmcid and not this.data.title and not this.data.id)) if this.plugin is 'shareyourpaper' delete this.data.title delete this.data.url delete this.data.id _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else _L.show '#_oab_error', '<p><span>&#10060;</span> Sorry please provide the full DOI, title, citation, PMID or PMC ID.</p>' else if this.data.doi and this.plugin is 'shareyourpaper' and (this.data.doi.indexOf('10') isnt 0 or this.data.doi.indexOf('/') is -1 or this.data.doi.indexOf('.') is -1 or this.data.doi.length < 8) delete this.data.doi _L.set '#_oab_input', '' _L.gebi('_oab_input').focus() _L.show '#_oab_error', '<p>Please provide a DOI. If you\'re not sure what a DOI is, go <a id="_oab_doi_howto" href="https://library.uic.edu/help/article/1966/what-is-a-doi-and-how-do-i-use-them-in-citations" target="_blank">here</a>.</p>' else this.state() this.loading() this.data.config = this.config this.data.from ?= this.uid this.data.plugin ?= this.plugin this.data.embedded ?= window.location.href this.data.pilot ?= this.config.pilot if this.config.pilot this.data.live ?= this.config.live if this.config.live if this.demo is true and (this.data.title is 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL' or this.data.doi is '10.1234/567890' or (this.data.doi? and this.data.doi.indexOf('10.1234/oab-syp') is 0)) data = {metadata: {title: 'Engineering a Powerfully Simple Interlibrary Loan Experience with InstantILL', year: '2019', crossref_type: 'journal-article', doi: this.data.doi ? '10.1234/oab-syp-aam'}} data.metadata.journal = 'Proceedings of the 16th IFLA ILDS conference: Beyond the paywall - Resource sharing in a disruptive ecosystem' data.metadata.author = [{given: 'PI:NAME:<NAME>END_PI', family: 'PI:NAME:<NAME>END_PI'}, {given: 'PI:NAME:<NAME>END_PI', family: 'PI:NAME:<NAME>END_PI'}, {given: 'PI:NAME:<NAME>END_PI', family: 'PI:NAME:<NAME>END_PI'}, {given: 'PI:NAME:<NAME>END_PI', family: 'PI:NAME:<NAME>END_PI'}] data.ill = {subscription: {findings:{}, uid: this.uid, lookups:[], error:[], url: 'https://scholarworks.iupui.edu/bitstream/handle/1805/20422/07-PAXTON.pdf?sequence=1&isAllowed=y'}} data.permissions = { permissions: { archiving_allowed: if this.data.doi is '10.1234/oab-syp-aam' then true else false, version_allowed: if this.data.doi is '10.1234/oab-syp-aam' then "postprint" else undefined }, file: {archivable: true, archivable_reason: "Demo acceptance", version: "postprint", licence: "cc-by", same_paper: true, name: "example.pdf", format: "pdf", checksum: "example-checksum"}} if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) else _L.post( this.api+'/find' this.data (data) => if this.plugin is 'instantill' then this.findings(data) else this.permissions(data) () => _L.show '#_oab_error', '<p>Oh dear, the service is down! We\'re aware, and working to fix the problem. ' + this.contact() + '</p>' ) catch this.ping this.plugin + '_try_find_catch' _oab.css = ' <style> ._oab_form { display: inline-block; width: 100%; height: 34px; padding: 6px 12px; font-size: 1em; line-height: 1.428571429; color: #555555; vertical-align: middle; background-color: #ffffff; background-image: none; border: 1px solid #cccccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; transition: border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s; } ._oab_button { display: table-cell; height:34px; padding: 6px 3px; margin-bottom: 0; font-size: 1em; font-weight: normal; line-height: 1.428571429; text-decoration: none; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: #ffffff; background-color: #428bca; border-color: #357ebd; } </style>' _oab.instantill_template = ' <div class="_oab_panel" id="_oab_inputs"> <p id="_oab_intro"> If you need <span class="_oab_paper">an article</span> you can request it from any library in the world through Interlibrary loan. <br>Start by entering a full <span class="_oab_paper">article</span> title, citation, DOI or URL:<br> </p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. World Scientists Warning of a Climate Emergency" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" id="_oab_find" href="#" aria-label="Search" style="min-width:140px;">Find <span class="_oab_paper">article</span></a></p> <div id="_oab_book_or_other"></div> <div id="_oab_advanced_account_info"></div> </div> <div class="_oab_panel" id="_oab_findings" style="display:none;"> <div id="_oab_citation"><h2>A title</h2><p><b>And citation string, OR demo title OR Unknown <span class="_oab_paper">article</span> and refer to library</b></p></div> <p id="_oab_wrong_paper"><a class="_oab_wrong" href="#"><b>This is not the <span class="_oab_paper">article</span> I searched</b></a></p> <div class="_oab_section" id="_oab_sub_available"> <h3>We have an online copy instantly available</h3> <p>You should be able to access it on the publisher\'s website.</p> <p><a target="_blank" id="_oab_sub_url" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_oa_available"> <h3><br>There is a free, instantly accessible copy online</h3> <p>It may not be the final published version and may lack graphs or figures making it unsuitable for citations.</p> <p><a id="_oab_url" target="_blank" href="#"><b>Open <span class="_oab_paper">article</span> in a new tab</b></a></p> </div> <div class="_oab_section" id="_oab_ask_library"> <h3><br>Ask the library to digitally send you the published full-text via Interlibrary Loan</h3> <div id="_oab_cost_time"><p>It is free to you, and we\'ll usually email the link within 24 hours.<br></p></div> <div id="_oab_collect_email"> <p id="_oab_terms_note"><input type="checkbox" id="_oab_read_terms"> I have read the <a id="_oab_terms_link" target="_blank" href="#">terms and conditions</a></p> <p><input placeholder="Your university email address" id="_oab_email" type="text" class="_oab_form"></p> </div> <p><a class="_oab_submit btn-iu _oab_button _oab_loading" href="#" id="_oab_submit" style="min-width:140px;">Complete request</a></p> </div> </div> <div class="_oab_panel" id="_oab_metadata" style="display:none;"> <h2>Sorry we didn\'t find that!</h2> <p id="_oab_doi_not_in_crossref" style="display:none;">The DOI <span id="_oab_bad_doi">you entered</span> does not appear in Crossref</p> <p>Please provide or amend the <span class="_oab_paper">article</span> details.</p> <p><span class="_oab_paper">Article</span> title (required)<br><input class="_oab_form" id="_oab_title" type="text" placeholder="e.g The State of OA: A large-scale analysis of Open Access"></p> <p>Journal title (required)<br><input class="_oab_form" id="_oab_journal" type="text" placeholder="e.g. Nature"></p> <p>Year of publication (required)<br><input class="_oab_form" id="_oab_year" type="text" placeholder="e.g 1992"></p> <p><span class="_oab_paper">Article</span> DOI or URL<br><input class="_oab_form" id="_oab_doi" type="text" placeholder="e.g 10.1126/scitranslmed.3008973"></p> <p><a href="#" class="_oab_find btn-iu _oab_button _oab_loading _oab_continue" id="_oab_continue" style="min-width:140px;">Continue</a></p> <p> <a href="#" class="_oab_restart" id="_oab_try_again"><b>Try again</b></a> <span id="_oab_advanced_ill_form" style="display:none;"></span> </p> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div id="_oab_done_header"> <h2>Thanks! Your request has been received.</h2> <p>And confirmation code and tell we will email soon - OR sorry we could not create an ILL, and refer back to library if possible.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" id="_oab_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' _oab.shareyourpaper_template = ' <div class="_oab_panel" id="_oab_inputs"> <h2>Make your research visible and see 30% more citations</h2> <p><span id="_oab_lib_info">We can help you make your paper Open Access, for free, wherever you publish. It\'s legal and takes just minutes.</span> Join millions of researchers sharing their papers freely with colleagues and the public.</p> <h3>Start by entering the DOI of your paper</h3> <p>We\'ll gather information about your paper and find the easiest way to share it.</p> <p><input class="_oab_form" type="text" id="_oab_input" placeholder="e.g. 10.1126/scitranslmed.3001922" aria-label="Enter a search term" style="box-shadow:none;"></input></p> <p><a class="_oab_find btn-iu _oab_button _oab_loading" href="#" id="_oab_find" aria-label="Search" style="min-width:140px;">Next</a></p> <p><a id="_oab_nodoi" href="mailto:PI:EMAIL:<EMAIL>END_PI?subject=Help%20depositing%20my%20paper&body=Hi%2C%0D%0A%0D%0AI\'d%20like%20to%20deposit%3A%0D%0A%0D%0A%3C%3CPlease%20insert%20a%20full%20citation%3E%3E%0D%0A%0D%0ACan%20you%20please%20assist%20me%3F%0D%0A%0D%0AYours%20sincerely%2C"><b>My paper doesn\'t have a DOI</b></a></p> </div> <div class="_oab_panel" id="_oab_permissions" style="display:none;"> <div class="_oab_section _oab_oa" id="_oab_oa"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared it.</p> <p><a target="_blank" href="#" class="_oab_oa_url btn-iu _oab_button" style="min-width:140px;">See free version</a></p> <p><a href="#" class="_oab_restart" id="_oab_restart"><b>Do another</b></a></p> </div> <div class="_oab_section _oab_permission_required" id="_oab_permission_required"> <h2>You may share your paper if you ask the journal</h2> <p>Unlike most, <span class="_oab_journal">the journal</span> requires that you ask them before you share your paper freely. Asking only takes a moment as we find out who to contact and have drafted an email for you.</p> <p><a target="_blank" id="_oab_reviewemail" href="#" class="btn-iu _oab_button" style="min-width:140px;">Review Email</a></p> <p><a target="_blank" id="_oab_permissionemail" class="_oab_restart" href="#"><b>I\'ve got permission now!</b></a></p> </div> <div class="_oab_section _oab_oa_deposit" id="_oab_oa_deposit"> <h2>Your paper is already freely available!</h2> <p>Great news, you\'re already getting the benefits of sharing your work! Your publisher or co-author have already shared a <a class="_oab_oa_url" id="_oab_goto_oa_url" target="_blank" href="#">freely available copy</a>.</p> <h3 class="_oab_section _oab_get_email">Give us your email to confirm deposit</h3> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable"> <h2>You can freely share your paper now!</h2> <p><span class="_oab_library">The library has</span> checked and <span class="_oab_journal">the journal</span> encourages you to freely share <span class="_oab_your_paper">your paper</span> so colleagues and the public can freely read and cite it. <span class="_oab_refs"></span></p> <div id="_oab_not_pdf"> <h3><span>&#10003;</span> Find the manuscript the journal accepted. It\'s not a PDF from the journal site</h3> <p>This is the only version you\'re able to share legally. The accepted manuscript is the word file or Latex export you sent the publisher after peer-review and before formatting (publisher proofs).</p> <h3><span>&#10003;</span> Check there aren\'t publisher logos or formatting</h3> <p>It\'s normal to share accepted manuscripts as the research is the same. It\'s fine to save your file as a pdf, make small edits to formatting, fix typos, remove comments, and arrange figures.</p> </div> <h3 class="_oab_section _oab_get_email"><span>&#10003;</span> Tell us your email</h3> </div> <div class="_oab_section _oab_dark_deposit" id="_oab_dark_deposit"> <h2>You can share your paper!</h2> <p>We checked and unfortunately <span class="_oab_journal">the journal</span> won\'t let you share <span class="_oab_your_paper">your paper</span> freely with everyone. <span class="_oab_refs"></span><br><br> The good news is the library can still legally make your paper much easier to find and access. We\'ll put the publisher PDF in <span class="_oab_repo">ScholarWorks</span> and then share it on your behalf whenever it is requested.</p> <h3 class="_oab_section _oab_get_email">All we need is your email</h3> </div> <div class="_oab_section _oab_get_email" id="_oab_get_email"> <p><input class="_oab_form" type="text" id="_oab_email" placeholder="" aria-label="Enter your email" style="box-shadow:none;"></input></p> <p class="_oab_section _oab_oa_deposit">We\'ll use this to send you a link. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> <p class="_oab_section _oab_archivable">We\'ll only use this if something goes wrong.<br> <p class="_oab_section _oab_dark_deposit">We\'ll only use this to send you a link to your paper when it is in <span class="_oab_repo">ScholarWorks</span>. By depositing, you\'re agreeing to the <span class="_oab_terms">terms</span>.</p> </div> <div class="_oab_section _oab_archivable" id="_oab_archivable_file"> <h3>We\'ll check it\'s legal, then promote, and preserve your work</h3> <p><input type="file" name="file" id="_oab_file" class="_oab_form"></p> <p>By depositing you\'re agreeing to the <span class="_oab_terms">terms</span> and to license your work <span class="_oab_licence">CC-BY</span>.</p> </div> <div class="_oab_section _oab_oa_deposit _oab_archivable _oab_dark_deposit" id="_oab_deposits"> <p><a href="#" class="_oab_deposit btn-iu _oab_button _oab_loading" style="min-width:140px;" id="_oab_deposit">Deposit</a></p> </div> </div> <div class="_oab_panel" id="_oab_done" style="display:none;"> <div class="_oab_done" id="_oab_confirm"> <h2>Hmmm, something looks wrong</h2> <p>You\'re nearly done. It looks like what you uploaded is a publisher\'s PDF which your journal prohibits legally sharing.<!-- It can only be shared on a limited basis.--><br><br> We just need the version accepted by the journal to make your work available to everyone.</p> <p><a href="#" class="_oab_reload btn-iu _oab_button" id="_oab_upload_again" style="min-width:140px;">Try uploading again</a></p> <p><a href="#" class="_oab_confirm _oab_loading" id="_oab_upload_accept"><b>My upload was an accepted manuscript</b></a></p> </div> <div class="_oab_done" id="_oab_check"> <h2>We\'ll double check your paper</h2> <p>You\'ve done your part for now. Hopefully, we\'ll send you a link soon. First, we\'ll check in the next working day to make sure it\'s legal to share.</p> </div> <div class="_oab_done" id="_oab_partial"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_zenodo"> <h2>Congrats! Your paper will be available to everyone, forever!</h2> <div id="_oab_zenodo_embargo"></div> <p><input id="_oab_zenodo_url" class="_oab_form" type="text" style="box-shadow:none;" value=""></input></p> <p>You can now put the link on your website, CV, any profiles, and ResearchGate.</p> </div> <div class="_oab_done" id="_oab_redeposit"> <h2>Congrats, you\'re done!</h2> <p>Check back soon to see your paper live, or we\'ll email you with issues.</p> </div> <div class="_oab_done" id="_oab_success"> <h2>HPI:NAME:<NAME>END_PI, you\'re done!</h2> <p>We\'ll email you a link to your paper in <span class="_oab_repo">ScholarWorks</span> soon. Next time, before you publish check to see if your journal allows you to have the most impact by making your research available to everyone, for free.</p> </div> <div class="_oab_done" id="_oab_review"> <h2>You\'ve done your part</h2> <p>All that\'s left to do is wait. Once the journal gives you permission to share, come back and we\'ll help you finish the job.</p> </div> <p><a href="#" class="_oab_restart btn-iu _oab_button" id="_oab_done_restart" style="min-width:140px;">Do another</a></p> </div> <div id="_oab_error"></div> <div id="_oab_pilot"></div>' # can pass in a key/value pair, or key can be a config object, in which case val can optionally be a user ID string, # or key can be a user ID string and val must be empty, or key and val can both be empty and config will attempt # to be retrieved from setup, or localstorage and/or from the API if a user ID is available from setup _oab.prototype.configure = (key, val, build, preview) -> if typeof key is 'string' and not val? and key.startsWith '{' try key = JSON.parse key if typeof key is 'string' and not val? and (not this.uid? or this.uid is 'anonymous') this.uid = key key = undefined if ((typeof key is 'string' and val?) or (not key? and not val?)) and JSON.stringify(this.config) is '{}' try if this.local isnt false # can be disabled if desired, by setting local to false at setup or in url param lc = JSON.parse localStorage.getItem '_oab_config_' + this.plugin if typeof lc is 'object' and lc isnt null console.log 'Config retrieved from local storage' this.config = lc if this.remote isnt false and this.uid and this.uid isnt 'anonymous' and JSON.stringify(this.config) is '{}' # should a remote call always be made to check for superseded config if one is not provided at startup? _L.jx this.api + '/' + (if this.plugin is 'instantill' then 'ill' else 'deposit') + '/config?uid='+this.uid, undefined, (res) => console.log 'Config retrieved from API' this.configure res if this.local is false return # stop here, once the retrieve from remote works, the rest will run if typeof key is 'object' this.uid = val if typeof val is 'string' for d of key if not this.config[d]? or (this.config[d] isnt key[d] and val is true) # val true allows overwrite present values build = true if build isnt false this.config[d] = if key[d] is 'true' then true else if key[d] is 'false' then false else key[d] if val is true for cd of this.config delete this.config[cd] if cd isnt 'owner' and not key[cd]? else if key? and val? this.config[key] = if val is 'true' then true else if val is 'false' then false else val # make a "writable" config without unecessary params, such as those setting false etc # keep separate from this.config so that additional calls to configure take account of false if they do exist though this.config.pilot = Date.now() if this.config.pilot is true this.config.live = Date.now() if this.config.live is true for k of wc = JSON.parse JSON.stringify this.config delete wc[k] if not wc[k]? or wc[k] is false or ((typeof wc[k] is 'string' or Array.isArray(wc[k])) and wc[k].length is 0) try localStorage.setItem('_oab_config_' + this.plugin, JSON.stringify wc) if JSON.stringify(wc) isnt '{}' and this.local isnt false if this.css isnt false and this.config.css_off this.css = false build = true if this.bootstrap isnt false and this.config.bootstrap_off this.bootstrap = false build = true this.element ?= '#' + this.plugin _whenready = () => if _L.gebi this.element if build isnt false console.log 'Building embed' #_L.append('body', '<div id="' + this.element + '"></div>') if not _L.gebi this.element _L.html this.element, '' if not this.bootstrap? # hack test for bootstrap calls or classes in page doc dstr = document.documentElement.innerHTML this.bootstrap = dstr.indexOf('bootstrap/') isnt -1 or dstr.indexOf('/bootstrap') isnt -1 or dstr.indexOf('bootstrap.css') isnt -1 or dstr.indexOf('bootstrap.min.css') isnt -1 or dstr.indexOf('btn-') isnt -1 console.log('Found bootstrap indicators in the doc') if this.bootstrap is true if this.bootstrap is true if this.template.indexOf('btn-primary') is -1 this.template = this.template.replace(/_oab_button/g,'_oab_button btn btn-primary').replace(/_oab_form/g,'_oab_form form-control') else if this.template.indexOf('btn-primary') isnt -1 this.template = this.template.replace(/ btn btn-primary/g,'').replace(/ form-control/g,'') if typeof this.css is 'string' and this.css isnt 'false' and this.bootstrap isnt true #this.bootstrap is false this.css = '<div id="_oab_css"><style>' + this.css + '</style></div>' if not this.css.startsWith '<style>' _L.append this.element, this.css _L.append this.element, this.template _L.each '._oab_paper', (el) => cs = el.innerHTML if this.config.say_paper if cs.indexOf('aper') is -1 el.innerHTML = (if cs is 'an article' then 'a paper' else if cs is 'article' then 'paper' else 'Paper') else if cs.indexOf('aper') isnt -1 el.innerHTML = (if cs is 'a paper' then 'an article' else if cs is 'paper' then 'article' else 'Article') if this.config.pilot pilot = '<p><br>Notice a change? We\'re testing a simpler and faster way to ' + (if this.plugin is 'instantill' then 'get' else 'deposit') + ' your ' + (if this.config.say_paper then 'paper' else 'article') + (if this.plugin is 'instantill' then '' else 's') + '. You can ' pilot += '<a href="mailto:' + this.cml() + '">give feedback</a> or ' if this.plugin is 'instantill' pilot += '<a class="_oab_ping" message="instantill_use_the_old_form" target="_blank" href="' + (if this.config.advanced_ill_form then this.config.advanced_ill_form else if this.config.ill_form then this.config.ill_form else 'mailto:'+this.cml()) + '">use the old form</a>.</p>' else pilot += '<a class="_oab_ping" message="shareyourpaper_use_the_old_form" target="_blank" href="' + (if this.config.old_way then (if this.config.old_way.indexOf('@') isnt -1 then 'mailto:' else '') + this.config.old_way else 'mailto:' + this.cml()) + '">use the old way</a>.</p>' _L.html '#_oab_pilot', pilot else _L.html '#_oab_pilot', '' # shareyourpaper exclusive configs if this.plugin is 'shareyourpaper' if this.cml()? and el = _L.gebi '_oab_nodoi' el.setAttribute 'href', el.getAttribute('href').replace('PI:EMAIL:<EMAIL>END_PI', this.cml()) if this.config.not_library _L.html '._oab_library', 'We have' else _L.html '#_oab_lib_info', 'Share your paper with help from the library in ' + (this.config.repo_name ? 'ScholarWorks') + '. Legally, for free, in minutes. ' else if this.plugin is 'instantill' if this.config.book or this.config.other boro = '<p>Need ' boro += 'a <a href="' + this.config.book + '">book chapter</a>' if this.config.book boro += (if this.config.book then ' or ' else ' ') + '<a href="' + this.config.other + '">something else</a>' if this.config.other _L.html '#_oab_book_or_other', boro + '?</p>' else _L.html '#_oab_book_or_other', '' if this.config.intro_off _L.hide '#_oab_intro' if this.config.advanced_ill_form or this.config.account or this.config.ill_info aai = '<p>Or ' if this.config.advanced_ill_form _L.show '#_oab_advanced_ill_form', ' or <a href="' + this.config.advanced_ill_form + '">use full request form</a>' aai += '<a href="' + this.config.advanced_ill_form + '">use full request form</a>' if this.config.account and this.config.ill_info aai += ', ' else if this.config.account or this.config.ill_info aai += ' and ' if this.config.account aai += '<a href="' + this.config.account + '">view account</a>' aai += ' and ' if this.config.ill_info aai += '<a href="' + this.config.ill_info + '">learn about Interlibrary Loan</a>' if this.config.ill_info _L.html '#_oab_advanced_account_info', aai + '</p>' else _L.html '#_oab_advanced_account_info', '' _L.hide '#_oab_advanced_ill_form' # would be better to make _L handle the bind so that this.find works rather than having to wrap it in a function that passes context _L.listen 'enter', '#_oab_input', (e) => this.find(e) _L.listen 'enter', '#_oab_email', (e) => this.validate(e) _L.listen 'click', '._oab_find', (e) => this.find(e) _L.listen 'click', '._oab_submit', (e) => this.submit(e) _L.listen 'click', '._oab_restart', (e) => this.restart(e) _L.listen 'click', '._oab_ping', (e) => this.ping(_L.get e.target, 'message') _L.listen 'click', '._oab_wrong', (e) => e.preventDefault() this.ping '_wrong_article' this.metadata() _L.listen 'click', '._oab_reload', (e) => e.preventDefault() gf.value = '' if gf = _L.gebi "_oab_file" this.file = false this.permissions() _L.listen 'click', '._oab_confirm', (e) => e.preventDefault(); this.data.confirmed = true; this.deposit() _L.listen 'click','#_oab_reviewemail', (e) => this.done 'review' _L.listen 'click','._oab_deposit', (e) => this.deposit(e) if el = _L.gebi '_oab_config' ncwc = JSON.parse JSON.stringify wc nk = ill_institution: 'institution' # translate instantill old config keys ill_redirect_base_url: 'ill_form' ill_redirect_params: 'ill_added_params' deposit_terms: 'terms' problem_email: 'problem' viewaccount: 'account' autorun: 'autorun_off' intropara: 'intro_off' norequests: 'requests_off' illinfo: 'ill_info' noillifoa: 'ill_if_oa_off' noillifsub: 'ill_if_sub_off' saypaper: 'say_paper' advancedform: 'advanced_ill_form' deposit_date: 'depositdate' # and shareyourpaper keys deposit_terms: 'terms' allow_oa_deposit: 'oa_deposit_off' ROR_ID: 'ror' not_a_library: 'not_library' adminemail: 'email' css: 'css_off' bootstrap: 'bootstrap_off' for k of nk if ncwc[k]? ncwc[nk[k]] = ncwc[k] delete ncwc[k] el.innerHTML = JSON.stringify ncwc if window.location.search.indexOf('panel=') isnt -1 this.panel window.location.search.split('panel=')[1].split('&')[0].split('#')[0], (if window.location.search.indexOf('section=') isnt -1 then window.location.search.split('section=')[1].split('&')[0].split('#')[0] else undefined) if preview preview = this.config.val if typeof preview isnt 'string' or (typeof this.config.val is 'string' and this.config.val.length) this.data = {} this.f = {} this.loading false gf.value = '' if gf = _L.gebi "_oab_file" this.file = false _L.hide '._oab_panel' _L.show '#_oab_inputs' _L.set '#_oab_input', preview setTimeout (() => this.find()), 1 this.loaded() if typeof this.loaded is 'function' else console.log 'waiting for ' + this.element setTimeout (() => _whenready()), 100 _whenready() return wc @shareyourpaper = (opts) -> opts ?= {}; opts.plugin = 'shareyourpaper'; return new _oab(opts); @instantill = (opts) -> opts ?= {}; opts.plugin = 'instantill'; return new _oab(opts);
[ { "context": "onForDeletedUser: ->\n json =\n firstName: \"deleted\"\n lastName: \" \"\n fullName: \"deleted\"\n ", "end": 367, "score": 0.8878745436668396, "start": 360, "tag": "NAME", "value": "deleted" } ]
model/conversion/json/UserConverter._coffee
CyberCRI/KnowNodes
5
NodeConverter = require './NodeConverter' module.exports = class UserConverter extends NodeConverter @toJSON: (user, _) -> json = super(user, _) delete json.dateOfBirth delete json.email delete json.__CreatedOn__ delete json.password json.fullName = user.fullName json @getJsonForDeletedUser: -> json = firstName: "deleted" lastName: " " fullName: "deleted" KN_ID: "deleted" id: "deleted" json
127524
NodeConverter = require './NodeConverter' module.exports = class UserConverter extends NodeConverter @toJSON: (user, _) -> json = super(user, _) delete json.dateOfBirth delete json.email delete json.__CreatedOn__ delete json.password json.fullName = user.fullName json @getJsonForDeletedUser: -> json = firstName: "<NAME>" lastName: " " fullName: "deleted" KN_ID: "deleted" id: "deleted" json
true
NodeConverter = require './NodeConverter' module.exports = class UserConverter extends NodeConverter @toJSON: (user, _) -> json = super(user, _) delete json.dateOfBirth delete json.email delete json.__CreatedOn__ delete json.password json.fullName = user.fullName json @getJsonForDeletedUser: -> json = firstName: "PI:NAME:<NAME>END_PI" lastName: " " fullName: "deleted" KN_ID: "deleted" id: "deleted" json
[ { "context": "inch.js - Powerfully simple javascript routing\n\tby Rick Allen (stoodder) and Greg Smith (smrq)\n\n\tVersion 0.5.15", "end": 67, "score": 0.9998860359191895, "start": 57, "tag": "NAME", "value": "Rick Allen" }, { "context": "erfully simple javascript routing\n\tby Rick...
coffee/banner.coffee
GerHobbelt/finchjs
0
### Finch.js - Powerfully simple javascript routing by Rick Allen (stoodder) and Greg Smith (smrq) Version 0.5.15 Full source at https://github.com/stoodder/finchjs Copyright (c) 2011 RokkinCat, http://www.rokkincat.com MIT License, https://github.com/stoodder/finchjs/blob/master/LICENSE.md This file is generated by `cake build`, do not edit it by hand. ###
20903
### Finch.js - Powerfully simple javascript routing by <NAME> (stoodder) and <NAME> (smrq) Version 0.5.15 Full source at https://github.com/stoodder/finchjs Copyright (c) 2011 RokkinCat, http://www.rokkincat.com MIT License, https://github.com/stoodder/finchjs/blob/master/LICENSE.md This file is generated by `cake build`, do not edit it by hand. ###
true
### Finch.js - Powerfully simple javascript routing by PI:NAME:<NAME>END_PI (stoodder) and PI:NAME:<NAME>END_PI (smrq) Version 0.5.15 Full source at https://github.com/stoodder/finchjs Copyright (c) 2011 RokkinCat, http://www.rokkincat.com MIT License, https://github.com/stoodder/finchjs/blob/master/LICENSE.md This file is generated by `cake build`, do not edit it by hand. ###
[ { "context": " document\n author: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'post", "end": 527, "score": 0.5380920767784119, "start": 519, "tag": "USERNAME", "value": "username" }, { "context": "ngoDB projections, as an array\n reviewers...
tests.coffee
peerlibrary/meteor-peerdb
78
WAIT_FOR_DATABASE_TIMEOUT = 2000 # ms # The order of documents here tests delayed definitions # Just to make sure things are sane assert.equal Document._delayed.length, 0 assert _.isEqual Document.list, [] assert _.isEqual Document._collections, {} globalTestTriggerCounters = {} class Post extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'Post' fields: -> # We can reference other document author: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] # Or an array of documents subscribers: [@ReferenceField Person] # Fields can be arbitrary MongoDB projections, as an array reviewers: [@ReferenceField Person, [username: 1]] subdocument: # Fields can be arbitrary MongoDB projections, as an object person: @ReferenceField Person, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] nested: [ required: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField Person, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] generators: -> subdocument: slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 # Store away for testing _TestPost = Post # Extending delayed document class Post extends Post @Meta name: 'Post' replaceParent: true fields: (fields) -> fields.subdocument.persons = [@ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] fields # Store away for testing _TestPost2 = Post class User extends Document @Meta name: 'User' # Specifying collection directly collection: Meteor.users class UserLink extends Document @Meta name: 'UserLink' fields: -> user: @ReferenceField User, ['username'], false class PostLink extends Document @Meta name: 'PostLink' # Store away for testing _TestPostLink = PostLink # To test extending when initial document has no fields class PostLink extends PostLink @Meta name: 'PostLink' replaceParent: true fields: -> post: @ReferenceField Post, ['subdocument.person', 'subdocument.persons'] class CircularFirst extends Document # Other fields: # content @Meta name: 'CircularFirst' # Store away for testing _TestCircularFirst = CircularFirst # To test extending when initial document has no fields and fields will be delayed class CircularFirst extends CircularFirst @Meta name: 'CircularFirst' replaceParent: true fields: (fields) -> # We can reference circular documents fields.second = @ReferenceField CircularSecond, ['content'], true, 'reverseFirsts', ['content'] fields class CircularSecond extends Document # Other fields: # content @Meta name: 'CircularSecond' fields: -> # But of course one should not be required so that we can insert without warnings first: @ReferenceField CircularFirst, ['content'], false, 'reverseSeconds', ['content'] class Person extends Document # Other fields: # username # displayName # field1 # field2 @Meta name: 'Person' generators: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] # Store away for testing _TestPerson = Person # To test if reverse fields *are* added to the extended class which replaces the parent class Person extends Person @Meta name: 'Person' replaceParent: true formatName: -> "#{ @username }-#{ @displayName or "none" }" # To test if reverse fields are *not* added to the extended class which replaces the parent class SpecialPerson extends Person @Meta name: 'SpecialPerson' fields: -> # posts and nestedPosts don't exist, so we remove count field as well count: undefined class RecursiveBase extends Document @Meta abstract: true fields: -> other: @ReferenceField 'self', ['content'], false, 'reverse', ['content'] class Recursive extends RecursiveBase # Other fields: # content @Meta name: 'Recursive' class IdentityGenerator extends Document # Other fields: # source @Meta name: 'IdentityGenerator' generators: -> result: @GeneratedField 'self', ['source'], (fields) -> throw new Error "Test exception" if fields.source is 'exception' return [fields._id, fields.source] results: [ @GeneratedField 'self', ['source'], (fields) -> return [fields._id, fields.source] ] # Extending and renaming the class, this creates new collection as well class SpecialPost extends Post @Meta name: 'SpecialPost' fields: -> special: @ReferenceField Person # To test redefinig after fields already have a reference to an old document class Post extends Post @Meta name: 'Post' replaceParent: true # To test handling of subfield references in bulk insert class SubfieldItem extends Document @Meta name: 'SubfieldItem' fields: -> toplevel: subitem: @ReferenceField 'self', [], false objectInArray: [ subitem: @ReferenceField 'self', [], false subitem2: @ReferenceField 'self', [] ] anArray: [@ReferenceField 'self', []] class LocalPost extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'LocalPost' collection: null fields: -> author: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] subscribers: [@ReferenceField LocalPerson] reviewers: [@ReferenceField LocalPerson, [username: 1]] subdocument: person: @ReferenceField LocalPerson, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] persons: [@ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] nested: [ required: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField LocalPerson, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 class LocalPerson extends Document # Other fields: # username # displayName # field1 # field2 @Meta name: 'LocalPerson' collection: null fields: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] formatName: -> "#{ @username }-#{ @displayName or "none" }" Document.defineAll() # Just to make sure things are sane assert.equal Document._delayed.length, 0 if Meteor.isServer # Initialize the database try Post.Meta.collection._dropCollection() User.Meta.collection._dropCollection() UserLink.Meta.collection._dropCollection() PostLink.Meta.collection._dropCollection() CircularFirst.Meta.collection._dropCollection() CircularSecond.Meta.collection._dropCollection() Person.Meta.collection._dropCollection() SpecialPerson.Meta.collection._dropCollection() Recursive.Meta.collection._dropCollection() IdentityGenerator.Meta.collection._dropCollection() SpecialPost.Meta.collection._dropCollection() SubfieldItem.Meta.collection._dropCollection() catch error throw error unless /ns not found/.test "#{error}" Meteor.publish null, -> Post.documents.find() # User is already published as Meteor.users Meteor.publish null, -> UserLink.documents.find() Meteor.publish null, -> PostLink.documents.find() Meteor.publish null, -> CircularFirst.documents.find() Meteor.publish null, -> CircularSecond.documents.find() Meteor.publish null, -> Person.documents.find() Meteor.publish null, -> Recursive.documents.find() Meteor.publish null, -> IdentityGenerator.documents.find() Meteor.publish null, -> SpecialPost.documents.find() Meteor.publish null, -> SubfieldItem.documents.find() Future = Npm.require 'fibers/future' Meteor.methods 'wait-for-database': -> future = new Future() timeout = null newTimeout = -> Meteor.clearTimeout timeout if timeout timeout = Meteor.setTimeout -> timeout = null future.return() unless future.isResolved() , WAIT_FOR_DATABASE_TIMEOUT newTimeout() handles = [] for document in Document.list do (document) -> handles.push document.documents.find({}).observeChanges added: (id, fields) -> newTimeout() changed: (id, fields) -> newTimeout() removed: (id) -> newTimeout() future.wait() for handle in handles handle.stop() waitForDatabase = (test, expect) -> Meteor.call 'wait-for-database', expect (error) -> test.isFalse error, error?.toString?() or error ALL = @ALL = [User, UserLink, CircularFirst, CircularSecond, SpecialPerson, Recursive, IdentityGenerator, SpecialPost, Post, Person, PostLink, SubfieldItem, LocalPost, LocalPerson] testDocumentList = (test, list) -> test.equal Document.list, list, "expected: #{ (d.Meta._name for d in list) } vs. actual: #{ (d.Meta._name for d in Document.list) }" intersectionObjects = (array, rest...) -> _.filter _.uniq(array), (item) -> _.every rest, (other) -> _.any other, (element) -> _.isEqual element, item testSetEqual = (test, a, b) -> a ||= [] b ||= [] if a.length is b.length and intersectionObjects(a, b).length is a.length test.ok() else test.fail type: 'assert_set_equal' actual: JSON.stringify a expected: JSON.stringify b testDefinition = (test) -> test.equal Post.Meta._name, 'Post' test.equal Post.Meta.parent, _TestPost2.Meta test.equal Post.Meta.document, Post test.equal Post.Meta.collection._name, 'Posts' test.equal _.size(Post.Meta.triggers), 1 test.instanceOf Post.Meta.triggers.testTrigger, Post._Trigger test.equal Post.Meta.triggers.testTrigger.name, 'testTrigger' test.equal Post.Meta.triggers.testTrigger.document, Post test.equal Post.Meta.triggers.testTrigger.collection._name, 'Posts' test.equal Post.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(Post.Meta.generators), 2 test.equal _.size(Post.Meta.generators.subdocument), 1 test.instanceOf Post.Meta.generators.subdocument.slug, Post._GeneratedField test.isNull Post.Meta.generators.subdocument.slug.ancestorArray, Post.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction Post.Meta.generators.subdocument.slug.generator test.equal Post.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal Post.Meta.generators.subdocument.slug.sourceDocument, Post test.equal Post.Meta.generators.subdocument.slug.targetDocument, Post test.equal Post.Meta.generators.subdocument.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.generators.subdocument.slug.reverseName test.isUndefined Post.Meta.generators.subdocument.slug.reverseFields test.instanceOf Post.Meta.generators.tags, Post._GeneratedField test.equal Post.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction Post.Meta.generators.tags.generator test.equal Post.Meta.generators.tags.sourcePath, 'tags' test.equal Post.Meta.generators.tags.sourceDocument, Post test.equal Post.Meta.generators.tags.targetDocument, Post test.equal Post.Meta.generators.tags.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.tags.targetCollection._name, 'Posts' test.equal Post.Meta.generators.tags.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined Post.Meta.generators.tags.reverseName test.isUndefined Post.Meta.generators.tags.reverseFields test.equal _.size(Post.Meta.fields), 6 test.instanceOf Post.Meta.fields.author, Post._ReferenceField test.isNull Post.Meta.fields.author.ancestorArray, Post.Meta.fields.author.ancestorArray test.isTrue Post.Meta.fields.author.required test.equal Post.Meta.fields.author.sourcePath, 'author' test.equal Post.Meta.fields.author.sourceDocument, Post test.equal Post.Meta.fields.author.targetDocument, Person test.equal Post.Meta.fields.author.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.author.targetCollection._name, 'Persons' test.equal Post.Meta.fields.author.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.author.reverseName, 'posts' test.equal Post.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subscribers, Post._ReferenceField test.equal Post.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue Post.Meta.fields.subscribers.required test.equal Post.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal Post.Meta.fields.subscribers.sourceDocument, Post test.equal Post.Meta.fields.subscribers.targetDocument, Person test.equal Post.Meta.fields.subscribers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subscribers.fields, [] test.isNull Post.Meta.fields.subscribers.reverseName test.equal Post.Meta.fields.subscribers.reverseFields, [] test.instanceOf Post.Meta.fields.reviewers, Post._ReferenceField test.equal Post.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue Post.Meta.fields.reviewers.required test.equal Post.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal Post.Meta.fields.reviewers.sourceDocument, Post test.equal Post.Meta.fields.reviewers.targetDocument, Person test.equal Post.Meta.fields.reviewers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.reviewers.fields, [username: 1] test.isNull Post.Meta.fields.reviewers.reverseName test.equal Post.Meta.fields.reviewers.reverseFields, [] test.equal _.size(Post.Meta.fields.subdocument), 2 test.instanceOf Post.Meta.fields.subdocument.person, Post._ReferenceField test.isNull Post.Meta.fields.subdocument.person.ancestorArray, Post.Meta.fields.subdocument.person.ancestorArray test.isFalse Post.Meta.fields.subdocument.person.required test.equal Post.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal Post.Meta.fields.subdocument.person.sourceDocument, Post test.equal Post.Meta.fields.subdocument.person.targetDocument, Person test.equal Post.Meta.fields.subdocument.person.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal Post.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal Post.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subdocument.persons, Post._ReferenceField test.equal Post.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue Post.Meta.fields.subdocument.persons.required test.equal Post.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument, Post test.equal Post.Meta.fields.subdocument.persons.targetDocument, Person test.equal Post.Meta.fields.subdocument.persons.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal Post.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(Post.Meta.fields.nested), 3 test.instanceOf Post.Meta.fields.nested.required, Post._ReferenceField test.equal Post.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue Post.Meta.fields.nested.required.required test.equal Post.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal Post.Meta.fields.nested.required.sourceDocument, Post test.equal Post.Meta.fields.nested.required.targetDocument, Person test.equal Post.Meta.fields.nested.required.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal Post.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.nested.optional, Post._ReferenceField test.equal Post.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse Post.Meta.fields.nested.optional.required test.equal Post.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal Post.Meta.fields.nested.optional.sourceDocument, Post test.equal Post.Meta.fields.nested.optional.targetDocument, Person test.equal Post.Meta.fields.nested.optional.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.fields, ['username'] test.isNull Post.Meta.fields.nested.optional.reverseName test.equal Post.Meta.fields.nested.optional.reverseFields, [] test.instanceOf Post.Meta.fields.nested.slug, Post._GeneratedField test.equal Post.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction Post.Meta.fields.nested.slug.generator test.equal Post.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal Post.Meta.fields.nested.slug.sourceDocument, Post test.equal Post.Meta.fields.nested.slug.targetDocument, Post test.equal Post.Meta.fields.nested.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined Post.Meta.fields.nested.slug.reverseName test.isUndefined Post.Meta.fields.nested.slug.reverseFields test.instanceOf Post.Meta.fields.slug, Post._GeneratedField test.isNull Post.Meta.fields.slug.ancestorArray, Post.Meta.fields.slug.ancestorArray test.isTrue _.isFunction Post.Meta.fields.slug.generator test.equal Post.Meta.fields.slug.sourcePath, 'slug' test.equal Post.Meta.fields.slug.sourceDocument, Post test.equal Post.Meta.fields.slug.targetDocument, Post test.equal Post.Meta.fields.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.fields.slug.reverseName test.isUndefined Post.Meta.fields.slug.reverseFields test.isTrue Post.Meta._observersSetup test.equal User.Meta._name, 'User' test.isFalse User.Meta.parent test.equal User.Meta.document, User test.equal User.Meta.collection._name, 'users' test.equal _.size(User.Meta.triggers), 0 test.equal _.size(User.Meta.fields), 0 test.isTrue User.Meta._observersSetup test.equal UserLink.Meta._name, 'UserLink' test.isFalse UserLink.Meta.parent test.equal UserLink.Meta.document, UserLink test.equal UserLink.Meta.collection._name, 'UserLinks' test.equal _.size(UserLink.Meta.triggers), 0 test.equal _.size(UserLink.Meta.fields), 1 test.instanceOf UserLink.Meta.fields.user, UserLink._ReferenceField test.isNull UserLink.Meta.fields.user.ancestorArray, UserLink.Meta.fields.user.ancestorArray test.isFalse UserLink.Meta.fields.user.required test.equal UserLink.Meta.fields.user.sourcePath, 'user' test.equal UserLink.Meta.fields.user.sourceDocument, UserLink test.equal UserLink.Meta.fields.user.targetDocument, User test.equal UserLink.Meta.fields.user.sourceCollection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.targetCollection._name, 'users' test.equal UserLink.Meta.fields.user.sourceDocument.Meta.collection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.fields, ['username'] test.isNull UserLink.Meta.fields.user.reverseName test.equal UserLink.Meta.fields.user.reverseFields, [] test.isTrue UserLink.Meta._observersSetup test.equal PostLink.Meta._name, 'PostLink' test.equal PostLink.Meta.parent, _TestPostLink.Meta test.equal PostLink.Meta.document, PostLink test.equal PostLink.Meta.collection._name, 'PostLinks' test.equal _.size(PostLink.Meta.triggers), 0 test.equal _.size(PostLink.Meta.fields), 1 test.instanceOf PostLink.Meta.fields.post, PostLink._ReferenceField test.isNull PostLink.Meta.fields.post.ancestorArray, PostLink.Meta.fields.post.ancestorArray test.isTrue PostLink.Meta.fields.post.required test.equal PostLink.Meta.fields.post.sourcePath, 'post' test.equal PostLink.Meta.fields.post.sourceDocument, PostLink test.equal PostLink.Meta.fields.post.targetDocument, Post test.equal PostLink.Meta.fields.post.sourceCollection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.targetCollection._name, 'Posts' test.equal PostLink.Meta.fields.post.sourceDocument.Meta.collection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.fields, ['subdocument.person', 'subdocument.persons'] test.isNull PostLink.Meta.fields.post.reverseName test.equal PostLink.Meta.fields.post.reverseFields, [] test.isTrue PostLink.Meta._observersSetup test.equal CircularFirst.Meta._name, 'CircularFirst' test.equal CircularFirst.Meta.parent, _TestCircularFirst.Meta test.equal CircularFirst.Meta.document, CircularFirst test.equal CircularFirst.Meta.collection._name, 'CircularFirsts' test.equal _.size(CircularFirst.Meta.triggers), 0 test.equal _.size(CircularFirst.Meta.fields), 2 test.instanceOf CircularFirst.Meta.fields.second, CircularFirst._ReferenceField test.isNull CircularFirst.Meta.fields.second.ancestorArray, CircularFirst.Meta.fields.second.ancestorArray test.isTrue CircularFirst.Meta.fields.second.required test.equal CircularFirst.Meta.fields.second.sourcePath, 'second' test.equal CircularFirst.Meta.fields.second.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.second.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.second.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.fields, ['content'] test.equal CircularFirst.Meta.fields.second.reverseName, 'reverseFirsts' test.equal CircularFirst.Meta.fields.second.reverseFields, ['content'] test.instanceOf CircularFirst.Meta.fields.reverseSeconds, CircularFirst._ReferenceField test.equal CircularFirst.Meta.fields.reverseSeconds.ancestorArray, 'reverseSeconds' test.isTrue CircularFirst.Meta.fields.reverseSeconds.required test.equal CircularFirst.Meta.fields.reverseSeconds.sourcePath, 'reverseSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.reverseSeconds.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.fields, ['content'] test.isNull CircularFirst.Meta.fields.reverseSeconds.reverseName test.equal CircularFirst.Meta.fields.reverseSeconds.reverseFields, [] test.isTrue CircularFirst.Meta._observersSetup test.equal CircularSecond.Meta._name, 'CircularSecond' test.isFalse CircularSecond.Meta.parent test.equal CircularSecond.Meta.document, CircularSecond test.equal CircularSecond.Meta.collection._name, 'CircularSeconds' test.equal _.size(CircularSecond.Meta.triggers), 0 test.equal _.size(CircularSecond.Meta.fields), 2 test.instanceOf CircularSecond.Meta.fields.first, CircularSecond._ReferenceField test.isNull CircularSecond.Meta.fields.first.ancestorArray, CircularSecond.Meta.fields.first.ancestorArray test.isFalse CircularSecond.Meta.fields.first.required test.equal CircularSecond.Meta.fields.first.sourcePath, 'first' test.equal CircularSecond.Meta.fields.first.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.first.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.first.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.fields, ['content'] test.equal CircularSecond.Meta.fields.first.reverseName, 'reverseSeconds' test.equal CircularSecond.Meta.fields.first.reverseFields, ['content'] test.instanceOf CircularSecond.Meta.fields.reverseFirsts, CircularSecond._ReferenceField test.equal CircularSecond.Meta.fields.reverseFirsts.ancestorArray, 'reverseFirsts' test.isTrue CircularSecond.Meta.fields.reverseFirsts.required test.equal CircularSecond.Meta.fields.reverseFirsts.sourcePath, 'reverseFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.reverseFirsts.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.fields, ['content'] test.isNull CircularSecond.Meta.fields.reverseFirsts.reverseName test.equal CircularSecond.Meta.fields.reverseFirsts.reverseFields, [] test.isTrue CircularSecond.Meta._observersSetup test.equal Person.Meta._name, 'Person' test.equal Person.Meta.parent, _TestPerson.Meta test.equal Person.Meta.document, Person test.equal Person.Meta.collection._name, 'Persons' test.equal _.size(Person.Meta.triggers), 0 test.equal _.size(Person.Meta.generators), 1 test.instanceOf Person.Meta.generators.count, Person._GeneratedField test.isNull Person.Meta.generators.count.ancestorArray, Person.Meta.generators.count.ancestorArray test.isTrue _.isFunction Person.Meta.generators.count.generator test.equal Person.Meta.generators.count.sourcePath, 'count' test.equal Person.Meta.generators.count.sourceDocument, Person test.equal Person.Meta.generators.count.targetDocument, Person test.equal Person.Meta.generators.count.sourceCollection._name, 'Persons' test.equal Person.Meta.generators.count.targetCollection._name, 'Persons' test.equal Person.Meta.generators.count.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.targetDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined Person.Meta.generators.count.reverseName test.isUndefined Person.Meta.generators.count.reverseFields test.equal _.size(Person.Meta.fields), 4 test.instanceOf Person.Meta.fields.posts, Person._ReferenceField test.equal Person.Meta.fields.posts.ancestorArray, 'posts' test.isTrue Person.Meta.fields.posts.required test.equal Person.Meta.fields.posts.sourcePath, 'posts' test.equal Person.Meta.fields.posts.sourceDocument, Person test.equal Person.Meta.fields.posts.targetDocument, Post test.equal Person.Meta.fields.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.posts.reverseName test.equal Person.Meta.fields.posts.reverseFields, [] test.instanceOf Person.Meta.fields.nestedPosts, Person._ReferenceField test.equal Person.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue Person.Meta.fields.nestedPosts.required test.equal Person.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal Person.Meta.fields.nestedPosts.sourceDocument, Person test.equal Person.Meta.fields.nestedPosts.targetDocument, Post test.equal Person.Meta.fields.nestedPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.nestedPosts.reverseName test.equal Person.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocument.posts, Person._ReferenceField test.equal Person.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue Person.Meta.fields.subdocument.posts.required test.equal Person.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument, Person test.equal Person.Meta.fields.subdocument.posts.targetDocument, Post test.equal Person.Meta.fields.subdocument.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocument.posts.reverseName test.equal Person.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocumentsPosts, Person._ReferenceField test.equal Person.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue Person.Meta.fields.subdocumentsPosts.required test.equal Person.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument, Person test.equal Person.Meta.fields.subdocumentsPosts.targetDocument, Post test.equal Person.Meta.fields.subdocumentsPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocumentsPosts.reverseName test.equal Person.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue Person.Meta._observersSetup test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.parent, Person.Meta test.equal SpecialPerson.Meta.document, SpecialPerson test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.collection._name, 'SpecialPersons' test.equal _.size(SpecialPerson.Meta.triggers), 0 test.equal _.size(SpecialPerson.Meta.fields), 0 test.isTrue SpecialPerson.Meta._observersSetup test.equal Recursive.Meta._name, 'Recursive' test.isFalse Recursive.Meta.parent test.equal Recursive.Meta.document, Recursive test.equal Recursive.Meta.collection._name, 'Recursives' test.equal _.size(Recursive.Meta.triggers), 0 test.equal _.size(Recursive.Meta.fields), 2 test.instanceOf Recursive.Meta.fields.other, Recursive._ReferenceField test.isNull Recursive.Meta.fields.other.ancestorArray, Recursive.Meta.fields.other.ancestorArray test.isFalse Recursive.Meta.fields.other.required test.equal Recursive.Meta.fields.other.sourcePath, 'other' test.equal Recursive.Meta.fields.other.sourceDocument, Recursive test.equal Recursive.Meta.fields.other.targetDocument, Recursive test.equal Recursive.Meta.fields.other.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.fields, ['content'] test.equal Recursive.Meta.fields.other.reverseName, 'reverse' test.equal Recursive.Meta.fields.other.reverseFields, ['content'] test.instanceOf Recursive.Meta.fields.reverse, Recursive._ReferenceField test.equal Recursive.Meta.fields.reverse.ancestorArray, 'reverse' test.isTrue Recursive.Meta.fields.reverse.required test.equal Recursive.Meta.fields.reverse.sourcePath, 'reverse' test.equal Recursive.Meta.fields.reverse.sourceDocument, Recursive test.equal Recursive.Meta.fields.reverse.targetDocument, Recursive test.equal Recursive.Meta.fields.reverse.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.fields, ['content'] test.isNull Recursive.Meta.fields.reverse.reverseName test.equal Recursive.Meta.fields.reverse.reverseFields, [] test.isTrue Recursive.Meta._observersSetup test.equal IdentityGenerator.Meta._name, 'IdentityGenerator' test.isFalse IdentityGenerator.Meta.parent test.equal IdentityGenerator.Meta.document, IdentityGenerator test.equal IdentityGenerator.Meta.collection._name, 'IdentityGenerators' test.equal _.size(IdentityGenerator.Meta.triggers), 0 test.equal _.size(IdentityGenerator.Meta.generators), 2 test.instanceOf IdentityGenerator.Meta.generators.result, IdentityGenerator._GeneratedField test.isNull IdentityGenerator.Meta.generators.result.ancestorArray, IdentityGenerator.Meta.generators.result.ancestorArray test.isTrue _.isFunction IdentityGenerator.Meta.generators.result.generator test.equal IdentityGenerator.Meta.generators.result.sourcePath, 'result' test.equal IdentityGenerator.Meta.generators.result.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.result.reverseName test.isUndefined IdentityGenerator.Meta.generators.result.reverseFields test.instanceOf IdentityGenerator.Meta.generators.results, IdentityGenerator._GeneratedField test.equal IdentityGenerator.Meta.generators.results.ancestorArray, 'results' test.isTrue _.isFunction IdentityGenerator.Meta.generators.results.generator test.equal IdentityGenerator.Meta.generators.results.sourcePath, 'results' test.equal IdentityGenerator.Meta.generators.results.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.results.reverseName test.isUndefined IdentityGenerator.Meta.generators.results.reverseFields test.equal _.size(IdentityGenerator.Meta.fields), 0 test.isTrue IdentityGenerator.Meta._observersSetup test.equal SpecialPost.Meta._name, 'SpecialPost' test.equal SpecialPost.Meta.parent, _TestPost2.Meta test.equal SpecialPost.Meta.document, SpecialPost test.equal SpecialPost.Meta.collection._name, 'SpecialPosts' test.equal _.size(SpecialPost.Meta.triggers), 1 test.instanceOf SpecialPost.Meta.triggers.testTrigger, SpecialPost._Trigger test.equal SpecialPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal SpecialPost.Meta.triggers.testTrigger.document, SpecialPost test.equal SpecialPost.Meta.triggers.testTrigger.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(SpecialPost.Meta.generators), 2 test.equal _.size(SpecialPost.Meta.generators.subdocument), 1 test.instanceOf SpecialPost.Meta.generators.subdocument.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.generators.subdocument.slug.ancestorArray, SpecialPost.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.generators.subdocument.slug.generator test.equal SpecialPost.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseName test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseFields test.instanceOf SpecialPost.Meta.generators.tags, SpecialPost._GeneratedField test.equal SpecialPost.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction SpecialPost.Meta.generators.tags.generator test.equal SpecialPost.Meta.generators.tags.sourcePath, 'tags' test.equal SpecialPost.Meta.generators.tags.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined SpecialPost.Meta.generators.tags.reverseName test.isUndefined SpecialPost.Meta.generators.tags.reverseFields test.equal _.size(SpecialPost.Meta.fields), 7 test.instanceOf SpecialPost.Meta.fields.author, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.author.ancestorArray, SpecialPost.Meta.fields.author.ancestorArray test.isTrue SpecialPost.Meta.fields.author.required test.equal SpecialPost.Meta.fields.author.sourcePath, 'author' test.equal SpecialPost.Meta.fields.author.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.author.targetDocument, Person test.equal SpecialPost.Meta.fields.author.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.author.reverseName, 'posts' test.equal SpecialPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subscribers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue SpecialPost.Meta.fields.subscribers.required test.equal SpecialPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subscribers.targetDocument, Person test.equal SpecialPost.Meta.fields.subscribers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.fields, [] test.isNull SpecialPost.Meta.fields.subscribers.reverseName test.equal SpecialPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.reviewers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue SpecialPost.Meta.fields.reviewers.required test.equal SpecialPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.reviewers.targetDocument, Person test.equal SpecialPost.Meta.fields.reviewers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.fields, [username: 1] test.isNull SpecialPost.Meta.fields.reviewers.reverseName test.equal SpecialPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(SpecialPost.Meta.fields.subdocument), 2 test.instanceOf SpecialPost.Meta.fields.subdocument.person, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.subdocument.person.ancestorArray, SpecialPost.Meta.fields.subdocument.person.ancestorArray test.isFalse SpecialPost.Meta.fields.subdocument.person.required test.equal SpecialPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.person.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal SpecialPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal SpecialPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subdocument.persons, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue SpecialPost.Meta.fields.subdocument.persons.required test.equal SpecialPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.persons.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(SpecialPost.Meta.fields.nested), 3 test.instanceOf SpecialPost.Meta.fields.nested.required, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue SpecialPost.Meta.fields.nested.required.required test.equal SpecialPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.required.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.required.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal SpecialPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.nested.optional, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse SpecialPost.Meta.fields.nested.optional.required test.equal SpecialPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.optional.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.optional.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.fields, ['username'] test.isNull SpecialPost.Meta.fields.nested.optional.reverseName test.equal SpecialPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.nested.slug, SpecialPost._GeneratedField test.equal SpecialPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction SpecialPost.Meta.fields.nested.slug.generator test.equal SpecialPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseName test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.fields.slug.ancestorArray, SpecialPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.fields.slug.generator test.equal SpecialPost.Meta.fields.slug.sourcePath, 'slug' test.equal SpecialPost.Meta.fields.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.fields.slug.reverseName test.isUndefined SpecialPost.Meta.fields.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.special, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.special.ancestorArray, SpecialPost.Meta.fields.special.ancestorArray test.isTrue SpecialPost.Meta.fields.special.required test.equal SpecialPost.Meta.fields.special.sourcePath, 'special' test.equal SpecialPost.Meta.fields.special.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.special.targetDocument, Person test.equal SpecialPost.Meta.fields.special.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.fields, [] test.isNull SpecialPost.Meta.fields.special.reverseName test.equal SpecialPost.Meta.fields.special.reverseFields, [] test.isTrue SpecialPost.Meta._observersSetup test.equal LocalPost.Meta._name, 'LocalPost' test.equal LocalPost.Meta.document, LocalPost test.isNull LocalPost.Meta.collection._name test.equal _.size(LocalPost.Meta.triggers), 1 test.instanceOf LocalPost.Meta.triggers.testTrigger, LocalPost._Trigger test.equal LocalPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal LocalPost.Meta.triggers.testTrigger.document, LocalPost test.isNull LocalPost.Meta.triggers.testTrigger.collection._name test.equal LocalPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(LocalPost.Meta.fields), 7 test.instanceOf LocalPost.Meta.fields.author, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.author.ancestorArray, LocalPost.Meta.fields.author.ancestorArray test.isTrue LocalPost.Meta.fields.author.required test.equal LocalPost.Meta.fields.author.sourcePath, 'author' test.equal LocalPost.Meta.fields.author.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.author.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.author.sourceCollection._name test.isNull LocalPost.Meta.fields.author.targetCollection._name test.isNull LocalPost.Meta.fields.author.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.author.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.author.reverseName, 'posts' test.equal LocalPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subscribers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue LocalPost.Meta.fields.subscribers.required test.equal LocalPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal LocalPost.Meta.fields.subscribers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subscribers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subscribers.sourceCollection._name test.isNull LocalPost.Meta.fields.subscribers.targetCollection._name test.isNull LocalPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subscribers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subscribers.fields, [] test.isNull LocalPost.Meta.fields.subscribers.reverseName test.equal LocalPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf LocalPost.Meta.fields.reviewers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue LocalPost.Meta.fields.reviewers.required test.equal LocalPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal LocalPost.Meta.fields.reviewers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.reviewers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.reviewers.sourceCollection._name test.isNull LocalPost.Meta.fields.reviewers.targetCollection._name test.isNull LocalPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.reviewers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.reviewers.fields, [username: 1] test.isNull LocalPost.Meta.fields.reviewers.reverseName test.equal LocalPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(LocalPost.Meta.fields.subdocument), 3 test.instanceOf LocalPost.Meta.fields.subdocument.person, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.subdocument.person.ancestorArray, LocalPost.Meta.fields.subdocument.person.ancestorArray test.isFalse LocalPost.Meta.fields.subdocument.person.required test.equal LocalPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal LocalPost.Meta.fields.subdocument.person.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.person.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.person.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal LocalPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal LocalPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.persons, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue LocalPost.Meta.fields.subdocument.persons.required test.equal LocalPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal LocalPost.Meta.fields.subdocument.persons.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.persons.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.persons.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal LocalPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.subdocument.slug.ancestorArray, LocalPost.Meta.fields.subdocument.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.subdocument.slug.generator test.equal LocalPost.Meta.fields.subdocument.slug.sourcePath, 'subdocument.slug' test.equal LocalPost.Meta.fields.subdocument.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.subdocument.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseName test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseFields test.equal _.size(LocalPost.Meta.fields.nested), 3 test.instanceOf LocalPost.Meta.fields.nested.required, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue LocalPost.Meta.fields.nested.required.required test.equal LocalPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal LocalPost.Meta.fields.nested.required.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.required.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.required.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.required.targetCollection._name test.isNull LocalPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.required.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal LocalPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.nested.optional, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse LocalPost.Meta.fields.nested.optional.required test.equal LocalPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal LocalPost.Meta.fields.nested.optional.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.optional.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.optional.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.optional.targetCollection._name test.isNull LocalPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.optional.fields, ['username'] test.isNull LocalPost.Meta.fields.nested.optional.reverseName test.equal LocalPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf LocalPost.Meta.fields.nested.slug, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction LocalPost.Meta.fields.nested.slug.generator test.equal LocalPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal LocalPost.Meta.fields.nested.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.nested.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.slug.targetCollection._name test.isNull LocalPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.nested.slug.reverseName test.isUndefined LocalPost.Meta.fields.nested.slug.reverseFields test.instanceOf LocalPost.Meta.fields.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.slug.ancestorArray, LocalPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.slug.generator test.equal LocalPost.Meta.fields.slug.sourcePath, 'slug' test.equal LocalPost.Meta.fields.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.slug.targetCollection._name test.isNull LocalPost.Meta.fields.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.slug.reverseName test.isUndefined LocalPost.Meta.fields.slug.reverseFields test.instanceOf LocalPost.Meta.fields.tags, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.tags.ancestorArray, 'tags' test.isTrue _.isFunction LocalPost.Meta.fields.tags.generator test.equal LocalPost.Meta.fields.tags.sourcePath, 'tags' test.equal LocalPost.Meta.fields.tags.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.tags.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.tags.sourceCollection._name test.isNull LocalPost.Meta.fields.tags.targetCollection._name test.isNull LocalPost.Meta.fields.tags.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.tags.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.tags.reverseName test.isUndefined LocalPost.Meta.fields.tags.reverseFields test.isTrue LocalPost.Meta._observersSetup test.equal LocalPerson.Meta._name, 'LocalPerson' test.equal LocalPerson.Meta.document, LocalPerson test.isNull LocalPerson.Meta.collection._name test.equal _.size(LocalPerson.Meta.triggers), 0 test.equal _.size(LocalPerson.Meta.fields), 5 test.instanceOf LocalPerson.Meta.fields.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.posts.ancestorArray, 'posts' test.isTrue LocalPerson.Meta.fields.posts.required test.equal LocalPerson.Meta.fields.posts.sourcePath, 'posts' test.equal LocalPerson.Meta.fields.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.posts.reverseName test.equal LocalPerson.Meta.fields.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.nestedPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue LocalPerson.Meta.fields.nestedPosts.required test.equal LocalPerson.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal LocalPerson.Meta.fields.nestedPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.nestedPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.nestedPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.nestedPosts.reverseName test.equal LocalPerson.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.count, LocalPerson._GeneratedField test.isNull LocalPerson.Meta.fields.count.ancestorArray, LocalPerson.Meta.fields.count.ancestorArray test.isTrue _.isFunction LocalPerson.Meta.fields.count.generator test.equal LocalPerson.Meta.fields.count.sourcePath, 'count' test.equal LocalPerson.Meta.fields.count.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.count.targetDocument, LocalPerson test.isNull LocalPerson.Meta.fields.count.sourceCollection._name test.isNull LocalPerson.Meta.fields.count.targetCollection._name test.isNull LocalPerson.Meta.fields.count.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.count.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined LocalPerson.Meta.fields.count.reverseName test.isUndefined LocalPerson.Meta.fields.count.reverseFields test.instanceOf LocalPerson.Meta.fields.subdocument.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue LocalPerson.Meta.fields.subdocument.posts.required test.equal LocalPerson.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal LocalPerson.Meta.fields.subdocument.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocument.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocument.posts.reverseName test.equal LocalPerson.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.subdocumentsPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue LocalPerson.Meta.fields.subdocumentsPosts.required test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocumentsPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocumentsPosts.reverseName test.equal LocalPerson.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue LocalPerson.Meta._observersSetup testDocumentList test, ALL plainObject = (obj) -> return obj unless _.isObject obj return (plainObject o for o in obj) if _.isArray obj keys = _.keys obj values = (plainObject o for o in _.values obj) _.object keys, values for name, documents of {server: {Person: Person, Post: Post}, local: {Person: LocalPerson, Post: LocalPost}} do (documents) -> testAsyncMulti "peerdb - references #{name}", [ (test, expect) -> testDefinition test # We should be able to call defineAll multiple times Document.defineAll() testDefinition test documents.Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id documents.Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id documents.Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to run (but no post is yet made, so nothing really happens). # We want to wait here so that we catch possible errors in source observers, otherwise target # observers can patch things up. For example, if we create a post first and target observers # (triggered by person inserts, but pending) run afterwards, then they can patch things which # should in fact be done by source observers (on post), like setting usernames in post's # references to persons. waitForDatabase test, expect , (test, expect) -> # Should work also with no argument (defaults to {}). test.isTrue documents.Person.documents.exists() test.isTrue documents.Person.documents.find().exists() test.isTrue documents.Person.documents.exists @person1Id test.isTrue documents.Person.documents.exists @person2Id test.isTrue documents.Person.documents.exists @person3Id test.isTrue documents.Person.documents.find(@person1Id).exists() test.isTrue documents.Person.documents.find(@person2Id).exists() test.isTrue documents.Person.documents.find(@person3Id).exists() test.equal documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).count(), 3 # Test without skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).exists() # With sorting. We are testing all this combinations because there are various code paths. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}).exists() # Test with skip and limit. # This behaves differently than .count() on the server because on the server # applySkipLimit is not set. But exists do respect skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}).exists() test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}).exists() @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 documents.Post.documents.insert author: _id: @person1._id # To test what happens if all fields are not up to date username: 'wrong' displayName: 'wrong' field1: 'wrong' field2: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: 'wrong' , _id: @person3._id username: 'wrong' ] subdocument: person: _id: @person2._id username: 'wrong' persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id username: 'wrong' body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # We inserted the document only with ids - subdocuments should be # automatically populated with additional fields as defined in @ReferenceField test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res documents.Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> documents.Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res , (test, expect) -> @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person3 was removed, references should be removed as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id ] reviewers: [ _id: @person2._id username: @person2.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: null slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person2 was removed, references should be removed as well, automatically, # but lists should be kept as empty lists test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' ] documents.Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # If directly referenced document is removed, dependency is removed as well test.isFalse @post, @post ] Tinytest.add 'peerdb - invalid optional', (test) -> test.throws -> class BadPost1 extends Document @Meta name: 'BadPost1' fields: -> reviewers: [@ReferenceField Person, ['username'], false] , /Reference field directly in an array cannot be optional/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - invalid nested arrays', (test) -> test.throws -> class BadPost2 extends Document @Meta name: 'BadPost2' fields: -> nested: [ many: [@ReferenceField Person, ['username']] ] , /Field cannot be in a nested array/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - abstract with parent', (test) -> test.throws -> class BadPost4 extends Post @Meta abstract: true , /Abstract document with a parent/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() testAsyncMulti 'peerdb - circular changes', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected CircularFirst.documents.insert second: null content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@circularFirstId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Document 'CircularFirst' '#{ @circularFirstId }' field 'second' was updated with an invalid value: null" test.equal intercepted.level, 'error' @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: null content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' CircularFirst.documents.update @circularFirstId, $set: second: _id: @circularSecondId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.update @circularFirstId, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.update @circularSecondId, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2a' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2a' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2a' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.remove @circularSecondId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularSecond, @circularSecond # If directly referenced document is removed, dependency is removed as well test.isFalse @circularFirst, @circularFirst Log._intercept 1 if Meteor.isServer and Document.instances is 1 CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId , (test, expect) -> CircularFirst.documents.insert second: _id: @circularSecondId content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() test.equal intercepted.length, 0, intercepted @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.remove @circularFirstId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update document waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularFirst, @circularFirst # If directly referenced but optional document is removed, dependency is not removed as well, but set to null test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [] ] testAsyncMulti 'peerdb - recursive two', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar 1' , expect (error, recursive1Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive1Id @recursive1Id = recursive1Id Recursive.documents.insert other: null content: 'FooBar 2' , expect (error, recursive2Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive2Id @recursive2Id = recursive2Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' Recursive.documents.update @recursive1Id, $set: other: _id: @recursive2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive2Id, $set: other: _id: @recursive1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive1Id, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.update @recursive2Id, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2a' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2a' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2a' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.remove @recursive2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.isFalse @recursive2, @recursive2 test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1a' reverse: [] ] testAsyncMulti 'peerdb - recursive one', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar' , expect (error, recursiveId) => test.isFalse error, error?.toString?() or error test.isTrue recursiveId @recursiveId = recursiveId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: null content: 'FooBar' Recursive.documents.update @recursiveId, $set: other: _id: @recursiveId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBar' content: 'FooBar' reverse: [ _id: @recursiveId content: 'FooBar' ] Recursive.documents.update @recursiveId, $set: content: 'FooBara' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBara' content: 'FooBara' reverse: [ _id: @recursiveId content: 'FooBara' ] Recursive.documents.remove @recursiveId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.isFalse @recursive, @recursive ] if Meteor.isServer and Document.instances is 1 Tinytest.add 'peerdb - errors', (test) -> Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: _id: 'nonexistent' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: 'foobar' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: [ _id: 'nonexistent' ] # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' was updated with an invalid value: null" test.equal intercepted.level, 'error' Log._intercept 1 userLinkId = UserLink.documents.insert user: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() # There should be no warning because user is optional test.equal intercepted.length, 0, intercepted testAsyncMulti 'peerdb - delayed defintion', [ (test, expect) -> class BadPost5 extends Document @Meta name: 'BadPost5' fields: -> author: @ReferenceField undefined, ['username'] Log._intercept 2 # Two to see if we catch more than expected # Sleep so that error is shown Meteor.setTimeout expect(), 1000 # We need 1000 here because we have a check which runs after 1000 ms to check for delayed definitions , (test, expect) -> intercepted = Log._intercepted() # One or two because we could intercepted something else as well test.isTrue 1 <= intercepted.length <= 2, intercepted # Let's find it for i in intercepted break if i.indexOf('BadPost5') isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message.lastIndexOf("Not all delayed document definitions were successfully retried:\nBadPost5 from"), 0, intercepted.message test.equal intercepted.level, 'error' testDocumentList test, ALL test.equal Document._delayed.length, 1 # Clear delayed so that we can retry tests without errors Document._delayed = [] Document._clearDelayedCheck() ] testAsyncMulti 'peerdb - subdocument fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] PostLink.documents.insert post: _id: @post._id , expect (error, postLinkId) => test.isFalse error, error?.toString?() or error test.isTrue postLinkId @postLinkId = postLinkId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Post.documents.remove @post._id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.isFalse @postLink, @postLink ] testAsyncMulti 'peerdb - generated fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobar-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' ] Post.documents.update @postId, $set: body: null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: null body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: null body: 'NestedFooBarZ' ] body: null slug: null tags: [] Post.documents.update @postId, $unset: body: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username body: 'NestedFooBarZ' ] tags: [] ] Tinytest.add 'peerdb - chain of extended classes', (test) -> list = _.clone Document.list firstReferenceA = undefined # To force delayed secondReferenceA = undefined # To force delayed firstReferenceB = undefined # To force delayed secondReferenceB = undefined # To force delayed class First extends Document @Meta name: 'First' fields: -> first: @ReferenceField firstReferenceA class Second extends First @Meta name: 'Second' fields: (fields) -> fields.second = @ReferenceField Post # Not undefined, but overall meta will still be delayed fields class Third extends Second @Meta name: 'Third' fields: (fields) -> fields.third = @ReferenceField secondReferenceA fields testDocumentList test, ALL test.equal Document._delayed.length, 3 test.equal Document._delayed[0], First test.equal Document._delayed[1], Second test.equal Document._delayed[2], Third _TestFirst = First class First extends First @Meta name: 'First' replaceParent: true fields: (fields) -> fields.first = @ReferenceField firstReferenceB fields _TestSecond = Second class Second extends Second @Meta name: 'Second' replaceParent: true fields: (fields) -> fields.second = @ReferenceField Person # Not undefined, but overall meta will still be delayed fields _TestThird = Third class Third extends Third @Meta name: 'Third' replaceParent: true fields: (fields) -> fields.third = @ReferenceField secondReferenceB fields testDocumentList test, ALL test.equal Document._delayed.length, 6 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], Third _TestThird2 = Third class Third extends Third @Meta name: 'Third' replaceParent: true fields: (fields) -> fields.third = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 7 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third _TestFirst2 = First class First extends First @Meta name: 'First' replaceParent: true fields: (fields) -> fields.first = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 8 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], _TestFirst2 test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third test.equal Document._delayed[7], First firstReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [_TestFirst, Second] test.equal Document._delayed.length, 5 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestFirst2 test.equal Document._delayed[2], _TestThird2 test.equal Document._delayed[3], Third test.equal Document._delayed[4], First test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] firstReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First] test.equal Document._delayed.length, 3 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestThird2 test.equal Document._delayed[2], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, _TestThird] test.equal Document._delayed.length, 2 test.equal Document._delayed[0], _TestThird2 test.equal Document._delayed[1], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, Third] test.equal Document._delayed.length, 0 test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] Document.defineAll() test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test Tinytest.addAsync 'peerdb - local collections', (test, onComplete) -> list = _.clone Document.list try class Local extends Document @Meta name: 'Local' collection: null fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [Local] test.equal Document._delayed.length, 0 test.equal Local.Meta._name, 'Local' test.isFalse Local.Meta.parent test.equal Local.Meta.document, Local test.equal Local.Meta.collection._name, null test.equal _.size(Local.Meta.fields), 1 test.instanceOf Local.Meta.fields.person, Local._ReferenceField test.isNull Local.Meta.fields.person.ancestorArray, Local.Meta.fields.person.ancestorArray test.isTrue Local.Meta.fields.person.required test.equal Local.Meta.fields.person.sourcePath, 'person' test.equal Local.Meta.fields.person.sourceDocument, Local test.equal Local.Meta.fields.person.targetDocument, Person test.isFalse Local.Meta.fields.person.sourceCollection._name test.equal Local.Meta.fields.person.targetCollection._name, 'Persons' test.isFalse Local.Meta.fields.person.sourceDocument.Meta.collection._name test.equal Local.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal Local.Meta.fields.person.fields, [] test.isNull Local.Meta.fields.person.reverseName test.equal Local.Meta.fields.person.reverseFields, [] test.isTrue Local.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'Locals', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() Tinytest.addAsync 'peerdb - collections with connection', (test, onComplete) -> list = _.clone Document.list try class CollectionWithConnection extends Document @Meta name: 'CollectionWithConnection' collection: new Mongo.Collection 'CollectionWithConnections', connection: DDP.connect Meteor.absoluteUrl() fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [CollectionWithConnection] test.equal Document._delayed.length, 0 test.equal CollectionWithConnection.Meta._name, 'CollectionWithConnection' test.isFalse CollectionWithConnection.Meta.parent test.equal CollectionWithConnection.Meta.document, CollectionWithConnection test.equal CollectionWithConnection.Meta.collection._name, 'CollectionWithConnections' test.equal _.size(CollectionWithConnection.Meta.fields), 1 test.instanceOf CollectionWithConnection.Meta.fields.person, CollectionWithConnection._ReferenceField test.isNull CollectionWithConnection.Meta.fields.person.ancestorArray, CollectionWithConnection.Meta.fields.person.ancestorArray test.isTrue CollectionWithConnection.Meta.fields.person.required test.equal CollectionWithConnection.Meta.fields.person.sourcePath, 'person' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument, CollectionWithConnection test.equal CollectionWithConnection.Meta.fields.person.targetDocument, Person test.equal CollectionWithConnection.Meta.fields.person.sourceCollection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetCollection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument.Meta.collection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.fields, [] test.isNull CollectionWithConnection.Meta.fields.person.reverseName test.equal CollectionWithConnection.Meta.fields.person.reverseFields, [] test.isTrue CollectionWithConnection.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'CollectionWithConnections', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() testAsyncMulti 'peerdb - errors for generated fields', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.insert source: 'foobar' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: 'foobar' result: 'foobar' Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.update @identityGeneratorId, $set: source: ['foobar2'] , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'result' not defined as an array with selector '#{ @identityGeneratorId }' was updated with an array value: [ 'foobar2' ]" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: ['foobar2'] result: 'foobar' results: ['foobar2'] ] Tinytest.add 'peerdb - tricky references', (test) -> list = _.clone Document.list # You can in fact use class name instead of "self", but you have to # make sure things work out at the end and class is really defined class First1 extends Document @Meta name: 'First1' fields: -> first: @ReferenceField First1 Document.defineAll() test.equal First1.Meta._name, 'First1' test.isFalse First1.Meta.parent test.equal First1.Meta.document, First1 test.equal First1.Meta.collection._name, 'First1s' test.equal _.size(First1.Meta.fields), 1 test.instanceOf First1.Meta.fields.first, First1._ReferenceField test.isFalse First1.Meta.fields.first.ancestorArray, First1.Meta.fields.first.ancestorArray test.isTrue First1.Meta.fields.first.required test.equal First1.Meta.fields.first.sourcePath, 'first' test.equal First1.Meta.fields.first.sourceDocument, First1 test.equal First1.Meta.fields.first.targetDocument, First1 test.equal First1.Meta.fields.first.sourceCollection._name, 'First1s' test.equal First1.Meta.fields.first.targetCollection._name, 'First1s' test.equal First1.Meta.fields.first.sourceDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.targetDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.fields, [] # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() class First2 extends Document @Meta name: 'First2' fields: -> first: @ReferenceField undefined # To force delayed class Second2 extends Document @Meta name: 'Second2' fields: -> first: @ReferenceField First2 test.throws -> Document.defineAll true , /Target document not defined/ test.throws -> Document.defineAll() , /Invalid fields/ # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test testAsyncMulti 'peerdb - duplicate values in lists', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id # To test what happens if fields are partially not up to date username: 'wrong' displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id username: 'wrong' displayName: 'wrong' , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' , _id: @person3._id # To test if the second person3 value will be updated username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person1Id, $set: # Updating two fields at the same time field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $set: username: 'person2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $set: username: 'person3b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $unset: # Removing two fields at the same time field1: '' field2: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $set: # Restoring two fields at the same time field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.4.body': 'NestedFooBarA' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobara-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.3.body': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobara-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $unset: 'nested.2.body': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobara-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $push: nested: required: _id: @person2._id optional: _id: @person3._id body: 'NewFooBar' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-newfoobar-suffix' body: 'NewFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' 'tag-5-prefix-foobarz-newfoobar-suffix' ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person3._id ] reviewers: [ _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null slug: null body: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' ] Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.isFalse @post, @post ] if Meteor.isServer and Document.instances is 1 testAsyncMulti 'peerdb - exception while processing', [ (test, expect) -> Log._intercept 3 IdentityGenerator.documents.insert source: 'exception' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> intercepted = Log._intercepted() test.isTrue intercepted.length is 3, intercepted # We are testing only the server one, so let's find it for i in intercepted # First error message if i.indexOf('PeerDB exception: Error: Test exception') isnt -1 i = EJSON.parse i test.equal i.message, "PeerDB exception: Error: Test exception: [ { source: 'exception', _id: '#{ @identityGeneratorId }' } ]" test.equal i.level, 'error' # Stack trace error message else if i.indexOf('Error: Test exception') isnt -1 i = EJSON.parse i test.isTrue i.message.indexOf('_GeneratedField.generator') isnt -1, i.message test.equal i.level, 'error' # Invalid update error message else if i.indexOf('defined as an array with selector') isnt -1 i = EJSON.parse i test.equal i.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'exception'" test.equal i.level, 'error' else test.fail type: 'assert_never' message: i ] testAsyncMulti 'peerdb - instances', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id test.instanceOf @person1, Person test.instanceOf @person2, Person test.instanceOf @person3, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal plainObject(@person2), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal plainObject(@person3), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 test.equal @person1.formatName(), 'person1-Person 1' test.equal @person2.formatName(), 'person2-Person 2' test.equal @person3.formatName(), 'person3-Person 3' Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] SpecialPost.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = SpecialPost.documents.findOne @postId test.instanceOf @post, SpecialPost test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.instanceOf @post.special, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] special: _id: @person1._id @username = Random.id() if Meteor.isServer @userId = Accounts.createUser username: @username password: 'test' else Accounts.createUser username: @username password: 'test' , expect (error) => test.isFalse error, error?.toString?() or error @userId = Meteor.userId() unless error , (test, expect) -> @user = User.documents.findOne @userId test.instanceOf @user, User test.equal @user.username, @username ] Tinytest.add 'peerdb - bad instances', (test) -> # Empty document should be always possible to create for document in Document.list test.isTrue new document # Something simple test.isTrue new Post author: _id: Random.id() username: 'Foobar' test.throws -> new Post author: [ _id: Random.id() username: 'Foobar' ] , /Document does not match schema, not a plain object/ test.throws -> new Post subscribers: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post subdocument: [] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [ persons: [] ] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [[ persons: [] ]] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: persons: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: required: [ _id: Random.id() ] , /Document does not match schema, expected an array/ test.throws -> new Post nested: required: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: [ _id: Random.id() ] ] , /Document does not match schema, not a plain object/ if Meteor.isServer and not Document.instanceDisabled testAsyncMulti 'peerdb - update all', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id Post.documents.insert author: _id: @person1._id # To test what happens if one field is already up to date, but the other is not username: @person1.username displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'author.username': 'wrong' 'reviewers.0.username': 'wrong' 'reviewers.1.username': 'wrong' 'subdocument.person.username': 'wrong' 'subdocument.persons.0.username': 'wrong' 'subdocument.persons.1.username': 'wrong' 'nested.0.required.username': 'wrong' 'nested.0.optional.username': 'wrong' slug: 'wrong' tags: 'wrong' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # Reference fields are automatically updated back, but generated fields are not test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'wrong' tags: 'wrong' # Update all fields back (a blocking operation) Document.updateAll() # Wait so that triggered observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] ] testAsyncMulti 'peerdb - reverse posts', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person2Id body: 'NestedFooBar1' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person2Id , _id: @person3Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar1' body: 'FooBar1' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId1 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar2' ] subdocument: person: _id: @person2Id persons: [ _id: @person2Id , _id: @person2Id , _id: @person2Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar2' body: 'FooBar2' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId2 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar3' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar3' body: 'FooBar3' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId3 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post1 = Post.documents.findOne @postId1, transform: null # So that we can use test.equal @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal @post3 = Post.documents.findOne @postId3, transform: null # So that we can use test.equal test.equal @post1, _id: @postId1 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar1-subdocumentfoobar1-suffix' body: 'SubdocumentFooBar1' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar1-nestedfoobar1-suffix' body: 'NestedFooBar1' ] body: 'FooBar1' slug: 'prefix-foobar1-subdocumentfoobar1-suffix' tags: [ 'tag-0-prefix-foobar1-subdocumentfoobar1-suffix' 'tag-1-prefix-foobar1-nestedfoobar1-suffix' ] test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2-subdocumentfoobar2-suffix' body: 'SubdocumentFooBar2' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2-nestedfoobar2-suffix' body: 'NestedFooBar2' ] body: 'FooBar2' slug: 'prefix-foobar2-subdocumentfoobar2-suffix' tags: [ 'tag-0-prefix-foobar2-subdocumentfoobar2-suffix' 'tag-1-prefix-foobar2-nestedfoobar2-suffix' ] test.equal @post3, _id: @postId3 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar3-subdocumentfoobar3-suffix' body: 'SubdocumentFooBar3' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar3-nestedfoobar3-suffix' body: 'NestedFooBar3' ] body: 'FooBar3' slug: 'prefix-foobar3-subdocumentfoobar3-suffix' tags: [ 'tag-0-prefix-foobar3-subdocumentfoobar3-suffix' 'tag-1-prefix-foobar3-nestedfoobar3-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 8 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 5 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person2Id ] body: 'SubdocumentFooBar4' body: 'FooBar4' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId4 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' ] subdocument: person: _id: @person3Id persons: [ _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar5' body: 'FooBar5' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId5 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] Post.documents.update @postId1, $set: 'body': 'FooBar1a' 'subdocument.body': 'SubdocumentFooBar1a' 'nested.0.body': 'NestedFooBar1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId2, $set: 'body': 'FooBar2a' 'subdocument.body': 'SubdocumentFooBar2a' 'nested.0.body': 'NestedFooBar2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId3, $set: 'body': 'FooBar3a' 'subdocument.body': 'SubdocumentFooBar3a' 'nested.0.body': 'NestedFooBar3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId4, $set: 'body': 'FooBar4a' 'subdocument.body': 'SubdocumentFooBar4a' 'nested.1.body': 'NestedFooBar4a' 'nested.3.body': 'NestedFooBar4a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId5, $set: 'body': 'FooBar5a' 'subdocument.body': 'SubdocumentFooBar5a' 'nested.1.body': 'NestedFooBar5a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $push: nested: required: _id: @person2Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId2, $push: nested: required: _id: @person3Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: null persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $unset: 'subdocument.person': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: author: _id: @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person2Id username: 'person2' displayName: 'Person 2' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.remove @postId5, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 7 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 6 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId2, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 10 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 4 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId3, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 7 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 4 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 2 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] for id in [@postId1, @postId2, @postId3, @postId4, @postId5] Post.documents.update _id: id , $set: nested: [] , expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 6 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 2 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 1 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [] ] if Meteor.isServer testAsyncMulti 'peerdb - triggers', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id test.instanceOf @person1, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person1.formatName(), 'person1-Person 1' Post.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] SpecialPost.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @specialPostId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 1 test.equal globalTestTriggerCounters[@specialPostId], 1 Post.documents.update @postId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar 1' tags: [] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar 1' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 Post.documents.update @postId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 ] testAsyncMulti 'peerdb - reverse fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 @changes = [] @handle = Person.documents.find(@person1Id).observe changed: (newDocument, oldDocument) => @changes.push newDocument Post.documents.insert author: _id: @person1._id subdocument: persons: [] body: 'SubdocumentFooBar' nested: [] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 1 posts: [ _id: @postId body: 'FooBar' nested: [] subdocument: body: 'SubdocumentFooBar' ] # This test is checking that all fields in reverse field subdocuments are populated # from the beginning. Otherwise there might be a short but existing time when # document does not match the schema, and is published as such to the client. for person in @changes for post in person.posts test.equal post.body, 'FooBar' test.equal post.nested, [] test.equal post.subdocument?.body, 'SubdocumentFooBar' @handle.stop() ] testAsyncMulti 'peerdb - bulk insert', [ (test, expect) -> @testContent = for i in [0..100] content: Random.id() ids = Recursive.documents.bulkInsert @testContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids?.length, @testContent.length @testIds = ids test.isTrue ids test.equal ids?.length, @testContent.length # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> docs = Recursive.documents.find( _id: $in: @testIds , fields: _id: 0 content: 1 transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> randomIds = for i in [0...100] Random.id() insertContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other reverse: [ _id: reverse ] @testContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other content: other reverse: [ _id: reverse content: reverse ] ids = Recursive.documents.bulkInsert insertContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids, _.pluck @testContent, '_id' test.equal ids, _.pluck @testContent, '_id' # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> # We sleep a bit so that all changes get to the client, when rnning on the client. Meteor.setTimeout expect(), 200 , (test, expect) -> docs = Recursive.documents.find( _id: $in: _.pluck(@testContent, '_id') , transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> # Test bulkInsert without any arguments. Recursive.documents.bulkInsert [] ] testAsyncMulti 'peerdb - bulk insert with subfield references', [ (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, _.extend {objectInArray: [], anArray: []}, @item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id item = _.extend {objectInArray: [], anArray: []}, @item # Missing references should be set to null. item.toplevel.subitem = null test.equal insertedItem, item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem: _id: itemId subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item # To make sure there are no residual observes going into @changes. waitForDatabase test, expect , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] @changes = [] initializing = true @handle = SubfieldItem.documents.find().observeChanges added: (id, fields) => @changes.push {type: 'added', id, fields} unless initializing changed: (id, fields) => @changes.push {type: 'changed', id, fields} initializing = false SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: hello: "world" toplevel: anotherA: "hello" anotherB: "world" , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray', 'toplevel' ] @changes = [] itemId = Random.id() @item._id = itemId SubfieldItem.documents.bulkInsert [@item], {dontDelay: ['toplevel.subitem']}, expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: _.pick @item, 'hello', 'toplevel' , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray' ] @handle.stop() ] Tinytest.add 'peerdb - local documents', (test) -> testDefinition test class ReallyLocalPost extends Post @Meta name: 'ReallyLocalPost' collection: null local: true testDefinition test
119565
WAIT_FOR_DATABASE_TIMEOUT = 2000 # ms # The order of documents here tests delayed definitions # Just to make sure things are sane assert.equal Document._delayed.length, 0 assert _.isEqual Document.list, [] assert _.isEqual Document._collections, {} globalTestTriggerCounters = {} class Post extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'Post' fields: -> # We can reference other document author: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] # Or an array of documents subscribers: [@ReferenceField Person] # Fields can be arbitrary MongoDB projections, as an array reviewers: [@ReferenceField Person, [username: 1]] subdocument: # Fields can be arbitrary MongoDB projections, as an object person: @ReferenceField Person, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] nested: [ required: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField Person, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] generators: -> subdocument: slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 # Store away for testing _TestPost = Post # Extending delayed document class Post extends Post @Meta name: 'Post' replaceParent: true fields: (fields) -> fields.subdocument.persons = [@ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] fields # Store away for testing _TestPost2 = Post class User extends Document @Meta name: 'User' # Specifying collection directly collection: Meteor.users class UserLink extends Document @Meta name: 'UserLink' fields: -> user: @ReferenceField User, ['username'], false class PostLink extends Document @Meta name: 'PostLink' # Store away for testing _TestPostLink = PostLink # To test extending when initial document has no fields class PostLink extends PostLink @Meta name: 'PostLink' replaceParent: true fields: -> post: @ReferenceField Post, ['subdocument.person', 'subdocument.persons'] class CircularFirst extends Document # Other fields: # content @Meta name: 'CircularFirst' # Store away for testing _TestCircularFirst = CircularFirst # To test extending when initial document has no fields and fields will be delayed class CircularFirst extends CircularFirst @Meta name: 'CircularFirst' replaceParent: true fields: (fields) -> # We can reference circular documents fields.second = @ReferenceField CircularSecond, ['content'], true, 'reverseFirsts', ['content'] fields class CircularSecond extends Document # Other fields: # content @Meta name: 'CircularSecond' fields: -> # But of course one should not be required so that we can insert without warnings first: @ReferenceField CircularFirst, ['content'], false, 'reverseSeconds', ['content'] class Person extends Document # Other fields: # username # <NAME> # field1 # field2 @Meta name: 'Person' generators: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] # Store away for testing _TestPerson = Person # To test if reverse fields *are* added to the extended class which replaces the parent class Person extends Person @Meta name: 'Person' replaceParent: true formatName: -> "#{ @username }-#{ @displayName or "none" }" # To test if reverse fields are *not* added to the extended class which replaces the parent class SpecialPerson extends Person @Meta name: 'SpecialPerson' fields: -> # posts and nestedPosts don't exist, so we remove count field as well count: undefined class RecursiveBase extends Document @Meta abstract: true fields: -> other: @ReferenceField 'self', ['content'], false, 'reverse', ['content'] class Recursive extends RecursiveBase # Other fields: # content @Meta name: 'Recursive' class IdentityGenerator extends Document # Other fields: # source @Meta name: 'IdentityGenerator' generators: -> result: @GeneratedField 'self', ['source'], (fields) -> throw new Error "Test exception" if fields.source is 'exception' return [fields._id, fields.source] results: [ @GeneratedField 'self', ['source'], (fields) -> return [fields._id, fields.source] ] # Extending and renaming the class, this creates new collection as well class SpecialPost extends Post @Meta name: 'SpecialPost' fields: -> special: @ReferenceField Person # To test redefinig after fields already have a reference to an old document class Post extends Post @Meta name: 'Post' replaceParent: true # To test handling of subfield references in bulk insert class SubfieldItem extends Document @Meta name: 'SubfieldItem' fields: -> toplevel: subitem: @ReferenceField 'self', [], false objectInArray: [ subitem: @ReferenceField 'self', [], false subitem2: @ReferenceField 'self', [] ] anArray: [@ReferenceField 'self', []] class LocalPost extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'LocalPost' collection: null fields: -> author: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] subscribers: [@ReferenceField LocalPerson] reviewers: [@ReferenceField LocalPerson, [username: 1]] subdocument: person: @ReferenceField LocalPerson, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] persons: [@ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] nested: [ required: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField LocalPerson, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 class LocalPerson extends Document # Other fields: # username # <NAME> # field1 # field2 @Meta name: 'LocalPerson' collection: null fields: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] formatName: -> "#{ @username }-#{ @displayName or "none" }" Document.defineAll() # Just to make sure things are sane assert.equal Document._delayed.length, 0 if Meteor.isServer # Initialize the database try Post.Meta.collection._dropCollection() User.Meta.collection._dropCollection() UserLink.Meta.collection._dropCollection() PostLink.Meta.collection._dropCollection() CircularFirst.Meta.collection._dropCollection() CircularSecond.Meta.collection._dropCollection() Person.Meta.collection._dropCollection() SpecialPerson.Meta.collection._dropCollection() Recursive.Meta.collection._dropCollection() IdentityGenerator.Meta.collection._dropCollection() SpecialPost.Meta.collection._dropCollection() SubfieldItem.Meta.collection._dropCollection() catch error throw error unless /ns not found/.test "#{error}" Meteor.publish null, -> Post.documents.find() # User is already published as Meteor.users Meteor.publish null, -> UserLink.documents.find() Meteor.publish null, -> PostLink.documents.find() Meteor.publish null, -> CircularFirst.documents.find() Meteor.publish null, -> CircularSecond.documents.find() Meteor.publish null, -> Person.documents.find() Meteor.publish null, -> Recursive.documents.find() Meteor.publish null, -> IdentityGenerator.documents.find() Meteor.publish null, -> SpecialPost.documents.find() Meteor.publish null, -> SubfieldItem.documents.find() Future = Npm.require 'fibers/future' Meteor.methods 'wait-for-database': -> future = new Future() timeout = null newTimeout = -> Meteor.clearTimeout timeout if timeout timeout = Meteor.setTimeout -> timeout = null future.return() unless future.isResolved() , WAIT_FOR_DATABASE_TIMEOUT newTimeout() handles = [] for document in Document.list do (document) -> handles.push document.documents.find({}).observeChanges added: (id, fields) -> newTimeout() changed: (id, fields) -> newTimeout() removed: (id) -> newTimeout() future.wait() for handle in handles handle.stop() waitForDatabase = (test, expect) -> Meteor.call 'wait-for-database', expect (error) -> test.isFalse error, error?.toString?() or error ALL = @ALL = [User, UserLink, CircularFirst, CircularSecond, SpecialPerson, Recursive, IdentityGenerator, SpecialPost, Post, Person, PostLink, SubfieldItem, LocalPost, LocalPerson] testDocumentList = (test, list) -> test.equal Document.list, list, "expected: #{ (d.Meta._name for d in list) } vs. actual: #{ (d.Meta._name for d in Document.list) }" intersectionObjects = (array, rest...) -> _.filter _.uniq(array), (item) -> _.every rest, (other) -> _.any other, (element) -> _.isEqual element, item testSetEqual = (test, a, b) -> a ||= [] b ||= [] if a.length is b.length and intersectionObjects(a, b).length is a.length test.ok() else test.fail type: 'assert_set_equal' actual: JSON.stringify a expected: JSON.stringify b testDefinition = (test) -> test.equal Post.Meta._name, 'Post' test.equal Post.Meta.parent, _TestPost2.Meta test.equal Post.Meta.document, Post test.equal Post.Meta.collection._name, 'Posts' test.equal _.size(Post.Meta.triggers), 1 test.instanceOf Post.Meta.triggers.testTrigger, Post._Trigger test.equal Post.Meta.triggers.testTrigger.name, 'testTrigger' test.equal Post.Meta.triggers.testTrigger.document, Post test.equal Post.Meta.triggers.testTrigger.collection._name, 'Posts' test.equal Post.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(Post.Meta.generators), 2 test.equal _.size(Post.Meta.generators.subdocument), 1 test.instanceOf Post.Meta.generators.subdocument.slug, Post._GeneratedField test.isNull Post.Meta.generators.subdocument.slug.ancestorArray, Post.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction Post.Meta.generators.subdocument.slug.generator test.equal Post.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal Post.Meta.generators.subdocument.slug.sourceDocument, Post test.equal Post.Meta.generators.subdocument.slug.targetDocument, Post test.equal Post.Meta.generators.subdocument.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.generators.subdocument.slug.reverseName test.isUndefined Post.Meta.generators.subdocument.slug.reverseFields test.instanceOf Post.Meta.generators.tags, Post._GeneratedField test.equal Post.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction Post.Meta.generators.tags.generator test.equal Post.Meta.generators.tags.sourcePath, 'tags' test.equal Post.Meta.generators.tags.sourceDocument, Post test.equal Post.Meta.generators.tags.targetDocument, Post test.equal Post.Meta.generators.tags.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.tags.targetCollection._name, 'Posts' test.equal Post.Meta.generators.tags.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined Post.Meta.generators.tags.reverseName test.isUndefined Post.Meta.generators.tags.reverseFields test.equal _.size(Post.Meta.fields), 6 test.instanceOf Post.Meta.fields.author, Post._ReferenceField test.isNull Post.Meta.fields.author.ancestorArray, Post.Meta.fields.author.ancestorArray test.isTrue Post.Meta.fields.author.required test.equal Post.Meta.fields.author.sourcePath, 'author' test.equal Post.Meta.fields.author.sourceDocument, Post test.equal Post.Meta.fields.author.targetDocument, Person test.equal Post.Meta.fields.author.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.author.targetCollection._name, 'Persons' test.equal Post.Meta.fields.author.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.author.reverseName, 'posts' test.equal Post.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subscribers, Post._ReferenceField test.equal Post.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue Post.Meta.fields.subscribers.required test.equal Post.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal Post.Meta.fields.subscribers.sourceDocument, Post test.equal Post.Meta.fields.subscribers.targetDocument, Person test.equal Post.Meta.fields.subscribers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subscribers.fields, [] test.isNull Post.Meta.fields.subscribers.reverseName test.equal Post.Meta.fields.subscribers.reverseFields, [] test.instanceOf Post.Meta.fields.reviewers, Post._ReferenceField test.equal Post.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue Post.Meta.fields.reviewers.required test.equal Post.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal Post.Meta.fields.reviewers.sourceDocument, Post test.equal Post.Meta.fields.reviewers.targetDocument, Person test.equal Post.Meta.fields.reviewers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.reviewers.fields, [username: 1] test.isNull Post.Meta.fields.reviewers.reverseName test.equal Post.Meta.fields.reviewers.reverseFields, [] test.equal _.size(Post.Meta.fields.subdocument), 2 test.instanceOf Post.Meta.fields.subdocument.person, Post._ReferenceField test.isNull Post.Meta.fields.subdocument.person.ancestorArray, Post.Meta.fields.subdocument.person.ancestorArray test.isFalse Post.Meta.fields.subdocument.person.required test.equal Post.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal Post.Meta.fields.subdocument.person.sourceDocument, Post test.equal Post.Meta.fields.subdocument.person.targetDocument, Person test.equal Post.Meta.fields.subdocument.person.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal Post.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal Post.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subdocument.persons, Post._ReferenceField test.equal Post.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue Post.Meta.fields.subdocument.persons.required test.equal Post.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument, Post test.equal Post.Meta.fields.subdocument.persons.targetDocument, Person test.equal Post.Meta.fields.subdocument.persons.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal Post.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(Post.Meta.fields.nested), 3 test.instanceOf Post.Meta.fields.nested.required, Post._ReferenceField test.equal Post.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue Post.Meta.fields.nested.required.required test.equal Post.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal Post.Meta.fields.nested.required.sourceDocument, Post test.equal Post.Meta.fields.nested.required.targetDocument, Person test.equal Post.Meta.fields.nested.required.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal Post.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.nested.optional, Post._ReferenceField test.equal Post.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse Post.Meta.fields.nested.optional.required test.equal Post.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal Post.Meta.fields.nested.optional.sourceDocument, Post test.equal Post.Meta.fields.nested.optional.targetDocument, Person test.equal Post.Meta.fields.nested.optional.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.fields, ['username'] test.isNull Post.Meta.fields.nested.optional.reverseName test.equal Post.Meta.fields.nested.optional.reverseFields, [] test.instanceOf Post.Meta.fields.nested.slug, Post._GeneratedField test.equal Post.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction Post.Meta.fields.nested.slug.generator test.equal Post.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal Post.Meta.fields.nested.slug.sourceDocument, Post test.equal Post.Meta.fields.nested.slug.targetDocument, Post test.equal Post.Meta.fields.nested.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined Post.Meta.fields.nested.slug.reverseName test.isUndefined Post.Meta.fields.nested.slug.reverseFields test.instanceOf Post.Meta.fields.slug, Post._GeneratedField test.isNull Post.Meta.fields.slug.ancestorArray, Post.Meta.fields.slug.ancestorArray test.isTrue _.isFunction Post.Meta.fields.slug.generator test.equal Post.Meta.fields.slug.sourcePath, 'slug' test.equal Post.Meta.fields.slug.sourceDocument, Post test.equal Post.Meta.fields.slug.targetDocument, Post test.equal Post.Meta.fields.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.fields.slug.reverseName test.isUndefined Post.Meta.fields.slug.reverseFields test.isTrue Post.Meta._observersSetup test.equal User.Meta._name, 'User' test.isFalse User.Meta.parent test.equal User.Meta.document, User test.equal User.Meta.collection._name, 'users' test.equal _.size(User.Meta.triggers), 0 test.equal _.size(User.Meta.fields), 0 test.isTrue User.Meta._observersSetup test.equal UserLink.Meta._name, 'UserLink' test.isFalse UserLink.Meta.parent test.equal UserLink.Meta.document, UserLink test.equal UserLink.Meta.collection._name, 'UserLinks' test.equal _.size(UserLink.Meta.triggers), 0 test.equal _.size(UserLink.Meta.fields), 1 test.instanceOf UserLink.Meta.fields.user, UserLink._ReferenceField test.isNull UserLink.Meta.fields.user.ancestorArray, UserLink.Meta.fields.user.ancestorArray test.isFalse UserLink.Meta.fields.user.required test.equal UserLink.Meta.fields.user.sourcePath, 'user' test.equal UserLink.Meta.fields.user.sourceDocument, UserLink test.equal UserLink.Meta.fields.user.targetDocument, User test.equal UserLink.Meta.fields.user.sourceCollection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.targetCollection._name, 'users' test.equal UserLink.Meta.fields.user.sourceDocument.Meta.collection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.fields, ['username'] test.isNull UserLink.Meta.fields.user.reverseName test.equal UserLink.Meta.fields.user.reverseFields, [] test.isTrue UserLink.Meta._observersSetup test.equal PostLink.Meta._name, 'PostLink' test.equal PostLink.Meta.parent, _TestPostLink.Meta test.equal PostLink.Meta.document, PostLink test.equal PostLink.Meta.collection._name, 'PostLinks' test.equal _.size(PostLink.Meta.triggers), 0 test.equal _.size(PostLink.Meta.fields), 1 test.instanceOf PostLink.Meta.fields.post, PostLink._ReferenceField test.isNull PostLink.Meta.fields.post.ancestorArray, PostLink.Meta.fields.post.ancestorArray test.isTrue PostLink.Meta.fields.post.required test.equal PostLink.Meta.fields.post.sourcePath, 'post' test.equal PostLink.Meta.fields.post.sourceDocument, PostLink test.equal PostLink.Meta.fields.post.targetDocument, Post test.equal PostLink.Meta.fields.post.sourceCollection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.targetCollection._name, 'Posts' test.equal PostLink.Meta.fields.post.sourceDocument.Meta.collection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.fields, ['subdocument.person', 'subdocument.persons'] test.isNull PostLink.Meta.fields.post.reverseName test.equal PostLink.Meta.fields.post.reverseFields, [] test.isTrue PostLink.Meta._observersSetup test.equal CircularFirst.Meta._name, 'CircularFirst' test.equal CircularFirst.Meta.parent, _TestCircularFirst.Meta test.equal CircularFirst.Meta.document, CircularFirst test.equal CircularFirst.Meta.collection._name, 'CircularFirsts' test.equal _.size(CircularFirst.Meta.triggers), 0 test.equal _.size(CircularFirst.Meta.fields), 2 test.instanceOf CircularFirst.Meta.fields.second, CircularFirst._ReferenceField test.isNull CircularFirst.Meta.fields.second.ancestorArray, CircularFirst.Meta.fields.second.ancestorArray test.isTrue CircularFirst.Meta.fields.second.required test.equal CircularFirst.Meta.fields.second.sourcePath, 'second' test.equal CircularFirst.Meta.fields.second.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.second.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.second.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.fields, ['content'] test.equal CircularFirst.Meta.fields.second.reverseName, 'reverseFirsts' test.equal CircularFirst.Meta.fields.second.reverseFields, ['content'] test.instanceOf CircularFirst.Meta.fields.reverseSeconds, CircularFirst._ReferenceField test.equal CircularFirst.Meta.fields.reverseSeconds.ancestorArray, 'reverseSeconds' test.isTrue CircularFirst.Meta.fields.reverseSeconds.required test.equal CircularFirst.Meta.fields.reverseSeconds.sourcePath, 'reverseSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.reverseSeconds.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.fields, ['content'] test.isNull CircularFirst.Meta.fields.reverseSeconds.reverseName test.equal CircularFirst.Meta.fields.reverseSeconds.reverseFields, [] test.isTrue CircularFirst.Meta._observersSetup test.equal CircularSecond.Meta._name, 'CircularSecond' test.isFalse CircularSecond.Meta.parent test.equal CircularSecond.Meta.document, CircularSecond test.equal CircularSecond.Meta.collection._name, 'CircularSeconds' test.equal _.size(CircularSecond.Meta.triggers), 0 test.equal _.size(CircularSecond.Meta.fields), 2 test.instanceOf CircularSecond.Meta.fields.first, CircularSecond._ReferenceField test.isNull CircularSecond.Meta.fields.first.ancestorArray, CircularSecond.Meta.fields.first.ancestorArray test.isFalse CircularSecond.Meta.fields.first.required test.equal CircularSecond.Meta.fields.first.sourcePath, 'first' test.equal CircularSecond.Meta.fields.first.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.first.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.first.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.fields, ['content'] test.equal CircularSecond.Meta.fields.first.reverseName, 'reverseSeconds' test.equal CircularSecond.Meta.fields.first.reverseFields, ['content'] test.instanceOf CircularSecond.Meta.fields.reverseFirsts, CircularSecond._ReferenceField test.equal CircularSecond.Meta.fields.reverseFirsts.ancestorArray, 'reverseFirsts' test.isTrue CircularSecond.Meta.fields.reverseFirsts.required test.equal CircularSecond.Meta.fields.reverseFirsts.sourcePath, 'reverseFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.reverseFirsts.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.fields, ['content'] test.isNull CircularSecond.Meta.fields.reverseFirsts.reverseName test.equal CircularSecond.Meta.fields.reverseFirsts.reverseFields, [] test.isTrue CircularSecond.Meta._observersSetup test.equal Person.Meta._name, 'Person' test.equal Person.Meta.parent, _TestPerson.Meta test.equal Person.Meta.document, Person test.equal Person.Meta.collection._name, 'Persons' test.equal _.size(Person.Meta.triggers), 0 test.equal _.size(Person.Meta.generators), 1 test.instanceOf Person.Meta.generators.count, Person._GeneratedField test.isNull Person.Meta.generators.count.ancestorArray, Person.Meta.generators.count.ancestorArray test.isTrue _.isFunction Person.Meta.generators.count.generator test.equal Person.Meta.generators.count.sourcePath, 'count' test.equal Person.Meta.generators.count.sourceDocument, Person test.equal Person.Meta.generators.count.targetDocument, Person test.equal Person.Meta.generators.count.sourceCollection._name, 'Persons' test.equal Person.Meta.generators.count.targetCollection._name, 'Persons' test.equal Person.Meta.generators.count.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.targetDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined Person.Meta.generators.count.reverseName test.isUndefined Person.Meta.generators.count.reverseFields test.equal _.size(Person.Meta.fields), 4 test.instanceOf Person.Meta.fields.posts, Person._ReferenceField test.equal Person.Meta.fields.posts.ancestorArray, 'posts' test.isTrue Person.Meta.fields.posts.required test.equal Person.Meta.fields.posts.sourcePath, 'posts' test.equal Person.Meta.fields.posts.sourceDocument, Person test.equal Person.Meta.fields.posts.targetDocument, Post test.equal Person.Meta.fields.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.posts.reverseName test.equal Person.Meta.fields.posts.reverseFields, [] test.instanceOf Person.Meta.fields.nestedPosts, Person._ReferenceField test.equal Person.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue Person.Meta.fields.nestedPosts.required test.equal Person.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal Person.Meta.fields.nestedPosts.sourceDocument, Person test.equal Person.Meta.fields.nestedPosts.targetDocument, Post test.equal Person.Meta.fields.nestedPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.nestedPosts.reverseName test.equal Person.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocument.posts, Person._ReferenceField test.equal Person.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue Person.Meta.fields.subdocument.posts.required test.equal Person.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument, Person test.equal Person.Meta.fields.subdocument.posts.targetDocument, Post test.equal Person.Meta.fields.subdocument.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocument.posts.reverseName test.equal Person.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocumentsPosts, Person._ReferenceField test.equal Person.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue Person.Meta.fields.subdocumentsPosts.required test.equal Person.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument, Person test.equal Person.Meta.fields.subdocumentsPosts.targetDocument, Post test.equal Person.Meta.fields.subdocumentsPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocumentsPosts.reverseName test.equal Person.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue Person.Meta._observersSetup test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.parent, Person.Meta test.equal SpecialPerson.Meta.document, SpecialPerson test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.collection._name, 'SpecialPersons' test.equal _.size(SpecialPerson.Meta.triggers), 0 test.equal _.size(SpecialPerson.Meta.fields), 0 test.isTrue SpecialPerson.Meta._observersSetup test.equal Recursive.Meta._name, 'Recursive' test.isFalse Recursive.Meta.parent test.equal Recursive.Meta.document, Recursive test.equal Recursive.Meta.collection._name, 'Recursives' test.equal _.size(Recursive.Meta.triggers), 0 test.equal _.size(Recursive.Meta.fields), 2 test.instanceOf Recursive.Meta.fields.other, Recursive._ReferenceField test.isNull Recursive.Meta.fields.other.ancestorArray, Recursive.Meta.fields.other.ancestorArray test.isFalse Recursive.Meta.fields.other.required test.equal Recursive.Meta.fields.other.sourcePath, 'other' test.equal Recursive.Meta.fields.other.sourceDocument, Recursive test.equal Recursive.Meta.fields.other.targetDocument, Recursive test.equal Recursive.Meta.fields.other.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.fields, ['content'] test.equal Recursive.Meta.fields.other.reverseName, 'reverse' test.equal Recursive.Meta.fields.other.reverseFields, ['content'] test.instanceOf Recursive.Meta.fields.reverse, Recursive._ReferenceField test.equal Recursive.Meta.fields.reverse.ancestorArray, 'reverse' test.isTrue Recursive.Meta.fields.reverse.required test.equal Recursive.Meta.fields.reverse.sourcePath, 'reverse' test.equal Recursive.Meta.fields.reverse.sourceDocument, Recursive test.equal Recursive.Meta.fields.reverse.targetDocument, Recursive test.equal Recursive.Meta.fields.reverse.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.fields, ['content'] test.isNull Recursive.Meta.fields.reverse.reverseName test.equal Recursive.Meta.fields.reverse.reverseFields, [] test.isTrue Recursive.Meta._observersSetup test.equal IdentityGenerator.Meta._name, 'IdentityGenerator' test.isFalse IdentityGenerator.Meta.parent test.equal IdentityGenerator.Meta.document, IdentityGenerator test.equal IdentityGenerator.Meta.collection._name, 'IdentityGenerators' test.equal _.size(IdentityGenerator.Meta.triggers), 0 test.equal _.size(IdentityGenerator.Meta.generators), 2 test.instanceOf IdentityGenerator.Meta.generators.result, IdentityGenerator._GeneratedField test.isNull IdentityGenerator.Meta.generators.result.ancestorArray, IdentityGenerator.Meta.generators.result.ancestorArray test.isTrue _.isFunction IdentityGenerator.Meta.generators.result.generator test.equal IdentityGenerator.Meta.generators.result.sourcePath, 'result' test.equal IdentityGenerator.Meta.generators.result.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.result.reverseName test.isUndefined IdentityGenerator.Meta.generators.result.reverseFields test.instanceOf IdentityGenerator.Meta.generators.results, IdentityGenerator._GeneratedField test.equal IdentityGenerator.Meta.generators.results.ancestorArray, 'results' test.isTrue _.isFunction IdentityGenerator.Meta.generators.results.generator test.equal IdentityGenerator.Meta.generators.results.sourcePath, 'results' test.equal IdentityGenerator.Meta.generators.results.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.results.reverseName test.isUndefined IdentityGenerator.Meta.generators.results.reverseFields test.equal _.size(IdentityGenerator.Meta.fields), 0 test.isTrue IdentityGenerator.Meta._observersSetup test.equal SpecialPost.Meta._name, 'SpecialPost' test.equal SpecialPost.Meta.parent, _TestPost2.Meta test.equal SpecialPost.Meta.document, SpecialPost test.equal SpecialPost.Meta.collection._name, 'SpecialPosts' test.equal _.size(SpecialPost.Meta.triggers), 1 test.instanceOf SpecialPost.Meta.triggers.testTrigger, SpecialPost._Trigger test.equal SpecialPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal SpecialPost.Meta.triggers.testTrigger.document, SpecialPost test.equal SpecialPost.Meta.triggers.testTrigger.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(SpecialPost.Meta.generators), 2 test.equal _.size(SpecialPost.Meta.generators.subdocument), 1 test.instanceOf SpecialPost.Meta.generators.subdocument.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.generators.subdocument.slug.ancestorArray, SpecialPost.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.generators.subdocument.slug.generator test.equal SpecialPost.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseName test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseFields test.instanceOf SpecialPost.Meta.generators.tags, SpecialPost._GeneratedField test.equal SpecialPost.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction SpecialPost.Meta.generators.tags.generator test.equal SpecialPost.Meta.generators.tags.sourcePath, 'tags' test.equal SpecialPost.Meta.generators.tags.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined SpecialPost.Meta.generators.tags.reverseName test.isUndefined SpecialPost.Meta.generators.tags.reverseFields test.equal _.size(SpecialPost.Meta.fields), 7 test.instanceOf SpecialPost.Meta.fields.author, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.author.ancestorArray, SpecialPost.Meta.fields.author.ancestorArray test.isTrue SpecialPost.Meta.fields.author.required test.equal SpecialPost.Meta.fields.author.sourcePath, 'author' test.equal SpecialPost.Meta.fields.author.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.author.targetDocument, Person test.equal SpecialPost.Meta.fields.author.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.author.reverseName, 'posts' test.equal SpecialPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subscribers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue SpecialPost.Meta.fields.subscribers.required test.equal SpecialPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subscribers.targetDocument, Person test.equal SpecialPost.Meta.fields.subscribers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.fields, [] test.isNull SpecialPost.Meta.fields.subscribers.reverseName test.equal SpecialPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.reviewers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue SpecialPost.Meta.fields.reviewers.required test.equal SpecialPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.reviewers.targetDocument, Person test.equal SpecialPost.Meta.fields.reviewers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.fields, [username: 1] test.isNull SpecialPost.Meta.fields.reviewers.reverseName test.equal SpecialPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(SpecialPost.Meta.fields.subdocument), 2 test.instanceOf SpecialPost.Meta.fields.subdocument.person, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.subdocument.person.ancestorArray, SpecialPost.Meta.fields.subdocument.person.ancestorArray test.isFalse SpecialPost.Meta.fields.subdocument.person.required test.equal SpecialPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.person.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal SpecialPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal SpecialPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subdocument.persons, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue SpecialPost.Meta.fields.subdocument.persons.required test.equal SpecialPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.persons.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(SpecialPost.Meta.fields.nested), 3 test.instanceOf SpecialPost.Meta.fields.nested.required, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue SpecialPost.Meta.fields.nested.required.required test.equal SpecialPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.required.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.required.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal SpecialPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.nested.optional, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse SpecialPost.Meta.fields.nested.optional.required test.equal SpecialPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.optional.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.optional.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.fields, ['username'] test.isNull SpecialPost.Meta.fields.nested.optional.reverseName test.equal SpecialPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.nested.slug, SpecialPost._GeneratedField test.equal SpecialPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction SpecialPost.Meta.fields.nested.slug.generator test.equal SpecialPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseName test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.fields.slug.ancestorArray, SpecialPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.fields.slug.generator test.equal SpecialPost.Meta.fields.slug.sourcePath, 'slug' test.equal SpecialPost.Meta.fields.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.fields.slug.reverseName test.isUndefined SpecialPost.Meta.fields.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.special, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.special.ancestorArray, SpecialPost.Meta.fields.special.ancestorArray test.isTrue SpecialPost.Meta.fields.special.required test.equal SpecialPost.Meta.fields.special.sourcePath, 'special' test.equal SpecialPost.Meta.fields.special.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.special.targetDocument, Person test.equal SpecialPost.Meta.fields.special.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.fields, [] test.isNull SpecialPost.Meta.fields.special.reverseName test.equal SpecialPost.Meta.fields.special.reverseFields, [] test.isTrue SpecialPost.Meta._observersSetup test.equal LocalPost.Meta._name, 'LocalPost' test.equal LocalPost.Meta.document, LocalPost test.isNull LocalPost.Meta.collection._name test.equal _.size(LocalPost.Meta.triggers), 1 test.instanceOf LocalPost.Meta.triggers.testTrigger, LocalPost._Trigger test.equal LocalPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal LocalPost.Meta.triggers.testTrigger.document, LocalPost test.isNull LocalPost.Meta.triggers.testTrigger.collection._name test.equal LocalPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(LocalPost.Meta.fields), 7 test.instanceOf LocalPost.Meta.fields.author, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.author.ancestorArray, LocalPost.Meta.fields.author.ancestorArray test.isTrue LocalPost.Meta.fields.author.required test.equal LocalPost.Meta.fields.author.sourcePath, 'author' test.equal LocalPost.Meta.fields.author.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.author.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.author.sourceCollection._name test.isNull LocalPost.Meta.fields.author.targetCollection._name test.isNull LocalPost.Meta.fields.author.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.author.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.author.reverseName, 'posts' test.equal LocalPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subscribers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue LocalPost.Meta.fields.subscribers.required test.equal LocalPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal LocalPost.Meta.fields.subscribers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subscribers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subscribers.sourceCollection._name test.isNull LocalPost.Meta.fields.subscribers.targetCollection._name test.isNull LocalPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subscribers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subscribers.fields, [] test.isNull LocalPost.Meta.fields.subscribers.reverseName test.equal LocalPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf LocalPost.Meta.fields.reviewers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue LocalPost.Meta.fields.reviewers.required test.equal LocalPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal LocalPost.Meta.fields.reviewers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.reviewers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.reviewers.sourceCollection._name test.isNull LocalPost.Meta.fields.reviewers.targetCollection._name test.isNull LocalPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.reviewers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.reviewers.fields, [username: 1] test.isNull LocalPost.Meta.fields.reviewers.reverseName test.equal LocalPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(LocalPost.Meta.fields.subdocument), 3 test.instanceOf LocalPost.Meta.fields.subdocument.person, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.subdocument.person.ancestorArray, LocalPost.Meta.fields.subdocument.person.ancestorArray test.isFalse LocalPost.Meta.fields.subdocument.person.required test.equal LocalPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal LocalPost.Meta.fields.subdocument.person.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.person.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.person.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal LocalPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal LocalPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.persons, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue LocalPost.Meta.fields.subdocument.persons.required test.equal LocalPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal LocalPost.Meta.fields.subdocument.persons.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.persons.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.persons.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal LocalPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.subdocument.slug.ancestorArray, LocalPost.Meta.fields.subdocument.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.subdocument.slug.generator test.equal LocalPost.Meta.fields.subdocument.slug.sourcePath, 'subdocument.slug' test.equal LocalPost.Meta.fields.subdocument.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.subdocument.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseName test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseFields test.equal _.size(LocalPost.Meta.fields.nested), 3 test.instanceOf LocalPost.Meta.fields.nested.required, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue LocalPost.Meta.fields.nested.required.required test.equal LocalPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal LocalPost.Meta.fields.nested.required.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.required.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.required.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.required.targetCollection._name test.isNull LocalPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.required.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal LocalPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.nested.optional, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse LocalPost.Meta.fields.nested.optional.required test.equal LocalPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal LocalPost.Meta.fields.nested.optional.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.optional.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.optional.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.optional.targetCollection._name test.isNull LocalPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.optional.fields, ['username'] test.isNull LocalPost.Meta.fields.nested.optional.reverseName test.equal LocalPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf LocalPost.Meta.fields.nested.slug, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction LocalPost.Meta.fields.nested.slug.generator test.equal LocalPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal LocalPost.Meta.fields.nested.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.nested.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.slug.targetCollection._name test.isNull LocalPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.nested.slug.reverseName test.isUndefined LocalPost.Meta.fields.nested.slug.reverseFields test.instanceOf LocalPost.Meta.fields.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.slug.ancestorArray, LocalPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.slug.generator test.equal LocalPost.Meta.fields.slug.sourcePath, 'slug' test.equal LocalPost.Meta.fields.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.slug.targetCollection._name test.isNull LocalPost.Meta.fields.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.slug.reverseName test.isUndefined LocalPost.Meta.fields.slug.reverseFields test.instanceOf LocalPost.Meta.fields.tags, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.tags.ancestorArray, 'tags' test.isTrue _.isFunction LocalPost.Meta.fields.tags.generator test.equal LocalPost.Meta.fields.tags.sourcePath, 'tags' test.equal LocalPost.Meta.fields.tags.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.tags.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.tags.sourceCollection._name test.isNull LocalPost.Meta.fields.tags.targetCollection._name test.isNull LocalPost.Meta.fields.tags.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.tags.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.tags.reverseName test.isUndefined LocalPost.Meta.fields.tags.reverseFields test.isTrue LocalPost.Meta._observersSetup test.equal LocalPerson.Meta._name, 'LocalPerson' test.equal LocalPerson.Meta.document, LocalPerson test.isNull LocalPerson.Meta.collection._name test.equal _.size(LocalPerson.Meta.triggers), 0 test.equal _.size(LocalPerson.Meta.fields), 5 test.instanceOf LocalPerson.Meta.fields.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.posts.ancestorArray, 'posts' test.isTrue LocalPerson.Meta.fields.posts.required test.equal LocalPerson.Meta.fields.posts.sourcePath, 'posts' test.equal LocalPerson.Meta.fields.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.posts.reverseName test.equal LocalPerson.Meta.fields.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.nestedPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue LocalPerson.Meta.fields.nestedPosts.required test.equal LocalPerson.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal LocalPerson.Meta.fields.nestedPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.nestedPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.nestedPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.nestedPosts.reverseName test.equal LocalPerson.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.count, LocalPerson._GeneratedField test.isNull LocalPerson.Meta.fields.count.ancestorArray, LocalPerson.Meta.fields.count.ancestorArray test.isTrue _.isFunction LocalPerson.Meta.fields.count.generator test.equal LocalPerson.Meta.fields.count.sourcePath, 'count' test.equal LocalPerson.Meta.fields.count.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.count.targetDocument, LocalPerson test.isNull LocalPerson.Meta.fields.count.sourceCollection._name test.isNull LocalPerson.Meta.fields.count.targetCollection._name test.isNull LocalPerson.Meta.fields.count.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.count.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined LocalPerson.Meta.fields.count.reverseName test.isUndefined LocalPerson.Meta.fields.count.reverseFields test.instanceOf LocalPerson.Meta.fields.subdocument.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue LocalPerson.Meta.fields.subdocument.posts.required test.equal LocalPerson.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal LocalPerson.Meta.fields.subdocument.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocument.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocument.posts.reverseName test.equal LocalPerson.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.subdocumentsPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue LocalPerson.Meta.fields.subdocumentsPosts.required test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocumentsPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocumentsPosts.reverseName test.equal LocalPerson.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue LocalPerson.Meta._observersSetup testDocumentList test, ALL plainObject = (obj) -> return obj unless _.isObject obj return (plainObject o for o in obj) if _.isArray obj keys = _.keys obj values = (plainObject o for o in _.values obj) _.object keys, values for name, documents of {server: {Person: Person, Post: Post}, local: {Person: LocalPerson, Post: LocalPost}} do (documents) -> testAsyncMulti "peerdb - references #{name}", [ (test, expect) -> testDefinition test # We should be able to call defineAll multiple times Document.defineAll() testDefinition test documents.Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id documents.Person.documents.insert username: 'person2' displayName: 'Person <NAME>' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id documents.Person.documents.insert username: 'person3' displayName: '<NAME>' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to run (but no post is yet made, so nothing really happens). # We want to wait here so that we catch possible errors in source observers, otherwise target # observers can patch things up. For example, if we create a post first and target observers # (triggered by person inserts, but pending) run afterwards, then they can patch things which # should in fact be done by source observers (on post), like setting usernames in post's # references to persons. waitForDatabase test, expect , (test, expect) -> # Should work also with no argument (defaults to {}). test.isTrue documents.Person.documents.exists() test.isTrue documents.Person.documents.find().exists() test.isTrue documents.Person.documents.exists @person1Id test.isTrue documents.Person.documents.exists @person2Id test.isTrue documents.Person.documents.exists @person3Id test.isTrue documents.Person.documents.find(@person1Id).exists() test.isTrue documents.Person.documents.find(@person2Id).exists() test.isTrue documents.Person.documents.find(@person3Id).exists() test.equal documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).count(), 3 # Test without skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).exists() # With sorting. We are testing all this combinations because there are various code paths. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}).exists() # Test with skip and limit. # This behaves differently than .count() on the server because on the server # applySkipLimit is not set. But exists do respect skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}).exists() test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}).exists() @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 documents.Post.documents.insert author: _id: @person1._id # To test what happens if all fields are not up to date username: 'wrong' displayName: 'wrong' field1: 'wrong' field2: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: 'wrong' , _id: @person3._id username: 'wrong' ] subdocument: person: _id: @person2._id username: 'wrong' persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id username: 'wrong' body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # We inserted the document only with ids - subdocuments should be # automatically populated with additional fields as defined in @ReferenceField test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res documents.Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> documents.Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res , (test, expect) -> @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person3 was removed, references should be removed as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id ] reviewers: [ _id: @person2._id username: @person2.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: null slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person2 was removed, references should be removed as well, automatically, # but lists should be kept as empty lists test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' ] documents.Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # If directly referenced document is removed, dependency is removed as well test.isFalse @post, @post ] Tinytest.add 'peerdb - invalid optional', (test) -> test.throws -> class BadPost1 extends Document @Meta name: 'BadPost1' fields: -> reviewers: [@ReferenceField Person, ['username'], false] , /Reference field directly in an array cannot be optional/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - invalid nested arrays', (test) -> test.throws -> class BadPost2 extends Document @Meta name: 'BadPost2' fields: -> nested: [ many: [@ReferenceField Person, ['username']] ] , /Field cannot be in a nested array/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - abstract with parent', (test) -> test.throws -> class BadPost4 extends Post @Meta abstract: true , /Abstract document with a parent/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() testAsyncMulti 'peerdb - circular changes', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected CircularFirst.documents.insert second: null content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@circularFirstId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Document 'CircularFirst' '#{ @circularFirstId }' field 'second' was updated with an invalid value: null" test.equal intercepted.level, 'error' @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: null content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' CircularFirst.documents.update @circularFirstId, $set: second: _id: @circularSecondId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.update @circularFirstId, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.update @circularSecondId, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2a' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2a' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2a' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.remove @circularSecondId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularSecond, @circularSecond # If directly referenced document is removed, dependency is removed as well test.isFalse @circularFirst, @circularFirst Log._intercept 1 if Meteor.isServer and Document.instances is 1 CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId , (test, expect) -> CircularFirst.documents.insert second: _id: @circularSecondId content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() test.equal intercepted.length, 0, intercepted @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.remove @circularFirstId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update document waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularFirst, @circularFirst # If directly referenced but optional document is removed, dependency is not removed as well, but set to null test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [] ] testAsyncMulti 'peerdb - recursive two', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar 1' , expect (error, recursive1Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive1Id @recursive1Id = recursive1Id Recursive.documents.insert other: null content: 'FooBar 2' , expect (error, recursive2Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive2Id @recursive2Id = recursive2Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' Recursive.documents.update @recursive1Id, $set: other: _id: @recursive2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive2Id, $set: other: _id: @recursive1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive1Id, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.update @recursive2Id, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2a' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2a' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2a' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.remove @recursive2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.isFalse @recursive2, @recursive2 test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1a' reverse: [] ] testAsyncMulti 'peerdb - recursive one', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar' , expect (error, recursiveId) => test.isFalse error, error?.toString?() or error test.isTrue recursiveId @recursiveId = recursiveId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: null content: 'FooBar' Recursive.documents.update @recursiveId, $set: other: _id: @recursiveId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBar' content: 'FooBar' reverse: [ _id: @recursiveId content: 'FooBar' ] Recursive.documents.update @recursiveId, $set: content: 'FooBara' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBara' content: 'FooBara' reverse: [ _id: @recursiveId content: 'FooBara' ] Recursive.documents.remove @recursiveId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.isFalse @recursive, @recursive ] if Meteor.isServer and Document.instances is 1 Tinytest.add 'peerdb - errors', (test) -> Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: _id: 'nonexistent' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: 'foobar' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: [ _id: 'nonexistent' ] # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' was updated with an invalid value: null" test.equal intercepted.level, 'error' Log._intercept 1 userLinkId = UserLink.documents.insert user: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() # There should be no warning because user is optional test.equal intercepted.length, 0, intercepted testAsyncMulti 'peerdb - delayed defintion', [ (test, expect) -> class BadPost5 extends Document @Meta name: 'BadPost5' fields: -> author: @ReferenceField undefined, ['username'] Log._intercept 2 # Two to see if we catch more than expected # Sleep so that error is shown Meteor.setTimeout expect(), 1000 # We need 1000 here because we have a check which runs after 1000 ms to check for delayed definitions , (test, expect) -> intercepted = Log._intercepted() # One or two because we could intercepted something else as well test.isTrue 1 <= intercepted.length <= 2, intercepted # Let's find it for i in intercepted break if i.indexOf('BadPost5') isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message.lastIndexOf("Not all delayed document definitions were successfully retried:\nBadPost5 from"), 0, intercepted.message test.equal intercepted.level, 'error' testDocumentList test, ALL test.equal Document._delayed.length, 1 # Clear delayed so that we can retry tests without errors Document._delayed = [] Document._clearDelayedCheck() ] testAsyncMulti 'peerdb - subdocument fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] PostLink.documents.insert post: _id: @post._id , expect (error, postLinkId) => test.isFalse error, error?.toString?() or error test.isTrue postLinkId @postLinkId = postLinkId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Post.documents.remove @post._id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.isFalse @postLink, @postLink ] testAsyncMulti 'peerdb - generated fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobar-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' ] Post.documents.update @postId, $set: body: null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: null body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: null body: 'NestedFooBarZ' ] body: null slug: null tags: [] Post.documents.update @postId, $unset: body: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username body: 'NestedFooBarZ' ] tags: [] ] Tinytest.add 'peerdb - chain of extended classes', (test) -> list = _.clone Document.list firstReferenceA = undefined # To force delayed secondReferenceA = undefined # To force delayed firstReferenceB = undefined # To force delayed secondReferenceB = undefined # To force delayed class First extends Document @Meta name: 'First' fields: -> first: @ReferenceField firstReferenceA class Second extends First @Meta name: 'Second' fields: (fields) -> fields.second = @ReferenceField Post # Not undefined, but overall meta will still be delayed fields class Third extends Second @Meta name: 'Third' fields: (fields) -> fields.third = @ReferenceField secondReferenceA fields testDocumentList test, ALL test.equal Document._delayed.length, 3 test.equal Document._delayed[0], First test.equal Document._delayed[1], Second test.equal Document._delayed[2], Third _TestFirst = First class First extends First @Meta name: 'First' replaceParent: true fields: (fields) -> fields.first = @ReferenceField firstReferenceB fields _TestSecond = Second class Second extends Second @Meta name: 'Second' replaceParent: true fields: (fields) -> fields.second = @ReferenceField Person # Not undefined, but overall meta will still be delayed fields _TestThird = Third class Third extends Third @Meta name: 'Third' replaceParent: true fields: (fields) -> fields.third = @ReferenceField secondReferenceB fields testDocumentList test, ALL test.equal Document._delayed.length, 6 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], Third _TestThird2 = Third class Third extends Third @Meta name: '<NAME>' replaceParent: true fields: (fields) -> fields.third = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 7 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third _TestFirst2 = First class First extends First @Meta name: '<NAME>' replaceParent: true fields: (fields) -> fields.first = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 8 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], _TestFirst2 test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third test.equal Document._delayed[7], First firstReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [_TestFirst, Second] test.equal Document._delayed.length, 5 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestFirst2 test.equal Document._delayed[2], _TestThird2 test.equal Document._delayed[3], Third test.equal Document._delayed[4], First test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] firstReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First] test.equal Document._delayed.length, 3 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestThird2 test.equal Document._delayed[2], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, _TestThird] test.equal Document._delayed.length, 2 test.equal Document._delayed[0], _TestThird2 test.equal Document._delayed[1], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, Third] test.equal Document._delayed.length, 0 test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] Document.defineAll() test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test Tinytest.addAsync 'peerdb - local collections', (test, onComplete) -> list = _.clone Document.list try class Local extends Document @Meta name: 'Local' collection: null fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [Local] test.equal Document._delayed.length, 0 test.equal Local.Meta._name, 'Local' test.isFalse Local.Meta.parent test.equal Local.Meta.document, Local test.equal Local.Meta.collection._name, null test.equal _.size(Local.Meta.fields), 1 test.instanceOf Local.Meta.fields.person, Local._ReferenceField test.isNull Local.Meta.fields.person.ancestorArray, Local.Meta.fields.person.ancestorArray test.isTrue Local.Meta.fields.person.required test.equal Local.Meta.fields.person.sourcePath, 'person' test.equal Local.Meta.fields.person.sourceDocument, Local test.equal Local.Meta.fields.person.targetDocument, Person test.isFalse Local.Meta.fields.person.sourceCollection._name test.equal Local.Meta.fields.person.targetCollection._name, 'Persons' test.isFalse Local.Meta.fields.person.sourceDocument.Meta.collection._name test.equal Local.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal Local.Meta.fields.person.fields, [] test.isNull Local.Meta.fields.person.reverseName test.equal Local.Meta.fields.person.reverseFields, [] test.isTrue Local.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'Locals', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() Tinytest.addAsync 'peerdb - collections with connection', (test, onComplete) -> list = _.clone Document.list try class CollectionWithConnection extends Document @Meta name: 'CollectionWithConnection' collection: new Mongo.Collection 'CollectionWithConnections', connection: DDP.connect Meteor.absoluteUrl() fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [CollectionWithConnection] test.equal Document._delayed.length, 0 test.equal CollectionWithConnection.Meta._name, 'CollectionWithConnection' test.isFalse CollectionWithConnection.Meta.parent test.equal CollectionWithConnection.Meta.document, CollectionWithConnection test.equal CollectionWithConnection.Meta.collection._name, 'CollectionWithConnections' test.equal _.size(CollectionWithConnection.Meta.fields), 1 test.instanceOf CollectionWithConnection.Meta.fields.person, CollectionWithConnection._ReferenceField test.isNull CollectionWithConnection.Meta.fields.person.ancestorArray, CollectionWithConnection.Meta.fields.person.ancestorArray test.isTrue CollectionWithConnection.Meta.fields.person.required test.equal CollectionWithConnection.Meta.fields.person.sourcePath, 'person' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument, CollectionWithConnection test.equal CollectionWithConnection.Meta.fields.person.targetDocument, Person test.equal CollectionWithConnection.Meta.fields.person.sourceCollection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetCollection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument.Meta.collection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.fields, [] test.isNull CollectionWithConnection.Meta.fields.person.reverseName test.equal CollectionWithConnection.Meta.fields.person.reverseFields, [] test.isTrue CollectionWithConnection.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'CollectionWithConnections', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() testAsyncMulti 'peerdb - errors for generated fields', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.insert source: 'foobar' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: 'foobar' result: 'foobar' Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.update @identityGeneratorId, $set: source: ['foobar2'] , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'result' not defined as an array with selector '#{ @identityGeneratorId }' was updated with an array value: [ 'foobar2' ]" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: ['foobar2'] result: 'foobar' results: ['foobar2'] ] Tinytest.add 'peerdb - tricky references', (test) -> list = _.clone Document.list # You can in fact use class name instead of "self", but you have to # make sure things work out at the end and class is really defined class First1 extends Document @Meta name: '<NAME>' fields: -> first: @ReferenceField First1 Document.defineAll() test.equal First1.Meta._name, 'First1' test.isFalse First1.Meta.parent test.equal First1.Meta.document, First1 test.equal First1.Meta.collection._name, 'First1s' test.equal _.size(First1.Meta.fields), 1 test.instanceOf First1.Meta.fields.first, First1._ReferenceField test.isFalse First1.Meta.fields.first.ancestorArray, First1.Meta.fields.first.ancestorArray test.isTrue First1.Meta.fields.first.required test.equal First1.Meta.fields.first.sourcePath, 'first' test.equal First1.Meta.fields.first.sourceDocument, First1 test.equal First1.Meta.fields.first.targetDocument, First1 test.equal First1.Meta.fields.first.sourceCollection._name, 'First1s' test.equal First1.Meta.fields.first.targetCollection._name, 'First1s' test.equal First1.Meta.fields.first.sourceDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.targetDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.fields, [] # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() class First2 extends Document @Meta name: 'First2' fields: -> first: @ReferenceField undefined # To force delayed class Second2 extends Document @Meta name: 'Second2' fields: -> first: @ReferenceField First2 test.throws -> Document.defineAll true , /Target document not defined/ test.throws -> Document.defineAll() , /Invalid fields/ # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test testAsyncMulti 'peerdb - duplicate values in lists', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id # To test what happens if fields are partially not up to date username: 'wrong' displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id username: 'wrong' displayName: 'wrong' , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' , _id: @person3._id # To test if the second person3 value will be updated username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: '<NAME> <NAME>' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: '<NAME> <NAME>' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person1Id, $set: # Updating two fields at the same time field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $set: username: 'person2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $set: username: 'person3b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $unset: # Removing two fields at the same time field1: '' field2: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $set: # Restoring two fields at the same time field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.4.body': 'NestedFooBarA' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobara-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.3.body': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobara-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $unset: 'nested.2.body': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobara-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $push: nested: required: _id: @person2._id optional: _id: @person3._id body: 'NewFooBar' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-newfoobar-suffix' body: 'NewFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' 'tag-5-prefix-foobarz-newfoobar-suffix' ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person3._id ] reviewers: [ _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null slug: null body: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' ] Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.isFalse @post, @post ] if Meteor.isServer and Document.instances is 1 testAsyncMulti 'peerdb - exception while processing', [ (test, expect) -> Log._intercept 3 IdentityGenerator.documents.insert source: 'exception' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> intercepted = Log._intercepted() test.isTrue intercepted.length is 3, intercepted # We are testing only the server one, so let's find it for i in intercepted # First error message if i.indexOf('PeerDB exception: Error: Test exception') isnt -1 i = EJSON.parse i test.equal i.message, "PeerDB exception: Error: Test exception: [ { source: 'exception', _id: '#{ @identityGeneratorId }' } ]" test.equal i.level, 'error' # Stack trace error message else if i.indexOf('Error: Test exception') isnt -1 i = EJSON.parse i test.isTrue i.message.indexOf('_GeneratedField.generator') isnt -1, i.message test.equal i.level, 'error' # Invalid update error message else if i.indexOf('defined as an array with selector') isnt -1 i = EJSON.parse i test.equal i.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'exception'" test.equal i.level, 'error' else test.fail type: 'assert_never' message: i ] testAsyncMulti 'peerdb - instances', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id test.instanceOf @person1, Person test.instanceOf @person2, Person test.instanceOf @person3, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal plainObject(@person2), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal plainObject(@person3), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 test.equal @person1.formatName(), 'person1-Person 1' test.equal @person2.formatName(), 'person2-Person 2' test.equal @person3.formatName(), 'person3-Person 3' Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] SpecialPost.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = SpecialPost.documents.findOne @postId test.instanceOf @post, SpecialPost test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.instanceOf @post.special, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] special: _id: @person1._id @username = Random.id() if Meteor.isServer @userId = Accounts.createUser username: @username password: '<PASSWORD>' else Accounts.createUser username: @username password: '<PASSWORD>' , expect (error) => test.isFalse error, error?.toString?() or error @userId = Meteor.userId() unless error , (test, expect) -> @user = User.documents.findOne @userId test.instanceOf @user, User test.equal @user.username, @username ] Tinytest.add 'peerdb - bad instances', (test) -> # Empty document should be always possible to create for document in Document.list test.isTrue new document # Something simple test.isTrue new Post author: _id: Random.id() username: 'Foobar' test.throws -> new Post author: [ _id: Random.id() username: 'Foobar' ] , /Document does not match schema, not a plain object/ test.throws -> new Post subscribers: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post subdocument: [] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [ persons: [] ] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [[ persons: [] ]] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: persons: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: required: [ _id: Random.id() ] , /Document does not match schema, expected an array/ test.throws -> new Post nested: required: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: [ _id: Random.id() ] ] , /Document does not match schema, not a plain object/ if Meteor.isServer and not Document.instanceDisabled testAsyncMulti 'peerdb - update all', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id Post.documents.insert author: _id: @person1._id # To test what happens if one field is already up to date, but the other is not username: @person1.username displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'author.username': 'wrong' 'reviewers.0.username': 'wrong' 'reviewers.1.username': 'wrong' 'subdocument.person.username': 'wrong' 'subdocument.persons.0.username': 'wrong' 'subdocument.persons.1.username': 'wrong' 'nested.0.required.username': 'wrong' 'nested.0.optional.username': 'wrong' slug: 'wrong' tags: 'wrong' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # Reference fields are automatically updated back, but generated fields are not test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'wrong' tags: 'wrong' # Update all fields back (a blocking operation) Document.updateAll() # Wait so that triggered observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] ] testAsyncMulti 'peerdb - reverse posts', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person2Id body: 'NestedFooBar1' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person2Id , _id: @person3Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar1' body: 'FooBar1' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId1 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar2' ] subdocument: person: _id: @person2Id persons: [ _id: @person2Id , _id: @person2Id , _id: @person2Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar2' body: 'FooBar2' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId2 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar3' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar3' body: 'FooBar3' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId3 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post1 = Post.documents.findOne @postId1, transform: null # So that we can use test.equal @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal @post3 = Post.documents.findOne @postId3, transform: null # So that we can use test.equal test.equal @post1, _id: @postId1 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar1-subdocumentfoobar1-suffix' body: 'SubdocumentFooBar1' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar1-nestedfoobar1-suffix' body: 'NestedFooBar1' ] body: 'FooBar1' slug: 'prefix-foobar1-subdocumentfoobar1-suffix' tags: [ 'tag-0-prefix-foobar1-subdocumentfoobar1-suffix' 'tag-1-prefix-foobar1-nestedfoobar1-suffix' ] test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2-subdocumentfoobar2-suffix' body: 'SubdocumentFooBar2' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2-nestedfoobar2-suffix' body: 'NestedFooBar2' ] body: 'FooBar2' slug: 'prefix-foobar2-subdocumentfoobar2-suffix' tags: [ 'tag-0-prefix-foobar2-subdocumentfoobar2-suffix' 'tag-1-prefix-foobar2-nestedfoobar2-suffix' ] test.equal @post3, _id: @postId3 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar3-subdocumentfoobar3-suffix' body: 'SubdocumentFooBar3' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar3-nestedfoobar3-suffix' body: 'NestedFooBar3' ] body: 'FooBar3' slug: 'prefix-foobar3-subdocumentfoobar3-suffix' tags: [ 'tag-0-prefix-foobar3-subdocumentfoobar3-suffix' 'tag-1-prefix-foobar3-nestedfoobar3-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 8 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: '<NAME> 3' count: 5 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person2Id ] body: 'SubdocumentFooBar4' body: 'FooBar4' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId4 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' ] subdocument: person: _id: @person3Id persons: [ _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar5' body: 'FooBar5' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId5 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] Post.documents.update @postId1, $set: 'body': 'FooBar1a' 'subdocument.body': 'SubdocumentFooBar1a' 'nested.0.body': 'NestedFooBar1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId2, $set: 'body': 'FooBar2a' 'subdocument.body': 'SubdocumentFooBar2a' 'nested.0.body': 'NestedFooBar2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId3, $set: 'body': 'FooBar3a' 'subdocument.body': 'SubdocumentFooBar3a' 'nested.0.body': 'NestedFooBar3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId4, $set: 'body': 'FooBar4a' 'subdocument.body': 'SubdocumentFooBar4a' 'nested.1.body': 'NestedFooBar4a' 'nested.3.body': 'NestedFooBar4a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId5, $set: 'body': 'FooBar5a' 'subdocument.body': 'SubdocumentFooBar5a' 'nested.1.body': 'NestedFooBar5a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $push: nested: required: _id: @person2Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person2Id username: 'person2' displayName: 'Person <NAME>' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: '<NAME> <NAME>' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId2, $push: nested: required: _id: @person3Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: null persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person <NAME>' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person <NAME>' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person <NAME>' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $unset: 'subdocument.person': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: author: _id: @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person2Id username: 'person2' displayName: 'Person 2' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.remove @postId5, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 7 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person <NAME>' count: 6 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId2, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 10 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 4 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId3, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 7 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 4 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 2 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] for id in [@postId1, @postId2, @postId3, @postId4, @postId5] Post.documents.update _id: id , $set: nested: [] , expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 6 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 2 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 1 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [] ] if Meteor.isServer testAsyncMulti 'peerdb - triggers', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id test.instanceOf @person1, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person1.formatName(), 'person1-Person 1' Post.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] SpecialPost.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @specialPostId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 1 test.equal globalTestTriggerCounters[@specialPostId], 1 Post.documents.update @postId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.<NAME> subdocument: {} body: 'FooBar 1' tags: [] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar 1' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 Post.documents.update @postId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 ] testAsyncMulti 'peerdb - reverse fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 @changes = [] @handle = Person.documents.find(@person1Id).observe changed: (newDocument, oldDocument) => @changes.push newDocument Post.documents.insert author: _id: @person1._id subdocument: persons: [] body: 'SubdocumentFooBar' nested: [] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 1 posts: [ _id: @postId body: 'FooBar' nested: [] subdocument: body: 'SubdocumentFooBar' ] # This test is checking that all fields in reverse field subdocuments are populated # from the beginning. Otherwise there might be a short but existing time when # document does not match the schema, and is published as such to the client. for person in @changes for post in person.posts test.equal post.body, 'FooBar' test.equal post.nested, [] test.equal post.subdocument?.body, 'SubdocumentFooBar' @handle.stop() ] testAsyncMulti 'peerdb - bulk insert', [ (test, expect) -> @testContent = for i in [0..100] content: Random.id() ids = Recursive.documents.bulkInsert @testContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids?.length, @testContent.length @testIds = ids test.isTrue ids test.equal ids?.length, @testContent.length # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> docs = Recursive.documents.find( _id: $in: @testIds , fields: _id: 0 content: 1 transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> randomIds = for i in [0...100] Random.id() insertContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other reverse: [ _id: reverse ] @testContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other content: other reverse: [ _id: reverse content: reverse ] ids = Recursive.documents.bulkInsert insertContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids, _.pluck @testContent, '_id' test.equal ids, _.pluck @testContent, '_id' # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> # We sleep a bit so that all changes get to the client, when rnning on the client. Meteor.setTimeout expect(), 200 , (test, expect) -> docs = Recursive.documents.find( _id: $in: _.pluck(@testContent, '_id') , transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> # Test bulkInsert without any arguments. Recursive.documents.bulkInsert [] ] testAsyncMulti 'peerdb - bulk insert with subfield references', [ (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, _.extend {objectInArray: [], anArray: []}, @item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id item = _.extend {objectInArray: [], anArray: []}, @item # Missing references should be set to null. item.toplevel.subitem = null test.equal insertedItem, item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem: _id: itemId subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item # To make sure there are no residual observes going into @changes. waitForDatabase test, expect , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] @changes = [] initializing = true @handle = SubfieldItem.documents.find().observeChanges added: (id, fields) => @changes.push {type: 'added', id, fields} unless initializing changed: (id, fields) => @changes.push {type: 'changed', id, fields} initializing = false SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: hello: "world" toplevel: anotherA: "hello" anotherB: "world" , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray', 'toplevel' ] @changes = [] itemId = Random.id() @item._id = itemId SubfieldItem.documents.bulkInsert [@item], {dontDelay: ['toplevel.subitem']}, expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: _.pick @item, 'hello', 'toplevel' , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray' ] @handle.stop() ] Tinytest.add 'peerdb - local documents', (test) -> testDefinition test class ReallyLocalPost extends Post @Meta name: 'ReallyLocalPost' collection: null local: true testDefinition test
true
WAIT_FOR_DATABASE_TIMEOUT = 2000 # ms # The order of documents here tests delayed definitions # Just to make sure things are sane assert.equal Document._delayed.length, 0 assert _.isEqual Document.list, [] assert _.isEqual Document._collections, {} globalTestTriggerCounters = {} class Post extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'Post' fields: -> # We can reference other document author: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] # Or an array of documents subscribers: [@ReferenceField Person] # Fields can be arbitrary MongoDB projections, as an array reviewers: [@ReferenceField Person, [username: 1]] subdocument: # Fields can be arbitrary MongoDB projections, as an object person: @ReferenceField Person, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] nested: [ required: @ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField Person, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] generators: -> subdocument: slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 # Store away for testing _TestPost = Post # Extending delayed document class Post extends Post @Meta name: 'Post' replaceParent: true fields: (fields) -> fields.subdocument.persons = [@ReferenceField Person, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] fields # Store away for testing _TestPost2 = Post class User extends Document @Meta name: 'User' # Specifying collection directly collection: Meteor.users class UserLink extends Document @Meta name: 'UserLink' fields: -> user: @ReferenceField User, ['username'], false class PostLink extends Document @Meta name: 'PostLink' # Store away for testing _TestPostLink = PostLink # To test extending when initial document has no fields class PostLink extends PostLink @Meta name: 'PostLink' replaceParent: true fields: -> post: @ReferenceField Post, ['subdocument.person', 'subdocument.persons'] class CircularFirst extends Document # Other fields: # content @Meta name: 'CircularFirst' # Store away for testing _TestCircularFirst = CircularFirst # To test extending when initial document has no fields and fields will be delayed class CircularFirst extends CircularFirst @Meta name: 'CircularFirst' replaceParent: true fields: (fields) -> # We can reference circular documents fields.second = @ReferenceField CircularSecond, ['content'], true, 'reverseFirsts', ['content'] fields class CircularSecond extends Document # Other fields: # content @Meta name: 'CircularSecond' fields: -> # But of course one should not be required so that we can insert without warnings first: @ReferenceField CircularFirst, ['content'], false, 'reverseSeconds', ['content'] class Person extends Document # Other fields: # username # PI:NAME:<NAME>END_PI # field1 # field2 @Meta name: 'Person' generators: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] # Store away for testing _TestPerson = Person # To test if reverse fields *are* added to the extended class which replaces the parent class Person extends Person @Meta name: 'Person' replaceParent: true formatName: -> "#{ @username }-#{ @displayName or "none" }" # To test if reverse fields are *not* added to the extended class which replaces the parent class SpecialPerson extends Person @Meta name: 'SpecialPerson' fields: -> # posts and nestedPosts don't exist, so we remove count field as well count: undefined class RecursiveBase extends Document @Meta abstract: true fields: -> other: @ReferenceField 'self', ['content'], false, 'reverse', ['content'] class Recursive extends RecursiveBase # Other fields: # content @Meta name: 'Recursive' class IdentityGenerator extends Document # Other fields: # source @Meta name: 'IdentityGenerator' generators: -> result: @GeneratedField 'self', ['source'], (fields) -> throw new Error "Test exception" if fields.source is 'exception' return [fields._id, fields.source] results: [ @GeneratedField 'self', ['source'], (fields) -> return [fields._id, fields.source] ] # Extending and renaming the class, this creates new collection as well class SpecialPost extends Post @Meta name: 'SpecialPost' fields: -> special: @ReferenceField Person # To test redefinig after fields already have a reference to an old document class Post extends Post @Meta name: 'Post' replaceParent: true # To test handling of subfield references in bulk insert class SubfieldItem extends Document @Meta name: 'SubfieldItem' fields: -> toplevel: subitem: @ReferenceField 'self', [], false objectInArray: [ subitem: @ReferenceField 'self', [], false subitem2: @ReferenceField 'self', [] ] anArray: [@ReferenceField 'self', []] class LocalPost extends Document # Other fields: # body # subdocument # body # nested # body @Meta name: 'LocalPost' collection: null fields: -> author: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'posts', ['body', 'subdocument.body', 'nested.body'] subscribers: [@ReferenceField LocalPerson] reviewers: [@ReferenceField LocalPerson, [username: 1]] subdocument: person: @ReferenceField LocalPerson, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1}, false, 'subdocument.posts', ['body', 'subdocument.body', 'nested.body'] persons: [@ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'subdocumentsPosts', ['body', 'subdocument.body', 'nested.body']] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "subdocument-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] nested: [ required: @ReferenceField LocalPerson, ['username', 'displayName', 'field1', 'field2'], true, 'nestedPosts', ['body', 'subdocument.body', 'nested.body'] optional: @ReferenceField LocalPerson, ['username'], false slug: @GeneratedField 'self', ['body', 'nested.body'], (fields) -> for nested in fields.nested or [] if _.isUndefined(fields.body) or _.isUndefined(nested.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(nested.body) [fields._id, null] else [fields._id, "nested-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix"] ] slug: @GeneratedField 'self', ['body', 'subdocument.body'], (fields) -> if _.isUndefined(fields.body) or _.isUndefined(fields.subdocument?.body) [fields._id, undefined] else if _.isNull(fields.body) or _.isNull(fields.subdocument.body) [fields._id, null] else [fields._id, "prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix"] tags: [ @GeneratedField 'self', ['body', 'subdocument.body', 'nested.body'], (fields) -> tags = [] if fields.body and fields.subdocument?.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ fields.subdocument.body.toLowerCase() }-suffix" if fields.body and fields.nested and _.isArray fields.nested for nested in fields.nested when nested.body tags.push "tag-#{ tags.length }-prefix-#{ fields.body.toLowerCase() }-#{ nested.body.toLowerCase() }-suffix" [fields._id, tags] ] triggers: -> testTrigger: @Trigger ['body'], (newDocument, oldDocument) -> return unless newDocument?._id globalTestTriggerCounters[newDocument._id] = (globalTestTriggerCounters[newDocument._id] or 0) + 1 class LocalPerson extends Document # Other fields: # username # PI:NAME:<NAME>END_PI # field1 # field2 @Meta name: 'LocalPerson' collection: null fields: -> count: @GeneratedField 'self', ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'], (fields) -> [fields._id, (fields.posts?.length or 0) + (fields.nestedPosts?.length or 0) + (fields.subdocument?.posts?.length or 0) + (fields.subdocumentsPosts?.length or 0)] formatName: -> "#{ @username }-#{ @displayName or "none" }" Document.defineAll() # Just to make sure things are sane assert.equal Document._delayed.length, 0 if Meteor.isServer # Initialize the database try Post.Meta.collection._dropCollection() User.Meta.collection._dropCollection() UserLink.Meta.collection._dropCollection() PostLink.Meta.collection._dropCollection() CircularFirst.Meta.collection._dropCollection() CircularSecond.Meta.collection._dropCollection() Person.Meta.collection._dropCollection() SpecialPerson.Meta.collection._dropCollection() Recursive.Meta.collection._dropCollection() IdentityGenerator.Meta.collection._dropCollection() SpecialPost.Meta.collection._dropCollection() SubfieldItem.Meta.collection._dropCollection() catch error throw error unless /ns not found/.test "#{error}" Meteor.publish null, -> Post.documents.find() # User is already published as Meteor.users Meteor.publish null, -> UserLink.documents.find() Meteor.publish null, -> PostLink.documents.find() Meteor.publish null, -> CircularFirst.documents.find() Meteor.publish null, -> CircularSecond.documents.find() Meteor.publish null, -> Person.documents.find() Meteor.publish null, -> Recursive.documents.find() Meteor.publish null, -> IdentityGenerator.documents.find() Meteor.publish null, -> SpecialPost.documents.find() Meteor.publish null, -> SubfieldItem.documents.find() Future = Npm.require 'fibers/future' Meteor.methods 'wait-for-database': -> future = new Future() timeout = null newTimeout = -> Meteor.clearTimeout timeout if timeout timeout = Meteor.setTimeout -> timeout = null future.return() unless future.isResolved() , WAIT_FOR_DATABASE_TIMEOUT newTimeout() handles = [] for document in Document.list do (document) -> handles.push document.documents.find({}).observeChanges added: (id, fields) -> newTimeout() changed: (id, fields) -> newTimeout() removed: (id) -> newTimeout() future.wait() for handle in handles handle.stop() waitForDatabase = (test, expect) -> Meteor.call 'wait-for-database', expect (error) -> test.isFalse error, error?.toString?() or error ALL = @ALL = [User, UserLink, CircularFirst, CircularSecond, SpecialPerson, Recursive, IdentityGenerator, SpecialPost, Post, Person, PostLink, SubfieldItem, LocalPost, LocalPerson] testDocumentList = (test, list) -> test.equal Document.list, list, "expected: #{ (d.Meta._name for d in list) } vs. actual: #{ (d.Meta._name for d in Document.list) }" intersectionObjects = (array, rest...) -> _.filter _.uniq(array), (item) -> _.every rest, (other) -> _.any other, (element) -> _.isEqual element, item testSetEqual = (test, a, b) -> a ||= [] b ||= [] if a.length is b.length and intersectionObjects(a, b).length is a.length test.ok() else test.fail type: 'assert_set_equal' actual: JSON.stringify a expected: JSON.stringify b testDefinition = (test) -> test.equal Post.Meta._name, 'Post' test.equal Post.Meta.parent, _TestPost2.Meta test.equal Post.Meta.document, Post test.equal Post.Meta.collection._name, 'Posts' test.equal _.size(Post.Meta.triggers), 1 test.instanceOf Post.Meta.triggers.testTrigger, Post._Trigger test.equal Post.Meta.triggers.testTrigger.name, 'testTrigger' test.equal Post.Meta.triggers.testTrigger.document, Post test.equal Post.Meta.triggers.testTrigger.collection._name, 'Posts' test.equal Post.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(Post.Meta.generators), 2 test.equal _.size(Post.Meta.generators.subdocument), 1 test.instanceOf Post.Meta.generators.subdocument.slug, Post._GeneratedField test.isNull Post.Meta.generators.subdocument.slug.ancestorArray, Post.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction Post.Meta.generators.subdocument.slug.generator test.equal Post.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal Post.Meta.generators.subdocument.slug.sourceDocument, Post test.equal Post.Meta.generators.subdocument.slug.targetDocument, Post test.equal Post.Meta.generators.subdocument.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetCollection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.generators.subdocument.slug.reverseName test.isUndefined Post.Meta.generators.subdocument.slug.reverseFields test.instanceOf Post.Meta.generators.tags, Post._GeneratedField test.equal Post.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction Post.Meta.generators.tags.generator test.equal Post.Meta.generators.tags.sourcePath, 'tags' test.equal Post.Meta.generators.tags.sourceDocument, Post test.equal Post.Meta.generators.tags.targetDocument, Post test.equal Post.Meta.generators.tags.sourceCollection._name, 'Posts' test.equal Post.Meta.generators.tags.targetCollection._name, 'Posts' test.equal Post.Meta.generators.tags.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined Post.Meta.generators.tags.reverseName test.isUndefined Post.Meta.generators.tags.reverseFields test.equal _.size(Post.Meta.fields), 6 test.instanceOf Post.Meta.fields.author, Post._ReferenceField test.isNull Post.Meta.fields.author.ancestorArray, Post.Meta.fields.author.ancestorArray test.isTrue Post.Meta.fields.author.required test.equal Post.Meta.fields.author.sourcePath, 'author' test.equal Post.Meta.fields.author.sourceDocument, Post test.equal Post.Meta.fields.author.targetDocument, Person test.equal Post.Meta.fields.author.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.author.targetCollection._name, 'Persons' test.equal Post.Meta.fields.author.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.author.reverseName, 'posts' test.equal Post.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subscribers, Post._ReferenceField test.equal Post.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue Post.Meta.fields.subscribers.required test.equal Post.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal Post.Meta.fields.subscribers.sourceDocument, Post test.equal Post.Meta.fields.subscribers.targetDocument, Person test.equal Post.Meta.fields.subscribers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subscribers.fields, [] test.isNull Post.Meta.fields.subscribers.reverseName test.equal Post.Meta.fields.subscribers.reverseFields, [] test.instanceOf Post.Meta.fields.reviewers, Post._ReferenceField test.equal Post.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue Post.Meta.fields.reviewers.required test.equal Post.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal Post.Meta.fields.reviewers.sourceDocument, Post test.equal Post.Meta.fields.reviewers.targetDocument, Person test.equal Post.Meta.fields.reviewers.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal Post.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.reviewers.fields, [username: 1] test.isNull Post.Meta.fields.reviewers.reverseName test.equal Post.Meta.fields.reviewers.reverseFields, [] test.equal _.size(Post.Meta.fields.subdocument), 2 test.instanceOf Post.Meta.fields.subdocument.person, Post._ReferenceField test.isNull Post.Meta.fields.subdocument.person.ancestorArray, Post.Meta.fields.subdocument.person.ancestorArray test.isFalse Post.Meta.fields.subdocument.person.required test.equal Post.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal Post.Meta.fields.subdocument.person.sourceDocument, Post test.equal Post.Meta.fields.subdocument.person.targetDocument, Person test.equal Post.Meta.fields.subdocument.person.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal Post.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal Post.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.subdocument.persons, Post._ReferenceField test.equal Post.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue Post.Meta.fields.subdocument.persons.required test.equal Post.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument, Post test.equal Post.Meta.fields.subdocument.persons.targetDocument, Person test.equal Post.Meta.fields.subdocument.persons.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal Post.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(Post.Meta.fields.nested), 3 test.instanceOf Post.Meta.fields.nested.required, Post._ReferenceField test.equal Post.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue Post.Meta.fields.nested.required.required test.equal Post.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal Post.Meta.fields.nested.required.sourceDocument, Post test.equal Post.Meta.fields.nested.required.targetDocument, Person test.equal Post.Meta.fields.nested.required.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal Post.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal Post.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf Post.Meta.fields.nested.optional, Post._ReferenceField test.equal Post.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse Post.Meta.fields.nested.optional.required test.equal Post.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal Post.Meta.fields.nested.optional.sourceDocument, Post test.equal Post.Meta.fields.nested.optional.targetDocument, Person test.equal Post.Meta.fields.nested.optional.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal Post.Meta.fields.nested.optional.fields, ['username'] test.isNull Post.Meta.fields.nested.optional.reverseName test.equal Post.Meta.fields.nested.optional.reverseFields, [] test.instanceOf Post.Meta.fields.nested.slug, Post._GeneratedField test.equal Post.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction Post.Meta.fields.nested.slug.generator test.equal Post.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal Post.Meta.fields.nested.slug.sourceDocument, Post test.equal Post.Meta.fields.nested.slug.targetDocument, Post test.equal Post.Meta.fields.nested.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined Post.Meta.fields.nested.slug.reverseName test.isUndefined Post.Meta.fields.nested.slug.reverseFields test.instanceOf Post.Meta.fields.slug, Post._GeneratedField test.isNull Post.Meta.fields.slug.ancestorArray, Post.Meta.fields.slug.ancestorArray test.isTrue _.isFunction Post.Meta.fields.slug.generator test.equal Post.Meta.fields.slug.sourcePath, 'slug' test.equal Post.Meta.fields.slug.sourceDocument, Post test.equal Post.Meta.fields.slug.targetDocument, Post test.equal Post.Meta.fields.slug.sourceCollection._name, 'Posts' test.equal Post.Meta.fields.slug.targetCollection._name, 'Posts' test.equal Post.Meta.fields.slug.sourceDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.targetDocument.Meta.collection._name, 'Posts' test.equal Post.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined Post.Meta.fields.slug.reverseName test.isUndefined Post.Meta.fields.slug.reverseFields test.isTrue Post.Meta._observersSetup test.equal User.Meta._name, 'User' test.isFalse User.Meta.parent test.equal User.Meta.document, User test.equal User.Meta.collection._name, 'users' test.equal _.size(User.Meta.triggers), 0 test.equal _.size(User.Meta.fields), 0 test.isTrue User.Meta._observersSetup test.equal UserLink.Meta._name, 'UserLink' test.isFalse UserLink.Meta.parent test.equal UserLink.Meta.document, UserLink test.equal UserLink.Meta.collection._name, 'UserLinks' test.equal _.size(UserLink.Meta.triggers), 0 test.equal _.size(UserLink.Meta.fields), 1 test.instanceOf UserLink.Meta.fields.user, UserLink._ReferenceField test.isNull UserLink.Meta.fields.user.ancestorArray, UserLink.Meta.fields.user.ancestorArray test.isFalse UserLink.Meta.fields.user.required test.equal UserLink.Meta.fields.user.sourcePath, 'user' test.equal UserLink.Meta.fields.user.sourceDocument, UserLink test.equal UserLink.Meta.fields.user.targetDocument, User test.equal UserLink.Meta.fields.user.sourceCollection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.targetCollection._name, 'users' test.equal UserLink.Meta.fields.user.sourceDocument.Meta.collection._name, 'UserLinks' test.equal UserLink.Meta.fields.user.fields, ['username'] test.isNull UserLink.Meta.fields.user.reverseName test.equal UserLink.Meta.fields.user.reverseFields, [] test.isTrue UserLink.Meta._observersSetup test.equal PostLink.Meta._name, 'PostLink' test.equal PostLink.Meta.parent, _TestPostLink.Meta test.equal PostLink.Meta.document, PostLink test.equal PostLink.Meta.collection._name, 'PostLinks' test.equal _.size(PostLink.Meta.triggers), 0 test.equal _.size(PostLink.Meta.fields), 1 test.instanceOf PostLink.Meta.fields.post, PostLink._ReferenceField test.isNull PostLink.Meta.fields.post.ancestorArray, PostLink.Meta.fields.post.ancestorArray test.isTrue PostLink.Meta.fields.post.required test.equal PostLink.Meta.fields.post.sourcePath, 'post' test.equal PostLink.Meta.fields.post.sourceDocument, PostLink test.equal PostLink.Meta.fields.post.targetDocument, Post test.equal PostLink.Meta.fields.post.sourceCollection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.targetCollection._name, 'Posts' test.equal PostLink.Meta.fields.post.sourceDocument.Meta.collection._name, 'PostLinks' test.equal PostLink.Meta.fields.post.fields, ['subdocument.person', 'subdocument.persons'] test.isNull PostLink.Meta.fields.post.reverseName test.equal PostLink.Meta.fields.post.reverseFields, [] test.isTrue PostLink.Meta._observersSetup test.equal CircularFirst.Meta._name, 'CircularFirst' test.equal CircularFirst.Meta.parent, _TestCircularFirst.Meta test.equal CircularFirst.Meta.document, CircularFirst test.equal CircularFirst.Meta.collection._name, 'CircularFirsts' test.equal _.size(CircularFirst.Meta.triggers), 0 test.equal _.size(CircularFirst.Meta.fields), 2 test.instanceOf CircularFirst.Meta.fields.second, CircularFirst._ReferenceField test.isNull CircularFirst.Meta.fields.second.ancestorArray, CircularFirst.Meta.fields.second.ancestorArray test.isTrue CircularFirst.Meta.fields.second.required test.equal CircularFirst.Meta.fields.second.sourcePath, 'second' test.equal CircularFirst.Meta.fields.second.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.second.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.second.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.second.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.second.fields, ['content'] test.equal CircularFirst.Meta.fields.second.reverseName, 'reverseFirsts' test.equal CircularFirst.Meta.fields.second.reverseFields, ['content'] test.instanceOf CircularFirst.Meta.fields.reverseSeconds, CircularFirst._ReferenceField test.equal CircularFirst.Meta.fields.reverseSeconds.ancestorArray, 'reverseSeconds' test.isTrue CircularFirst.Meta.fields.reverseSeconds.required test.equal CircularFirst.Meta.fields.reverseSeconds.sourcePath, 'reverseSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument, CircularFirst test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument, CircularSecond test.equal CircularFirst.Meta.fields.reverseSeconds.sourceCollection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetCollection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.sourceDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularFirst.Meta.fields.reverseSeconds.targetDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularFirst.Meta.fields.reverseSeconds.fields, ['content'] test.isNull CircularFirst.Meta.fields.reverseSeconds.reverseName test.equal CircularFirst.Meta.fields.reverseSeconds.reverseFields, [] test.isTrue CircularFirst.Meta._observersSetup test.equal CircularSecond.Meta._name, 'CircularSecond' test.isFalse CircularSecond.Meta.parent test.equal CircularSecond.Meta.document, CircularSecond test.equal CircularSecond.Meta.collection._name, 'CircularSeconds' test.equal _.size(CircularSecond.Meta.triggers), 0 test.equal _.size(CircularSecond.Meta.fields), 2 test.instanceOf CircularSecond.Meta.fields.first, CircularSecond._ReferenceField test.isNull CircularSecond.Meta.fields.first.ancestorArray, CircularSecond.Meta.fields.first.ancestorArray test.isFalse CircularSecond.Meta.fields.first.required test.equal CircularSecond.Meta.fields.first.sourcePath, 'first' test.equal CircularSecond.Meta.fields.first.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.first.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.first.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.first.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.first.fields, ['content'] test.equal CircularSecond.Meta.fields.first.reverseName, 'reverseSeconds' test.equal CircularSecond.Meta.fields.first.reverseFields, ['content'] test.instanceOf CircularSecond.Meta.fields.reverseFirsts, CircularSecond._ReferenceField test.equal CircularSecond.Meta.fields.reverseFirsts.ancestorArray, 'reverseFirsts' test.isTrue CircularSecond.Meta.fields.reverseFirsts.required test.equal CircularSecond.Meta.fields.reverseFirsts.sourcePath, 'reverseFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument, CircularSecond test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument, CircularFirst test.equal CircularSecond.Meta.fields.reverseFirsts.sourceCollection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetCollection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.sourceDocument.Meta.collection._name, 'CircularSeconds' test.equal CircularSecond.Meta.fields.reverseFirsts.targetDocument.Meta.collection._name, 'CircularFirsts' test.equal CircularSecond.Meta.fields.reverseFirsts.fields, ['content'] test.isNull CircularSecond.Meta.fields.reverseFirsts.reverseName test.equal CircularSecond.Meta.fields.reverseFirsts.reverseFields, [] test.isTrue CircularSecond.Meta._observersSetup test.equal Person.Meta._name, 'Person' test.equal Person.Meta.parent, _TestPerson.Meta test.equal Person.Meta.document, Person test.equal Person.Meta.collection._name, 'Persons' test.equal _.size(Person.Meta.triggers), 0 test.equal _.size(Person.Meta.generators), 1 test.instanceOf Person.Meta.generators.count, Person._GeneratedField test.isNull Person.Meta.generators.count.ancestorArray, Person.Meta.generators.count.ancestorArray test.isTrue _.isFunction Person.Meta.generators.count.generator test.equal Person.Meta.generators.count.sourcePath, 'count' test.equal Person.Meta.generators.count.sourceDocument, Person test.equal Person.Meta.generators.count.targetDocument, Person test.equal Person.Meta.generators.count.sourceCollection._name, 'Persons' test.equal Person.Meta.generators.count.targetCollection._name, 'Persons' test.equal Person.Meta.generators.count.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.targetDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.generators.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined Person.Meta.generators.count.reverseName test.isUndefined Person.Meta.generators.count.reverseFields test.equal _.size(Person.Meta.fields), 4 test.instanceOf Person.Meta.fields.posts, Person._ReferenceField test.equal Person.Meta.fields.posts.ancestorArray, 'posts' test.isTrue Person.Meta.fields.posts.required test.equal Person.Meta.fields.posts.sourcePath, 'posts' test.equal Person.Meta.fields.posts.sourceDocument, Person test.equal Person.Meta.fields.posts.targetDocument, Post test.equal Person.Meta.fields.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.posts.reverseName test.equal Person.Meta.fields.posts.reverseFields, [] test.instanceOf Person.Meta.fields.nestedPosts, Person._ReferenceField test.equal Person.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue Person.Meta.fields.nestedPosts.required test.equal Person.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal Person.Meta.fields.nestedPosts.sourceDocument, Person test.equal Person.Meta.fields.nestedPosts.targetDocument, Post test.equal Person.Meta.fields.nestedPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.nestedPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.nestedPosts.reverseName test.equal Person.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocument.posts, Person._ReferenceField test.equal Person.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue Person.Meta.fields.subdocument.posts.required test.equal Person.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument, Person test.equal Person.Meta.fields.subdocument.posts.targetDocument, Post test.equal Person.Meta.fields.subdocument.posts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocument.posts.reverseName test.equal Person.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf Person.Meta.fields.subdocumentsPosts, Person._ReferenceField test.equal Person.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue Person.Meta.fields.subdocumentsPosts.required test.equal Person.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument, Person test.equal Person.Meta.fields.subdocumentsPosts.targetDocument, Post test.equal Person.Meta.fields.subdocumentsPosts.sourceCollection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetCollection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name, 'Persons' test.equal Person.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name, 'Posts' test.equal Person.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull Person.Meta.fields.subdocumentsPosts.reverseName test.equal Person.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue Person.Meta._observersSetup test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.parent, Person.Meta test.equal SpecialPerson.Meta.document, SpecialPerson test.equal SpecialPerson.Meta._name, 'SpecialPerson' test.equal SpecialPerson.Meta.collection._name, 'SpecialPersons' test.equal _.size(SpecialPerson.Meta.triggers), 0 test.equal _.size(SpecialPerson.Meta.fields), 0 test.isTrue SpecialPerson.Meta._observersSetup test.equal Recursive.Meta._name, 'Recursive' test.isFalse Recursive.Meta.parent test.equal Recursive.Meta.document, Recursive test.equal Recursive.Meta.collection._name, 'Recursives' test.equal _.size(Recursive.Meta.triggers), 0 test.equal _.size(Recursive.Meta.fields), 2 test.instanceOf Recursive.Meta.fields.other, Recursive._ReferenceField test.isNull Recursive.Meta.fields.other.ancestorArray, Recursive.Meta.fields.other.ancestorArray test.isFalse Recursive.Meta.fields.other.required test.equal Recursive.Meta.fields.other.sourcePath, 'other' test.equal Recursive.Meta.fields.other.sourceDocument, Recursive test.equal Recursive.Meta.fields.other.targetDocument, Recursive test.equal Recursive.Meta.fields.other.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.other.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.other.fields, ['content'] test.equal Recursive.Meta.fields.other.reverseName, 'reverse' test.equal Recursive.Meta.fields.other.reverseFields, ['content'] test.instanceOf Recursive.Meta.fields.reverse, Recursive._ReferenceField test.equal Recursive.Meta.fields.reverse.ancestorArray, 'reverse' test.isTrue Recursive.Meta.fields.reverse.required test.equal Recursive.Meta.fields.reverse.sourcePath, 'reverse' test.equal Recursive.Meta.fields.reverse.sourceDocument, Recursive test.equal Recursive.Meta.fields.reverse.targetDocument, Recursive test.equal Recursive.Meta.fields.reverse.sourceCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetCollection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.sourceDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.targetDocument.Meta.collection._name, 'Recursives' test.equal Recursive.Meta.fields.reverse.fields, ['content'] test.isNull Recursive.Meta.fields.reverse.reverseName test.equal Recursive.Meta.fields.reverse.reverseFields, [] test.isTrue Recursive.Meta._observersSetup test.equal IdentityGenerator.Meta._name, 'IdentityGenerator' test.isFalse IdentityGenerator.Meta.parent test.equal IdentityGenerator.Meta.document, IdentityGenerator test.equal IdentityGenerator.Meta.collection._name, 'IdentityGenerators' test.equal _.size(IdentityGenerator.Meta.triggers), 0 test.equal _.size(IdentityGenerator.Meta.generators), 2 test.instanceOf IdentityGenerator.Meta.generators.result, IdentityGenerator._GeneratedField test.isNull IdentityGenerator.Meta.generators.result.ancestorArray, IdentityGenerator.Meta.generators.result.ancestorArray test.isTrue _.isFunction IdentityGenerator.Meta.generators.result.generator test.equal IdentityGenerator.Meta.generators.result.sourcePath, 'result' test.equal IdentityGenerator.Meta.generators.result.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.result.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.result.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.result.reverseName test.isUndefined IdentityGenerator.Meta.generators.result.reverseFields test.instanceOf IdentityGenerator.Meta.generators.results, IdentityGenerator._GeneratedField test.equal IdentityGenerator.Meta.generators.results.ancestorArray, 'results' test.isTrue _.isFunction IdentityGenerator.Meta.generators.results.generator test.equal IdentityGenerator.Meta.generators.results.sourcePath, 'results' test.equal IdentityGenerator.Meta.generators.results.sourceDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.targetDocument, IdentityGenerator test.equal IdentityGenerator.Meta.generators.results.sourceCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetCollection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.sourceDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.targetDocument.Meta.collection._name, 'IdentityGenerators' test.equal IdentityGenerator.Meta.generators.results.fields, ['source'] test.isUndefined IdentityGenerator.Meta.generators.results.reverseName test.isUndefined IdentityGenerator.Meta.generators.results.reverseFields test.equal _.size(IdentityGenerator.Meta.fields), 0 test.isTrue IdentityGenerator.Meta._observersSetup test.equal SpecialPost.Meta._name, 'SpecialPost' test.equal SpecialPost.Meta.parent, _TestPost2.Meta test.equal SpecialPost.Meta.document, SpecialPost test.equal SpecialPost.Meta.collection._name, 'SpecialPosts' test.equal _.size(SpecialPost.Meta.triggers), 1 test.instanceOf SpecialPost.Meta.triggers.testTrigger, SpecialPost._Trigger test.equal SpecialPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal SpecialPost.Meta.triggers.testTrigger.document, SpecialPost test.equal SpecialPost.Meta.triggers.testTrigger.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(SpecialPost.Meta.generators), 2 test.equal _.size(SpecialPost.Meta.generators.subdocument), 1 test.instanceOf SpecialPost.Meta.generators.subdocument.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.generators.subdocument.slug.ancestorArray, SpecialPost.Meta.generators.subdocument.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.generators.subdocument.slug.generator test.equal SpecialPost.Meta.generators.subdocument.slug.sourcePath, 'subdocument.slug' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.subdocument.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseName test.isUndefined SpecialPost.Meta.generators.subdocument.slug.reverseFields test.instanceOf SpecialPost.Meta.generators.tags, SpecialPost._GeneratedField test.equal SpecialPost.Meta.generators.tags.ancestorArray, 'tags' test.isTrue _.isFunction SpecialPost.Meta.generators.tags.generator test.equal SpecialPost.Meta.generators.tags.sourcePath, 'tags' test.equal SpecialPost.Meta.generators.tags.sourceDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.targetDocument, SpecialPost test.equal SpecialPost.Meta.generators.tags.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.generators.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined SpecialPost.Meta.generators.tags.reverseName test.isUndefined SpecialPost.Meta.generators.tags.reverseFields test.equal _.size(SpecialPost.Meta.fields), 7 test.instanceOf SpecialPost.Meta.fields.author, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.author.ancestorArray, SpecialPost.Meta.fields.author.ancestorArray test.isTrue SpecialPost.Meta.fields.author.required test.equal SpecialPost.Meta.fields.author.sourcePath, 'author' test.equal SpecialPost.Meta.fields.author.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.author.targetDocument, Person test.equal SpecialPost.Meta.fields.author.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.author.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.author.reverseName, 'posts' test.equal SpecialPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subscribers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue SpecialPost.Meta.fields.subscribers.required test.equal SpecialPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subscribers.targetDocument, Person test.equal SpecialPost.Meta.fields.subscribers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subscribers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subscribers.fields, [] test.isNull SpecialPost.Meta.fields.subscribers.reverseName test.equal SpecialPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.reviewers, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue SpecialPost.Meta.fields.reviewers.required test.equal SpecialPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.reviewers.targetDocument, Person test.equal SpecialPost.Meta.fields.reviewers.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.reviewers.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.reviewers.fields, [username: 1] test.isNull SpecialPost.Meta.fields.reviewers.reverseName test.equal SpecialPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(SpecialPost.Meta.fields.subdocument), 2 test.instanceOf SpecialPost.Meta.fields.subdocument.person, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.subdocument.person.ancestorArray, SpecialPost.Meta.fields.subdocument.person.ancestorArray test.isFalse SpecialPost.Meta.fields.subdocument.person.required test.equal SpecialPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.person.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal SpecialPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal SpecialPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.subdocument.persons, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue SpecialPost.Meta.fields.subdocument.persons.required test.equal SpecialPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument, Person test.equal SpecialPost.Meta.fields.subdocument.persons.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal SpecialPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.equal _.size(SpecialPost.Meta.fields.nested), 3 test.instanceOf SpecialPost.Meta.fields.nested.required, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue SpecialPost.Meta.fields.nested.required.required test.equal SpecialPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.required.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.required.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.required.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal SpecialPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal SpecialPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf SpecialPost.Meta.fields.nested.optional, SpecialPost._ReferenceField test.equal SpecialPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse SpecialPost.Meta.fields.nested.optional.required test.equal SpecialPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.optional.targetDocument, Person test.equal SpecialPost.Meta.fields.nested.optional.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.nested.optional.fields, ['username'] test.isNull SpecialPost.Meta.fields.nested.optional.reverseName test.equal SpecialPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf SpecialPost.Meta.fields.nested.slug, SpecialPost._GeneratedField test.equal SpecialPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction SpecialPost.Meta.fields.nested.slug.generator test.equal SpecialPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.nested.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseName test.isUndefined SpecialPost.Meta.fields.nested.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.slug, SpecialPost._GeneratedField test.isNull SpecialPost.Meta.fields.slug.ancestorArray, SpecialPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction SpecialPost.Meta.fields.slug.generator test.equal SpecialPost.Meta.fields.slug.sourcePath, 'slug' test.equal SpecialPost.Meta.fields.slug.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.targetDocument, SpecialPost test.equal SpecialPost.Meta.fields.slug.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.targetDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined SpecialPost.Meta.fields.slug.reverseName test.isUndefined SpecialPost.Meta.fields.slug.reverseFields test.instanceOf SpecialPost.Meta.fields.special, SpecialPost._ReferenceField test.isNull SpecialPost.Meta.fields.special.ancestorArray, SpecialPost.Meta.fields.special.ancestorArray test.isTrue SpecialPost.Meta.fields.special.required test.equal SpecialPost.Meta.fields.special.sourcePath, 'special' test.equal SpecialPost.Meta.fields.special.sourceDocument, SpecialPost test.equal SpecialPost.Meta.fields.special.targetDocument, Person test.equal SpecialPost.Meta.fields.special.sourceCollection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetCollection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.sourceDocument.Meta.collection._name, 'SpecialPosts' test.equal SpecialPost.Meta.fields.special.targetDocument.Meta.collection._name, 'Persons' test.equal SpecialPost.Meta.fields.special.fields, [] test.isNull SpecialPost.Meta.fields.special.reverseName test.equal SpecialPost.Meta.fields.special.reverseFields, [] test.isTrue SpecialPost.Meta._observersSetup test.equal LocalPost.Meta._name, 'LocalPost' test.equal LocalPost.Meta.document, LocalPost test.isNull LocalPost.Meta.collection._name test.equal _.size(LocalPost.Meta.triggers), 1 test.instanceOf LocalPost.Meta.triggers.testTrigger, LocalPost._Trigger test.equal LocalPost.Meta.triggers.testTrigger.name, 'testTrigger' test.equal LocalPost.Meta.triggers.testTrigger.document, LocalPost test.isNull LocalPost.Meta.triggers.testTrigger.collection._name test.equal LocalPost.Meta.triggers.testTrigger.fields, ['body'] test.equal _.size(LocalPost.Meta.fields), 7 test.instanceOf LocalPost.Meta.fields.author, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.author.ancestorArray, LocalPost.Meta.fields.author.ancestorArray test.isTrue LocalPost.Meta.fields.author.required test.equal LocalPost.Meta.fields.author.sourcePath, 'author' test.equal LocalPost.Meta.fields.author.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.author.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.author.sourceCollection._name test.isNull LocalPost.Meta.fields.author.targetCollection._name test.isNull LocalPost.Meta.fields.author.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.author.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.author.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.author.reverseName, 'posts' test.equal LocalPost.Meta.fields.author.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subscribers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subscribers.ancestorArray, 'subscribers' test.isTrue LocalPost.Meta.fields.subscribers.required test.equal LocalPost.Meta.fields.subscribers.sourcePath, 'subscribers' test.equal LocalPost.Meta.fields.subscribers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subscribers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subscribers.sourceCollection._name test.isNull LocalPost.Meta.fields.subscribers.targetCollection._name test.isNull LocalPost.Meta.fields.subscribers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subscribers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subscribers.fields, [] test.isNull LocalPost.Meta.fields.subscribers.reverseName test.equal LocalPost.Meta.fields.subscribers.reverseFields, [] test.instanceOf LocalPost.Meta.fields.reviewers, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.reviewers.ancestorArray, 'reviewers' test.isTrue LocalPost.Meta.fields.reviewers.required test.equal LocalPost.Meta.fields.reviewers.sourcePath, 'reviewers' test.equal LocalPost.Meta.fields.reviewers.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.reviewers.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.reviewers.sourceCollection._name test.isNull LocalPost.Meta.fields.reviewers.targetCollection._name test.isNull LocalPost.Meta.fields.reviewers.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.reviewers.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.reviewers.fields, [username: 1] test.isNull LocalPost.Meta.fields.reviewers.reverseName test.equal LocalPost.Meta.fields.reviewers.reverseFields, [] test.equal _.size(LocalPost.Meta.fields.subdocument), 3 test.instanceOf LocalPost.Meta.fields.subdocument.person, LocalPost._ReferenceField test.isNull LocalPost.Meta.fields.subdocument.person.ancestorArray, LocalPost.Meta.fields.subdocument.person.ancestorArray test.isFalse LocalPost.Meta.fields.subdocument.person.required test.equal LocalPost.Meta.fields.subdocument.person.sourcePath, 'subdocument.person' test.equal LocalPost.Meta.fields.subdocument.person.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.person.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.person.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.person.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.person.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.person.fields, {'username': 1, 'displayName': 1, 'field1': 1, 'field2': 1} test.equal LocalPost.Meta.fields.subdocument.person.reverseName, 'subdocument.posts' test.equal LocalPost.Meta.fields.subdocument.person.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.persons, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.subdocument.persons.ancestorArray, 'subdocument.persons' test.isTrue LocalPost.Meta.fields.subdocument.persons.required test.equal LocalPost.Meta.fields.subdocument.persons.sourcePath, 'subdocument.persons' test.equal LocalPost.Meta.fields.subdocument.persons.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.persons.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.subdocument.persons.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.persons.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.persons.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.persons.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.subdocument.persons.reverseName, 'subdocumentsPosts' test.equal LocalPost.Meta.fields.subdocument.persons.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.subdocument.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.subdocument.slug.ancestorArray, LocalPost.Meta.fields.subdocument.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.subdocument.slug.generator test.equal LocalPost.Meta.fields.subdocument.slug.sourcePath, 'subdocument.slug' test.equal LocalPost.Meta.fields.subdocument.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.subdocument.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.subdocument.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetCollection._name test.isNull LocalPost.Meta.fields.subdocument.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.subdocument.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.subdocument.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseName test.isUndefined LocalPost.Meta.fields.subdocument.slug.reverseFields test.equal _.size(LocalPost.Meta.fields.nested), 3 test.instanceOf LocalPost.Meta.fields.nested.required, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.required.ancestorArray, 'nested' test.isTrue LocalPost.Meta.fields.nested.required.required test.equal LocalPost.Meta.fields.nested.required.sourcePath, 'nested.required' test.equal LocalPost.Meta.fields.nested.required.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.required.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.required.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.required.targetCollection._name test.isNull LocalPost.Meta.fields.nested.required.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.required.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.required.fields, ['username', 'displayName', 'field1', 'field2'] test.equal LocalPost.Meta.fields.nested.required.reverseName, 'nestedPosts' test.equal LocalPost.Meta.fields.nested.required.reverseFields, ['body', 'subdocument.body', 'nested.body'] test.instanceOf LocalPost.Meta.fields.nested.optional, LocalPost._ReferenceField test.equal LocalPost.Meta.fields.nested.optional.ancestorArray, 'nested' test.isFalse LocalPost.Meta.fields.nested.optional.required test.equal LocalPost.Meta.fields.nested.optional.sourcePath, 'nested.optional' test.equal LocalPost.Meta.fields.nested.optional.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.optional.targetDocument, LocalPerson test.isNull LocalPost.Meta.fields.nested.optional.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.optional.targetCollection._name test.isNull LocalPost.Meta.fields.nested.optional.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.optional.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.optional.fields, ['username'] test.isNull LocalPost.Meta.fields.nested.optional.reverseName test.equal LocalPost.Meta.fields.nested.optional.reverseFields, [] test.instanceOf LocalPost.Meta.fields.nested.slug, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.nested.slug.ancestorArray, 'nested' test.isTrue _.isFunction LocalPost.Meta.fields.nested.slug.generator test.equal LocalPost.Meta.fields.nested.slug.sourcePath, 'nested.slug' test.equal LocalPost.Meta.fields.nested.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.nested.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.nested.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.nested.slug.targetCollection._name test.isNull LocalPost.Meta.fields.nested.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.nested.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.nested.slug.fields, ['body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.nested.slug.reverseName test.isUndefined LocalPost.Meta.fields.nested.slug.reverseFields test.instanceOf LocalPost.Meta.fields.slug, LocalPost._GeneratedField test.isNull LocalPost.Meta.fields.slug.ancestorArray, LocalPost.Meta.fields.slug.ancestorArray test.isTrue _.isFunction LocalPost.Meta.fields.slug.generator test.equal LocalPost.Meta.fields.slug.sourcePath, 'slug' test.equal LocalPost.Meta.fields.slug.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.slug.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.slug.sourceCollection._name test.isNull LocalPost.Meta.fields.slug.targetCollection._name test.isNull LocalPost.Meta.fields.slug.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.slug.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.slug.fields, ['body', 'subdocument.body'] test.isUndefined LocalPost.Meta.fields.slug.reverseName test.isUndefined LocalPost.Meta.fields.slug.reverseFields test.instanceOf LocalPost.Meta.fields.tags, LocalPost._GeneratedField test.equal LocalPost.Meta.fields.tags.ancestorArray, 'tags' test.isTrue _.isFunction LocalPost.Meta.fields.tags.generator test.equal LocalPost.Meta.fields.tags.sourcePath, 'tags' test.equal LocalPost.Meta.fields.tags.sourceDocument, LocalPost test.equal LocalPost.Meta.fields.tags.targetDocument, LocalPost test.isNull LocalPost.Meta.fields.tags.sourceCollection._name test.isNull LocalPost.Meta.fields.tags.targetCollection._name test.isNull LocalPost.Meta.fields.tags.sourceDocument.Meta.collection._name test.isNull LocalPost.Meta.fields.tags.targetDocument.Meta.collection._name test.equal LocalPost.Meta.fields.tags.fields, ['body', 'subdocument.body', 'nested.body'] test.isUndefined LocalPost.Meta.fields.tags.reverseName test.isUndefined LocalPost.Meta.fields.tags.reverseFields test.isTrue LocalPost.Meta._observersSetup test.equal LocalPerson.Meta._name, 'LocalPerson' test.equal LocalPerson.Meta.document, LocalPerson test.isNull LocalPerson.Meta.collection._name test.equal _.size(LocalPerson.Meta.triggers), 0 test.equal _.size(LocalPerson.Meta.fields), 5 test.instanceOf LocalPerson.Meta.fields.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.posts.ancestorArray, 'posts' test.isTrue LocalPerson.Meta.fields.posts.required test.equal LocalPerson.Meta.fields.posts.sourcePath, 'posts' test.equal LocalPerson.Meta.fields.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.posts.reverseName test.equal LocalPerson.Meta.fields.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.nestedPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.nestedPosts.ancestorArray, 'nestedPosts' test.isTrue LocalPerson.Meta.fields.nestedPosts.required test.equal LocalPerson.Meta.fields.nestedPosts.sourcePath, 'nestedPosts' test.equal LocalPerson.Meta.fields.nestedPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.nestedPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.nestedPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.nestedPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.nestedPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.nestedPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.nestedPosts.reverseName test.equal LocalPerson.Meta.fields.nestedPosts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.count, LocalPerson._GeneratedField test.isNull LocalPerson.Meta.fields.count.ancestorArray, LocalPerson.Meta.fields.count.ancestorArray test.isTrue _.isFunction LocalPerson.Meta.fields.count.generator test.equal LocalPerson.Meta.fields.count.sourcePath, 'count' test.equal LocalPerson.Meta.fields.count.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.count.targetDocument, LocalPerson test.isNull LocalPerson.Meta.fields.count.sourceCollection._name test.isNull LocalPerson.Meta.fields.count.targetCollection._name test.isNull LocalPerson.Meta.fields.count.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.count.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.count.fields, ['posts', 'subdocument.posts', 'subdocumentsPosts', 'nestedPosts'] test.isUndefined LocalPerson.Meta.fields.count.reverseName test.isUndefined LocalPerson.Meta.fields.count.reverseFields test.instanceOf LocalPerson.Meta.fields.subdocument.posts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocument.posts.ancestorArray, 'subdocument.posts' test.isTrue LocalPerson.Meta.fields.subdocument.posts.required test.equal LocalPerson.Meta.fields.subdocument.posts.sourcePath, 'subdocument.posts' test.equal LocalPerson.Meta.fields.subdocument.posts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocument.posts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocument.posts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocument.posts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocument.posts.reverseName test.equal LocalPerson.Meta.fields.subdocument.posts.reverseFields, [] test.instanceOf LocalPerson.Meta.fields.subdocumentsPosts, LocalPerson._ReferenceField test.equal LocalPerson.Meta.fields.subdocumentsPosts.ancestorArray, 'subdocumentsPosts' test.isTrue LocalPerson.Meta.fields.subdocumentsPosts.required test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourcePath, 'subdocumentsPosts' test.equal LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument, LocalPerson test.equal LocalPerson.Meta.fields.subdocumentsPosts.targetDocument, LocalPost test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetCollection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.sourceDocument.Meta.collection._name test.isNull LocalPerson.Meta.fields.subdocumentsPosts.targetDocument.Meta.collection._name test.equal LocalPerson.Meta.fields.subdocumentsPosts.fields, ['body', 'subdocument.body', 'nested.body'] test.isNull LocalPerson.Meta.fields.subdocumentsPosts.reverseName test.equal LocalPerson.Meta.fields.subdocumentsPosts.reverseFields, [] test.isTrue LocalPerson.Meta._observersSetup testDocumentList test, ALL plainObject = (obj) -> return obj unless _.isObject obj return (plainObject o for o in obj) if _.isArray obj keys = _.keys obj values = (plainObject o for o in _.values obj) _.object keys, values for name, documents of {server: {Person: Person, Post: Post}, local: {Person: LocalPerson, Post: LocalPost}} do (documents) -> testAsyncMulti "peerdb - references #{name}", [ (test, expect) -> testDefinition test # We should be able to call defineAll multiple times Document.defineAll() testDefinition test documents.Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id documents.Person.documents.insert username: 'person2' displayName: 'Person PI:NAME:<NAME>END_PI' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id documents.Person.documents.insert username: 'person3' displayName: 'PI:NAME:<NAME>END_PI' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to run (but no post is yet made, so nothing really happens). # We want to wait here so that we catch possible errors in source observers, otherwise target # observers can patch things up. For example, if we create a post first and target observers # (triggered by person inserts, but pending) run afterwards, then they can patch things which # should in fact be done by source observers (on post), like setting usernames in post's # references to persons. waitForDatabase test, expect , (test, expect) -> # Should work also with no argument (defaults to {}). test.isTrue documents.Person.documents.exists() test.isTrue documents.Person.documents.find().exists() test.isTrue documents.Person.documents.exists @person1Id test.isTrue documents.Person.documents.exists @person2Id test.isTrue documents.Person.documents.exists @person3Id test.isTrue documents.Person.documents.find(@person1Id).exists() test.isTrue documents.Person.documents.find(@person2Id).exists() test.isTrue documents.Person.documents.find(@person3Id).exists() test.equal documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).count(), 3 # Test without skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}).exists() # With sorting. We are testing all this combinations because there are various code paths. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {sort: [['username', 'asc']]}).exists() # Test with skip and limit. # This behaves differently than .count() on the server because on the server # applySkipLimit is not set. But exists do respect skip and limit. test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1}).exists() test.isTrue documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}) test.isTrue documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 2, limit: 1, sort: [['username', 'asc']]}).exists() test.isFalse documents.Person.documents.exists({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}) test.isFalse documents.Person.documents.find({_id: $in: [@person1Id, @person2Id, @person3Id]}, {skip: 3, limit: 1, sort: [['username', 'asc']]}).exists() @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 documents.Post.documents.insert author: _id: @person1._id # To test what happens if all fields are not up to date username: 'wrong' displayName: 'wrong' field1: 'wrong' field2: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: 'wrong' , _id: @person3._id username: 'wrong' ] subdocument: person: _id: @person2._id username: 'wrong' persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id username: 'wrong' body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # We inserted the document only with ids - subdocuments should be # automatically populated with additional fields as defined in @ReferenceField test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res documents.Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> documents.Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res , (test, expect) -> @person1 = documents.Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = documents.Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = documents.Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 1 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person3 was removed, references should be removed as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id ] reviewers: [ _id: @person2._id username: @person2.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: null slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] documents.Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # person2 was removed, references should be removed as well, automatically, # but lists should be kept as empty lists test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' ] documents.Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = documents.Post.documents.findOne @postId, transform: null # So that we can use test.equal # If directly referenced document is removed, dependency is removed as well test.isFalse @post, @post ] Tinytest.add 'peerdb - invalid optional', (test) -> test.throws -> class BadPost1 extends Document @Meta name: 'BadPost1' fields: -> reviewers: [@ReferenceField Person, ['username'], false] , /Reference field directly in an array cannot be optional/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - invalid nested arrays', (test) -> test.throws -> class BadPost2 extends Document @Meta name: 'BadPost2' fields: -> nested: [ many: [@ReferenceField Person, ['username']] ] , /Field cannot be in a nested array/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() Tinytest.add 'peerdb - abstract with parent', (test) -> test.throws -> class BadPost4 extends Post @Meta abstract: true , /Abstract document with a parent/ # Invalid document should not be added to the list testDocumentList test, ALL # Should not try to define invalid document again Document.defineAll() testAsyncMulti 'peerdb - circular changes', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected CircularFirst.documents.insert second: null content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@circularFirstId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Document 'CircularFirst' '#{ @circularFirstId }' field 'second' was updated with an invalid value: null" test.equal intercepted.level, 'error' @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: null content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' CircularFirst.documents.update @circularFirstId, $set: second: _id: @circularSecondId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.update @circularFirstId, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.update @circularSecondId, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2a' content: 'FooBar 1a' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2a' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1a' content: 'FooBar 2a' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1a' ] CircularSecond.documents.remove @circularSecondId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularSecond, @circularSecond # If directly referenced document is removed, dependency is removed as well test.isFalse @circularFirst, @circularFirst Log._intercept 1 if Meteor.isServer and Document.instances is 1 CircularSecond.documents.insert first: null content: 'FooBar 2' , expect (error, circularSecondId) => test.isFalse error, error?.toString?() or error test.isTrue circularSecondId @circularSecondId = circularSecondId , (test, expect) -> CircularFirst.documents.insert second: _id: @circularSecondId content: 'FooBar 1' , expect (error, circularFirstId) => test.isFalse error, error?.toString?() or error test.isTrue circularFirstId @circularFirstId = circularFirstId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() test.equal intercepted.length, 0, intercepted @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularSecond.documents.update @circularSecondId, $set: first: _id: @circularFirstId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.equal @circularFirst, _id: @circularFirstId second: _id: @circularSecondId content: 'FooBar 2' content: 'FooBar 1' reverseSeconds: [ _id: @circularSecondId content: 'FooBar 2' ] test.equal @circularSecond, _id: @circularSecondId first: _id: @circularFirstId content: 'FooBar 1' content: 'FooBar 2' reverseFirsts: [ _id: @circularFirstId content: 'FooBar 1' ] CircularFirst.documents.remove @circularFirstId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update document waitForDatabase test, expect , (test, expect) -> @circularFirst = CircularFirst.documents.findOne @circularFirstId, transform: null # So that we can use test.equal @circularSecond = CircularSecond.documents.findOne @circularSecondId, transform: null # So that we can use test.equal test.isFalse @circularFirst, @circularFirst # If directly referenced but optional document is removed, dependency is not removed as well, but set to null test.equal @circularSecond, _id: @circularSecondId first: null content: 'FooBar 2' reverseFirsts: [] ] testAsyncMulti 'peerdb - recursive two', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar 1' , expect (error, recursive1Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive1Id @recursive1Id = recursive1Id Recursive.documents.insert other: null content: 'FooBar 2' , expect (error, recursive2Id) => test.isFalse error, error?.toString?() or error test.isTrue recursive2Id @recursive2Id = recursive2Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' Recursive.documents.update @recursive1Id, $set: other: _id: @recursive2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' test.equal @recursive2, _id: @recursive2Id other: null content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive2Id, $set: other: _id: @recursive1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1' ] Recursive.documents.update @recursive1Id, $set: content: 'FooBar 1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.update @recursive2Id, $set: content: 'FooBar 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.equal @recursive1, _id: @recursive1Id other: _id: @recursive2Id content: 'FooBar 2a' content: 'FooBar 1a' reverse: [ _id: @recursive2Id content: 'FooBar 2a' ] test.equal @recursive2, _id: @recursive2Id other: _id: @recursive1Id content: 'FooBar 1a' content: 'FooBar 2a' reverse: [ _id: @recursive1Id content: 'FooBar 1a' ] Recursive.documents.remove @recursive2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive1 = Recursive.documents.findOne @recursive1Id, transform: null # So that we can use test.equal @recursive2 = Recursive.documents.findOne @recursive2Id, transform: null # So that we can use test.equal test.isFalse @recursive2, @recursive2 test.equal @recursive1, _id: @recursive1Id other: null content: 'FooBar 1a' reverse: [] ] testAsyncMulti 'peerdb - recursive one', [ (test, expect) -> Recursive.documents.insert other: null content: 'FooBar' , expect (error, recursiveId) => test.isFalse error, error?.toString?() or error test.isTrue recursiveId @recursiveId = recursiveId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: null content: 'FooBar' Recursive.documents.update @recursiveId, $set: other: _id: @recursiveId , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBar' content: 'FooBar' reverse: [ _id: @recursiveId content: 'FooBar' ] Recursive.documents.update @recursiveId, $set: content: 'FooBara' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.equal @recursive, _id: @recursiveId other: _id: @recursiveId content: 'FooBara' content: 'FooBara' reverse: [ _id: @recursiveId content: 'FooBara' ] Recursive.documents.remove @recursiveId, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @recursive = Recursive.documents.findOne @recursiveId, transform: null # So that we can use test.equal test.isFalse @recursive, @recursive ] if Meteor.isServer and Document.instances is 1 Tinytest.add 'peerdb - errors', (test) -> Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: _id: 'nonexistent' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: 'foobar' # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert subscribers: [ _id: 'nonexistent' ] # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'subscribers' is referencing a nonexistent document 'nonexistent'" test.equal intercepted.level, 'error' Log._intercept 2 # Two to see if we catch more than expected postId = Post.documents.insert author: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() test.equal intercepted.length, 1, intercepted test.isTrue _.isString(intercepted[0]), intercepted[0] intercepted = EJSON.parse intercepted[0] test.equal intercepted.message, "Document 'Post' '#{ postId }' field 'author' was updated with an invalid value: null" test.equal intercepted.level, 'error' Log._intercept 1 userLinkId = UserLink.documents.insert user: null # Wait so that observers have time to update documents Meteor.call 'wait-for-database' intercepted = Log._intercepted() # There should be no warning because user is optional test.equal intercepted.length, 0, intercepted testAsyncMulti 'peerdb - delayed defintion', [ (test, expect) -> class BadPost5 extends Document @Meta name: 'BadPost5' fields: -> author: @ReferenceField undefined, ['username'] Log._intercept 2 # Two to see if we catch more than expected # Sleep so that error is shown Meteor.setTimeout expect(), 1000 # We need 1000 here because we have a check which runs after 1000 ms to check for delayed definitions , (test, expect) -> intercepted = Log._intercepted() # One or two because we could intercepted something else as well test.isTrue 1 <= intercepted.length <= 2, intercepted # Let's find it for i in intercepted break if i.indexOf('BadPost5') isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message.lastIndexOf("Not all delayed document definitions were successfully retried:\nBadPost5 from"), 0, intercepted.message test.equal intercepted.level, 'error' testDocumentList test, ALL test.equal Document._delayed.length, 1 # Clear delayed so that we can retry tests without errors Document._delayed = [] Document._clearDelayedCheck() ] testAsyncMulti 'peerdb - subdocument fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] PostLink.documents.insert post: _id: @post._id , expect (error, postLinkId) => test.isFalse error, error?.toString?() or error test.isTrue postLinkId @postLinkId = postLinkId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] subdocumentsPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] nestedPosts: [ _id: @postId body: 'FooBar' nested: [ body: 'NestedFooBar' ] subdocument: body: 'SubdocumentFooBar' ] count: 3 @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.equal @postLink, _id: @postLinkId post: _id: @post._id subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] Post.documents.remove @post._id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @postLink = PostLink.documents.findOne @postLinkId, transform: null # So that we can use test.equal test.isFalse @postLink, @postLink ] testAsyncMulti 'peerdb - generated fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobar-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # All persons had usernames changed, they should # be updated in the post as well, automatically test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' ] Post.documents.update @postId, $set: body: null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: null body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: null body: 'NestedFooBarZ' ] body: null slug: null tags: [] Post.documents.update @postId, $unset: body: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username body: 'NestedFooBarZ' ] tags: [] ] Tinytest.add 'peerdb - chain of extended classes', (test) -> list = _.clone Document.list firstReferenceA = undefined # To force delayed secondReferenceA = undefined # To force delayed firstReferenceB = undefined # To force delayed secondReferenceB = undefined # To force delayed class First extends Document @Meta name: 'First' fields: -> first: @ReferenceField firstReferenceA class Second extends First @Meta name: 'Second' fields: (fields) -> fields.second = @ReferenceField Post # Not undefined, but overall meta will still be delayed fields class Third extends Second @Meta name: 'Third' fields: (fields) -> fields.third = @ReferenceField secondReferenceA fields testDocumentList test, ALL test.equal Document._delayed.length, 3 test.equal Document._delayed[0], First test.equal Document._delayed[1], Second test.equal Document._delayed[2], Third _TestFirst = First class First extends First @Meta name: 'First' replaceParent: true fields: (fields) -> fields.first = @ReferenceField firstReferenceB fields _TestSecond = Second class Second extends Second @Meta name: 'Second' replaceParent: true fields: (fields) -> fields.second = @ReferenceField Person # Not undefined, but overall meta will still be delayed fields _TestThird = Third class Third extends Third @Meta name: 'Third' replaceParent: true fields: (fields) -> fields.third = @ReferenceField secondReferenceB fields testDocumentList test, ALL test.equal Document._delayed.length, 6 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], Third _TestThird2 = Third class Third extends Third @Meta name: 'PI:NAME:<NAME>END_PI' replaceParent: true fields: (fields) -> fields.third = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 7 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], First test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third _TestFirst2 = First class First extends First @Meta name: 'PI:NAME:<NAME>END_PI' replaceParent: true fields: (fields) -> fields.first = @ReferenceField Person fields testDocumentList test, ALL test.equal Document._delayed.length, 8 test.equal Document._delayed[0], _TestFirst test.equal Document._delayed[1], _TestSecond test.equal Document._delayed[2], _TestThird test.equal Document._delayed[3], _TestFirst2 test.equal Document._delayed[4], Second test.equal Document._delayed[5], _TestThird2 test.equal Document._delayed[6], Third test.equal Document._delayed[7], First firstReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [_TestFirst, Second] test.equal Document._delayed.length, 5 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestFirst2 test.equal Document._delayed[2], _TestThird2 test.equal Document._delayed[3], Third test.equal Document._delayed[4], First test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] firstReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First] test.equal Document._delayed.length, 3 test.equal Document._delayed[0], _TestThird test.equal Document._delayed[1], _TestThird2 test.equal Document._delayed[2], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceA = First Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, _TestThird] test.equal Document._delayed.length, 2 test.equal Document._delayed[0], _TestThird2 test.equal Document._delayed[1], Third test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] secondReferenceB = Post Document._retryDelayed() testDocumentList test, ALL.concat [Second, First, Third] test.equal Document._delayed.length, 0 test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] Document.defineAll() test.equal Second.Meta._name, 'Second' test.equal Second.Meta.parent, _TestSecond.Meta test.equal Second.Meta.document, Second test.equal Second.Meta.collection._name, 'Seconds' test.equal _.size(Second.Meta.fields), 2 test.instanceOf Second.Meta.fields.first, Second._ReferenceField test.isFalse Second.Meta.fields.first.ancestorArray, Second.Meta.fields.first.ancestorArray test.isTrue Second.Meta.fields.first.required test.equal Second.Meta.fields.first.sourcePath, 'first' test.equal Second.Meta.fields.first.sourceDocument, Second test.equal Second.Meta.fields.first.targetDocument, firstReferenceA test.equal Second.Meta.fields.first.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Second.Meta.fields.first.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Second.Meta.fields.first.fields, [] test.isNull Second.Meta.fields.first.reverseName test.equal Second.Meta.fields.first.reverseFields, [] test.instanceOf Second.Meta.fields.second, Second._ReferenceField test.isFalse Second.Meta.fields.second.ancestorArray, Second.Meta.fields.second.ancestorArray test.isTrue Second.Meta.fields.second.required test.equal Second.Meta.fields.second.sourcePath, 'second' test.equal Second.Meta.fields.second.sourceDocument, Second test.equal Second.Meta.fields.second.targetDocument, Person test.equal Second.Meta.fields.second.sourceCollection._name, 'Seconds' test.equal Second.Meta.fields.second.targetCollection._name, 'Persons' test.equal Second.Meta.fields.second.sourceDocument.Meta.collection._name, 'Seconds' test.equal Second.Meta.fields.second.targetDocument.Meta.collection._name, 'Persons' test.equal Second.Meta.fields.second.fields, [] test.isNull Second.Meta.fields.second.reverseName test.equal Second.Meta.fields.second.reverseFields, [] test.equal First.Meta._name, 'First' test.equal First.Meta.parent, _TestFirst2.Meta test.equal First.Meta.document, First test.equal First.Meta.collection._name, 'Firsts' test.equal _.size(First.Meta.fields), 1 test.instanceOf First.Meta.fields.first, First._ReferenceField test.isFalse First.Meta.fields.first.ancestorArray, First.Meta.fields.first.ancestorArray test.isTrue First.Meta.fields.first.required test.equal First.Meta.fields.first.sourcePath, 'first' test.equal First.Meta.fields.first.sourceDocument, First test.equal First.Meta.fields.first.targetDocument, Person test.equal First.Meta.fields.first.sourceCollection._name, 'Firsts' test.equal First.Meta.fields.first.targetCollection._name, 'Persons' test.equal First.Meta.fields.first.sourceDocument.Meta.collection._name, 'Firsts' test.equal First.Meta.fields.first.targetDocument.Meta.collection._name, 'Persons' test.equal First.Meta.fields.first.fields, [] test.isNull First.Meta.fields.first.reverseName test.equal First.Meta.fields.first.reverseFields, [] test.equal Third.Meta._name, 'Third' test.equal Third.Meta.parent, _TestThird2.Meta test.equal Third.Meta.document, Third test.equal Third.Meta.collection._name, 'Thirds' test.equal _.size(Third.Meta.fields), 3 test.instanceOf Third.Meta.fields.first, Third._ReferenceField test.isFalse Third.Meta.fields.first.ancestorArray, Third.Meta.fields.first.ancestorArray test.isTrue Third.Meta.fields.first.required test.equal Third.Meta.fields.first.sourcePath, 'first' test.equal Third.Meta.fields.first.sourceDocument, Third test.equal Third.Meta.fields.first.targetDocument, firstReferenceA test.equal Third.Meta.fields.first.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.first.targetCollection._name, 'Firsts' test.equal Third.Meta.fields.first.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.first.targetDocument.Meta.collection._name, 'Firsts' test.equal Third.Meta.fields.first.fields, [] test.isNull Third.Meta.fields.first.reverseName test.equal Third.Meta.fields.first.reverseFields, [] test.instanceOf Third.Meta.fields.second, Third._ReferenceField test.isFalse Third.Meta.fields.second.ancestorArray, Third.Meta.fields.second.ancestorArray test.isTrue Third.Meta.fields.second.required test.equal Third.Meta.fields.second.sourcePath, 'second' test.equal Third.Meta.fields.second.sourceDocument, Third test.equal Third.Meta.fields.second.targetDocument, Post test.equal Third.Meta.fields.second.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.second.targetCollection._name, 'Posts' test.equal Third.Meta.fields.second.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.second.targetDocument.Meta.collection._name, 'Posts' test.equal Third.Meta.fields.second.fields, [] test.isNull Third.Meta.fields.second.reverseName test.equal Third.Meta.fields.second.reverseFields, [] test.instanceOf Third.Meta.fields.third, Third._ReferenceField test.isFalse Third.Meta.fields.third.ancestorArray, Third.Meta.fields.third.ancestorArray test.isTrue Third.Meta.fields.third.required test.equal Third.Meta.fields.third.sourcePath, 'third' test.equal Third.Meta.fields.third.sourceDocument, Third test.equal Third.Meta.fields.third.targetDocument, Person test.equal Third.Meta.fields.third.sourceCollection._name, 'Thirds' test.equal Third.Meta.fields.third.targetCollection._name, 'Persons' test.equal Third.Meta.fields.third.sourceDocument.Meta.collection._name, 'Thirds' test.equal Third.Meta.fields.third.targetDocument.Meta.collection._name, 'Persons' test.equal Third.Meta.fields.third.fields, [] test.isNull Third.Meta.fields.third.reverseName test.equal Third.Meta.fields.third.reverseFields, [] # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test Tinytest.addAsync 'peerdb - local collections', (test, onComplete) -> list = _.clone Document.list try class Local extends Document @Meta name: 'Local' collection: null fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [Local] test.equal Document._delayed.length, 0 test.equal Local.Meta._name, 'Local' test.isFalse Local.Meta.parent test.equal Local.Meta.document, Local test.equal Local.Meta.collection._name, null test.equal _.size(Local.Meta.fields), 1 test.instanceOf Local.Meta.fields.person, Local._ReferenceField test.isNull Local.Meta.fields.person.ancestorArray, Local.Meta.fields.person.ancestorArray test.isTrue Local.Meta.fields.person.required test.equal Local.Meta.fields.person.sourcePath, 'person' test.equal Local.Meta.fields.person.sourceDocument, Local test.equal Local.Meta.fields.person.targetDocument, Person test.isFalse Local.Meta.fields.person.sourceCollection._name test.equal Local.Meta.fields.person.targetCollection._name, 'Persons' test.isFalse Local.Meta.fields.person.sourceDocument.Meta.collection._name test.equal Local.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal Local.Meta.fields.person.fields, [] test.isNull Local.Meta.fields.person.reverseName test.equal Local.Meta.fields.person.reverseFields, [] test.isTrue Local.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'Locals', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() Tinytest.addAsync 'peerdb - collections with connection', (test, onComplete) -> list = _.clone Document.list try class CollectionWithConnection extends Document @Meta name: 'CollectionWithConnection' collection: new Mongo.Collection 'CollectionWithConnections', connection: DDP.connect Meteor.absoluteUrl() fields: -> person: @ReferenceField Person testDocumentList test, ALL.concat [CollectionWithConnection] test.equal Document._delayed.length, 0 test.equal CollectionWithConnection.Meta._name, 'CollectionWithConnection' test.isFalse CollectionWithConnection.Meta.parent test.equal CollectionWithConnection.Meta.document, CollectionWithConnection test.equal CollectionWithConnection.Meta.collection._name, 'CollectionWithConnections' test.equal _.size(CollectionWithConnection.Meta.fields), 1 test.instanceOf CollectionWithConnection.Meta.fields.person, CollectionWithConnection._ReferenceField test.isNull CollectionWithConnection.Meta.fields.person.ancestorArray, CollectionWithConnection.Meta.fields.person.ancestorArray test.isTrue CollectionWithConnection.Meta.fields.person.required test.equal CollectionWithConnection.Meta.fields.person.sourcePath, 'person' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument, CollectionWithConnection test.equal CollectionWithConnection.Meta.fields.person.targetDocument, Person test.equal CollectionWithConnection.Meta.fields.person.sourceCollection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetCollection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.sourceDocument.Meta.collection._name, 'CollectionWithConnections' test.equal CollectionWithConnection.Meta.fields.person.targetDocument.Meta.collection._name, 'Persons' test.equal CollectionWithConnection.Meta.fields.person.fields, [] test.isNull CollectionWithConnection.Meta.fields.person.reverseName test.equal CollectionWithConnection.Meta.fields.person.reverseFields, [] test.isTrue CollectionWithConnection.Meta._observersSetup finally # Restore Document.list = list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test if Meteor.isServer Post.Meta.collection.rawDatabase().collection 'CollectionWithConnections', {strict: true}, Meteor.bindEnvironment (error, collection) => test.isTrue error onComplete() else onComplete() testAsyncMulti 'peerdb - errors for generated fields', [ (test, expect) -> Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.insert source: 'foobar' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'foobar'" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: 'foobar' result: 'foobar' Log._intercept 3 if Meteor.isServer and Document.instances is 1 # Three to see if we catch more than expected IdentityGenerator.documents.update @identityGeneratorId, $set: source: ['foobar2'] , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> if Meteor.isServer and Document.instances is 1 intercepted = Log._intercepted() # One or two because it depends if the client tests are running at the same time test.isTrue 1 <= intercepted.length <= 2, intercepted # We are testing only the server one, so let's find it for i in intercepted break if i.indexOf(@identityGeneratorId) isnt -1 test.isTrue _.isString(i), i intercepted = EJSON.parse i test.equal intercepted.message, "Generated field 'result' not defined as an array with selector '#{ @identityGeneratorId }' was updated with an array value: [ 'foobar2' ]" test.equal intercepted.level, 'error' @identityGenerator = IdentityGenerator.documents.findOne @identityGeneratorId, transform: null # So that we can use test.equal test.equal @identityGenerator, _id: @identityGeneratorId source: ['foobar2'] result: 'foobar' results: ['foobar2'] ] Tinytest.add 'peerdb - tricky references', (test) -> list = _.clone Document.list # You can in fact use class name instead of "self", but you have to # make sure things work out at the end and class is really defined class First1 extends Document @Meta name: 'PI:NAME:<NAME>END_PI' fields: -> first: @ReferenceField First1 Document.defineAll() test.equal First1.Meta._name, 'First1' test.isFalse First1.Meta.parent test.equal First1.Meta.document, First1 test.equal First1.Meta.collection._name, 'First1s' test.equal _.size(First1.Meta.fields), 1 test.instanceOf First1.Meta.fields.first, First1._ReferenceField test.isFalse First1.Meta.fields.first.ancestorArray, First1.Meta.fields.first.ancestorArray test.isTrue First1.Meta.fields.first.required test.equal First1.Meta.fields.first.sourcePath, 'first' test.equal First1.Meta.fields.first.sourceDocument, First1 test.equal First1.Meta.fields.first.targetDocument, First1 test.equal First1.Meta.fields.first.sourceCollection._name, 'First1s' test.equal First1.Meta.fields.first.targetCollection._name, 'First1s' test.equal First1.Meta.fields.first.sourceDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.targetDocument.Meta.collection._name, 'First1s' test.equal First1.Meta.fields.first.fields, [] # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() class First2 extends Document @Meta name: 'First2' fields: -> first: @ReferenceField undefined # To force delayed class Second2 extends Document @Meta name: 'Second2' fields: -> first: @ReferenceField First2 test.throws -> Document.defineAll true , /Target document not defined/ test.throws -> Document.defineAll() , /Invalid fields/ # Restore Document.list = _.clone list Document._delayed = [] Document._clearDelayedCheck() # Verify we are back to normal testDefinition test testAsyncMulti 'peerdb - duplicate values in lists', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 test.equal @person2, _id: @person2Id username: 'person2' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' count: 0 test.equal @person3, _id: @person3Id username: 'person3' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' count: 0 Post.documents.insert author: _id: @person1._id # To test what happens if fields are partially not up to date username: 'wrong' displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id username: 'wrong' displayName: 'wrong' , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' , _id: @person3._id # To test if the second person3 value will be updated username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: 'wrong' displayName: 'wrong' optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: 'wrong' optional: _id: @person2._id body: 'NestedFooBar' , required: _id: @person3._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Person.documents.update @person2Id, $set: username: 'person2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents # so that persons updates are not merged together to better # test the code for multiple updates waitForDatabase test, expect , (test, expect) -> Person.documents.update @person3Id, $set: username: 'person3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' field1: 'Field 1 - 1' field2: 'Field 1 - 2' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2a' displayName: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3a' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person1Id, $set: # Updating two fields at the same time field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1a' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $unset: username: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person1Id, $set: username: 'person1b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person2Id, $set: username: 'person2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1' field2: 'Field 2 - 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id , _id: @person3._id ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Person.documents.update @person3Id, $set: username: 'person3b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $unset: # Removing two fields at the same time field1: '' field2: '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] (test, expect) -> Person.documents.update @person2Id, $set: # Restoring two fields at the same time field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBar' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'subdocument.body': 'SubdocumentFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.0.body': 'NestedFooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.4.body': 'NestedFooBarA' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' 'tag-5-prefix-foobar-nestedfoobara-suffix' 'tag-6-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'nested.3.body': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , body: 'NestedFooBar' , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobar-suffix' 'tag-4-prefix-foobar-nestedfoobara-suffix' 'tag-5-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $unset: 'nested.2.body': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBar' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobar-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobar-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobarz-suffix' 'tag-1-prefix-foobar-nestedfoobarz-suffix' 'tag-2-prefix-foobar-nestedfoobar-suffix' 'tag-3-prefix-foobar-nestedfoobara-suffix' 'tag-4-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: body: 'FooBarZ' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' ] Post.documents.update @postId, $push: nested: required: _id: @person2._id optional: _id: @person3._id body: 'NewFooBar' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person2, _id: @person2Id username: 'person2b' displayName: 'Person 2' field1: 'Field 2 - 1b' field2: 'Field 2 - 2b' subdocument: posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 3 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ body: 'NestedFooBarZ' , body: 'NestedFooBar' , {} , body: null , body: 'NestedFooBarA' , body: 'NestedFooBar' , body: 'NewFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person2._id , _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobarz-suffix' body: 'NestedFooBarZ' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person2._id username: @person2.username slug: null body: null , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person2._id username: @person2.username slug: 'nested-prefix-foobarz-nestedfoobara-suffix' body: 'NestedFooBarA' , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' , required: _id: @person2._id username: @person2.username displayName: @person2.displayName field1: @person2.field1 field2: @person2.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-newfoobar-suffix' body: 'NewFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobarz-suffix' 'tag-2-prefix-foobarz-nestedfoobar-suffix' 'tag-3-prefix-foobarz-nestedfoobara-suffix' 'tag-4-prefix-foobarz-nestedfoobar-suffix' 'tag-5-prefix-foobarz-newfoobar-suffix' ] Person.documents.remove @person2Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 1 test.equal @person3, _id: @person3Id username: 'person3b' displayName: 'Person 3' field1: 'Field 3 - 1' field2: 'Field 3 - 2' subdocumentsPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] nestedPosts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [ {} , body: null , body: 'NestedFooBar' ] body: 'FooBarZ' ] count: 2 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [ _id: @person3._id ] reviewers: [ _id: @person3._id username: @person3.username , _id: @person3._id username: @person3.username ] subdocument: person: null persons: [ _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 , _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 ] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [ required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: null slug: null body: null , required: _id: @person3._id username: @person3.username displayName: @person3.displayName field1: @person3.field1 field2: @person3.field2 optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobarz-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' 'tag-1-prefix-foobarz-nestedfoobar-suffix' ] Person.documents.remove @person3Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1b' displayName: 'Person 1' field1: 'Field 1 - 1a' field2: 'Field 1 - 2a' posts: [ _id: @postId subdocument: body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' ] count: 1 @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName field1: @person1.field1 field2: @person1.field2 subscribers: [] reviewers: [] subdocument: person: null persons: [] slug: 'subdocument-prefix-foobarz-subdocumentfoobarz-suffix' body: 'SubdocumentFooBarZ' nested: [] body: 'FooBarZ' slug: 'prefix-foobarz-subdocumentfoobarz-suffix' tags: [ 'tag-0-prefix-foobarz-subdocumentfoobarz-suffix' ] Person.documents.remove @person1Id, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.isFalse @post, @post ] if Meteor.isServer and Document.instances is 1 testAsyncMulti 'peerdb - exception while processing', [ (test, expect) -> Log._intercept 3 IdentityGenerator.documents.insert source: 'exception' , expect (error, identityGeneratorId) => test.isFalse error, error?.toString?() or error test.isTrue identityGeneratorId @identityGeneratorId = identityGeneratorId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> intercepted = Log._intercepted() test.isTrue intercepted.length is 3, intercepted # We are testing only the server one, so let's find it for i in intercepted # First error message if i.indexOf('PeerDB exception: Error: Test exception') isnt -1 i = EJSON.parse i test.equal i.message, "PeerDB exception: Error: Test exception: [ { source: 'exception', _id: '#{ @identityGeneratorId }' } ]" test.equal i.level, 'error' # Stack trace error message else if i.indexOf('Error: Test exception') isnt -1 i = EJSON.parse i test.isTrue i.message.indexOf('_GeneratedField.generator') isnt -1, i.message test.equal i.level, 'error' # Invalid update error message else if i.indexOf('defined as an array with selector') isnt -1 i = EJSON.parse i test.equal i.message, "Generated field 'results' defined as an array with selector '#{ @identityGeneratorId }' was updated with a non-array value: 'exception'" test.equal i.level, 'error' else test.fail type: 'assert_never' message: i ] testAsyncMulti 'peerdb - instances', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id test.instanceOf @person1, Person test.instanceOf @person2, Person test.instanceOf @person3, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal plainObject(@person2), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 0 test.equal plainObject(@person3), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 0 test.equal @person1.formatName(), 'person1-Person 1' test.equal @person2.formatName(), 'person2-Person 2' test.equal @person3.formatName(), 'person3-Person 3' Post.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] SpecialPost.documents.insert author: _id: @person1._id subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = SpecialPost.documents.findOne @postId test.instanceOf @post, SpecialPost test.instanceOf @post.author, Person test.instanceOf @post.subscribers[0], Person test.instanceOf @post.subscribers[1], Person test.instanceOf @post.reviewers[0], Person test.instanceOf @post.reviewers[1], Person test.instanceOf @post.subdocument.person, Person test.instanceOf @post.subdocument.persons[0], Person test.instanceOf @post.subdocument.persons[1], Person test.instanceOf @post.nested[0].required, Person test.instanceOf @post.nested[0].optional, Person test.instanceOf @post.special, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] special: _id: @person1._id @username = Random.id() if Meteor.isServer @userId = Accounts.createUser username: @username password: 'PI:PASSWORD:<PASSWORD>END_PI' else Accounts.createUser username: @username password: 'PI:PASSWORD:<PASSWORD>END_PI' , expect (error) => test.isFalse error, error?.toString?() or error @userId = Meteor.userId() unless error , (test, expect) -> @user = User.documents.findOne @userId test.instanceOf @user, User test.equal @user.username, @username ] Tinytest.add 'peerdb - bad instances', (test) -> # Empty document should be always possible to create for document in Document.list test.isTrue new document # Something simple test.isTrue new Post author: _id: Random.id() username: 'Foobar' test.throws -> new Post author: [ _id: Random.id() username: 'Foobar' ] , /Document does not match schema, not a plain object/ test.throws -> new Post subscribers: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post subdocument: [] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [ persons: [] ] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: [[ persons: [] ]] , /Document does not match schema, an unexpected array/ test.throws -> new Post subdocument: persons: [ Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: Random.id() ] , /Document does not match schema, not a plain object/ test.throws -> new Post nested: required: [ _id: Random.id() ] , /Document does not match schema, expected an array/ test.throws -> new Post nested: required: _id: Random.id() , /Document does not match schema, expected an array/ test.throws -> new Post nested: [ required: [ _id: Random.id() ] ] , /Document does not match schema, not a plain object/ if Meteor.isServer and not Document.instanceDisabled testAsyncMulti 'peerdb - update all', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id @person2 = Person.documents.findOne @person2Id @person3 = Person.documents.findOne @person3Id Post.documents.insert author: _id: @person1._id # To test what happens if one field is already up to date, but the other is not username: @person1.username displayName: 'wrong' subscribers: [ _id: @person2._id , _id: @person3._id ] reviewers: [ _id: @person2._id , _id: @person3._id ] subdocument: person: _id: @person2._id persons: [ _id: @person2._id , _id: @person3._id ] body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id optional: _id: @person3._id body: 'NestedFooBar' ] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] Post.documents.update @postId, $set: 'author.username': 'wrong' 'reviewers.0.username': 'wrong' 'reviewers.1.username': 'wrong' 'subdocument.person.username': 'wrong' 'subdocument.persons.0.username': 'wrong' 'subdocument.persons.1.username': 'wrong' 'nested.0.required.username': 'wrong' 'nested.0.optional.username': 'wrong' slug: 'wrong' tags: 'wrong' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal # Reference fields are automatically updated back, but generated fields are not test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'wrong' tags: 'wrong' # Update all fields back (a blocking operation) Document.updateAll() # Wait so that triggered observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId, transform: null # So that we can use test.equal test.equal @post, _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName # subscribers have only ids subscribers: [ _id: @person2._id , _id: @person3._id ] # But reviewers have usernames as well reviewers: [ _id: @person2._id username: @person2.username , _id: @person3._id username: @person3.username ] subdocument: person: _id: @person2._id username: @person2.username displayName: @person2.displayName persons: [ _id: @person2._id username: @person2.username displayName: @person2.displayName , _id: @person3._id username: @person3.username displayName: @person3.displayName ] slug: 'subdocument-prefix-foobar-subdocumentfoobar-suffix' body: 'SubdocumentFooBar' nested: [ required: _id: @person2._id username: @person2.username displayName: @person2.displayName optional: _id: @person3._id username: @person3.username slug: 'nested-prefix-foobar-nestedfoobar-suffix' body: 'NestedFooBar' ] body: 'FooBar' slug: 'prefix-foobar-subdocumentfoobar-suffix' tags: [ 'tag-0-prefix-foobar-subdocumentfoobar-suffix' 'tag-1-prefix-foobar-nestedfoobar-suffix' ] ] testAsyncMulti 'peerdb - reverse posts', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id Person.documents.insert username: 'person2' displayName: 'Person 2' , expect (error, person2Id) => test.isFalse error, error?.toString?() or error test.isTrue person2Id @person2Id = person2Id Person.documents.insert username: 'person3' displayName: 'Person 3' , expect (error, person3Id) => test.isFalse error, error?.toString?() or error test.isTrue person3Id @person3Id = person3Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person2Id body: 'NestedFooBar1' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person2Id , _id: @person3Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar1' body: 'FooBar1' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId1 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar2' ] subdocument: person: _id: @person2Id persons: [ _id: @person2Id , _id: @person2Id , _id: @person2Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar2' body: 'FooBar2' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId2 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar3' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar3' body: 'FooBar3' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId3 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post1 = Post.documents.findOne @postId1, transform: null # So that we can use test.equal @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal @post3 = Post.documents.findOne @postId3, transform: null # So that we can use test.equal test.equal @post1, _id: @postId1 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar1-subdocumentfoobar1-suffix' body: 'SubdocumentFooBar1' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar1-nestedfoobar1-suffix' body: 'NestedFooBar1' ] body: 'FooBar1' slug: 'prefix-foobar1-subdocumentfoobar1-suffix' tags: [ 'tag-0-prefix-foobar1-subdocumentfoobar1-suffix' 'tag-1-prefix-foobar1-nestedfoobar1-suffix' ] test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2-subdocumentfoobar2-suffix' body: 'SubdocumentFooBar2' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2-nestedfoobar2-suffix' body: 'NestedFooBar2' ] body: 'FooBar2' slug: 'prefix-foobar2-subdocumentfoobar2-suffix' tags: [ 'tag-0-prefix-foobar2-subdocumentfoobar2-suffix' 'tag-1-prefix-foobar2-nestedfoobar2-suffix' ] test.equal @post3, _id: @postId3 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar3-subdocumentfoobar3-suffix' body: 'SubdocumentFooBar3' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar3-nestedfoobar3-suffix' body: 'NestedFooBar3' ] body: 'FooBar3' slug: 'prefix-foobar3-subdocumentfoobar3-suffix' tags: [ 'tag-0-prefix-foobar3-subdocumentfoobar3-suffix' 'tag-1-prefix-foobar3-nestedfoobar3-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 8 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'PI:NAME:<NAME>END_PI 3' count: 5 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' ] Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' , required: _id: @person1Id body: 'NestedFooBar4' , required: _id: @person2Id body: 'NestedFooBar4' , required: _id: @person3Id body: 'NestedFooBar4' ] subdocument: person: _id: @person1Id persons: [ _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person1Id , _id: @person2Id , _id: @person2Id ] body: 'SubdocumentFooBar4' body: 'FooBar4' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId4 = postId Post.documents.insert author: _id: @person1Id nested: [ required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' , required: _id: @person3Id body: 'NestedFooBar5' ] subdocument: person: _id: @person3Id persons: [ _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person3Id , _id: @person2Id , _id: @person3Id ] body: 'SubdocumentFooBar5' body: 'FooBar5' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId5 = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1' nested: [ body: 'NestedFooBar1' ] body: 'FooBar1' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2' nested: [ body: 'NestedFooBar2' ] body: 'FooBar2' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3' nested: [ body: 'NestedFooBar3' ] body: 'FooBar3' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5' , body: 'NestedFooBar5' ] body: 'FooBar5' ] Post.documents.update @postId1, $set: 'body': 'FooBar1a' 'subdocument.body': 'SubdocumentFooBar1a' 'nested.0.body': 'NestedFooBar1a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId2, $set: 'body': 'FooBar2a' 'subdocument.body': 'SubdocumentFooBar2a' 'nested.0.body': 'NestedFooBar2a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId3, $set: 'body': 'FooBar3a' 'subdocument.body': 'SubdocumentFooBar3a' 'nested.0.body': 'NestedFooBar3a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId4, $set: 'body': 'FooBar4a' 'subdocument.body': 'SubdocumentFooBar4a' 'nested.1.body': 'NestedFooBar4a' 'nested.3.body': 'NestedFooBar4a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res Post.documents.update @postId5, $set: 'body': 'FooBar5a' 'subdocument.body': 'SubdocumentFooBar5a' 'nested.1.body': 'NestedFooBar5a' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $push: nested: required: _id: @person2Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person2Id username: 'person2' displayName: 'Person PI:NAME:<NAME>END_PI' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId2, $push: nested: required: _id: @person3Id body: 'NestedFooBarNew' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobarnew-suffix' body: 'NestedFooBarNew' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' 'tag-2-prefix-foobar2a-nestedfoobarnew-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' , body: 'NestedFooBarNew' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId2, $pop: nested: 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post2 = Post.documents.findOne @postId2, transform: null # So that we can use test.equal test.equal @post2, _id: @postId2 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person2Id displayName: 'Person 2' username: 'person2' persons: [ _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar2a-subdocumentfoobar2a-suffix' body: 'SubdocumentFooBar2a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar2a-nestedfoobar2a-suffix' body: 'NestedFooBar2a' ] body: 'FooBar2a' slug: 'prefix-foobar2a-subdocumentfoobar2a-suffix' tags: [ 'tag-0-prefix-foobar2a-subdocumentfoobar2a-suffix' 'tag-1-prefix-foobar2a-nestedfoobar2a-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person2Id username: 'person2' displayName: 'Person 2' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'nested.0.required._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $push: 'subdocument.persons': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $pop: 'subdocument.persons': 1 , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person1Id displayName: 'Person 1' username: 'person1' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] # Add one which already exist Post.documents.update @postId5, $set: 'subdocument.persons.2._id': @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': null , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: null persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person3Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person3Id displayName: 'Person 3' username: 'person3' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person PI:NAME:<NAME>END_PI' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person PI:NAME:<NAME>END_PI' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person PI:NAME:<NAME>END_PI' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 9 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: 'subdocument.person': _id: @person1Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: person: _id: @person1Id displayName: 'Person 1' username: 'person1' persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 14 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $unset: 'subdocument.person': '' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person1Id username: 'person1' displayName: 'Person 1' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 13 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 8 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.update @postId5, $set: author: _id: @person2Id , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post5 = Post.documents.findOne @postId5, transform: null # So that we can use test.equal test.equal @post5, _id: @postId5 author: _id: @person2Id username: 'person2' displayName: 'Person 2' subdocument: persons: [ _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person3Id displayName: 'Person 3' username: 'person3' , _id: @person2Id displayName: 'Person 2' username: 'person2' , _id: @person3Id displayName: 'Person 3' username: 'person3' ] slug: 'subdocument-prefix-foobar5a-subdocumentfoobar5a-suffix' body: 'SubdocumentFooBar5a' nested: [ required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5a-suffix' body: 'NestedFooBar5a' , required: _id: @person3Id username: 'person3' displayName: 'Person 3' slug: 'nested-prefix-foobar5a-nestedfoobar5-suffix' body: 'NestedFooBar5' ] body: 'FooBar5a' slug: 'prefix-foobar5a-subdocumentfoobar5a-suffix' tags: [ 'tag-0-prefix-foobar5a-subdocumentfoobar5a-suffix' 'tag-1-prefix-foobar5a-nestedfoobar5-suffix' 'tag-2-prefix-foobar5a-nestedfoobar5a-suffix' 'tag-3-prefix-foobar5a-nestedfoobar5-suffix' ] @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 9 testSetEqual test, @person2.posts, [ _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 8 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' , _id: @postId5 subdocument: body: 'SubdocumentFooBar5a' nested: [ body: 'NestedFooBar5' , body: 'NestedFooBar5a' , body: 'NestedFooBar5' ] body: 'FooBar5a' ] Post.documents.remove @postId5, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 12 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 7 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' ] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person PI:NAME:<NAME>END_PI' count: 6 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId2 subdocument: body: 'SubdocumentFooBar2a' nested: [ body: 'NestedFooBar2a' ] body: 'FooBar2a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId2, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 10 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 5 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 4 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId3 subdocument: body: 'SubdocumentFooBar3a' nested: [ body: 'NestedFooBar3a' ] body: 'FooBar3a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] Post.documents.remove @postId3, expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 7 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 4 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 2 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [ body: 'NestedFooBar1a' ] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [ _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [ body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4a' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' , body: 'NestedFooBar4' ] body: 'FooBar4a' ] for id in [@postId1, @postId2, @postId3, @postId4, @postId5] Post.documents.update _id: id , $set: nested: [] , expect (error) => test.isFalse error, error?.toString?() or error # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal @person2 = Person.documents.findOne @person2Id, transform: null # So that we can use test.equal @person3 = Person.documents.findOne @person3Id, transform: null # So that we can use test.equal test.equal _.omit(@person1, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 6 testSetEqual test, @person1.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocument?.posts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person1.nestedPosts, [] test.equal _.omit(@person2, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person2Id username: 'person2' displayName: 'Person 2' count: 2 testSetEqual test, @person2.posts, [] testSetEqual test, @person2.subdocument?.posts, [] testSetEqual test, @person2.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' , _id: @postId4 subdocument: body: 'SubdocumentFooBar4a' nested: [] body: 'FooBar4a' ] testSetEqual test, @person2.nestedPosts, [] test.equal _.omit(@person3, 'posts', 'subdocument', 'subdocumentsPosts', 'nestedPosts'), _id: @person3Id username: 'person3' displayName: 'Person 3' count: 1 testSetEqual test, @person3.posts, [] testSetEqual test, @person3.subdocument?.posts, [] testSetEqual test, @person3.subdocumentsPosts, [ _id: @postId1 subdocument: body: 'SubdocumentFooBar1a' nested: [] body: 'FooBar1a' ] testSetEqual test, @person3.nestedPosts, [] ] if Meteor.isServer testAsyncMulti 'peerdb - triggers', [ (test, expect) -> testDefinition test Person.documents.insert username: 'person1' displayName: 'Person 1' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id test.instanceOf @person1, Person test.equal plainObject(@person1), _id: @person1Id username: 'person1' displayName: 'Person 1' count: 0 test.equal @person1.formatName(), 'person1-Person 1' Post.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] SpecialPost.documents.insert author: _id: @person1._id subdocument: {} body: 'FooBar' special: _id: @person1._id , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @specialPostId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 1 test.equal globalTestTriggerCounters[@specialPostId], 1 Post.documents.update @postId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: body: 'FooBar 1' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.PI:EMAIL:<NAME>END_PI subdocument: {} body: 'FooBar 1' tags: [] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: {} body: 'FooBar 1' tags: [] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 Post.documents.update @postId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res SpecialPost.documents.update @specialPostId, $set: 'subdocument.body': 'FooBar zzz' , expect (error, res) => test.isFalse error, error?.toString?() or error test.isTrue res # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @post = Post.documents.findOne @postId test.instanceOf @post, Post test.instanceOf @post.author, Person test.equal @post.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@post), _id: @postId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] @specialPost = SpecialPost.documents.findOne @specialPostId test.instanceOf @specialPost, SpecialPost test.instanceOf @specialPost.author, Person test.instanceOf @specialPost.special, Person test.equal @specialPost.author.formatName(), "#{ @person1.username }-#{ @person1.displayName }" test.equal plainObject(@specialPost), _id: @specialPostId author: _id: @person1._id username: @person1.username displayName: @person1.displayName subdocument: body: 'FooBar zzz' slug: 'subdocument-prefix-foobar 1-foobar zzz-suffix' body: 'FooBar 1' slug: 'prefix-foobar 1-foobar zzz-suffix' tags: [ 'tag-0-prefix-foobar 1-foobar zzz-suffix' ] special: _id: @person1._id test.equal globalTestTriggerCounters[@postId], 2 test.equal globalTestTriggerCounters[@specialPostId], 2 ] testAsyncMulti 'peerdb - reverse fields', [ (test, expect) -> Person.documents.insert username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' , expect (error, person1Id) => test.isFalse error, error?.toString?() or error test.isTrue person1Id @person1Id = person1Id # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 0 @changes = [] @handle = Person.documents.find(@person1Id).observe changed: (newDocument, oldDocument) => @changes.push newDocument Post.documents.insert author: _id: @person1._id subdocument: persons: [] body: 'SubdocumentFooBar' nested: [] body: 'FooBar' , expect (error, postId) => test.isFalse error, error?.toString?() or error test.isTrue postId @postId = postId # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> @person1 = Person.documents.findOne @person1Id, transform: null # So that we can use test.equal test.equal @person1, _id: @person1Id username: 'person1' displayName: 'Person 1' field1: 'Field 1 - 1' field2: 'Field 1 - 2' count: 1 posts: [ _id: @postId body: 'FooBar' nested: [] subdocument: body: 'SubdocumentFooBar' ] # This test is checking that all fields in reverse field subdocuments are populated # from the beginning. Otherwise there might be a short but existing time when # document does not match the schema, and is published as such to the client. for person in @changes for post in person.posts test.equal post.body, 'FooBar' test.equal post.nested, [] test.equal post.subdocument?.body, 'SubdocumentFooBar' @handle.stop() ] testAsyncMulti 'peerdb - bulk insert', [ (test, expect) -> @testContent = for i in [0..100] content: Random.id() ids = Recursive.documents.bulkInsert @testContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids?.length, @testContent.length @testIds = ids test.isTrue ids test.equal ids?.length, @testContent.length # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> docs = Recursive.documents.find( _id: $in: @testIds , fields: _id: 0 content: 1 transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> randomIds = for i in [0...100] Random.id() insertContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other reverse: [ _id: reverse ] @testContent = for i in [0...100] other = randomIds[(i + 50) % 100] reverse = randomIds[(100 + i - 50) % 100] _id: randomIds[i] content: randomIds[i] other: _id: other content: other reverse: [ _id: reverse content: reverse ] ids = Recursive.documents.bulkInsert insertContent, expect (error, ids) => test.isFalse error, error?.toString?() or error test.isTrue ids test.equal ids, _.pluck @testContent, '_id' test.equal ids, _.pluck @testContent, '_id' # Wait so that observers have time to update documents waitForDatabase test, expect , (test, expect) -> # We sleep a bit so that all changes get to the client, when rnning on the client. Meteor.setTimeout expect(), 200 , (test, expect) -> docs = Recursive.documents.find( _id: $in: _.pluck(@testContent, '_id') , transform: null # So that we can use test.equal ).fetch() testSetEqual test, @testContent, docs , (test, expect) -> # Test bulkInsert without any arguments. Recursive.documents.bulkInsert [] ] testAsyncMulti 'peerdb - bulk insert with subfield references', [ (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, _.extend {objectInArray: [], anArray: []}, @item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: anotherA: "hello" anotherB: "world" # Do not set the array fields on purpose. SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id item = _.extend {objectInArray: [], anArray: []}, @item # Missing references should be set to null. item.toplevel.subitem = null test.equal insertedItem, item , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem: _id: itemId subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item # To make sure there are no residual observes going into @changes. waitForDatabase test, expect , (test, expect) -> itemId = Random.id() @item = _id: itemId hello: "world" toplevel: subitem: _id: itemId anotherA: "hello" anotherB: "world" objectInArray: [ subitem2: _id: itemId otheritem: 42 ] anArray: [ _id: itemId ] @changes = [] initializing = true @handle = SubfieldItem.documents.find().observeChanges added: (id, fields) => @changes.push {type: 'added', id, fields} unless initializing changed: (id, fields) => @changes.push {type: 'changed', id, fields} initializing = false SubfieldItem.documents.bulkInsert [@item], expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: hello: "world" toplevel: anotherA: "hello" anotherB: "world" , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray', 'toplevel' ] @changes = [] itemId = Random.id() @item._id = itemId SubfieldItem.documents.bulkInsert [@item], {dontDelay: ['toplevel.subitem']}, expect (error, ids) => test.exception error if error test.equal ids, [itemId] # Wait so that observers have time to update documents. It is not really necessary for PeerDB observes, but for # our observe above. It seems findOne return already correct document, while changed callback above is not # necessary already called and @changes does not contain all values. waitForDatabase test, expect , (test, expect) -> insertedItem = SubfieldItem.documents.findOne @item._id test.equal insertedItem, @item test.equal @changes, [ type: 'added' id: @item._id fields: _.pick @item, 'hello', 'toplevel' , type: 'changed' id: @item._id fields: _.pick @item, 'objectInArray', 'anArray' ] @handle.stop() ] Tinytest.add 'peerdb - local documents', (test) -> testDefinition test class ReallyLocalPost extends Post @Meta name: 'ReallyLocalPost' collection: null local: true testDefinition test
[ { "context": "ngs.ENCRYPTION_KEY or settings.SESSION_SECRET or '5random7493nonsens!e'\n gzip = zlib.createGzip()\n st = null\n ", "end": 1447, "score": 0.7267846465110779, "start": 1427, "tag": "KEY", "value": "5random7493nonsens!e" }, { "context": "ngs.ENCRYPTION_KEY or se...
src/storage.coffee
ndxbxrme/ndxdb
1
'use strict' settings = require './settings' async = require 'async' crypto = require 'crypto' jsonStream = require 'JSONStream' es = require 'event-stream' zlib = require 'zlib' module.exports = -> algorithm = settings.ENCRYPTION_ALGORITHM or 'aes-256-ctr' doencrypt = !settings.DO_NOT_ENCRYPT dozip = !settings.DO_NOT_ENCRYPT s3 = require('./s3')() local = require('./local')() devices = [] if settings.LOCAL_STORAGE devices.push local if settings.AWS_OK devices.push s3 checkDataDir: -> if settings.LOCAL_STORAGE local.checkDataDir() keys: (from, prefix, cb) -> if not devices.length cb? 'no storage', null else calledBack = false async.each devices, (device, callback) -> device.keys from, prefix, (e, r) -> if not e or calledBack calledBack = true cb? e, r callback() , -> if not calledBack cb? 'nothing found', null del: (key, cb) -> async.each devices, (device, callback) -> device.del key, -> callback() , -> cb?() put: (key, o, cb, notCritical, writeStream) -> if not devices.length or notCritical cb? null, null else if key.indexOf(':node:') isnt -1 key = "#{key}" jsStringify = new jsonStream.stringify() encrypt = crypto.createCipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or '5random7493nonsens!e' gzip = zlib.createGzip() st = null ws = null if dozip st = jsStringify.pipe gzip if doencrypt if st st = st.pipe encrypt else st = jsStringify.pipe encrypt if not st st = jsStringify if writeStream st = st.pipe writeStream else for device in devices writeStream = device.getWriteStream(key) st = st.pipe writeStream jsStringify.write o, -> jsStringify.flush() jsStringify.end() st.on 'close', -> cb? null, null st.on 'error', (er) -> writeStream.on 'error', (er) -> writeStream.on 'uploaded', (res) -> cb? null, null gzip.on 'error', (er) -> encrypt.on 'error', (er) -> #jsStringify.end() get: (key, cb, reader) -> if not devices cb? 'no devices', null done?() else jsParse = new jsonStream.parse '*' decrypt = crypto.createDecipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or '5random7493nonsens!e' gunzip = zlib.createGunzip() finished = false async.eachSeries devices, (device, callback) -> if not finished calledBack = false if not reader reader = device.getReadStream key st = reader if doencrypt st = st.pipe decrypt if dozip st = st.pipe gunzip st.pipe jsParse .pipe es.mapSync (data) -> finished = true calledBack = true cb? null, data done?() callback() reader.on 'error', (e) -> if not calledBack calledBack = true callback() st.on 'error', (e) -> if not calledBack calledBack = true finished = true cb? 'encrypt error', null callback() jsParse.on 'error', (e) -> console.log 'Error parsing database - have you changed your encryption key or turned encryption on or off? If so, update your database using ndx-framework.' st.on 'end', -> if not calledBack calledBack = true callback() else callback() , -> if not finished cb? 'nothing found', null done?() putOld: (key, o, cb, notCritical) -> if settings.LOCAL_STORAGE if not notCritical local.put key, o, (e, r) -> if settings.AWS_OK s3.put key, o, cb else cb? e, r else if settings.AWS_OK and (not notCritical) s3.put key, o, cb else cb? null, null getOld: (key, cb) -> if not settings.PREFER_LOCAL if settings.LOCAL_STORAGE local.get key, (e, r) -> if e and settings.AWS_OK s3.get key, cb else cb e, r else if settings.AWS_OK s3.get key, cb else cb 'no storage', null else if settings.AWS_OK s3.get key, (e, r) -> if e and settings.LOCAL_STORAGE local.get key, cb else cb e, r else if settings.LOCAL_STORAGE local.get key, cb else cb 'no storage', null
222991
'use strict' settings = require './settings' async = require 'async' crypto = require 'crypto' jsonStream = require 'JSONStream' es = require 'event-stream' zlib = require 'zlib' module.exports = -> algorithm = settings.ENCRYPTION_ALGORITHM or 'aes-256-ctr' doencrypt = !settings.DO_NOT_ENCRYPT dozip = !settings.DO_NOT_ENCRYPT s3 = require('./s3')() local = require('./local')() devices = [] if settings.LOCAL_STORAGE devices.push local if settings.AWS_OK devices.push s3 checkDataDir: -> if settings.LOCAL_STORAGE local.checkDataDir() keys: (from, prefix, cb) -> if not devices.length cb? 'no storage', null else calledBack = false async.each devices, (device, callback) -> device.keys from, prefix, (e, r) -> if not e or calledBack calledBack = true cb? e, r callback() , -> if not calledBack cb? 'nothing found', null del: (key, cb) -> async.each devices, (device, callback) -> device.del key, -> callback() , -> cb?() put: (key, o, cb, notCritical, writeStream) -> if not devices.length or notCritical cb? null, null else if key.indexOf(':node:') isnt -1 key = "#{key}" jsStringify = new jsonStream.stringify() encrypt = crypto.createCipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or '<KEY>' gzip = zlib.createGzip() st = null ws = null if dozip st = jsStringify.pipe gzip if doencrypt if st st = st.pipe encrypt else st = jsStringify.pipe encrypt if not st st = jsStringify if writeStream st = st.pipe writeStream else for device in devices writeStream = device.getWriteStream(key) st = st.pipe writeStream jsStringify.write o, -> jsStringify.flush() jsStringify.end() st.on 'close', -> cb? null, null st.on 'error', (er) -> writeStream.on 'error', (er) -> writeStream.on 'uploaded', (res) -> cb? null, null gzip.on 'error', (er) -> encrypt.on 'error', (er) -> #jsStringify.end() get: (key, cb, reader) -> if not devices cb? 'no devices', null done?() else jsParse = new jsonStream.parse '*' decrypt = crypto.createDecipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or '<KEY>' gunzip = zlib.createGunzip() finished = false async.eachSeries devices, (device, callback) -> if not finished calledBack = false if not reader reader = device.getReadStream key st = reader if doencrypt st = st.pipe decrypt if dozip st = st.pipe gunzip st.pipe jsParse .pipe es.mapSync (data) -> finished = true calledBack = true cb? null, data done?() callback() reader.on 'error', (e) -> if not calledBack calledBack = true callback() st.on 'error', (e) -> if not calledBack calledBack = true finished = true cb? 'encrypt error', null callback() jsParse.on 'error', (e) -> console.log 'Error parsing database - have you changed your encryption key or turned encryption on or off? If so, update your database using ndx-framework.' st.on 'end', -> if not calledBack calledBack = true callback() else callback() , -> if not finished cb? 'nothing found', null done?() putOld: (key, o, cb, notCritical) -> if settings.LOCAL_STORAGE if not notCritical local.put key, o, (e, r) -> if settings.AWS_OK s3.put key, o, cb else cb? e, r else if settings.AWS_OK and (not notCritical) s3.put key, o, cb else cb? null, null getOld: (key, cb) -> if not settings.PREFER_LOCAL if settings.LOCAL_STORAGE local.get key, (e, r) -> if e and settings.AWS_OK s3.get key, cb else cb e, r else if settings.AWS_OK s3.get key, cb else cb 'no storage', null else if settings.AWS_OK s3.get key, (e, r) -> if e and settings.LOCAL_STORAGE local.get key, cb else cb e, r else if settings.LOCAL_STORAGE local.get key, cb else cb 'no storage', null
true
'use strict' settings = require './settings' async = require 'async' crypto = require 'crypto' jsonStream = require 'JSONStream' es = require 'event-stream' zlib = require 'zlib' module.exports = -> algorithm = settings.ENCRYPTION_ALGORITHM or 'aes-256-ctr' doencrypt = !settings.DO_NOT_ENCRYPT dozip = !settings.DO_NOT_ENCRYPT s3 = require('./s3')() local = require('./local')() devices = [] if settings.LOCAL_STORAGE devices.push local if settings.AWS_OK devices.push s3 checkDataDir: -> if settings.LOCAL_STORAGE local.checkDataDir() keys: (from, prefix, cb) -> if not devices.length cb? 'no storage', null else calledBack = false async.each devices, (device, callback) -> device.keys from, prefix, (e, r) -> if not e or calledBack calledBack = true cb? e, r callback() , -> if not calledBack cb? 'nothing found', null del: (key, cb) -> async.each devices, (device, callback) -> device.del key, -> callback() , -> cb?() put: (key, o, cb, notCritical, writeStream) -> if not devices.length or notCritical cb? null, null else if key.indexOf(':node:') isnt -1 key = "#{key}" jsStringify = new jsonStream.stringify() encrypt = crypto.createCipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or 'PI:KEY:<KEY>END_PI' gzip = zlib.createGzip() st = null ws = null if dozip st = jsStringify.pipe gzip if doencrypt if st st = st.pipe encrypt else st = jsStringify.pipe encrypt if not st st = jsStringify if writeStream st = st.pipe writeStream else for device in devices writeStream = device.getWriteStream(key) st = st.pipe writeStream jsStringify.write o, -> jsStringify.flush() jsStringify.end() st.on 'close', -> cb? null, null st.on 'error', (er) -> writeStream.on 'error', (er) -> writeStream.on 'uploaded', (res) -> cb? null, null gzip.on 'error', (er) -> encrypt.on 'error', (er) -> #jsStringify.end() get: (key, cb, reader) -> if not devices cb? 'no devices', null done?() else jsParse = new jsonStream.parse '*' decrypt = crypto.createDecipher algorithm, settings.ENCRYPTION_KEY or settings.SESSION_SECRET or 'PI:KEY:<KEY>END_PI' gunzip = zlib.createGunzip() finished = false async.eachSeries devices, (device, callback) -> if not finished calledBack = false if not reader reader = device.getReadStream key st = reader if doencrypt st = st.pipe decrypt if dozip st = st.pipe gunzip st.pipe jsParse .pipe es.mapSync (data) -> finished = true calledBack = true cb? null, data done?() callback() reader.on 'error', (e) -> if not calledBack calledBack = true callback() st.on 'error', (e) -> if not calledBack calledBack = true finished = true cb? 'encrypt error', null callback() jsParse.on 'error', (e) -> console.log 'Error parsing database - have you changed your encryption key or turned encryption on or off? If so, update your database using ndx-framework.' st.on 'end', -> if not calledBack calledBack = true callback() else callback() , -> if not finished cb? 'nothing found', null done?() putOld: (key, o, cb, notCritical) -> if settings.LOCAL_STORAGE if not notCritical local.put key, o, (e, r) -> if settings.AWS_OK s3.put key, o, cb else cb? e, r else if settings.AWS_OK and (not notCritical) s3.put key, o, cb else cb? null, null getOld: (key, cb) -> if not settings.PREFER_LOCAL if settings.LOCAL_STORAGE local.get key, (e, r) -> if e and settings.AWS_OK s3.get key, cb else cb e, r else if settings.AWS_OK s3.get key, cb else cb 'no storage', null else if settings.AWS_OK s3.get key, (e, r) -> if e and settings.LOCAL_STORAGE local.get key, cb else cb e, r else if settings.LOCAL_STORAGE local.get key, cb else cb 'no storage', null
[ { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed unde", "end": 23, "score": 0.999565601348877, "start": 17, "tag": "NAME", "value": "SASAKI" }, { "context": "# Copyright 2015 SASAKI, Shunsuke. All rights reserved.\n#\n# Licensed under the Apac", ...
src/fm_index.coffee
erukiti/cerebrums
7
# Copyright 2015 SASAKI, Shunsuke. All rights reserved. # # 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. WaveletMatrix = require './wavelet_matrix.coffee' class FmIndex constructor: (documents) -> _encode = (s) => ary = [0..s.length - 1].sort (a, b) => while true return -1 if s[a] == 0 return 1 if s[b] == 0 return -1 if s[a] < s[b] return 1 if s[a] > s[b] a++ b++ # console.dir ary result = [] ind = 0 last = null for a in ary if s[a - 1] result.push s[a - 1] else last = ind result.push 0 ind++ @bwt = new WaveletMatrix(result) @last = last @usedChars = [] n = 2 for doc in documents if doc.text for ch in doc.text @usedChars[ch.charCodeAt(0)] = n++ unless @usedChars[ch.charCodeAt(0)] s = [] @metaArray = [] for doc in documents if doc.text for ch in doc.text s.push @usedChars[ch.charCodeAt(0)] s.push 1 @metaArray.push {uuid: doc.uuid} s.pop() # 最後の1を捨てる s.push 0 _encode(s) @bwtLength = s.length ind = @last metaInd = @metaArray.length - 1 @wayPoints = [] @wayPointsPerFile = [] _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) i = 0 wayPoints = [] while i < @bwtLength c = @bwt.get(ind) # console.log "#{ind}: #{c}" if ind % 16 == 0 wayPoints.push {ind: ind, i: i} if c == 1 for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd metaInd-- wayPoints = [] ind = _lf(ind, c) i++ for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd search: (query, max = 0) -> _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) q = [] for ch in query unless @usedChars[ch.charCodeAt(0)] return {hits: 0, results:[]} else q.push @usedChars[ch.charCodeAt(0)] start = 0 end = @bwtLength i = q.length - 1 while i >= 0 c = q[i] start = _lf(start, c) end = _lf(end, c) return {hits: 0, results:[]} if start >= end i-- if max > 0 && end - start > max return {hits: end - start, results: []} results = for ind in [start...end] pos = 0 metaInd = 0 while (c = @bwt.get(ind)) != 0 if (c == 1) metaInd = @wayPointsPerFile[ind] break if ind % 16 == 0 wp = @wayPoints[ind >> 4] metaInd = wp.meta pos += wp.ind break ind = _lf(ind, c) pos++ {uuid: @metaArray[metaInd].uuid, pos: pos} {hits: end - start, results: results} module.exports = FmIndex
116470
# Copyright 2015 <NAME>, <NAME>. All rights reserved. # # 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. WaveletMatrix = require './wavelet_matrix.coffee' class FmIndex constructor: (documents) -> _encode = (s) => ary = [0..s.length - 1].sort (a, b) => while true return -1 if s[a] == 0 return 1 if s[b] == 0 return -1 if s[a] < s[b] return 1 if s[a] > s[b] a++ b++ # console.dir ary result = [] ind = 0 last = null for a in ary if s[a - 1] result.push s[a - 1] else last = ind result.push 0 ind++ @bwt = new WaveletMatrix(result) @last = last @usedChars = [] n = 2 for doc in documents if doc.text for ch in doc.text @usedChars[ch.charCodeAt(0)] = n++ unless @usedChars[ch.charCodeAt(0)] s = [] @metaArray = [] for doc in documents if doc.text for ch in doc.text s.push @usedChars[ch.charCodeAt(0)] s.push 1 @metaArray.push {uuid: doc.uuid} s.pop() # 最後の1を捨てる s.push 0 _encode(s) @bwtLength = s.length ind = @last metaInd = @metaArray.length - 1 @wayPoints = [] @wayPointsPerFile = [] _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) i = 0 wayPoints = [] while i < @bwtLength c = @bwt.get(ind) # console.log "#{ind}: #{c}" if ind % 16 == 0 wayPoints.push {ind: ind, i: i} if c == 1 for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd metaInd-- wayPoints = [] ind = _lf(ind, c) i++ for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd search: (query, max = 0) -> _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) q = [] for ch in query unless @usedChars[ch.charCodeAt(0)] return {hits: 0, results:[]} else q.push @usedChars[ch.charCodeAt(0)] start = 0 end = @bwtLength i = q.length - 1 while i >= 0 c = q[i] start = _lf(start, c) end = _lf(end, c) return {hits: 0, results:[]} if start >= end i-- if max > 0 && end - start > max return {hits: end - start, results: []} results = for ind in [start...end] pos = 0 metaInd = 0 while (c = @bwt.get(ind)) != 0 if (c == 1) metaInd = @wayPointsPerFile[ind] break if ind % 16 == 0 wp = @wayPoints[ind >> 4] metaInd = wp.meta pos += wp.ind break ind = _lf(ind, c) pos++ {uuid: @metaArray[metaInd].uuid, pos: pos} {hits: end - start, results: results} module.exports = FmIndex
true
# Copyright 2015 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI. All rights reserved. # # 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. WaveletMatrix = require './wavelet_matrix.coffee' class FmIndex constructor: (documents) -> _encode = (s) => ary = [0..s.length - 1].sort (a, b) => while true return -1 if s[a] == 0 return 1 if s[b] == 0 return -1 if s[a] < s[b] return 1 if s[a] > s[b] a++ b++ # console.dir ary result = [] ind = 0 last = null for a in ary if s[a - 1] result.push s[a - 1] else last = ind result.push 0 ind++ @bwt = new WaveletMatrix(result) @last = last @usedChars = [] n = 2 for doc in documents if doc.text for ch in doc.text @usedChars[ch.charCodeAt(0)] = n++ unless @usedChars[ch.charCodeAt(0)] s = [] @metaArray = [] for doc in documents if doc.text for ch in doc.text s.push @usedChars[ch.charCodeAt(0)] s.push 1 @metaArray.push {uuid: doc.uuid} s.pop() # 最後の1を捨てる s.push 0 _encode(s) @bwtLength = s.length ind = @last metaInd = @metaArray.length - 1 @wayPoints = [] @wayPointsPerFile = [] _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) i = 0 wayPoints = [] while i < @bwtLength c = @bwt.get(ind) # console.log "#{ind}: #{c}" if ind % 16 == 0 wayPoints.push {ind: ind, i: i} if c == 1 for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd metaInd-- wayPoints = [] ind = _lf(ind, c) i++ for wayPoint in wayPoints @wayPoints[wayPoint.ind >> 4] = {meta: metaInd, ind: i - wayPoint.i} @wayPointsPerFile[ind] = metaInd search: (query, max = 0) -> _lf = (ind, c) => @bwt.rank(ind, c) + @bwt.rankLessThan(@bwtLength, c) q = [] for ch in query unless @usedChars[ch.charCodeAt(0)] return {hits: 0, results:[]} else q.push @usedChars[ch.charCodeAt(0)] start = 0 end = @bwtLength i = q.length - 1 while i >= 0 c = q[i] start = _lf(start, c) end = _lf(end, c) return {hits: 0, results:[]} if start >= end i-- if max > 0 && end - start > max return {hits: end - start, results: []} results = for ind in [start...end] pos = 0 metaInd = 0 while (c = @bwt.get(ind)) != 0 if (c == 1) metaInd = @wayPointsPerFile[ind] break if ind % 16 == 0 wp = @wayPoints[ind >> 4] metaInd = wp.meta pos += wp.ind break ind = _lf(ind, c) pos++ {uuid: @metaArray[metaInd].uuid, pos: pos} {hits: end - start, results: results} module.exports = FmIndex
[ { "context": "rd events\n\n channel = new RemoteQueue\n name: \"greeting\"\n transport: transport\n \n channel\n\n\ntest", "end": 317, "score": 0.993945300579071, "start": 309, "tag": "USERNAME", "value": "greeting" }, { "context": "n 'on' handler\", ->\n assert...
test/remote-queue.coffee
GemHQ/mutual
6
Transport = require "../src/redis-transport" RemoteQueue = require "../src/remote-queue" helpers = require "./helpers" {testify, assert, events} = helpers make = -> transport = new Transport host: "localhost" port: 6379 transport.events.forward events channel = new RemoteQueue name: "greeting" transport: transport channel testify.test "A remote queue", (context) -> context.test "can send and receive events", (context) -> sender = make() receiver = make() listen = receiver.listen() listen.on "success", -> receiver.on "hello", (name) -> context.test "using an 'on' handler", -> assert.ok (name is "Dan") receiver.end() sender.end() sender.emit "hello", "Dan"
7675
Transport = require "../src/redis-transport" RemoteQueue = require "../src/remote-queue" helpers = require "./helpers" {testify, assert, events} = helpers make = -> transport = new Transport host: "localhost" port: 6379 transport.events.forward events channel = new RemoteQueue name: "greeting" transport: transport channel testify.test "A remote queue", (context) -> context.test "can send and receive events", (context) -> sender = make() receiver = make() listen = receiver.listen() listen.on "success", -> receiver.on "hello", (name) -> context.test "using an 'on' handler", -> assert.ok (name is "<NAME>") receiver.end() sender.end() sender.emit "hello", "<NAME>"
true
Transport = require "../src/redis-transport" RemoteQueue = require "../src/remote-queue" helpers = require "./helpers" {testify, assert, events} = helpers make = -> transport = new Transport host: "localhost" port: 6379 transport.events.forward events channel = new RemoteQueue name: "greeting" transport: transport channel testify.test "A remote queue", (context) -> context.test "can send and receive events", (context) -> sender = make() receiver = make() listen = receiver.listen() listen.on "success", -> receiver.on "hello", (name) -> context.test "using an 'on' handler", -> assert.ok (name is "PI:NAME:<NAME>END_PI") receiver.end() sender.end() sender.emit "hello", "PI:NAME:<NAME>END_PI"
[ { "context": "console.log(user)\n hashPwd = user.password || 'unknown'\n salt=''\n hashKey = (crypto.pbkdf2Sync opt", "end": 3029, "score": 0.9859483242034912, "start": 3022, "tag": "PASSWORD", "value": "unknown" } ]
_attachments/app/models/User.coffee
jongoz/coconut-analytice
3
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ BackbonePouch = require 'backbone-pouch' Cookies = require 'js-cookie' moment = require 'moment' crypto = require('crypto') Config = require './Config' class User extends Backbone.Model sync: BackbonePouch.sync db: Coconut.database username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") password: -> @get("password") passwordIsValid: (password) -> @get("password") is password isAdmin: -> _(@get("roles")).include "admin" inActive: -> @get("inactive") hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() nameOrUsernameWithDescription: => "#{@nameOrUsername()} #{if @district() then " - #{@district()}" else ""}" User.isAuthenticated = (options) -> username = Cookies.get('current_user') if username? and username isnt "" id = "user.#{username}" Coconut.currentUser = new User() # id is not recognized when put in constructor for some reason Coconut.currentUser.id = id Coconut.currentUser.fetch error: (error) -> options.error(error) success: -> options.success(Coconut.currentUser) else # No cookie. Not logged in options.error("User not logged in") User.login = (options) -> user = new User _id: "user.#{options.username}" user.fetch success: -> if !(user.inActive()) hashPwd = user.get("password") || 'unknown' #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync options.password, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey Coconut.currentUser = user Coconut.currentlogin = user.username() Cookies.set('current_user', Coconut.currentlogin) Cookies.set('current_password',user.get "password") $("span#username").html user.username() $("a#logout").show() $("a#login").hide() if user.isAdmin() then $("#admin-main").show() else $("#admin-main").hide() Coconut.database.post collection: "login" user: Coconut.currentlogin date: moment(new Date()).format(Coconut.config.date_format) .catch (error) -> console.error error options.success() else options.error("Invalid username/password") else options.error("User account disabled") error: -> options.error() User.logout = (options) -> Cookies.remove('current_user') Cookies.remove('current_password') $('#district').html "" $("a#logout").hide() $("a#login").show() Coconut.currentUser = null User.changePass = (options) -> Coconut.database.get Coconut.currentUser.id, include_docs: true .catch (error) => options.error('Error encountered resetting password...') console.error error .then (user) => console.log(user) hashPwd = user.password || 'unknown' salt='' hashKey = (crypto.pbkdf2Sync options.currentPass, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey user.password = (crypto.pbkdf2Sync options.newPasswd, '', 1000, 256/8, 'sha256').toString('base64') Coconut.database.put user .catch (error) -> console.error error .then -> Cookies.set('current_password',user.password) options.success() else options.error("Invalid Current Password") User.inactiveStatus = (inactive) -> if (inactive) then "Yes" else "No" User.token = () -> return Math.random().toString(36).substr(2).toUpperCase() module.exports = User
121925
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ BackbonePouch = require 'backbone-pouch' Cookies = require 'js-cookie' moment = require 'moment' crypto = require('crypto') Config = require './Config' class User extends Backbone.Model sync: BackbonePouch.sync db: Coconut.database username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") password: -> @get("password") passwordIsValid: (password) -> @get("password") is password isAdmin: -> _(@get("roles")).include "admin" inActive: -> @get("inactive") hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() nameOrUsernameWithDescription: => "#{@nameOrUsername()} #{if @district() then " - #{@district()}" else ""}" User.isAuthenticated = (options) -> username = Cookies.get('current_user') if username? and username isnt "" id = "user.#{username}" Coconut.currentUser = new User() # id is not recognized when put in constructor for some reason Coconut.currentUser.id = id Coconut.currentUser.fetch error: (error) -> options.error(error) success: -> options.success(Coconut.currentUser) else # No cookie. Not logged in options.error("User not logged in") User.login = (options) -> user = new User _id: "user.#{options.username}" user.fetch success: -> if !(user.inActive()) hashPwd = user.get("password") || 'unknown' #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync options.password, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey Coconut.currentUser = user Coconut.currentlogin = user.username() Cookies.set('current_user', Coconut.currentlogin) Cookies.set('current_password',user.get "password") $("span#username").html user.username() $("a#logout").show() $("a#login").hide() if user.isAdmin() then $("#admin-main").show() else $("#admin-main").hide() Coconut.database.post collection: "login" user: Coconut.currentlogin date: moment(new Date()).format(Coconut.config.date_format) .catch (error) -> console.error error options.success() else options.error("Invalid username/password") else options.error("User account disabled") error: -> options.error() User.logout = (options) -> Cookies.remove('current_user') Cookies.remove('current_password') $('#district').html "" $("a#logout").hide() $("a#login").show() Coconut.currentUser = null User.changePass = (options) -> Coconut.database.get Coconut.currentUser.id, include_docs: true .catch (error) => options.error('Error encountered resetting password...') console.error error .then (user) => console.log(user) hashPwd = user.password || '<PASSWORD>' salt='' hashKey = (crypto.pbkdf2Sync options.currentPass, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey user.password = (crypto.pbkdf2Sync options.newPasswd, '', 1000, 256/8, 'sha256').toString('base64') Coconut.database.put user .catch (error) -> console.error error .then -> Cookies.set('current_password',user.password) options.success() else options.error("Invalid Current Password") User.inactiveStatus = (inactive) -> if (inactive) then "Yes" else "No" User.token = () -> return Math.random().toString(36).substr(2).toUpperCase() module.exports = User
true
_ = require 'underscore' $ = require 'jquery' Backbone = require 'backbone' Backbone.$ = $ BackbonePouch = require 'backbone-pouch' Cookies = require 'js-cookie' moment = require 'moment' crypto = require('crypto') Config = require './Config' class User extends Backbone.Model sync: BackbonePouch.sync db: Coconut.database username: -> @get("_id").replace(/^user\./,"") district: -> @get("district") password: -> @get("password") passwordIsValid: (password) -> @get("password") is password isAdmin: -> _(@get("roles")).include "admin" inActive: -> @get("inactive") hasRole: (role) -> _(@get("roles")).include role nameOrUsername: -> @get("name") or @username() nameOrUsernameWithDescription: => "#{@nameOrUsername()} #{if @district() then " - #{@district()}" else ""}" User.isAuthenticated = (options) -> username = Cookies.get('current_user') if username? and username isnt "" id = "user.#{username}" Coconut.currentUser = new User() # id is not recognized when put in constructor for some reason Coconut.currentUser.id = id Coconut.currentUser.fetch error: (error) -> options.error(error) success: -> options.success(Coconut.currentUser) else # No cookie. Not logged in options.error("User not logged in") User.login = (options) -> user = new User _id: "user.#{options.username}" user.fetch success: -> if !(user.inActive()) hashPwd = user.get("password") || 'unknown' #salt = Config.salt() salt = "" hashKey = (crypto.pbkdf2Sync options.password, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey Coconut.currentUser = user Coconut.currentlogin = user.username() Cookies.set('current_user', Coconut.currentlogin) Cookies.set('current_password',user.get "password") $("span#username").html user.username() $("a#logout").show() $("a#login").hide() if user.isAdmin() then $("#admin-main").show() else $("#admin-main").hide() Coconut.database.post collection: "login" user: Coconut.currentlogin date: moment(new Date()).format(Coconut.config.date_format) .catch (error) -> console.error error options.success() else options.error("Invalid username/password") else options.error("User account disabled") error: -> options.error() User.logout = (options) -> Cookies.remove('current_user') Cookies.remove('current_password') $('#district').html "" $("a#logout").hide() $("a#login").show() Coconut.currentUser = null User.changePass = (options) -> Coconut.database.get Coconut.currentUser.id, include_docs: true .catch (error) => options.error('Error encountered resetting password...') console.error error .then (user) => console.log(user) hashPwd = user.password || 'PI:PASSWORD:<PASSWORD>END_PI' salt='' hashKey = (crypto.pbkdf2Sync options.currentPass, salt, 1000, 256/8, 'sha256').toString('base64') if hashPwd is hashKey user.password = (crypto.pbkdf2Sync options.newPasswd, '', 1000, 256/8, 'sha256').toString('base64') Coconut.database.put user .catch (error) -> console.error error .then -> Cookies.set('current_password',user.password) options.success() else options.error("Invalid Current Password") User.inactiveStatus = (inactive) -> if (inactive) then "Yes" else "No" User.token = () -> return Math.random().toString(36).substr(2).toUpperCase() module.exports = User
[ { "context": "\"a\", [\"A$\"]],\n [\"a\", [\"AAA\"]],\n [\"a\", [\"Andaluc\"]],\n [\"a\", [\"Armat\"]],\n [\"a\", [\"Asturias\"]],\n", "end": 1575, "score": 0.6830939054489136, "start": 1573, "tag": "NAME", "value": "uc" }, { "context": "\"a\", [\"AAA\"]],\n [\"a\", [\"An...
generate/GenerateArticledata.coffee
chadkirby/Articles
22
fs = require 'fs' ### http://home.nerbonne.org/A-vs-An/ http://stackoverflow.com/questions/1288291/how-can-i-correctly-prefix-a-word-with-a-and-an/1288473#1288473 This page determines whether "a" or "an" should precede a word. It does this using the method described in this stackoverflow response. The dataset used is the wikipedia-article-text dump. Some additional preprocessing was done to remove as much wiki-markup as possible and extract only things vague resembling sentences using regular expressions. If the word following 'a' or 'an' was quoted, those quotes were ignored. The entire resultant dataset is merely 13KB in size and could be compressed further; it's included inline in this page. ### articleArray = [ ["an", ["8"]], ["an", ["11","18"]], ["a", ["110","111","112","113","114","115","116","117","118","119","180","890"]], ["an", ["1800","1801","1802","1803","1804","1805","1806","1807","1808","1809"]], ["an", ["`a","£8"]], ["an", ["0-11"]], ["a", ["0-4 "]], ["an", ["0-4"]], ["an", ["0-6-"]], ["an", ["0-8"]], ["an", ["08","09"]], ["a", ["11.4","181-","181 ","182-","182 ","183-","183 ","184-","184 ","185-","185 ","186-","186 ","187-","187 ","188-","188 ","189-","189 "]], ["a", ["8,1"]], ["a", ["800x"]], ["an", ["∞"]], ["a", ["a "]], ["an", ["about-"]], ["a", ["abou","agai","al-I","algu","alth","amon"]], ["a", ["an "]], ["an", ["anda","ande","andr"]], ["a", ["and"]], ["a", ["anot","anyw","apre","are ","are:","artí"]], ["an", ["a"]], ["a", ["A$"]], ["a", ["AAA"]], ["a", ["Andaluc"]], ["a", ["Armat"]], ["a", ["Asturias"]], ["an", ["Athleti"]], ["an", ["Athlo"]], ["a", ["Athl"]], ["a", ["AU$","AUD"]], ["a", ["AUSC"]], ["an", ["A","Á"]], ["an", ["á;"]], ["an", ["à","Ä","ā","Å","æ"]], ["a", ["Æn"]], ["an", ["Æ"]], ["a", ["Dún","e.g"]], ["a", ["each "]], ["a", ["either ","either."]], ["a", ["el-"]], ["a", ["ella"]], ["a", ["empez","enoug"]], ["an", ["eup "]], ["a", ["eu","ew"]], ["a", ["exists"]], ["an", ["e"]], ["a", ["Empez"]], ["a", ["Enam"]], ["an", ["Espad"]], ["an", ["Espe","Espo"]], ["a", ["Esp"]], ["an", ["Eul"]], ["a", ["Eu"]], ["a", ["EUR"]], ["an", ["E"]], ["a", ["ég"]], ["an", ["éta","étu"]], ["a", ["ét"]], ["an", ["é","É"]], ["an", ["f-","f ","f/","fM","fp","ft","F'","F-","F ","F\"","F#","F,","F.","F/","F”","F0","F1","F2","F3","F4","F5","F6","F9"]], ["a", ["FAC","FAD"]], ["a", ["FAIR"]], ["a", ["FAL","FAM","FAN","FAP","FAQ","FAR","FAS","FAT"]], ["an", ["FA","FB","FC","Fc","FD"]], ["an", ["FEC","FEI"]], ["a", ["FF "]], ["an", ["FF","Ff","Fh","FH"]], ["a", ["FIAT"]], ["an", ["FIA"]], ["an", ["FID ","FIR ","FIS "]], ["an", ["FK"]], ["an", ["FLC","FLN","FLP"]], ["a", ["FMR"]], ["an", ["FM"]], ["an", ["FO "]], ["an", ["FOI "]], ["a", ["FP.","FP?"]], ["a", ["FPC?"]], ["an", ["FP"]], ["an", ["FRC","FRS"]], ["an", ["FS"]], ["a", ["FTS","FTT"]], ["an", ["FT"]], ["an", ["FU ","FU,","FU."]], ["an", ["FV"]], ["a", ["FWD"]], ["an", ["FW","FX","FY","Fσ"]], ["an", ["Ghae","Ghai"]], ["an", ["h'"]], ["a", ["h-U"]], ["an", ["h-","h ","h\"","h,","hC"]], ["a", ["heira"]], ["an", ["heir","hims"]], ["a", ["historic"]], ["an", ["homa","homm"]], ["a", ["honey"]], ["a", ["honk","honv"]], ["an", ["hon"]], ["an", ["hors "]], ["an", ["hour"]], ["an", ["http "]], ["a", ["htt"]], ["an", ["ht","H'","H-","H ","H\"","H&","H,"]], ["a", ["H.A"]], ["an", ["H.","H+","H1","H2","H3","H4","H5"]], ["an", ["Habilitations"]], ["an", ["HB","HC"]], ["a", ["HDB"]], ["an", ["HD"]], ["an", ["Heir"]], ["an", ["HF","HG","HH"]], ["a", ["HID","HIG","HIM","HIP"]], ["an", ["HI"]], ["a", ["HLA-D"]], ["an", ["HL","HM","HN"]], ["a", ["Hond"]], ["an", ["Hones"]], ["a", ["Hone","Hong","Honk"]], ["a", ["Honol"]], ["an", ["Hon"]], ["an", ["Hour"]], ["an", ["HO ","HOV"]], ["an", ["HP","HQ"]], ["a", ["HRT"]], ["an", ["HR"]], ["a", ["HS ","HSR","HST"]], ["an", ["HS"]], ["a", ["HTP"]], ["an", ["HT","HV"]], ["an", ["HWT"]], ["a", ["i.e","ibn","if "]], ["a", ["ii"]], ["a", ["includi"]], ["a", ["indicates"]], ["an", ["instead?"]], ["a", ["instea"]], ["a", ["is ","is.","it "]], ["a", ["iu"]], ["an", ["i"]], ["a", ["I-A","I-I","III","Ilb","IMH"]], ["a", ["Imams"]], ["a", ["IR£"]], ["a", ["Islam ","Islam,","Islam."]], ["a", ["Islands"]], ["an", ["I","İ"]], ["a", ["Jian"]], ["an", ["Jia","ku "]], ["an", ["l ","l\"","lp"]], ["a", ["L'A"]], ["an", ["L'"]], ["a", ["L-a"]], ["an", ["L-","L ","L\"","L&","L,","L.","L/","L1","L2","L3","L5"]], ["an", ["Lae"]], ["an", ["Laoig"]], ["an", ["LA ","LAL","LAP"]], ["an", ["LB","LC","LD"]], ["a", ["LEA","LEE","LEG","LEO","LEP","LET"]], ["an", ["LE","LF","LG","LH"]], ["an", ["LIR"]], ["an", ["LL"]], ["a", ["LMX"]], ["an", ["LM","LN"]], ["an", ["Locha"]], ["an", ["LOE"]], ["an", ["LP","LR","LS","LT"]], ["an", ["LU "]], ["an", ["LV","LX","LZ","m-","m ","m\"","m&"]], ["an", ["makes "]], ["an", ["mb"]], ["an", ["mein"]], ["an", ["mentions"]], ["an", ["mf","mp","mR","mt","M'"]], ["a", ["M-t"]], ["an", ["M-","M ","M\"","M&","M,"]], ["a", ["M.A.S"]], ["an", ["M.","M/"]], ["an", ["M190"]], ["a", ["M19"]], ["an", ["M1","M2","M3","M4","M5","M6","M7","M8","M9"]], ["a", ["MAC","MAD","MAF","MAG","MAJ","MAL","MAM","MAN","MAP","MAR","MAS","MAT","MAX","MAY"]], ["an", ["MA","MB","MC","MD"]], ["an", ["Me-","MEd","MEn","MEP"]], ["an", ["MF","Mf","MG","MH","Mh"]], ["an", ["Mie","MI ","MI5","MI6","MIA","MIT"]], ["an", ["MK","ML"]], ["a", ["MMT"]], ["an", ["MM","MN"]], ["an", ["MoU","MO "]], ["an", ["MOT "]], ["an", ["MOU"]], ["an", ["MP","MR","MS"]], ["an", ["Msc"]], ["a", ["MTR"]], ["an", ["MT"]], ["an", ["MUV"]], ["an", ["MV","MX","N'"]], ["a", ["N-a","N-S"]], ["an", ["N-","N ","N\"","N,"]], ["a", ["N.Y"]], ["an", ["N.","N=","N²","N4","N6"]], ["an", ["Nao","NA "]], ["a", ["NAAF"]], ["an", ["NAA","NAI"]], ["an", ["NASL"]], ["an", ["NB","NC","ND"]], ["an", ["NEA","NEH"]], ["an", ["NES "]], ["an", ["NF","NG","NH"]], ["a", ["NIC","NIL"]], ["an", ["NIMH"]], ["a", ["NIM","NIN","NIS"]], ["an", ["NI"]], ["an", ["NJC"]], ["an", ["NK"]], ["a", ["NLS"]], ["an", ["NL","NM"]], ["an", ["NNR","NNT"]], ["an", ["NPOV-"]], ["a", ["NPO"]], ["an", ["NP"]], ["a", ["NRJ","NRT"]], ["an", ["NR"]], ["a", ["NSW"]], ["an", ["NS"]], ["a", ["NT$"]], ["an", ["NT"]], ["an", ["NUS"]], ["an", ["NV","Nv"]], ["an", ["NWA"]], ["an", ["NX"]], ["an", ["NYP","NYU"]], ["an", ["n-","n−","n ","n\"","n&","n,","n+","n×"]], ["an", ["nda","npa"]], ["an", ["nt","nV","nW"]], ["a", ["obr"]], ["a", ["occurs"]], ["a", ["ocho"]], ["a", ["of "]], ["an", ["on-","on/","onb"]], ["an", ["onco"]], ["an", ["ond"]], ["an", ["oner"]], ["an", ["ong","oni","onl","onm","ono","onr","ons","ont","onu","onw","ony"]], ["a", ["on"]], ["a", ["or ","or,","oui"]], ["an", ["o"]], ["an", ["Oberst ","Oberstl"]], ["a", ["Obers"]], ["a", ["Olv"]], ["an", ["Onei"]], ["a", ["One","ONE","Oop","Oui"]], ["an", ["O","Ó","Ö","ö","Ō","ō"]], ["an", ["Phob","Phoi"]], ["an", ["r'","r-","r ","r\"","r&","r."]], ["an", ["refers"]], ["an", ["rf","rm","rs","R'","R-","R ","R\"","R&","R,"]], ["a", ["R.C"]], ["an", ["R.","R/"]], ["a", ["R10"]], ["an", ["R1","R2","R3","R4","R5","R6"]], ["an", ["RA ","RAF"]], ["an", ["RB","RC","RD"]], ["an", ["RE ","RER"]], ["an", ["RF","Rf","RG"]], ["an", ["RHS","RIA"]], ["an", ["RIC "]], ["an", ["RJ","RK"]], ["a", ["RL "]], ["an", ["RL"]], ["a", ["RM1"]], ["an", ["RM"]], ["a", ["RNG"]], ["an", ["RN"]], ["an", ["ROT"]], ["an", ["RP","RQ","RR"]], ["a", ["RS ","RS)","RS,","RS.","RS?","RST"]], ["an", ["RS","RT","RU","RV","RX","s-","s\"","s)","s,","s."]], ["an", ["says","sich"]], ["an", ["sp3"]], ["an", ["sprot"]], ["an", ["ssh"]], ["an", ["states ","states:"]], ["a", ["sva","sve"]], ["an", ["sv","S'","S-","S ","S\""]], ["a", ["S&W"]], ["an", ["S&","S,"]], ["an", ["S.B","S.M","S.O"]], ["an", ["S”","S1","S2","S3","S4","S5","S6"]], ["a", ["SA-1"]], ["an", ["SA-","SA "]], ["an", ["SACD"]], ["an", ["SAE"]], ["a", ["SASE"]], ["an", ["SAS"]], ["an", ["SAT ","SATB"]], ["an", ["SB"]], ["an", ["SCA "]], ["an", ["SCC","SCM"]], ["an", ["SCO "]], ["a", ["SCRA"]], ["an", ["SCR","SCT"]], ["an", ["SD"]], ["an", ["SE "]], ["a", ["SECO","SECR"]], ["an", ["SEC","SEI","SEO"]], ["an", ["SF","SG"]], ["an", ["SH-","SH2","SH3","SI "]], ["an", ["SJ","SK"]], ["a", ["SLA","SLI","SLO"]], ["an", ["SL"]], ["a", ["SMA"]], ["an", ["SME "]], ["a", ["SME","SMI"]], ["an", ["SM"]], ["a", ["SNA","SNE","SNO"]], ["an", ["SN"]], ["an", ["SO("]], ["an", ["SOA ","SOAI"]], ["an", ["SOE","SOI","SOS","SOV"]], ["a", ["SPAC","SPAD","SPAM","SPAN","SPAR"]], ["an", ["SPE "]], ["a", ["SPE"]], ["a", ["SPIC"]], ["a", ["SPO","SPU"]], ["an", ["SP","SR","SS"]], ["an", ["ST-"]], ["an", ["STA "]], ["an", ["STB","STC","STD","STF","STL","STM","STS","STV"]], ["an", ["Sura "]], ["a", ["SUB","SUL","SUN","SUP","SUS"]], ["an", ["SU","SV"]], ["an", ["SWF","SWP","SWR"]], ["a", ["SXS"]], ["an", ["SX"]], ["an", ["t-S"]], ["an", ["tS"]], ["an", ["Taves"]], ["an", ["Tà"]], ["a", ["u-","u ","u\"","u."]], ["an", ["ube"]], ["a", ["ub","uf"]], ["an", ["uka"]], ["a", ["uk"]], ["a", ["ulu","um ","un "]], ["a", ["una "]], ["an", ["unana","unann","unans","unant"]], ["a", ["unan"]], ["a", ["unary"]], ["a", ["une "]], ["an", ["unicorp"]], ["a", ["unidi"]], ["an", ["unid"]], ["a", ["unimo"]], ["an", ["unim","unin"]], ["an", ["univo"]], ["a", ["uni"]], ["a", ["unles"]], ["a", ["upo","ura","ure","uri","url","uro"]], ["an", ["us-","us ","ush"]], ["a", ["us"]], ["an", ["utm","utt"]], ["a", ["ut","uv","uw"]], ["an", ["u"]], ["a", ["U-Bo"]], ["an", ["U-B"]], ["an", ["U1","Ua"]], ["a", ["Ubi"]], ["an", ["Ub"]], ["an", ["UDP-"]], ["an", ["Ud"]], ["an", ["Ugl"]], ["an", ["Uh","Ui"]], ["a", ["Uli"]], ["an", ["Ul","Um"]], ["an", ["UMN","Un-"]], ["a", ["Unan"]], ["an", ["Una","Unb","Unc","Und"]], ["a", ["Unes"]], ["an", ["Une","Unf","Ung","Unh"]], ["an", ["Unid","Unin"]], ["an", ["Unk","Unl","Unm","Unn","Uno","Unp","Unr","Uns"]], ["a", ["Unters"]], ["an", ["Unt","Unu","Unw"]], ["an", ["Up"]], ["a", ["Ura","Uri"]], ["an", ["Uruguayan-"]], ["an", ["Uruk"]], ["a", ["Uru"]], ["an", ["Ur"]], ["an", ["Ush","Ust","Utn"]], ["an", ["Uto-"]], ["an", ["Utr","Utt"]], ["an", ["Ux","Uz"]], ["an", ["ü","Ü"]], ["an", ["VII"]], ["a", ["xa","xe","xi","xo","xx","xy"]], ["an", ["x"]], ["a", ["Xa","XA","Xe","Xh","Xi"]], ["a", ["XIV","XIX"]], ["a", ["Xo","Xu","XU","XV"]], ["an", ["XX "]], ["a", ["XX","Xy"]], ["an", ["X"]], ["an", ["Yp"]], ["an", ["α","ε","ω"]] ["a", [""]] ] setPath = (obj, prefix, article) -> return unless prefix.length > 0 letter = prefix[0] obj[letter] = {} unless obj[letter] if prefix.length is 1 obj[letter].article = article else setPath obj[letter], prefix[1..], article articles = {} for [article, prefixList] in articleArray for prefix in prefixList setPath articles, prefix, article fs.writeFile '../lib/articledata.json', JSON.stringify(articles)
60281
fs = require 'fs' ### http://home.nerbonne.org/A-vs-An/ http://stackoverflow.com/questions/1288291/how-can-i-correctly-prefix-a-word-with-a-and-an/1288473#1288473 This page determines whether "a" or "an" should precede a word. It does this using the method described in this stackoverflow response. The dataset used is the wikipedia-article-text dump. Some additional preprocessing was done to remove as much wiki-markup as possible and extract only things vague resembling sentences using regular expressions. If the word following 'a' or 'an' was quoted, those quotes were ignored. The entire resultant dataset is merely 13KB in size and could be compressed further; it's included inline in this page. ### articleArray = [ ["an", ["8"]], ["an", ["11","18"]], ["a", ["110","111","112","113","114","115","116","117","118","119","180","890"]], ["an", ["1800","1801","1802","1803","1804","1805","1806","1807","1808","1809"]], ["an", ["`a","£8"]], ["an", ["0-11"]], ["a", ["0-4 "]], ["an", ["0-4"]], ["an", ["0-6-"]], ["an", ["0-8"]], ["an", ["08","09"]], ["a", ["11.4","181-","181 ","182-","182 ","183-","183 ","184-","184 ","185-","185 ","186-","186 ","187-","187 ","188-","188 ","189-","189 "]], ["a", ["8,1"]], ["a", ["800x"]], ["an", ["∞"]], ["a", ["a "]], ["an", ["about-"]], ["a", ["abou","agai","al-I","algu","alth","amon"]], ["a", ["an "]], ["an", ["anda","ande","andr"]], ["a", ["and"]], ["a", ["anot","anyw","apre","are ","are:","artí"]], ["an", ["a"]], ["a", ["A$"]], ["a", ["AAA"]], ["a", ["Andal<NAME>"]], ["a", ["<NAME>"]], ["a", ["Ast<NAME>"]], ["an", ["Athleti"]], ["an", ["Athlo"]], ["a", ["Athl"]], ["a", ["AU$","AUD"]], ["a", ["AUSC"]], ["an", ["A","Á"]], ["an", ["á;"]], ["an", ["à","Ä","ā","Å","æ"]], ["a", ["Æn"]], ["an", ["Æ"]], ["a", ["Dún","e.g"]], ["a", ["each "]], ["a", ["either ","either."]], ["a", ["el-"]], ["a", ["ella"]], ["a", ["empez","enoug"]], ["an", ["eup "]], ["a", ["eu","ew"]], ["a", ["exists"]], ["an", ["e"]], ["a", ["Emp<NAME>"]], ["a", ["Enam"]], ["an", ["Espad"]], ["an", ["Espe","Espo"]], ["a", ["Esp"]], ["an", ["Eul"]], ["a", ["Eu"]], ["a", ["EUR"]], ["an", ["E"]], ["a", ["ég"]], ["an", ["éta","étu"]], ["a", ["ét"]], ["an", ["é","É"]], ["an", ["f-","f ","f/","fM","fp","ft","F'","F-","F ","F\"","F#","F,","F.","F/","F”","F0","F1","F2","F3","F4","F5","F6","F9"]], ["a", ["FAC","FAD"]], ["a", ["FAIR"]], ["a", ["FAL","FAM","FAN","FAP","FAQ","FAR","FAS","FAT"]], ["an", ["FA","FB","FC","Fc","FD"]], ["an", ["FEC","FEI"]], ["a", ["FF "]], ["an", ["FF","Ff","Fh","FH"]], ["a", ["FIAT"]], ["an", ["FIA"]], ["an", ["FID ","FIR ","FIS "]], ["an", ["FK"]], ["an", ["FLC","FLN","FLP"]], ["a", ["FMR"]], ["an", ["FM"]], ["an", ["FO "]], ["an", ["FOI "]], ["a", ["FP.","FP?"]], ["a", ["FPC?"]], ["an", ["FP"]], ["an", ["FRC","FRS"]], ["an", ["FS"]], ["a", ["FTS","FTT"]], ["an", ["FT"]], ["an", ["FU ","FU,","FU."]], ["an", ["FV"]], ["a", ["FWD"]], ["an", ["FW","FX","FY","Fσ"]], ["an", ["Ghae","Ghai"]], ["an", ["h'"]], ["a", ["h-U"]], ["an", ["h-","h ","h\"","h,","hC"]], ["a", ["heira"]], ["an", ["heir","hims"]], ["a", ["historic"]], ["an", ["homa","homm"]], ["a", ["honey"]], ["a", ["honk","honv"]], ["an", ["hon"]], ["an", ["hors "]], ["an", ["hour"]], ["an", ["http "]], ["a", ["htt"]], ["an", ["ht","H'","H-","H ","H\"","H&","H,"]], ["a", ["H.A"]], ["an", ["H.","H+","H1","H2","H3","H4","H5"]], ["an", ["Habilitations"]], ["an", ["HB","HC"]], ["a", ["HDB"]], ["an", ["HD"]], ["an", ["Heir"]], ["an", ["HF","HG","HH"]], ["a", ["HID","HIG","HIM","HIP"]], ["an", ["HI"]], ["a", ["HLA-D"]], ["an", ["HL","HM","HN"]], ["a", ["Hond"]], ["an", ["Hones"]], ["a", ["Hone","Hong","Honk"]], ["a", ["Honol"]], ["an", ["Hon"]], ["an", ["Hour"]], ["an", ["HO ","HOV"]], ["an", ["HP","HQ"]], ["a", ["HRT"]], ["an", ["HR"]], ["a", ["HS ","HSR","HST"]], ["an", ["HS"]], ["a", ["HTP"]], ["an", ["HT","HV"]], ["an", ["HWT"]], ["a", ["i.e","ibn","if "]], ["a", ["ii"]], ["a", ["includi"]], ["a", ["indicates"]], ["an", ["instead?"]], ["a", ["instea"]], ["a", ["is ","is.","it "]], ["a", ["iu"]], ["an", ["i"]], ["a", ["I-A","I-I","III","Ilb","IMH"]], ["a", ["Imams"]], ["a", ["IR£"]], ["a", ["Islam ","Islam,","Islam."]], ["a", ["Islands"]], ["an", ["I","İ"]], ["a", ["Jian"]], ["an", ["Jia","ku "]], ["an", ["l ","l\"","lp"]], ["a", ["L'A"]], ["an", ["L'"]], ["a", ["L-a"]], ["an", ["L-","L ","L\"","L&","L,","L.","L/","L1","L2","L3","L5"]], ["an", ["Lae"]], ["an", ["Laoig"]], ["an", ["LA ","LAL","LAP"]], ["an", ["LB","LC","LD"]], ["a", ["LEA","LEE","LEG","LEO","LEP","LET"]], ["an", ["LE","LF","LG","LH"]], ["an", ["LIR"]], ["an", ["LL"]], ["a", ["LMX"]], ["an", ["LM","LN"]], ["an", ["Locha"]], ["an", ["LOE"]], ["an", ["LP","LR","LS","LT"]], ["an", ["LU "]], ["an", ["LV","LX","LZ","m-","m ","m\"","m&"]], ["an", ["makes "]], ["an", ["mb"]], ["an", ["mein"]], ["an", ["mentions"]], ["an", ["mf","mp","mR","mt","M'"]], ["a", ["M-t"]], ["an", ["M-","M ","M\"","M&","M,"]], ["a", ["M.A.S"]], ["an", ["M.","M/"]], ["an", ["M190"]], ["a", ["M19"]], ["an", ["M1","M2","M3","M4","M5","M6","M7","M8","M9"]], ["a", ["MAC","MAD","MAF","MAG","MAJ","MAL","MAM","MAN","MAP","MAR","MAS","MAT","MAX","MAY"]], ["an", ["MA","MB","MC","MD"]], ["an", ["Me-","MEd","MEn","MEP"]], ["an", ["MF","Mf","MG","MH","Mh"]], ["an", ["Mie","MI ","MI5","MI6","MIA","MIT"]], ["an", ["MK","ML"]], ["a", ["MMT"]], ["an", ["MM","MN"]], ["an", ["MoU","MO "]], ["an", ["MOT "]], ["an", ["MOU"]], ["an", ["MP","MR","MS"]], ["an", ["Msc"]], ["a", ["MTR"]], ["an", ["MT"]], ["an", ["MUV"]], ["an", ["MV","MX","N'"]], ["a", ["N-a","N-S"]], ["an", ["N-","N ","N\"","N,"]], ["a", ["N.Y"]], ["an", ["N.","N=","N²","N4","N6"]], ["an", ["Nao","NA "]], ["a", ["NAAF"]], ["an", ["NAA","NAI"]], ["an", ["NASL"]], ["an", ["NB","NC","ND"]], ["an", ["NEA","NEH"]], ["an", ["NES "]], ["an", ["NF","NG","NH"]], ["a", ["NIC","NIL"]], ["an", ["NIMH"]], ["a", ["NIM","NIN","NIS"]], ["an", ["NI"]], ["an", ["NJC"]], ["an", ["NK"]], ["a", ["NLS"]], ["an", ["NL","NM"]], ["an", ["NNR","NNT"]], ["an", ["NPOV-"]], ["a", ["NPO"]], ["an", ["NP"]], ["a", ["NRJ","NRT"]], ["an", ["NR"]], ["a", ["NSW"]], ["an", ["NS"]], ["a", ["NT$"]], ["an", ["NT"]], ["an", ["NUS"]], ["an", ["NV","Nv"]], ["an", ["NWA"]], ["an", ["NX"]], ["an", ["NYP","NYU"]], ["an", ["n-","n−","n ","n\"","n&","n,","n+","n×"]], ["an", ["nda","npa"]], ["an", ["nt","nV","nW"]], ["a", ["obr"]], ["a", ["occurs"]], ["a", ["ocho"]], ["a", ["of "]], ["an", ["on-","on/","onb"]], ["an", ["onco"]], ["an", ["ond"]], ["an", ["oner"]], ["an", ["ong","oni","onl","onm","ono","onr","ons","ont","onu","onw","ony"]], ["a", ["on"]], ["a", ["or ","or,","oui"]], ["an", ["o"]], ["an", ["Oberst ","Oberstl"]], ["a", ["<NAME>"]], ["a", ["<NAME>"]], ["an", ["Onei"]], ["a", ["One","ONE","Oop","Oui"]], ["an", ["O","Ó","Ö","ö","Ō","ō"]], ["an", ["Phob","Phoi"]], ["an", ["r'","r-","r ","r\"","r&","r."]], ["an", ["refers"]], ["an", ["rf","rm","rs","R'","R-","R ","R\"","R&","R,"]], ["a", ["R.C"]], ["an", ["R.","R/"]], ["a", ["R10"]], ["an", ["R1","R2","R3","R4","R5","R6"]], ["an", ["RA ","RAF"]], ["an", ["RB","RC","RD"]], ["an", ["RE ","RER"]], ["an", ["RF","Rf","RG"]], ["an", ["RHS","RIA"]], ["an", ["RIC "]], ["an", ["RJ","RK"]], ["a", ["RL "]], ["an", ["RL"]], ["a", ["RM1"]], ["an", ["RM"]], ["a", ["RNG"]], ["an", ["RN"]], ["an", ["ROT"]], ["an", ["RP","RQ","RR"]], ["a", ["RS ","RS)","RS,","RS.","RS?","RST"]], ["an", ["RS","RT","RU","RV","RX","s-","s\"","s)","s,","s."]], ["an", ["says","sich"]], ["an", ["sp3"]], ["an", ["sprot"]], ["an", ["ssh"]], ["an", ["states ","states:"]], ["a", ["sva","sve"]], ["an", ["sv","S'","S-","S ","S\""]], ["a", ["S&W"]], ["an", ["S&","S,"]], ["an", ["S.B","S.M","S.O"]], ["an", ["S”","S1","S2","S3","S4","S5","S6"]], ["a", ["SA-1"]], ["an", ["SA-","SA "]], ["an", ["SACD"]], ["an", ["SAE"]], ["a", ["SASE"]], ["an", ["SAS"]], ["an", ["SAT ","SATB"]], ["an", ["SB"]], ["an", ["SCA "]], ["an", ["SCC","SCM"]], ["an", ["SCO "]], ["a", ["SCRA"]], ["an", ["SCR","SCT"]], ["an", ["SD"]], ["an", ["SE "]], ["a", ["SECO","SECR"]], ["an", ["SEC","SEI","SEO"]], ["an", ["SF","SG"]], ["an", ["SH-","SH2","SH3","SI "]], ["an", ["SJ","SK"]], ["a", ["SLA","SLI","SLO"]], ["an", ["SL"]], ["a", ["SMA"]], ["an", ["SME "]], ["a", ["SME","SMI"]], ["an", ["SM"]], ["a", ["SNA","SNE","SNO"]], ["an", ["SN"]], ["an", ["SO("]], ["an", ["SOA ","SOAI"]], ["an", ["SOE","SOI","SOS","SOV"]], ["a", ["SPAC","SPAD","SPAM","SPAN","SPAR"]], ["an", ["SPE "]], ["a", ["SPE"]], ["a", ["SPIC"]], ["a", ["SPO","SPU"]], ["an", ["SP","SR","SS"]], ["an", ["ST-"]], ["an", ["STA "]], ["an", ["STB","STC","STD","STF","STL","STM","STS","STV"]], ["an", ["Sura "]], ["a", ["SUB","SUL","SUN","SUP","SUS"]], ["an", ["SU","SV"]], ["an", ["SWF","SWP","SWR"]], ["a", ["SXS"]], ["an", ["SX"]], ["an", ["t-S"]], ["an", ["tS"]], ["an", ["Taves"]], ["an", ["Tà"]], ["a", ["u-","u ","u\"","u."]], ["an", ["ube"]], ["a", ["ub","uf"]], ["an", ["uka"]], ["a", ["uk"]], ["a", ["ulu","um ","un "]], ["a", ["una "]], ["an", ["unana","unann","unans","unant"]], ["a", ["unan"]], ["a", ["unary"]], ["a", ["une "]], ["an", ["unicorp"]], ["a", ["unidi"]], ["an", ["unid"]], ["a", ["unimo"]], ["an", ["unim","unin"]], ["an", ["univo"]], ["a", ["uni"]], ["a", ["unles"]], ["a", ["upo","ura","ure","uri","url","uro"]], ["an", ["us-","us ","ush"]], ["a", ["us"]], ["an", ["utm","utt"]], ["a", ["ut","uv","uw"]], ["an", ["u"]], ["a", ["U-Bo"]], ["an", ["U-B"]], ["an", ["U1","Ua"]], ["a", ["Ubi"]], ["an", ["Ub"]], ["an", ["UDP-"]], ["an", ["Ud"]], ["an", ["Ugl"]], ["an", ["Uh","Ui"]], ["a", ["Uli"]], ["an", ["Ul","Um"]], ["an", ["UMN","Un-"]], ["a", ["Unan"]], ["an", ["Una","Unb","Unc","Und"]], ["a", ["Unes"]], ["an", ["Une","Unf","Ung","Unh"]], ["an", ["Unid","Unin"]], ["an", ["Unk","Unl","Unm","Unn","Uno","Unp","Unr","Uns"]], ["a", ["Unters"]], ["an", ["Unt","Unu","Unw"]], ["an", ["Up"]], ["a", ["Ura","Uri"]], ["an", ["Uruguayan-"]], ["an", ["Uruk"]], ["a", ["Uru"]], ["an", ["Ur"]], ["an", ["Ush","Ust","Utn"]], ["an", ["Uto-"]], ["an", ["Utr","Utt"]], ["an", ["Ux","Uz"]], ["an", ["ü","Ü"]], ["an", ["VII"]], ["a", ["xa","xe","xi","xo","xx","xy"]], ["an", ["x"]], ["a", ["Xa","XA","Xe","Xh","Xi"]], ["a", ["XIV","XIX"]], ["a", ["Xo","Xu","XU","XV"]], ["an", ["XX "]], ["a", ["XX","Xy"]], ["an", ["X"]], ["an", ["Yp"]], ["an", ["α","ε","ω"]] ["a", [""]] ] setPath = (obj, prefix, article) -> return unless prefix.length > 0 letter = prefix[0] obj[letter] = {} unless obj[letter] if prefix.length is 1 obj[letter].article = article else setPath obj[letter], prefix[1..], article articles = {} for [article, prefixList] in articleArray for prefix in prefixList setPath articles, prefix, article fs.writeFile '../lib/articledata.json', JSON.stringify(articles)
true
fs = require 'fs' ### http://home.nerbonne.org/A-vs-An/ http://stackoverflow.com/questions/1288291/how-can-i-correctly-prefix-a-word-with-a-and-an/1288473#1288473 This page determines whether "a" or "an" should precede a word. It does this using the method described in this stackoverflow response. The dataset used is the wikipedia-article-text dump. Some additional preprocessing was done to remove as much wiki-markup as possible and extract only things vague resembling sentences using regular expressions. If the word following 'a' or 'an' was quoted, those quotes were ignored. The entire resultant dataset is merely 13KB in size and could be compressed further; it's included inline in this page. ### articleArray = [ ["an", ["8"]], ["an", ["11","18"]], ["a", ["110","111","112","113","114","115","116","117","118","119","180","890"]], ["an", ["1800","1801","1802","1803","1804","1805","1806","1807","1808","1809"]], ["an", ["`a","£8"]], ["an", ["0-11"]], ["a", ["0-4 "]], ["an", ["0-4"]], ["an", ["0-6-"]], ["an", ["0-8"]], ["an", ["08","09"]], ["a", ["11.4","181-","181 ","182-","182 ","183-","183 ","184-","184 ","185-","185 ","186-","186 ","187-","187 ","188-","188 ","189-","189 "]], ["a", ["8,1"]], ["a", ["800x"]], ["an", ["∞"]], ["a", ["a "]], ["an", ["about-"]], ["a", ["abou","agai","al-I","algu","alth","amon"]], ["a", ["an "]], ["an", ["anda","ande","andr"]], ["a", ["and"]], ["a", ["anot","anyw","apre","are ","are:","artí"]], ["an", ["a"]], ["a", ["A$"]], ["a", ["AAA"]], ["a", ["AndalPI:NAME:<NAME>END_PI"]], ["a", ["PI:NAME:<NAME>END_PI"]], ["a", ["AstPI:NAME:<NAME>END_PI"]], ["an", ["Athleti"]], ["an", ["Athlo"]], ["a", ["Athl"]], ["a", ["AU$","AUD"]], ["a", ["AUSC"]], ["an", ["A","Á"]], ["an", ["á;"]], ["an", ["à","Ä","ā","Å","æ"]], ["a", ["Æn"]], ["an", ["Æ"]], ["a", ["Dún","e.g"]], ["a", ["each "]], ["a", ["either ","either."]], ["a", ["el-"]], ["a", ["ella"]], ["a", ["empez","enoug"]], ["an", ["eup "]], ["a", ["eu","ew"]], ["a", ["exists"]], ["an", ["e"]], ["a", ["EmpPI:NAME:<NAME>END_PI"]], ["a", ["Enam"]], ["an", ["Espad"]], ["an", ["Espe","Espo"]], ["a", ["Esp"]], ["an", ["Eul"]], ["a", ["Eu"]], ["a", ["EUR"]], ["an", ["E"]], ["a", ["ég"]], ["an", ["éta","étu"]], ["a", ["ét"]], ["an", ["é","É"]], ["an", ["f-","f ","f/","fM","fp","ft","F'","F-","F ","F\"","F#","F,","F.","F/","F”","F0","F1","F2","F3","F4","F5","F6","F9"]], ["a", ["FAC","FAD"]], ["a", ["FAIR"]], ["a", ["FAL","FAM","FAN","FAP","FAQ","FAR","FAS","FAT"]], ["an", ["FA","FB","FC","Fc","FD"]], ["an", ["FEC","FEI"]], ["a", ["FF "]], ["an", ["FF","Ff","Fh","FH"]], ["a", ["FIAT"]], ["an", ["FIA"]], ["an", ["FID ","FIR ","FIS "]], ["an", ["FK"]], ["an", ["FLC","FLN","FLP"]], ["a", ["FMR"]], ["an", ["FM"]], ["an", ["FO "]], ["an", ["FOI "]], ["a", ["FP.","FP?"]], ["a", ["FPC?"]], ["an", ["FP"]], ["an", ["FRC","FRS"]], ["an", ["FS"]], ["a", ["FTS","FTT"]], ["an", ["FT"]], ["an", ["FU ","FU,","FU."]], ["an", ["FV"]], ["a", ["FWD"]], ["an", ["FW","FX","FY","Fσ"]], ["an", ["Ghae","Ghai"]], ["an", ["h'"]], ["a", ["h-U"]], ["an", ["h-","h ","h\"","h,","hC"]], ["a", ["heira"]], ["an", ["heir","hims"]], ["a", ["historic"]], ["an", ["homa","homm"]], ["a", ["honey"]], ["a", ["honk","honv"]], ["an", ["hon"]], ["an", ["hors "]], ["an", ["hour"]], ["an", ["http "]], ["a", ["htt"]], ["an", ["ht","H'","H-","H ","H\"","H&","H,"]], ["a", ["H.A"]], ["an", ["H.","H+","H1","H2","H3","H4","H5"]], ["an", ["Habilitations"]], ["an", ["HB","HC"]], ["a", ["HDB"]], ["an", ["HD"]], ["an", ["Heir"]], ["an", ["HF","HG","HH"]], ["a", ["HID","HIG","HIM","HIP"]], ["an", ["HI"]], ["a", ["HLA-D"]], ["an", ["HL","HM","HN"]], ["a", ["Hond"]], ["an", ["Hones"]], ["a", ["Hone","Hong","Honk"]], ["a", ["Honol"]], ["an", ["Hon"]], ["an", ["Hour"]], ["an", ["HO ","HOV"]], ["an", ["HP","HQ"]], ["a", ["HRT"]], ["an", ["HR"]], ["a", ["HS ","HSR","HST"]], ["an", ["HS"]], ["a", ["HTP"]], ["an", ["HT","HV"]], ["an", ["HWT"]], ["a", ["i.e","ibn","if "]], ["a", ["ii"]], ["a", ["includi"]], ["a", ["indicates"]], ["an", ["instead?"]], ["a", ["instea"]], ["a", ["is ","is.","it "]], ["a", ["iu"]], ["an", ["i"]], ["a", ["I-A","I-I","III","Ilb","IMH"]], ["a", ["Imams"]], ["a", ["IR£"]], ["a", ["Islam ","Islam,","Islam."]], ["a", ["Islands"]], ["an", ["I","İ"]], ["a", ["Jian"]], ["an", ["Jia","ku "]], ["an", ["l ","l\"","lp"]], ["a", ["L'A"]], ["an", ["L'"]], ["a", ["L-a"]], ["an", ["L-","L ","L\"","L&","L,","L.","L/","L1","L2","L3","L5"]], ["an", ["Lae"]], ["an", ["Laoig"]], ["an", ["LA ","LAL","LAP"]], ["an", ["LB","LC","LD"]], ["a", ["LEA","LEE","LEG","LEO","LEP","LET"]], ["an", ["LE","LF","LG","LH"]], ["an", ["LIR"]], ["an", ["LL"]], ["a", ["LMX"]], ["an", ["LM","LN"]], ["an", ["Locha"]], ["an", ["LOE"]], ["an", ["LP","LR","LS","LT"]], ["an", ["LU "]], ["an", ["LV","LX","LZ","m-","m ","m\"","m&"]], ["an", ["makes "]], ["an", ["mb"]], ["an", ["mein"]], ["an", ["mentions"]], ["an", ["mf","mp","mR","mt","M'"]], ["a", ["M-t"]], ["an", ["M-","M ","M\"","M&","M,"]], ["a", ["M.A.S"]], ["an", ["M.","M/"]], ["an", ["M190"]], ["a", ["M19"]], ["an", ["M1","M2","M3","M4","M5","M6","M7","M8","M9"]], ["a", ["MAC","MAD","MAF","MAG","MAJ","MAL","MAM","MAN","MAP","MAR","MAS","MAT","MAX","MAY"]], ["an", ["MA","MB","MC","MD"]], ["an", ["Me-","MEd","MEn","MEP"]], ["an", ["MF","Mf","MG","MH","Mh"]], ["an", ["Mie","MI ","MI5","MI6","MIA","MIT"]], ["an", ["MK","ML"]], ["a", ["MMT"]], ["an", ["MM","MN"]], ["an", ["MoU","MO "]], ["an", ["MOT "]], ["an", ["MOU"]], ["an", ["MP","MR","MS"]], ["an", ["Msc"]], ["a", ["MTR"]], ["an", ["MT"]], ["an", ["MUV"]], ["an", ["MV","MX","N'"]], ["a", ["N-a","N-S"]], ["an", ["N-","N ","N\"","N,"]], ["a", ["N.Y"]], ["an", ["N.","N=","N²","N4","N6"]], ["an", ["Nao","NA "]], ["a", ["NAAF"]], ["an", ["NAA","NAI"]], ["an", ["NASL"]], ["an", ["NB","NC","ND"]], ["an", ["NEA","NEH"]], ["an", ["NES "]], ["an", ["NF","NG","NH"]], ["a", ["NIC","NIL"]], ["an", ["NIMH"]], ["a", ["NIM","NIN","NIS"]], ["an", ["NI"]], ["an", ["NJC"]], ["an", ["NK"]], ["a", ["NLS"]], ["an", ["NL","NM"]], ["an", ["NNR","NNT"]], ["an", ["NPOV-"]], ["a", ["NPO"]], ["an", ["NP"]], ["a", ["NRJ","NRT"]], ["an", ["NR"]], ["a", ["NSW"]], ["an", ["NS"]], ["a", ["NT$"]], ["an", ["NT"]], ["an", ["NUS"]], ["an", ["NV","Nv"]], ["an", ["NWA"]], ["an", ["NX"]], ["an", ["NYP","NYU"]], ["an", ["n-","n−","n ","n\"","n&","n,","n+","n×"]], ["an", ["nda","npa"]], ["an", ["nt","nV","nW"]], ["a", ["obr"]], ["a", ["occurs"]], ["a", ["ocho"]], ["a", ["of "]], ["an", ["on-","on/","onb"]], ["an", ["onco"]], ["an", ["ond"]], ["an", ["oner"]], ["an", ["ong","oni","onl","onm","ono","onr","ons","ont","onu","onw","ony"]], ["a", ["on"]], ["a", ["or ","or,","oui"]], ["an", ["o"]], ["an", ["Oberst ","Oberstl"]], ["a", ["PI:NAME:<NAME>END_PI"]], ["a", ["PI:NAME:<NAME>END_PI"]], ["an", ["Onei"]], ["a", ["One","ONE","Oop","Oui"]], ["an", ["O","Ó","Ö","ö","Ō","ō"]], ["an", ["Phob","Phoi"]], ["an", ["r'","r-","r ","r\"","r&","r."]], ["an", ["refers"]], ["an", ["rf","rm","rs","R'","R-","R ","R\"","R&","R,"]], ["a", ["R.C"]], ["an", ["R.","R/"]], ["a", ["R10"]], ["an", ["R1","R2","R3","R4","R5","R6"]], ["an", ["RA ","RAF"]], ["an", ["RB","RC","RD"]], ["an", ["RE ","RER"]], ["an", ["RF","Rf","RG"]], ["an", ["RHS","RIA"]], ["an", ["RIC "]], ["an", ["RJ","RK"]], ["a", ["RL "]], ["an", ["RL"]], ["a", ["RM1"]], ["an", ["RM"]], ["a", ["RNG"]], ["an", ["RN"]], ["an", ["ROT"]], ["an", ["RP","RQ","RR"]], ["a", ["RS ","RS)","RS,","RS.","RS?","RST"]], ["an", ["RS","RT","RU","RV","RX","s-","s\"","s)","s,","s."]], ["an", ["says","sich"]], ["an", ["sp3"]], ["an", ["sprot"]], ["an", ["ssh"]], ["an", ["states ","states:"]], ["a", ["sva","sve"]], ["an", ["sv","S'","S-","S ","S\""]], ["a", ["S&W"]], ["an", ["S&","S,"]], ["an", ["S.B","S.M","S.O"]], ["an", ["S”","S1","S2","S3","S4","S5","S6"]], ["a", ["SA-1"]], ["an", ["SA-","SA "]], ["an", ["SACD"]], ["an", ["SAE"]], ["a", ["SASE"]], ["an", ["SAS"]], ["an", ["SAT ","SATB"]], ["an", ["SB"]], ["an", ["SCA "]], ["an", ["SCC","SCM"]], ["an", ["SCO "]], ["a", ["SCRA"]], ["an", ["SCR","SCT"]], ["an", ["SD"]], ["an", ["SE "]], ["a", ["SECO","SECR"]], ["an", ["SEC","SEI","SEO"]], ["an", ["SF","SG"]], ["an", ["SH-","SH2","SH3","SI "]], ["an", ["SJ","SK"]], ["a", ["SLA","SLI","SLO"]], ["an", ["SL"]], ["a", ["SMA"]], ["an", ["SME "]], ["a", ["SME","SMI"]], ["an", ["SM"]], ["a", ["SNA","SNE","SNO"]], ["an", ["SN"]], ["an", ["SO("]], ["an", ["SOA ","SOAI"]], ["an", ["SOE","SOI","SOS","SOV"]], ["a", ["SPAC","SPAD","SPAM","SPAN","SPAR"]], ["an", ["SPE "]], ["a", ["SPE"]], ["a", ["SPIC"]], ["a", ["SPO","SPU"]], ["an", ["SP","SR","SS"]], ["an", ["ST-"]], ["an", ["STA "]], ["an", ["STB","STC","STD","STF","STL","STM","STS","STV"]], ["an", ["Sura "]], ["a", ["SUB","SUL","SUN","SUP","SUS"]], ["an", ["SU","SV"]], ["an", ["SWF","SWP","SWR"]], ["a", ["SXS"]], ["an", ["SX"]], ["an", ["t-S"]], ["an", ["tS"]], ["an", ["Taves"]], ["an", ["Tà"]], ["a", ["u-","u ","u\"","u."]], ["an", ["ube"]], ["a", ["ub","uf"]], ["an", ["uka"]], ["a", ["uk"]], ["a", ["ulu","um ","un "]], ["a", ["una "]], ["an", ["unana","unann","unans","unant"]], ["a", ["unan"]], ["a", ["unary"]], ["a", ["une "]], ["an", ["unicorp"]], ["a", ["unidi"]], ["an", ["unid"]], ["a", ["unimo"]], ["an", ["unim","unin"]], ["an", ["univo"]], ["a", ["uni"]], ["a", ["unles"]], ["a", ["upo","ura","ure","uri","url","uro"]], ["an", ["us-","us ","ush"]], ["a", ["us"]], ["an", ["utm","utt"]], ["a", ["ut","uv","uw"]], ["an", ["u"]], ["a", ["U-Bo"]], ["an", ["U-B"]], ["an", ["U1","Ua"]], ["a", ["Ubi"]], ["an", ["Ub"]], ["an", ["UDP-"]], ["an", ["Ud"]], ["an", ["Ugl"]], ["an", ["Uh","Ui"]], ["a", ["Uli"]], ["an", ["Ul","Um"]], ["an", ["UMN","Un-"]], ["a", ["Unan"]], ["an", ["Una","Unb","Unc","Und"]], ["a", ["Unes"]], ["an", ["Une","Unf","Ung","Unh"]], ["an", ["Unid","Unin"]], ["an", ["Unk","Unl","Unm","Unn","Uno","Unp","Unr","Uns"]], ["a", ["Unters"]], ["an", ["Unt","Unu","Unw"]], ["an", ["Up"]], ["a", ["Ura","Uri"]], ["an", ["Uruguayan-"]], ["an", ["Uruk"]], ["a", ["Uru"]], ["an", ["Ur"]], ["an", ["Ush","Ust","Utn"]], ["an", ["Uto-"]], ["an", ["Utr","Utt"]], ["an", ["Ux","Uz"]], ["an", ["ü","Ü"]], ["an", ["VII"]], ["a", ["xa","xe","xi","xo","xx","xy"]], ["an", ["x"]], ["a", ["Xa","XA","Xe","Xh","Xi"]], ["a", ["XIV","XIX"]], ["a", ["Xo","Xu","XU","XV"]], ["an", ["XX "]], ["a", ["XX","Xy"]], ["an", ["X"]], ["an", ["Yp"]], ["an", ["α","ε","ω"]] ["a", [""]] ] setPath = (obj, prefix, article) -> return unless prefix.length > 0 letter = prefix[0] obj[letter] = {} unless obj[letter] if prefix.length is 1 obj[letter].article = article else setPath obj[letter], prefix[1..], article articles = {} for [article, prefixList] in articleArray for prefix in prefixList setPath articles, prefix, article fs.writeFile '../lib/articledata.json', JSON.stringify(articles)
[ { "context": "s a collection of your favorite tweets.\n# Author: Divshot, Inc.\n\n(($, window) ->\n pluginName = 'tweetscrol", "end": 160, "score": 0.8448241949081421, "start": 153, "tag": "NAME", "value": "Divshot" } ]
coffee/jquery.tweetscroller.coffee
divshot/tweetscroller
5
# Project: TweetScroller # Description: A pseudo-infinite tweet scroller that automatically refreshes a collection of your favorite tweets. # Author: Divshot, Inc. (($, window) -> pluginName = 'tweetscroller' document = window.document defaults = url: '' tweet: '.tweet' template: '#tweet-template' height: 600 speed: 30 # ms, 30-80 ms recommended, slower = better performance autoplay: false # CPU intensive class TweetScroller constructor: (@element, options) -> @options = $.extend {}, defaults, options @_defaults = defaults @_name = pluginName @_initialTweetCount = 0 @init() init: -> $(@element).height @options.height @checkDependencies() @getTweets() getTweets: -> $.getJSON @options.url, (data) => $(@element).append('<div class="tweetscroller"></div>') @board = $(@element).find('.tweetscroller') $.each data, (i, tweet) => tweet.created_at = new Date(Date.parse(tweet.created_at)) tweet.created_at = moment(tweet.created_at).format('D MMM YY') source = $(@options.template).html() template = Handlebars.compile(source) @board.append(template(tweet)) @board.masonry itemSelector: @options.tweet @_initialTweetCount = @board.find(@options.tweet).length @scrollTweets() scrollTweets: -> scrollActive = 0 scrollInterval = null autoScroll = => scrollActive = 1 $(@element).scrollTop($(@element).scrollTop() + 1) # Scroll event to manage tweets $(@element).scroll (e) => @scrollRefresh(e) # Hover to scroll if !@options.autoplay $(@element).hoverIntent interval: 100 over: => if !scrollActive scrollInterval = setInterval(autoScroll, @options.speed) out: => scrollActive = 0 clearInterval(scrollInterval) else scrollInterval = setInterval(autoScroll, @options.speed) scrollRefresh: (e) -> _this = this if @board.parent()[0].scrollHeight - @board.parent().scrollTop() <= @board.parent().height() @board.find(@options.tweet).each (i) -> tweet = $(this).clone() _this.board.append(tweet).masonry('appended', tweet, true) if i <= _this.board.find('.tweet').length - _this._initialTweetCount $(this).remove() checkDependencies: -> if !Handlebars throw new Error('This plugin requires requires Handlebars: http://handlebarsjs.com') if typeof moment != 'function' throw new Error('This plugin requires requires Moment.js: http://momentjs.com') if !jQuery().masonry throw new Error('This plugin requires requires Masonry: http://masonry.desandro.com/') if !jQuery().hoverIntent throw new Error('This plugin requires hoverIntent: http://cherne.net/brian/resources/jquery.hoverIntent.html') $.fn[pluginName] = (options) -> @each -> if !$.data(this, "plugin_#{pluginName}") $.data(@, "plugin_#{pluginName}", new TweetScroller(@, options)) )(jQuery, window)
38420
# Project: TweetScroller # Description: A pseudo-infinite tweet scroller that automatically refreshes a collection of your favorite tweets. # Author: <NAME>, Inc. (($, window) -> pluginName = 'tweetscroller' document = window.document defaults = url: '' tweet: '.tweet' template: '#tweet-template' height: 600 speed: 30 # ms, 30-80 ms recommended, slower = better performance autoplay: false # CPU intensive class TweetScroller constructor: (@element, options) -> @options = $.extend {}, defaults, options @_defaults = defaults @_name = pluginName @_initialTweetCount = 0 @init() init: -> $(@element).height @options.height @checkDependencies() @getTweets() getTweets: -> $.getJSON @options.url, (data) => $(@element).append('<div class="tweetscroller"></div>') @board = $(@element).find('.tweetscroller') $.each data, (i, tweet) => tweet.created_at = new Date(Date.parse(tweet.created_at)) tweet.created_at = moment(tweet.created_at).format('D MMM YY') source = $(@options.template).html() template = Handlebars.compile(source) @board.append(template(tweet)) @board.masonry itemSelector: @options.tweet @_initialTweetCount = @board.find(@options.tweet).length @scrollTweets() scrollTweets: -> scrollActive = 0 scrollInterval = null autoScroll = => scrollActive = 1 $(@element).scrollTop($(@element).scrollTop() + 1) # Scroll event to manage tweets $(@element).scroll (e) => @scrollRefresh(e) # Hover to scroll if !@options.autoplay $(@element).hoverIntent interval: 100 over: => if !scrollActive scrollInterval = setInterval(autoScroll, @options.speed) out: => scrollActive = 0 clearInterval(scrollInterval) else scrollInterval = setInterval(autoScroll, @options.speed) scrollRefresh: (e) -> _this = this if @board.parent()[0].scrollHeight - @board.parent().scrollTop() <= @board.parent().height() @board.find(@options.tweet).each (i) -> tweet = $(this).clone() _this.board.append(tweet).masonry('appended', tweet, true) if i <= _this.board.find('.tweet').length - _this._initialTweetCount $(this).remove() checkDependencies: -> if !Handlebars throw new Error('This plugin requires requires Handlebars: http://handlebarsjs.com') if typeof moment != 'function' throw new Error('This plugin requires requires Moment.js: http://momentjs.com') if !jQuery().masonry throw new Error('This plugin requires requires Masonry: http://masonry.desandro.com/') if !jQuery().hoverIntent throw new Error('This plugin requires hoverIntent: http://cherne.net/brian/resources/jquery.hoverIntent.html') $.fn[pluginName] = (options) -> @each -> if !$.data(this, "plugin_#{pluginName}") $.data(@, "plugin_#{pluginName}", new TweetScroller(@, options)) )(jQuery, window)
true
# Project: TweetScroller # Description: A pseudo-infinite tweet scroller that automatically refreshes a collection of your favorite tweets. # Author: PI:NAME:<NAME>END_PI, Inc. (($, window) -> pluginName = 'tweetscroller' document = window.document defaults = url: '' tweet: '.tweet' template: '#tweet-template' height: 600 speed: 30 # ms, 30-80 ms recommended, slower = better performance autoplay: false # CPU intensive class TweetScroller constructor: (@element, options) -> @options = $.extend {}, defaults, options @_defaults = defaults @_name = pluginName @_initialTweetCount = 0 @init() init: -> $(@element).height @options.height @checkDependencies() @getTweets() getTweets: -> $.getJSON @options.url, (data) => $(@element).append('<div class="tweetscroller"></div>') @board = $(@element).find('.tweetscroller') $.each data, (i, tweet) => tweet.created_at = new Date(Date.parse(tweet.created_at)) tweet.created_at = moment(tweet.created_at).format('D MMM YY') source = $(@options.template).html() template = Handlebars.compile(source) @board.append(template(tweet)) @board.masonry itemSelector: @options.tweet @_initialTweetCount = @board.find(@options.tweet).length @scrollTweets() scrollTweets: -> scrollActive = 0 scrollInterval = null autoScroll = => scrollActive = 1 $(@element).scrollTop($(@element).scrollTop() + 1) # Scroll event to manage tweets $(@element).scroll (e) => @scrollRefresh(e) # Hover to scroll if !@options.autoplay $(@element).hoverIntent interval: 100 over: => if !scrollActive scrollInterval = setInterval(autoScroll, @options.speed) out: => scrollActive = 0 clearInterval(scrollInterval) else scrollInterval = setInterval(autoScroll, @options.speed) scrollRefresh: (e) -> _this = this if @board.parent()[0].scrollHeight - @board.parent().scrollTop() <= @board.parent().height() @board.find(@options.tweet).each (i) -> tweet = $(this).clone() _this.board.append(tweet).masonry('appended', tweet, true) if i <= _this.board.find('.tweet').length - _this._initialTweetCount $(this).remove() checkDependencies: -> if !Handlebars throw new Error('This plugin requires requires Handlebars: http://handlebarsjs.com') if typeof moment != 'function' throw new Error('This plugin requires requires Moment.js: http://momentjs.com') if !jQuery().masonry throw new Error('This plugin requires requires Masonry: http://masonry.desandro.com/') if !jQuery().hoverIntent throw new Error('This plugin requires hoverIntent: http://cherne.net/brian/resources/jquery.hoverIntent.html') $.fn[pluginName] = (options) -> @each -> if !$.data(this, "plugin_#{pluginName}") $.data(@, "plugin_#{pluginName}", new TweetScroller(@, options)) )(jQuery, window)
[ { "context": "offee - Markov chains in CoffeeScript.\ngithub.com/SyntaxColoring/Markov-Word-Generator\n\nReleased under the MIT lic", "end": 76, "score": 0.9777269959449768, "start": 62, "tag": "USERNAME", "value": "SyntaxColoring" }, { "context": "eleased under the MIT license.\n\nC...
markov.coffee
SyntaxColoring/Markov-Word-Generator
33
### Markov.coffee - Markov chains in CoffeeScript. github.com/SyntaxColoring/Markov-Word-Generator Released under the MIT license. Copyright (c) 2013 Max Marrone 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. ### class Markov # Creates a new Markov chain from the given array of sequences # (to collectively use as a corpus) and value for n (to use as the Markov order). # sequences may be empty. n must be an integer no lower than 0. # Feel free to directly access and modify an object's .sequences and .n. constructor: (@sequences = [], @n = 2, @maxLength = 20) -> # Generates a new pseudorandom sequence generated by the Markov chain and # returns it as an array. Its length will be truncated to @maxLength if necessary. generate: -> result = [] currentState = => # Returns at most the last @ elements of result. result[Math.max(0, result.length-@n)...result.length] continuation = => @continue(currentState()) while result.length < @maxLength and (nextElement = continuation())? result.push nextElement return result # Returns in an array the n-grams that went into making the Markov chain # Note that the size of the n-grams will always be one greater than the # Markov order - if a Markov chain was created with n=2, this method # will return an array of 3-grams. ngrams: -> ngramsFromSequence = (sequence, n) -> if n < 1 or n > sequence.length then [] else sequence[i...i+n] for i in [0..sequence.length-n] @sequences.reduce ((a, b) => a.concat ngramsFromSequence b, @n+1), [] # Builds a probability tree and returns the node of the given sequence, or # the root node if no sequence is specified. Returns null if the given # sequence is not represented in the tree. # # Each node has a "count", "frequency" and "continuations" property. # For example: # node = myMarkov.tree("abc") # c = node.continuations["d"].count # f = node.continuations["d"].frequency # c would be the number of times that "d" came after "abc" in the original corpus. # f would be the probability that the letter to follow "abc" is "d." tree: (sequence = []) -> ngrams = @ngrams() root = { continuations: {}, count: ngrams.length, frequency: 1.0 } # Build the tree and supply each node with its count property. for ngram in ngrams node = root for element in ngram unless node.continuations[element]? # If we need to create a new node, do so. node.continuations[element] = { continuations: {}, count: 0 } node = node.continuations[element] node.count++ # Recursively descend through the tree we just built and give each node its # frequency property. normalize = (node) -> for childName, child of node.continuations child.frequency = child.count / node.count normalize child normalize root # Navigate to the desired sequence. sequence = sequence.split("") if typeof sequence is "string" reduce = (node, element) -> if node? then node.continuations[element] ? null else null sequence.reduce reduce, root # Uses the Markov chain to pick the next element to come after sequence. # Returns null if there are no possible continuations. continue: (sequence) -> node = @tree(sequence) if node? target = Math.random() sum = 0 for continuationName, continuationNode of node.continuations sum += continuationNode.frequency if sum >= target then return continuationName return null # Either the node was null or it had no continuations. if module? then module.exports = Markov else this.Markov = Markov
41120
### Markov.coffee - Markov chains in CoffeeScript. github.com/SyntaxColoring/Markov-Word-Generator Released under the MIT license. Copyright (c) 2013 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### class Markov # Creates a new Markov chain from the given array of sequences # (to collectively use as a corpus) and value for n (to use as the Markov order). # sequences may be empty. n must be an integer no lower than 0. # Feel free to directly access and modify an object's .sequences and .n. constructor: (@sequences = [], @n = 2, @maxLength = 20) -> # Generates a new pseudorandom sequence generated by the Markov chain and # returns it as an array. Its length will be truncated to @maxLength if necessary. generate: -> result = [] currentState = => # Returns at most the last @ elements of result. result[Math.max(0, result.length-@n)...result.length] continuation = => @continue(currentState()) while result.length < @maxLength and (nextElement = continuation())? result.push nextElement return result # Returns in an array the n-grams that went into making the Markov chain # Note that the size of the n-grams will always be one greater than the # Markov order - if a Markov chain was created with n=2, this method # will return an array of 3-grams. ngrams: -> ngramsFromSequence = (sequence, n) -> if n < 1 or n > sequence.length then [] else sequence[i...i+n] for i in [0..sequence.length-n] @sequences.reduce ((a, b) => a.concat ngramsFromSequence b, @n+1), [] # Builds a probability tree and returns the node of the given sequence, or # the root node if no sequence is specified. Returns null if the given # sequence is not represented in the tree. # # Each node has a "count", "frequency" and "continuations" property. # For example: # node = myMarkov.tree("abc") # c = node.continuations["d"].count # f = node.continuations["d"].frequency # c would be the number of times that "d" came after "abc" in the original corpus. # f would be the probability that the letter to follow "abc" is "d." tree: (sequence = []) -> ngrams = @ngrams() root = { continuations: {}, count: ngrams.length, frequency: 1.0 } # Build the tree and supply each node with its count property. for ngram in ngrams node = root for element in ngram unless node.continuations[element]? # If we need to create a new node, do so. node.continuations[element] = { continuations: {}, count: 0 } node = node.continuations[element] node.count++ # Recursively descend through the tree we just built and give each node its # frequency property. normalize = (node) -> for childName, child of node.continuations child.frequency = child.count / node.count normalize child normalize root # Navigate to the desired sequence. sequence = sequence.split("") if typeof sequence is "string" reduce = (node, element) -> if node? then node.continuations[element] ? null else null sequence.reduce reduce, root # Uses the Markov chain to pick the next element to come after sequence. # Returns null if there are no possible continuations. continue: (sequence) -> node = @tree(sequence) if node? target = Math.random() sum = 0 for continuationName, continuationNode of node.continuations sum += continuationNode.frequency if sum >= target then return continuationName return null # Either the node was null or it had no continuations. if module? then module.exports = Markov else this.Markov = Markov
true
### Markov.coffee - Markov chains in CoffeeScript. github.com/SyntaxColoring/Markov-Word-Generator Released under the MIT license. Copyright (c) 2013 PI:NAME:<NAME>END_PI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### class Markov # Creates a new Markov chain from the given array of sequences # (to collectively use as a corpus) and value for n (to use as the Markov order). # sequences may be empty. n must be an integer no lower than 0. # Feel free to directly access and modify an object's .sequences and .n. constructor: (@sequences = [], @n = 2, @maxLength = 20) -> # Generates a new pseudorandom sequence generated by the Markov chain and # returns it as an array. Its length will be truncated to @maxLength if necessary. generate: -> result = [] currentState = => # Returns at most the last @ elements of result. result[Math.max(0, result.length-@n)...result.length] continuation = => @continue(currentState()) while result.length < @maxLength and (nextElement = continuation())? result.push nextElement return result # Returns in an array the n-grams that went into making the Markov chain # Note that the size of the n-grams will always be one greater than the # Markov order - if a Markov chain was created with n=2, this method # will return an array of 3-grams. ngrams: -> ngramsFromSequence = (sequence, n) -> if n < 1 or n > sequence.length then [] else sequence[i...i+n] for i in [0..sequence.length-n] @sequences.reduce ((a, b) => a.concat ngramsFromSequence b, @n+1), [] # Builds a probability tree and returns the node of the given sequence, or # the root node if no sequence is specified. Returns null if the given # sequence is not represented in the tree. # # Each node has a "count", "frequency" and "continuations" property. # For example: # node = myMarkov.tree("abc") # c = node.continuations["d"].count # f = node.continuations["d"].frequency # c would be the number of times that "d" came after "abc" in the original corpus. # f would be the probability that the letter to follow "abc" is "d." tree: (sequence = []) -> ngrams = @ngrams() root = { continuations: {}, count: ngrams.length, frequency: 1.0 } # Build the tree and supply each node with its count property. for ngram in ngrams node = root for element in ngram unless node.continuations[element]? # If we need to create a new node, do so. node.continuations[element] = { continuations: {}, count: 0 } node = node.continuations[element] node.count++ # Recursively descend through the tree we just built and give each node its # frequency property. normalize = (node) -> for childName, child of node.continuations child.frequency = child.count / node.count normalize child normalize root # Navigate to the desired sequence. sequence = sequence.split("") if typeof sequence is "string" reduce = (node, element) -> if node? then node.continuations[element] ? null else null sequence.reduce reduce, root # Uses the Markov chain to pick the next element to come after sequence. # Returns null if there are no possible continuations. continue: (sequence) -> node = @tree(sequence) if node? target = Math.random() sum = 0 for continuationName, continuationNode of node.continuations sum += continuationNode.frequency if sum >= target then return continuationName return null # Either the node was null or it had no continuations. if module? then module.exports = Markov else this.Markov = Markov
[ { "context": "rs.insertOne(\n emails: [\n { address: 'alice@example.com', verified: true }\n ]\n )\n alice = awai", "end": 1363, "score": 0.999917209148407, "start": 1346, "tag": "EMAIL", "value": "alice@example.com" }, { "context": " ]\n )\n alice = awai...
test/PerformAirdrop.test.coffee
DenisGorbachev/talloc
0
import _ from 'lodash' import moment from 'moment' import { MongoClient } from 'mongodb' import PerformAirdrop from '../src/Functor/PerformAirdrop' import { perms } from '../src/helpers' import { complete } from '../src/test_helpers' describe 'PerformAirdrop', -> connection = null db = null beforeAll -> connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true }) db = await connection.db(global.__MONGO_DB_NAME__) db.Users = db.collection('Users') db.Persons = db.collection('Persons') db.Projects = db.collection('Projects') db.Channels = db.collection('Channels') db.Messages = db.collection('Messages') db.Artefacts = db.collection('Artefacts') db.Assets = db.collection('Assets') db.Transactions = db.collection('Transactions') afterAll -> await connection.close() await db.close() it 'should return the task', -> deps = { db, now: new Date('2019-07-26T00:00:00Z') } functor = new PerformAirdrop({ projectUid: 'BTCV', networks: ['Twitter', 'Facebook', 'Telegram', 'Discord'] assetUid: 'MOON', limit: 1000, from: new Date('2019-07-22'), to: new Date('2019-07-31'), referralLimit: 100, }, deps) { insertedId: aliceId } = await db.Users.insertOne( emails: [ { address: 'alice@example.com', verified: true } ] ) alice = await db.Users.findOne({ _id: aliceId }) await db.Projects.insertOne( uid: 'BTCV', url: 'https://btcv.volatility-tokens.com/', ) await db.Assets.insertOne( uid: 'BTCV', maxSupply: 100000000, circulatingSupply: 9117300, initialOfferingPrice: 0.03 # USD ) await db.Assets.insertOne( uid: 'MOON', maxSupply: 10000000000, circulatingSupply: 10000000000, initialOfferingPrice: 0.001 # USD ) # await functor.reexecute() # expect(_.first(functor.tasks)).toMatchObject( # type: 'SetField', # context: {} # priority: 10, # genome: [] # ) { insertedId: airdropsIOOwnerId } = await db.Persons.insertOne( name: '' ) { insertedId: airdropsIOId } = await db.Channels.insertOne( uid: 'airdrops.io' network: 'Internet' name: 'Airdrops.io' tags: ['Airdrop'] permissions: [ perms('public', ['read']) perms('protected', ['read']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateChannel', context: blueprint: network: 'Twitter' tags: ['BTCV'] ) channelIds = [] while task and task.type is 'CreateChannel' result = await db.Channels.insertOne(Object.assign( name: "#{task.context.blueprint.tags[0]} #{task.context.blueprint.network} channel" , task.context.blueprint)) expect(result).toMatchObject({ insertedId: expect.any(Object) }) channelIds.push(result.insertedId) task = await functor.getNextTask(alice) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'DecorateChannel', context: channel: expect.objectContaining({ tags: ['BTCV'] }) priority: 10, ) await db.Channels.updateMany({ _id: { $in: channelIds } }, { $set: { isDecorated: true } }) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channelId: expect.any(Object) ) for channelId in channelIds messages = for i in [1..5] { channelId: channelId, text: "Message for channel #{channelId} with index #{i}", author: "@Author", context: {} } await db.Messages.insertMany(messages) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateArtefact', context: blueprint: tags: ['ClaimAirdropApp'] description: 'https://workflowy.com/#/17112ae471fc' ) await complete(task, deps) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreatePrivateChannelWithOwner', context: person: _id: airdropsIOOwnerId ) await complete(task, deps) await db.Channels.insertOne( uid: 'https://airdrops.io/contact/' network: 'ContactForm' name: 'Airdrops.io contact form' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) { insertedId: airdropsIOWriterTelegramId } = await db.Channels.insertOne( uid: 'AirdropsTeam' network: 'Telegram' name: 'Airdrops.io listings Telegram' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) await db.Channels.insertOne( uid: 'mail@airdrops.io' network: 'Email' name: 'Airdrops.io listings email' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channel: _id: airdropsIOWriterTelegramId ) await complete(task, deps) # TODO: add tests for messages # Jest requires `describe` callback to return undefined return undefined
140884
import _ from 'lodash' import moment from 'moment' import { MongoClient } from 'mongodb' import PerformAirdrop from '../src/Functor/PerformAirdrop' import { perms } from '../src/helpers' import { complete } from '../src/test_helpers' describe 'PerformAirdrop', -> connection = null db = null beforeAll -> connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true }) db = await connection.db(global.__MONGO_DB_NAME__) db.Users = db.collection('Users') db.Persons = db.collection('Persons') db.Projects = db.collection('Projects') db.Channels = db.collection('Channels') db.Messages = db.collection('Messages') db.Artefacts = db.collection('Artefacts') db.Assets = db.collection('Assets') db.Transactions = db.collection('Transactions') afterAll -> await connection.close() await db.close() it 'should return the task', -> deps = { db, now: new Date('2019-07-26T00:00:00Z') } functor = new PerformAirdrop({ projectUid: 'BTCV', networks: ['Twitter', 'Facebook', 'Telegram', 'Discord'] assetUid: 'MOON', limit: 1000, from: new Date('2019-07-22'), to: new Date('2019-07-31'), referralLimit: 100, }, deps) { insertedId: aliceId } = await db.Users.insertOne( emails: [ { address: '<EMAIL>', verified: true } ] ) alice = await db.Users.findOne({ _id: aliceId }) await db.Projects.insertOne( uid: 'BTCV', url: 'https://btcv.volatility-tokens.com/', ) await db.Assets.insertOne( uid: 'BTCV', maxSupply: 100000000, circulatingSupply: 9117300, initialOfferingPrice: 0.03 # USD ) await db.Assets.insertOne( uid: 'MOON', maxSupply: 10000000000, circulatingSupply: 10000000000, initialOfferingPrice: 0.001 # USD ) # await functor.reexecute() # expect(_.first(functor.tasks)).toMatchObject( # type: 'SetField', # context: {} # priority: 10, # genome: [] # ) { insertedId: airdropsIOOwnerId } = await db.Persons.insertOne( name: '' ) { insertedId: airdropsIOId } = await db.Channels.insertOne( uid: 'airdrops.io' network: 'Internet' name: 'Airdrops.io' tags: ['Airdrop'] permissions: [ perms('public', ['read']) perms('protected', ['read']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateChannel', context: blueprint: network: 'Twitter' tags: ['BTCV'] ) channelIds = [] while task and task.type is 'CreateChannel' result = await db.Channels.insertOne(Object.assign( name: "#{task.context.blueprint.tags[0]} #{task.context.blueprint.network} channel" , task.context.blueprint)) expect(result).toMatchObject({ insertedId: expect.any(Object) }) channelIds.push(result.insertedId) task = await functor.getNextTask(alice) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'DecorateChannel', context: channel: expect.objectContaining({ tags: ['BTCV'] }) priority: 10, ) await db.Channels.updateMany({ _id: { $in: channelIds } }, { $set: { isDecorated: true } }) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channelId: expect.any(Object) ) for channelId in channelIds messages = for i in [1..5] { channelId: channelId, text: "Message for channel #{channelId} with index #{i}", author: "@Author", context: {} } await db.Messages.insertMany(messages) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateArtefact', context: blueprint: tags: ['ClaimAirdropApp'] description: 'https://workflowy.com/#/17112ae471fc' ) await complete(task, deps) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreatePrivateChannelWithOwner', context: person: _id: airdropsIOOwnerId ) await complete(task, deps) await db.Channels.insertOne( uid: 'https://airdrops.io/contact/' network: 'ContactForm' name: 'Airdrops.io contact form' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) { insertedId: airdropsIOWriterTelegramId } = await db.Channels.insertOne( uid: 'AirdropsTeam' network: 'Telegram' name: 'Airdrops.io listings Telegram' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) await db.Channels.insertOne( uid: '<EMAIL>' network: 'Email' name: 'Airdrops.io listings email' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channel: _id: airdropsIOWriterTelegramId ) await complete(task, deps) # TODO: add tests for messages # Jest requires `describe` callback to return undefined return undefined
true
import _ from 'lodash' import moment from 'moment' import { MongoClient } from 'mongodb' import PerformAirdrop from '../src/Functor/PerformAirdrop' import { perms } from '../src/helpers' import { complete } from '../src/test_helpers' describe 'PerformAirdrop', -> connection = null db = null beforeAll -> connection = await MongoClient.connect(global.__MONGO_URI__, { useNewUrlParser: true }) db = await connection.db(global.__MONGO_DB_NAME__) db.Users = db.collection('Users') db.Persons = db.collection('Persons') db.Projects = db.collection('Projects') db.Channels = db.collection('Channels') db.Messages = db.collection('Messages') db.Artefacts = db.collection('Artefacts') db.Assets = db.collection('Assets') db.Transactions = db.collection('Transactions') afterAll -> await connection.close() await db.close() it 'should return the task', -> deps = { db, now: new Date('2019-07-26T00:00:00Z') } functor = new PerformAirdrop({ projectUid: 'BTCV', networks: ['Twitter', 'Facebook', 'Telegram', 'Discord'] assetUid: 'MOON', limit: 1000, from: new Date('2019-07-22'), to: new Date('2019-07-31'), referralLimit: 100, }, deps) { insertedId: aliceId } = await db.Users.insertOne( emails: [ { address: 'PI:EMAIL:<EMAIL>END_PI', verified: true } ] ) alice = await db.Users.findOne({ _id: aliceId }) await db.Projects.insertOne( uid: 'BTCV', url: 'https://btcv.volatility-tokens.com/', ) await db.Assets.insertOne( uid: 'BTCV', maxSupply: 100000000, circulatingSupply: 9117300, initialOfferingPrice: 0.03 # USD ) await db.Assets.insertOne( uid: 'MOON', maxSupply: 10000000000, circulatingSupply: 10000000000, initialOfferingPrice: 0.001 # USD ) # await functor.reexecute() # expect(_.first(functor.tasks)).toMatchObject( # type: 'SetField', # context: {} # priority: 10, # genome: [] # ) { insertedId: airdropsIOOwnerId } = await db.Persons.insertOne( name: '' ) { insertedId: airdropsIOId } = await db.Channels.insertOne( uid: 'airdrops.io' network: 'Internet' name: 'Airdrops.io' tags: ['Airdrop'] permissions: [ perms('public', ['read']) perms('protected', ['read']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateChannel', context: blueprint: network: 'Twitter' tags: ['BTCV'] ) channelIds = [] while task and task.type is 'CreateChannel' result = await db.Channels.insertOne(Object.assign( name: "#{task.context.blueprint.tags[0]} #{task.context.blueprint.network} channel" , task.context.blueprint)) expect(result).toMatchObject({ insertedId: expect.any(Object) }) channelIds.push(result.insertedId) task = await functor.getNextTask(alice) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'DecorateChannel', context: channel: expect.objectContaining({ tags: ['BTCV'] }) priority: 10, ) await db.Channels.updateMany({ _id: { $in: channelIds } }, { $set: { isDecorated: true } }) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channelId: expect.any(Object) ) for channelId in channelIds messages = for i in [1..5] { channelId: channelId, text: "Message for channel #{channelId} with index #{i}", author: "@Author", context: {} } await db.Messages.insertMany(messages) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreateArtefact', context: blueprint: tags: ['ClaimAirdropApp'] description: 'https://workflowy.com/#/17112ae471fc' ) await complete(task, deps) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'CreatePrivateChannelWithOwner', context: person: _id: airdropsIOOwnerId ) await complete(task, deps) await db.Channels.insertOne( uid: 'https://airdrops.io/contact/' network: 'ContactForm' name: 'Airdrops.io contact form' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) { insertedId: airdropsIOWriterTelegramId } = await db.Channels.insertOne( uid: 'AirdropsTeam' network: 'Telegram' name: 'Airdrops.io listings Telegram' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) await db.Channels.insertOne( uid: 'PI:EMAIL:<EMAIL>END_PI' network: 'Email' name: 'Airdrops.io listings email' tags: ['Listing'] permissions: [ perms('public', ['create']) perms('private', 'all', [airdropsIOOwnerId]) ] ) task = await functor.getNextTask(alice) expect(task).toMatchObject( type: 'SendMessage', context: blueprint: channel: _id: airdropsIOWriterTelegramId ) await complete(task, deps) # TODO: add tests for messages # Jest requires `describe` callback to return undefined return undefined
[ { "context": "qual\n deq = deepEqual\n\n john = {firstname: 'John', lastname: 'Silver', age: 30}\n john_id = john", "end": 238, "score": 0.9996370077133179, "start": 234, "tag": "NAME", "value": "John" }, { "context": "pEqual\n\n john = {firstname: 'John', lastname: 'Silv...
tests/test.coffee
dundalek/warehouse
74
@run_tests = (store, name) -> name = if typeof name == 'undefined' then store.constructor.name else name if typeof qinit != 'undefined' qinit(QUnit) eq = strictEqual deq = deepEqual john = {firstname: 'John', lastname: 'Silver', age: 30} john_id = john[store.keyPath] = 1 james = {firstname: 'James', lastname: 'Wood', age: 42} james_id = james[store.keyPath] = 2 jane = {firstname: 'Jane', lastname: 'White', age: 28} jane_id = jane[store.keyPath] = 3 config_reorder = QUnit.config.reorder config_autostart = QUnit.config.autostart config_autorun = QUnit.config.autorun QUnit.config.reorder = false QUnit.config.autostart = false QUnit.config.autorun = false checkFail = (promise) -> promise.fail (err) -> ok false, 'fail' eq err, '', 'error message' start() QUnit.moduleStart(if typeof setup != 'undefined' then (-> QUnit.stop(); setup().then( -> QUnit.start())) else ->) QUnit.module "#{name}: CRUD" asyncTest 'clear', -> checkFail store.clear() .then -> ok true start() asyncTest 'is empty', -> checkFail store.query() .then (res) -> eq res.length, 0, 'store is empty' start() # asyncTest 'error when getting non existing item', -> # checkFail store.get 4 # .then (res) -> # ok err # ok !res # start() asyncTest 'add item', -> checkFail store.add(john) .then (res) -> deq res, john john_id = res[store.keyPath] start() asyncTest 'get item', -> checkFail store.get(john_id) .then (res) -> deepEqual res, john start() asyncTest 'get item type coerce', -> checkFail store.get(''+john_id) .then (res) -> deepEqual res, john start() # asyncTest 'error when adding items with same id', -> # checkFail store.add john # .then (res) -> # ok err, '' # ok !res # start() asyncTest 'add item', -> checkFail store.add(james) .then (res) -> deq res, james james_id = res[store.keyPath] start() # asyncTest 'error when updating non existing item', -> # checkFail store.put jane.id, jane # .then (res) -> # ok err # ok !res # start() asyncTest 'update item', -> john.age = 35 checkFail store.put(john, john_id) .then (res) -> deq res, john start() asyncTest 'get item', -> checkFail store.get(john_id) .then (res) -> deepEqual res, john start() asyncTest 'add item', -> checkFail store.add(jane) .then (res) -> deq res, jane jane_id = res[store.keyPath] start() asyncTest 'find by id', -> checkFail store.query(store.keyPath + '=' + james_id) .then (res) -> deq res, [james] start() asyncTest 'delete', -> checkFail store.delete(james_id) .then (res) -> deq res, 1 start() asyncTest 'check deleted', -> checkFail store.query() .then (res) -> deq res.length, 2 start() asyncTest 'delete non-existing item', -> checkFail store.delete(10) .then (res) -> deq res, 0 start() QUnit.module "#{name}: Querying" asyncTest 'find by name', -> checkFail store.query('firstname=John') .then (res) -> deq res, [john] start() asyncTest 'sorting', -> checkFail store.query('sort(+age)') .then (res) -> deq res, [jane, john] start() # testing in node needs a little push if typeof require != 'undefined' QUnit.start() QUnit.config.reorder = config_reorder QUnit.config.autostart = config_autostart QUnit.config.autorun = config_autorun if typeof require != 'undefined' @run_tests(store, if typeof name == 'undefined' then undefined else name)
70572
@run_tests = (store, name) -> name = if typeof name == 'undefined' then store.constructor.name else name if typeof qinit != 'undefined' qinit(QUnit) eq = strictEqual deq = deepEqual john = {firstname: '<NAME>', lastname: '<NAME>', age: 30} john_id = john[store.keyPath] = 1 james = {firstname: '<NAME>', lastname: '<NAME>', age: 42} james_id = james[store.keyPath] = 2 jane = {firstname: '<NAME>', lastname: '<NAME>', age: 28} jane_id = jane[store.keyPath] = 3 config_reorder = QUnit.config.reorder config_autostart = QUnit.config.autostart config_autorun = QUnit.config.autorun QUnit.config.reorder = false QUnit.config.autostart = false QUnit.config.autorun = false checkFail = (promise) -> promise.fail (err) -> ok false, 'fail' eq err, '', 'error message' start() QUnit.moduleStart(if typeof setup != 'undefined' then (-> QUnit.stop(); setup().then( -> QUnit.start())) else ->) QUnit.module "#{name}: CRUD" asyncTest 'clear', -> checkFail store.clear() .then -> ok true start() asyncTest 'is empty', -> checkFail store.query() .then (res) -> eq res.length, 0, 'store is empty' start() # asyncTest 'error when getting non existing item', -> # checkFail store.get 4 # .then (res) -> # ok err # ok !res # start() asyncTest 'add item', -> checkFail store.add(john) .then (res) -> deq res, john john_id = res[store.keyPath] start() asyncTest 'get item', -> checkFail store.get(john_id) .then (res) -> deepEqual res, john start() asyncTest 'get item type coerce', -> checkFail store.get(''+john_id) .then (res) -> deepEqual res, john start() # asyncTest 'error when adding items with same id', -> # checkFail store.add <NAME> <NAME> # .then (res) -> # ok err, '' # ok !res # start() asyncTest 'add item', -> checkFail store.add(<NAME> <NAME>) .then (res) -> deq res, <NAME> <NAME> james_id = res[store.keyPath] start() # asyncTest 'error when updating non existing item', -> # checkFail store.put jane.id, <NAME>ane # .then (res) -> # ok err # ok !res # start() asyncTest 'update item', -> john.age = 35 checkFail store.put(<NAME>, john_id) .then (res) -> deq res, john start() asyncTest 'get item', -> checkFail store.get(<NAME>_id) .then (res) -> deepEqual res, john start() asyncTest 'add item', -> checkFail store.add(<NAME>ane) .then (res) -> deq res, jane jane_id = res[store.keyPath] start() asyncTest 'find by id', -> checkFail store.query(store.keyPath + '=' + james_id) .then (res) -> deq res, [james] start() asyncTest 'delete', -> checkFail store.delete(j<NAME>_id) .then (res) -> deq res, 1 start() asyncTest 'check deleted', -> checkFail store.query() .then (res) -> deq res.length, 2 start() asyncTest 'delete non-existing item', -> checkFail store.delete(10) .then (res) -> deq res, 0 start() QUnit.module "#{name}: Querying" asyncTest 'find by name', -> checkFail store.query('firstname=<NAME>') .then (res) -> deq res, [<NAME>] start() asyncTest 'sorting', -> checkFail store.query('sort(+age)') .then (res) -> deq res, [<NAME>, <NAME>] start() # testing in node needs a little push if typeof require != 'undefined' QUnit.start() QUnit.config.reorder = config_reorder QUnit.config.autostart = config_autostart QUnit.config.autorun = config_autorun if typeof require != 'undefined' @run_tests(store, if typeof name == 'undefined' then undefined else name)
true
@run_tests = (store, name) -> name = if typeof name == 'undefined' then store.constructor.name else name if typeof qinit != 'undefined' qinit(QUnit) eq = strictEqual deq = deepEqual john = {firstname: 'PI:NAME:<NAME>END_PI', lastname: 'PI:NAME:<NAME>END_PI', age: 30} john_id = john[store.keyPath] = 1 james = {firstname: 'PI:NAME:<NAME>END_PI', lastname: 'PI:NAME:<NAME>END_PI', age: 42} james_id = james[store.keyPath] = 2 jane = {firstname: 'PI:NAME:<NAME>END_PI', lastname: 'PI:NAME:<NAME>END_PI', age: 28} jane_id = jane[store.keyPath] = 3 config_reorder = QUnit.config.reorder config_autostart = QUnit.config.autostart config_autorun = QUnit.config.autorun QUnit.config.reorder = false QUnit.config.autostart = false QUnit.config.autorun = false checkFail = (promise) -> promise.fail (err) -> ok false, 'fail' eq err, '', 'error message' start() QUnit.moduleStart(if typeof setup != 'undefined' then (-> QUnit.stop(); setup().then( -> QUnit.start())) else ->) QUnit.module "#{name}: CRUD" asyncTest 'clear', -> checkFail store.clear() .then -> ok true start() asyncTest 'is empty', -> checkFail store.query() .then (res) -> eq res.length, 0, 'store is empty' start() # asyncTest 'error when getting non existing item', -> # checkFail store.get 4 # .then (res) -> # ok err # ok !res # start() asyncTest 'add item', -> checkFail store.add(john) .then (res) -> deq res, john john_id = res[store.keyPath] start() asyncTest 'get item', -> checkFail store.get(john_id) .then (res) -> deepEqual res, john start() asyncTest 'get item type coerce', -> checkFail store.get(''+john_id) .then (res) -> deepEqual res, john start() # asyncTest 'error when adding items with same id', -> # checkFail store.add PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI # .then (res) -> # ok err, '' # ok !res # start() asyncTest 'add item', -> checkFail store.add(PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI) .then (res) -> deq res, PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI james_id = res[store.keyPath] start() # asyncTest 'error when updating non existing item', -> # checkFail store.put jane.id, PI:NAME:<NAME>END_PIane # .then (res) -> # ok err # ok !res # start() asyncTest 'update item', -> john.age = 35 checkFail store.put(PI:NAME:<NAME>END_PI, john_id) .then (res) -> deq res, john start() asyncTest 'get item', -> checkFail store.get(PI:NAME:<NAME>END_PI_id) .then (res) -> deepEqual res, john start() asyncTest 'add item', -> checkFail store.add(PI:NAME:<NAME>END_PIane) .then (res) -> deq res, jane jane_id = res[store.keyPath] start() asyncTest 'find by id', -> checkFail store.query(store.keyPath + '=' + james_id) .then (res) -> deq res, [james] start() asyncTest 'delete', -> checkFail store.delete(jPI:NAME:<NAME>END_PI_id) .then (res) -> deq res, 1 start() asyncTest 'check deleted', -> checkFail store.query() .then (res) -> deq res.length, 2 start() asyncTest 'delete non-existing item', -> checkFail store.delete(10) .then (res) -> deq res, 0 start() QUnit.module "#{name}: Querying" asyncTest 'find by name', -> checkFail store.query('firstname=PI:NAME:<NAME>END_PI') .then (res) -> deq res, [PI:NAME:<NAME>END_PI] start() asyncTest 'sorting', -> checkFail store.query('sort(+age)') .then (res) -> deq res, [PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI] start() # testing in node needs a little push if typeof require != 'undefined' QUnit.start() QUnit.config.reorder = config_reorder QUnit.config.autostart = config_autostart QUnit.config.autorun = config_autorun if typeof require != 'undefined' @run_tests(store, if typeof name == 'undefined' then undefined else name)
[ { "context": "###\n# config/secrets.coffee\n#\n# © 2014 Dan Nichols\n# See LICENSE for more details\n#\n# This module lo", "end": 50, "score": 0.9997211694717407, "start": 39, "tag": "NAME", "value": "Dan Nichols" } ]
lib/config/secrets.coffee
dlnichols/h_media
0
### # config/secrets.coffee # # © 2014 Dan Nichols # See LICENSE for more details # # This module loads and merges all JSON in the secrets folder and places them # in the env for the application to use ### 'use strict' # External libs _ = require 'lodash' fs = require 'fs' path = require 'path' debug = require('debug') 'hMedia:secrets' secretsPath = path.join __dirname, 'secrets' ### # requireSecret ### requireSecret = (secretName, secrets, environment) -> return unless secretName? return unless /^(.*)\.(json)$/.test secretName return unless fs.existsSync(secretName) secret = require secretName secrets = _.extend secrets, secret[environment] ### # Load our secrets ### module.exports = (environment) -> return unless environment? secrets = {} debug 'Loading secrets...' files = fs.readdirSync(secretsPath) requireSecret path.join(secretsPath, file), secrets, environment for file in files secrets
104354
### # config/secrets.coffee # # © 2014 <NAME> # See LICENSE for more details # # This module loads and merges all JSON in the secrets folder and places them # in the env for the application to use ### 'use strict' # External libs _ = require 'lodash' fs = require 'fs' path = require 'path' debug = require('debug') 'hMedia:secrets' secretsPath = path.join __dirname, 'secrets' ### # requireSecret ### requireSecret = (secretName, secrets, environment) -> return unless secretName? return unless /^(.*)\.(json)$/.test secretName return unless fs.existsSync(secretName) secret = require secretName secrets = _.extend secrets, secret[environment] ### # Load our secrets ### module.exports = (environment) -> return unless environment? secrets = {} debug 'Loading secrets...' files = fs.readdirSync(secretsPath) requireSecret path.join(secretsPath, file), secrets, environment for file in files secrets
true
### # config/secrets.coffee # # © 2014 PI:NAME:<NAME>END_PI # See LICENSE for more details # # This module loads and merges all JSON in the secrets folder and places them # in the env for the application to use ### 'use strict' # External libs _ = require 'lodash' fs = require 'fs' path = require 'path' debug = require('debug') 'hMedia:secrets' secretsPath = path.join __dirname, 'secrets' ### # requireSecret ### requireSecret = (secretName, secrets, environment) -> return unless secretName? return unless /^(.*)\.(json)$/.test secretName return unless fs.existsSync(secretName) secret = require secretName secrets = _.extend secrets, secret[environment] ### # Load our secrets ### module.exports = (environment) -> return unless environment? secrets = {} debug 'Loading secrets...' files = fs.readdirSync(secretsPath) requireSecret path.join(secretsPath, file), secrets, environment for file in files secrets
[ { "context": "# Hot Tech Boy of the Week: Zach Holman\n# A side-effect of http://social-proof.org/post/1", "end": 39, "score": 0.9995604753494263, "start": 28, "tag": "NAME", "value": "Zach Holman" }, { "context": "76795/hot-tech-boy-of-the-week-zach-holman\n#\n# ask holman - Answer ...
src/scripts/holman.coffee
iangreenleaf/hubot-scripts
0
# Hot Tech Boy of the Week: Zach Holman # A side-effect of http://social-proof.org/post/18387776795/hot-tech-boy-of-the-week-zach-holman # # ask holman - Answer with tech hotness from Zach "Fork Me" Holman module.exports = (robot) -> robot.hear /ask holman/i, (msg) -> quotes = [ "Hard hitting questions right away?", "Carnegie Mellon… it’s an… excellent institution.", "I can do whatever I want which is kind of rad.", "The industry is really lacking in women and it sucks. Look at San Francisco, every meet up you go to is all dudes.", "Come on, a pony tail and sucker, what more could you want?", "I would get bored by someone who is not independent. By that I mean they actually do shit in the industry.", "With these kinds of people I’m uninterested to the point where I get angry at them for being very bland.", "I usually just drink gin and tonic… Let me point out that women who like gin are really awesome women.", "Rickhouse has the best gin and tonics in San Francisco.", "I can't, I’m sitting on a grassy knoll and thinking for a few hours.", "I love all women. I don’t prefer a certain race. I mean I hear ya, but I have no preference.", "CAN I GET INTO YOUR PANTS", "CAN I GET INTO YOUR PANTS\n\nlol jk.\n\nmaybe?", "I haven’t used it in practice, but I’ve always wanted to use it.", "I use that after I get to know someone and then I actually sink the deal.", "It’s pretty rad right?", "Come jump on my train!", "I was once in an orgy in Rickhouse.", "Sometimes it's fun to be a little whimsical.", "Sometimes it's fun to be a little creepy.", "I WAS AMBUSHED BY THOSE JOURNALISTS THEY PUT WORDS IN MY MOUTH", "Mom may have wanted me to be a doctor or something, but hey, \"Hot Tech Boy of the Week\" will do.", "Are we going to Rickhouse now?", "http://i.imgur.com/Myent.jpg", "http://www.youtube.com/watch?v=z6nt6l_iv0g" ] msg.send msg.random quotes
90988
# Hot Tech Boy of the Week: <NAME> # A side-effect of http://social-proof.org/post/18387776795/hot-tech-boy-of-the-week-zach-holman # # ask holman - Answer with tech hotness from Zach "Fork Me" <NAME> module.exports = (robot) -> robot.hear /ask holman/i, (msg) -> quotes = [ "Hard hitting questions right away?", "<NAME>… it’s an… excellent institution.", "I can do whatever I want which is kind of rad.", "The industry is really lacking in women and it sucks. Look at San Francisco, every meet up you go to is all dudes.", "Come on, a pony tail and sucker, what more could you want?", "I would get bored by someone who is not independent. By that I mean they actually do shit in the industry.", "With these kinds of people I’m uninterested to the point where I get angry at them for being very bland.", "I usually just drink gin and tonic… Let me point out that women who like gin are really awesome women.", "Rickhouse has the best gin and tonics in San Francisco.", "I can't, I’m sitting on a grassy knoll and thinking for a few hours.", "I love all women. I don’t prefer a certain race. I mean I hear ya, but I have no preference.", "CAN I GET INTO YOUR PANTS", "CAN I GET INTO YOUR PANTS\n\nlol jk.\n\nmaybe?", "I haven’t used it in practice, but I’ve always wanted to use it.", "I use that after I get to know someone and then I actually sink the deal.", "It’s pretty rad right?", "Come jump on my train!", "I was once in an orgy in Rickhouse.", "Sometimes it's fun to be a little whimsical.", "Sometimes it's fun to be a little creepy.", "I WAS AMBUSHED BY THOSE JOURNALISTS THEY PUT WORDS IN MY MOUTH", "Mom may have wanted me to be a doctor or something, but hey, \"Hot Tech Boy of the Week\" will do.", "Are we going to Rickhouse now?", "http://i.imgur.com/Myent.jpg", "http://www.youtube.com/watch?v=z6nt6l_iv0g" ] msg.send msg.random quotes
true
# Hot Tech Boy of the Week: PI:NAME:<NAME>END_PI # A side-effect of http://social-proof.org/post/18387776795/hot-tech-boy-of-the-week-zach-holman # # ask holman - Answer with tech hotness from Zach "Fork Me" PI:NAME:<NAME>END_PI module.exports = (robot) -> robot.hear /ask holman/i, (msg) -> quotes = [ "Hard hitting questions right away?", "PI:NAME:<NAME>END_PI… it’s an… excellent institution.", "I can do whatever I want which is kind of rad.", "The industry is really lacking in women and it sucks. Look at San Francisco, every meet up you go to is all dudes.", "Come on, a pony tail and sucker, what more could you want?", "I would get bored by someone who is not independent. By that I mean they actually do shit in the industry.", "With these kinds of people I’m uninterested to the point where I get angry at them for being very bland.", "I usually just drink gin and tonic… Let me point out that women who like gin are really awesome women.", "Rickhouse has the best gin and tonics in San Francisco.", "I can't, I’m sitting on a grassy knoll and thinking for a few hours.", "I love all women. I don’t prefer a certain race. I mean I hear ya, but I have no preference.", "CAN I GET INTO YOUR PANTS", "CAN I GET INTO YOUR PANTS\n\nlol jk.\n\nmaybe?", "I haven’t used it in practice, but I’ve always wanted to use it.", "I use that after I get to know someone and then I actually sink the deal.", "It’s pretty rad right?", "Come jump on my train!", "I was once in an orgy in Rickhouse.", "Sometimes it's fun to be a little whimsical.", "Sometimes it's fun to be a little creepy.", "I WAS AMBUSHED BY THOSE JOURNALISTS THEY PUT WORDS IN MY MOUTH", "Mom may have wanted me to be a doctor or something, but hey, \"Hot Tech Boy of the Week\" will do.", "Are we going to Rickhouse now?", "http://i.imgur.com/Myent.jpg", "http://www.youtube.com/watch?v=z6nt6l_iv0g" ] msg.send msg.random quotes
[ { "context": " project: atom.project.getPaths()[0]\n name: 'Test'\n command: 'echo %f'\n wd: '.'\n env", "end": 280, "score": 0.9976068139076233, "start": 276, "tag": "NAME", "value": "Test" } ]
spec/modifier-wildcards-spec.coffee
fstiewitz/build-tools-cpp
3
Wildcards = require '../lib/modifier/wildcards' Command = require '../lib/provider/command' path = require 'path' describe 'Command Modifier - Wildcards', -> command = null beforeEach -> command = new Command({ project: atom.project.getPaths()[0] name: 'Test' command: 'echo %f' wd: '.' env: {} modifier: wildcards: {} stdout: highlighting: 'nh' stderr: highlighting: 'nh' output: console: close_success: false version: 1 }) jasmine.attachToDOM(atom.views.getView(atom.workspace)) waitsForPromise -> atom.workspace.open path.join(atom.project.getPaths()[0], 'test.vhd') Wildcards.activate() waitsForPromise -> Wildcards.preSplit command it 'returns valid data', -> expect(command.command).toBe 'echo test.vhd'
196256
Wildcards = require '../lib/modifier/wildcards' Command = require '../lib/provider/command' path = require 'path' describe 'Command Modifier - Wildcards', -> command = null beforeEach -> command = new Command({ project: atom.project.getPaths()[0] name: '<NAME>' command: 'echo %f' wd: '.' env: {} modifier: wildcards: {} stdout: highlighting: 'nh' stderr: highlighting: 'nh' output: console: close_success: false version: 1 }) jasmine.attachToDOM(atom.views.getView(atom.workspace)) waitsForPromise -> atom.workspace.open path.join(atom.project.getPaths()[0], 'test.vhd') Wildcards.activate() waitsForPromise -> Wildcards.preSplit command it 'returns valid data', -> expect(command.command).toBe 'echo test.vhd'
true
Wildcards = require '../lib/modifier/wildcards' Command = require '../lib/provider/command' path = require 'path' describe 'Command Modifier - Wildcards', -> command = null beforeEach -> command = new Command({ project: atom.project.getPaths()[0] name: 'PI:NAME:<NAME>END_PI' command: 'echo %f' wd: '.' env: {} modifier: wildcards: {} stdout: highlighting: 'nh' stderr: highlighting: 'nh' output: console: close_success: false version: 1 }) jasmine.attachToDOM(atom.views.getView(atom.workspace)) waitsForPromise -> atom.workspace.open path.join(atom.project.getPaths()[0], 'test.vhd') Wildcards.activate() waitsForPromise -> Wildcards.preSplit command it 'returns valid data', -> expect(command.command).toBe 'echo test.vhd'
[ { "context": ": ->\n returnValue = {}\n returnValue.key = @_id if @_id\n returnValue.secret = @_secret if @_se", "end": 2492, "score": 0.6964929103851318, "start": 2490, "tag": "KEY", "value": "id" }, { "context": " if @_tokenKey\n returnValue.tokenKey = @_tokenK...
src/util/oauth.coffee
fatihacet/dropbox-js
1
# Stripped-down OAuth 2 implementation that works with the Dropbox API server. class Dropbox.Util.Oauth # Creates an Oauth instance that manages an application's key and token data. # # @private # This constructor is called by {Dropbox.Client}. This class should not be # instantiated directly. # # @param {Object} options the application type and API key; alternatively, # the result of a previous {Dropbox.Util.Oauth#credentials} call can be # passed in to create an identical {Dropbox.Util.Oauth} instance # @option options {String} key the Dropbox application's key (client # identifier, in OAuth2 vocabulary) # @option options {String} secret the Dropbox application's secret (client # secret, in OAuth vocabulary); browser-side applications should not use # this option # @option options {String} token (optional) the user's OAuth 2.0 access token constructor: (options) -> @_id = null @_secret = null @_stateParam = null @_authCode = null @_token = null @_tokenKey = null @_tokenKid = null @_error = null @_appHash = null @_loaded = null @setCredentials options # Resets the credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#setCredentials} instead. # # @param {Object} options same as for #{Dropbox.Util.Oauth#constructor} # @return {Dropbox.Util.Oauth} this, for easy call chaining # # @see Dropbox.Util.Oauth#constructor setCredentials: (options) -> if options.key @_id = options.key else unless options.token throw new Error 'No API key supplied' @_id = null @_secret = options.secret or null @_appHash = null @_error = null @_loaded = true @reset() if options.token @_token = options.token if options.tokenKey @_tokenKey = options.tokenKey @_tokenKid = options.tokenKid else if options.oauthCode @_authCode = options.oauthCode else if options.oauthStateParam @_stateParam = options.oauthStateParam @ # The credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#credentials} instead. # # @return {Object<String, String>} an object that can be passed into # {Dropbox.Util.Oauth#constructor} or into {Dropbox.Util.Oauth#reset} to # obtain a new instance that uses the same credentials; the object can be # serialized using JSON credentials: -> returnValue = {} returnValue.key = @_id if @_id returnValue.secret = @_secret if @_secret if @_token isnt null returnValue.token = @_token if @_tokenKey returnValue.tokenKey = @_tokenKey returnValue.tokenKid = @_tokenKid else if @_authCode isnt null returnValue.oauthCode = @_authCode else if @_stateParam isnt null returnValue.oauthStateParam = @_stateParam returnValue # The authentication process step that this instance's credentials are for # # @private # Use {Dropbox.Client#authStep} instead. # # @return {Number} one of the constants defined on {Dropbox.Client}, such as # {Dropbox.Client.DONE} step: -> if @_token isnt null Dropbox.Client.DONE else if @_authCode isnt null Dropbox.Client.AUTHORIZED else if @_stateParam isnt null if @_loaded Dropbox.Client.PARAM_LOADED else Dropbox.Client.PARAM_SET else if @_error isnt null Dropbox.Client.ERROR else Dropbox.Client.RESET # Sets the "state" parameter value for the following /authorize request. # # @private # Use {Dropbox.Client#authorize} instead. # # @param {String} stateParam the value of the "state" parameter # @return {Dropbox.Util.OAuth} this, for easy call chaining setAuthStateParam: (stateParam) -> if @_id is null throw new Error('No API key supplied, cannot do authorization') @reset() @_loaded = false @_stateParam = stateParam @ # Verifies the "state" query parameter in an /authorize redirect. # # If this method returns false, the /authorize redirect should be ignored. # # @param {String} stateParam the value of the "state" query parameter in the # request caused by an /authorize HTTP redirect # @return {Boolean} true if the given value matches the "state" parameter # sent to /authorize; false if no /authorize redirect was expected, or if # the value doesn't match checkAuthStateParam: (stateParam) -> (@_stateParam is stateParam) and (@_stateParam isnt null) # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Util.Oauth#checkAuthStateParam} instead. # # @return {String} the "state" query parameter set by setAuthStateParam authStateParam: -> @_stateParam # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Client#error} instead. error: -> @_error # Assimilates the information in an /authorize redirect's query parameters. # # The parameters may contain an access code, which will bring the Oauth # instance in the {Dropbox.Client.AUTHORIZED} state, or may contain an access # token, which will bring the Oauth instance in the {Dropbox.Client.DONE} # state. # # @private # This should only be called by {Dropbox.Client#authenticate}. OAuth drivers # should pass the redirect parameters to the callback of # {Dropbox.AuthDriver#doAuthorize} or {Dropbox.AuthDriver#resumeAuthorize}. # # @param {Object<String, String>} queryParams the query parameters that # contain an authorization code or access token; these should be query # parameters received from an /authorize redirect # @return {Boolean} true if the query parameters contained information about # an OAuth 2 authorization code or access token; false if no useful # information was found and this instance's state was not changed # # @see http://tools.ietf.org/html/rfc6749#section-4.1.2 RFC 6749 Section 4.1.2 # @see http://tools.ietf.org/html/rfc6750#section-4 RFC 6750 Section 4 # @see http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-03 processRedirectParams: (queryParams) -> if queryParams.error if @_id is null throw new Error('No API key supplied, cannot process errors') @reset() @_error = new Dropbox.AuthError(queryParams) return true if queryParams.code if @_id is null throw new Error('No API key supplied, cannot do Authorization Codes') @reset() @_loaded = false @_authCode = queryParams.code return true tokenType = queryParams.token_type if tokenType # NOTE: the API server used to use 'bearer' instead of 'Bearer' as the # token_type; the OAuth spec is hard to follow, so it's better to # be permissive tokenType = tokenType.toLowerCase() if tokenType isnt 'bearer' and tokenType isnt 'mac' throw new Error("Unimplemented token type #{tokenType}") @reset() @_loaded = false if tokenType is 'mac' if queryParams.mac_algorithm isnt 'hmac-sha-1' throw new Error( "Unimplemented MAC algorithms #{queryParams.mac_algorithm}") @_tokenKey = queryParams.mac_key @_tokenKid = queryParams.kid @_token = queryParams.access_token return true false # Computes the value of the OAuth 2-specified Authorization HTTP header. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by this method) is the recommended # method, and form parameters (implemented by addAuthParams) is the fallback # method. The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters # @return {String} the value to be used for the Authorization HTTP header authHeader: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) userPassword = if @_secret is null Dropbox.Util.btoa("#{@_id}:") else Dropbox.Util.btoa("#{@_id}:#{@_secret}") "Basic #{userPassword}" else if @_tokenKey is null # RFC 6750: Bearer Tokens. "Bearer #{@_token}" else # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params "MAC kid=#{macParams.kid} ts=#{macParams.ts} " + "access_token=#{@_token} mac=#{macParams.mac}" # Generates OAuth-required form parameters. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by authHeader) is the recommended method, # and form parameters (implemented by this method) is the fallback method. # The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters; this parameter will be mutated # @return {Object} the value of the params argument addAuthParams: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) params.client_id = @_id if @_secret isnt null params.client_secret = @_secret else if @_tokenKey isnt null # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params params.kid = macParams.kid params.ts = macParams.ts params.mac = macParams.mac # RFC 6750: Bearer Tokens and IETF draft-ietf-oauth-v2-http-mac params.access_token = @_token params # The query parameters to be used in an OAuth 2 /authorize URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} responseType one of the /authorize response types # implemented by dropbox.js # @param {?String} redirectUrl the URL that the user's browser should be # redirected to in order to perform an /authorize request # @return {Object<String, String>} the query parameters for the # /authorize URL # # @see Dropbox.AuthDriver#authType # @see RFC 6749 for the authorization process in OAuth 2.0 authorizeUrlParams: (responseType, redirectUrl) -> if responseType isnt 'token' and responseType isnt 'code' throw new Error("Unimplemented /authorize response type #{responseType}") # NOTE: these parameters will never contain the client secret params = client_id: @_id, state: @_stateParam, response_type: responseType params.redirect_uri = redirectUrl if redirectUrl params # The query parameters to be used in an /oauth2/token URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {?String} redirectUrl the URL that the user's browser was redirected # to after performing the /oauth2/authorize request; this must be the same # as the redirectUrl parameter passed to authorizeUrlParams # @return {Object<String, String>} the query parameters for the /oauth2/token # URL accessTokenParams: (redirectUrl) -> params = { grant_type: 'authorization_code', code: @_authCode } params.redirect_uri = redirectUrl if redirectUrl params # Extracts the query parameters in an /authorize redirect URL. # # This is provided as a helper for dropbox.js OAuth drivers. It is not a # general-purpose URL parser, but it will handle the URLs generated by the # Dropbox API server. # # @param {String} url a redirect URL generated by Dropbox's OAuth # authorization page # @return {Object<String, String>} the OAuth 2 parameters passed in the URL; # this should be passed to the callback of {Dropbox.AuthDriver#doAuthorize} # or {Dropbox.AuthDriver#resumeAuthorize} @queryParamsFromUrl: (url) -> match = /^[^?#]+(\?([^\#]*))?(\#(.*))?$/.exec url return {} unless match query = match[2] or '' fragment = match[4] or '' fragmentOffset = fragment.indexOf '?' if fragmentOffset isnt -1 fragment = fragment.substring fragmentOffset + 1 params = {} for kvp in query.split('&').concat fragment.split('&') offset = kvp.indexOf '=' continue if offset is -1 params[decodeURIComponent(kvp.substring(0, offset))] = decodeURIComponent kvp.substring(offset + 1) params # The parameters of an OAuth 2 MAC authenticator. # # @private # This is called internally by addHeader and addAuthParams when OAuth 2 MAC # tokens are in use. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} queryParams an associative array (hash) containing the # query parameters in the HTTP request URL # @return {Object<String, String>} the MAC authenticator attributes macParams: (method, url, params) -> macParams = { kid: @_tokenKid, ts: Dropbox.Util.Oauth.timestamp() } # TODO(pwnall): upgrade to the OAuth 2 MAC tokens algorithm string = method.toUpperCase() + '&' + Dropbox.Util.Xhr.urlEncodeValue(url) + '&' + Dropbox.Util.Xhr.urlEncodeValue(Dropbox.Util.Xhr.urlEncode(params)) macParams.mac = Dropbox.Util.hmac string, @_tokenKey macParams # @private # Use {Dropbox.Client#appHash} instead. # # @return {String} a string that uniquely identifies the application, based # on its OAuth client id appHash: -> return @_appHash if @_appHash @_appHash = Dropbox.Util.sha1('oauth2-' + @_id).replace(/[\/+=]/g, '') # Drops all user-specific OAuth information. # # @private # Use {Dropbox.Client#reset} instead. # # After this method is called, the Oauth instance will be in the # {Dropbox.Client.RESET} step. # # @return {Dropbox.Util.Oauth} this, for easy call chaining reset: -> @_stateParam = null @_authCode = null @_token = null @_tokenKey = null @_tokenKid = null @ # The timestamp used for an OAuth 2 request. # # @private # This method is separated out for testing purposes. # # @return {Number} a timestamp suitable for use in computing OAuth 2 MAC # authenticators @timestamp: -> Math.floor(Date.now() / 1000) # Generates a random OAuth 2 authentication state parameter value. # # This is used for authentication drivers that do not implement # Dropbox.AuthDriver#getStateParam. # # @return {String} a randomly generated parameter @randomAuthStateParam: -> ['oas', Date.now().toString(36), Math.random().toString(36)].join '_' # Date.now() workaround for Internet Explorer 8. unless Date.now? Dropbox.Util.Oauth.timestamp = -> Math.floor((new Date()).getTime() / 1000)
72455
# Stripped-down OAuth 2 implementation that works with the Dropbox API server. class Dropbox.Util.Oauth # Creates an Oauth instance that manages an application's key and token data. # # @private # This constructor is called by {Dropbox.Client}. This class should not be # instantiated directly. # # @param {Object} options the application type and API key; alternatively, # the result of a previous {Dropbox.Util.Oauth#credentials} call can be # passed in to create an identical {Dropbox.Util.Oauth} instance # @option options {String} key the Dropbox application's key (client # identifier, in OAuth2 vocabulary) # @option options {String} secret the Dropbox application's secret (client # secret, in OAuth vocabulary); browser-side applications should not use # this option # @option options {String} token (optional) the user's OAuth 2.0 access token constructor: (options) -> @_id = null @_secret = null @_stateParam = null @_authCode = null @_token = null @_tokenKey = null @_tokenKid = null @_error = null @_appHash = null @_loaded = null @setCredentials options # Resets the credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#setCredentials} instead. # # @param {Object} options same as for #{Dropbox.Util.Oauth#constructor} # @return {Dropbox.Util.Oauth} this, for easy call chaining # # @see Dropbox.Util.Oauth#constructor setCredentials: (options) -> if options.key @_id = options.key else unless options.token throw new Error 'No API key supplied' @_id = null @_secret = options.secret or null @_appHash = null @_error = null @_loaded = true @reset() if options.token @_token = options.token if options.tokenKey @_tokenKey = options.tokenKey @_tokenKid = options.tokenKid else if options.oauthCode @_authCode = options.oauthCode else if options.oauthStateParam @_stateParam = options.oauthStateParam @ # The credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#credentials} instead. # # @return {Object<String, String>} an object that can be passed into # {Dropbox.Util.Oauth#constructor} or into {Dropbox.Util.Oauth#reset} to # obtain a new instance that uses the same credentials; the object can be # serialized using JSON credentials: -> returnValue = {} returnValue.key = @_<KEY> if @_id returnValue.secret = @_secret if @_secret if @_token isnt null returnValue.token = @_token if @_tokenKey returnValue.tokenKey = <KEY>tokenKey returnValue.tokenKid = @_tokenKid else if @_authCode isnt null returnValue.oauthCode = @_authCode else if @_stateParam isnt null returnValue.oauthStateParam = @_stateParam returnValue # The authentication process step that this instance's credentials are for # # @private # Use {Dropbox.Client#authStep} instead. # # @return {Number} one of the constants defined on {Dropbox.Client}, such as # {Dropbox.Client.DONE} step: -> if @_token isnt null Dropbox.Client.DONE else if @_authCode isnt null Dropbox.Client.AUTHORIZED else if @_stateParam isnt null if @_loaded Dropbox.Client.PARAM_LOADED else Dropbox.Client.PARAM_SET else if @_error isnt null Dropbox.Client.ERROR else Dropbox.Client.RESET # Sets the "state" parameter value for the following /authorize request. # # @private # Use {Dropbox.Client#authorize} instead. # # @param {String} stateParam the value of the "state" parameter # @return {Dropbox.Util.OAuth} this, for easy call chaining setAuthStateParam: (stateParam) -> if @_id is null throw new Error('No API key supplied, cannot do authorization') @reset() @_loaded = false @_stateParam = stateParam @ # Verifies the "state" query parameter in an /authorize redirect. # # If this method returns false, the /authorize redirect should be ignored. # # @param {String} stateParam the value of the "state" query parameter in the # request caused by an /authorize HTTP redirect # @return {Boolean} true if the given value matches the "state" parameter # sent to /authorize; false if no /authorize redirect was expected, or if # the value doesn't match checkAuthStateParam: (stateParam) -> (@_stateParam is stateParam) and (@_stateParam isnt null) # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Util.Oauth#checkAuthStateParam} instead. # # @return {String} the "state" query parameter set by setAuthStateParam authStateParam: -> @_stateParam # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Client#error} instead. error: -> @_error # Assimilates the information in an /authorize redirect's query parameters. # # The parameters may contain an access code, which will bring the Oauth # instance in the {Dropbox.Client.AUTHORIZED} state, or may contain an access # token, which will bring the Oauth instance in the {Dropbox.Client.DONE} # state. # # @private # This should only be called by {Dropbox.Client#authenticate}. OAuth drivers # should pass the redirect parameters to the callback of # {Dropbox.AuthDriver#doAuthorize} or {Dropbox.AuthDriver#resumeAuthorize}. # # @param {Object<String, String>} queryParams the query parameters that # contain an authorization code or access token; these should be query # parameters received from an /authorize redirect # @return {Boolean} true if the query parameters contained information about # an OAuth 2 authorization code or access token; false if no useful # information was found and this instance's state was not changed # # @see http://tools.ietf.org/html/rfc6749#section-4.1.2 RFC 6749 Section 4.1.2 # @see http://tools.ietf.org/html/rfc6750#section-4 RFC 6750 Section 4 # @see http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-03 processRedirectParams: (queryParams) -> if queryParams.error if @_id is null throw new Error('No API key supplied, cannot process errors') @reset() @_error = new Dropbox.AuthError(queryParams) return true if queryParams.code if @_id is null throw new Error('No API key supplied, cannot do Authorization Codes') @reset() @_loaded = false @_authCode = queryParams.code return true tokenType = queryParams.token_type if tokenType # NOTE: the API server used to use 'bearer' instead of 'Bearer' as the # token_type; the OAuth spec is hard to follow, so it's better to # be permissive tokenType = tokenType.toLowerCase() if tokenType isnt 'bearer' and tokenType isnt 'mac' throw new Error("Unimplemented token type #{tokenType}") @reset() @_loaded = false if tokenType is 'mac' if queryParams.mac_algorithm isnt 'hmac-sha-1' throw new Error( "Unimplemented MAC algorithms #{queryParams.mac_algorithm}") @_tokenKey = queryParams.mac_key @_tokenKid = queryParams.kid @_token = queryParams.access_token return true false # Computes the value of the OAuth 2-specified Authorization HTTP header. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by this method) is the recommended # method, and form parameters (implemented by addAuthParams) is the fallback # method. The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters # @return {String} the value to be used for the Authorization HTTP header authHeader: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) userPassword = if @_secret is null Dropbox.Util.btoa("#{@_id}:") else Dropbox.Util.btoa("#{@_id}:#{@_secret}") "Basic #{userPassword}" else if @_tokenKey is null # RFC 6750: Bearer Tokens. "Bearer #{@_token}" else # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params "MAC kid=#{macParams.kid} ts=#{macParams.ts} " + "access_token=#{@_token} mac=#{macParams.mac}" # Generates OAuth-required form parameters. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by authHeader) is the recommended method, # and form parameters (implemented by this method) is the fallback method. # The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters; this parameter will be mutated # @return {Object} the value of the params argument addAuthParams: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) params.client_id = @_id if @_secret isnt null params.client_secret = @_secret else if @_tokenKey isnt null # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params params.kid = macParams.kid params.ts = macParams.ts params.mac = macParams.mac # RFC 6750: Bearer Tokens and IETF draft-ietf-oauth-v2-http-mac params.access_token = @_token params # The query parameters to be used in an OAuth 2 /authorize URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} responseType one of the /authorize response types # implemented by dropbox.js # @param {?String} redirectUrl the URL that the user's browser should be # redirected to in order to perform an /authorize request # @return {Object<String, String>} the query parameters for the # /authorize URL # # @see Dropbox.AuthDriver#authType # @see RFC 6749 for the authorization process in OAuth 2.0 authorizeUrlParams: (responseType, redirectUrl) -> if responseType isnt 'token' and responseType isnt 'code' throw new Error("Unimplemented /authorize response type #{responseType}") # NOTE: these parameters will never contain the client secret params = client_id: @_id, state: @_stateParam, response_type: responseType params.redirect_uri = redirectUrl if redirectUrl params # The query parameters to be used in an /oauth2/token URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {?String} redirectUrl the URL that the user's browser was redirected # to after performing the /oauth2/authorize request; this must be the same # as the redirectUrl parameter passed to authorizeUrlParams # @return {Object<String, String>} the query parameters for the /oauth2/token # URL accessTokenParams: (redirectUrl) -> params = { grant_type: 'authorization_code', code: @_authCode } params.redirect_uri = redirectUrl if redirectUrl params # Extracts the query parameters in an /authorize redirect URL. # # This is provided as a helper for dropbox.js OAuth drivers. It is not a # general-purpose URL parser, but it will handle the URLs generated by the # Dropbox API server. # # @param {String} url a redirect URL generated by Dropbox's OAuth # authorization page # @return {Object<String, String>} the OAuth 2 parameters passed in the URL; # this should be passed to the callback of {Dropbox.AuthDriver#doAuthorize} # or {Dropbox.AuthDriver#resumeAuthorize} @queryParamsFromUrl: (url) -> match = /^[^?#]+(\?([^\#]*))?(\#(.*))?$/.exec url return {} unless match query = match[2] or '' fragment = match[4] or '' fragmentOffset = fragment.indexOf '?' if fragmentOffset isnt -1 fragment = fragment.substring fragmentOffset + 1 params = {} for kvp in query.split('&').concat fragment.split('&') offset = kvp.indexOf '=' continue if offset is -1 params[decodeURIComponent(kvp.substring(0, offset))] = decodeURIComponent kvp.substring(offset + 1) params # The parameters of an OAuth 2 MAC authenticator. # # @private # This is called internally by addHeader and addAuthParams when OAuth 2 MAC # tokens are in use. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} queryParams an associative array (hash) containing the # query parameters in the HTTP request URL # @return {Object<String, String>} the MAC authenticator attributes macParams: (method, url, params) -> macParams = { kid: @_tokenKid, ts: Dropbox.Util.Oauth.timestamp() } # TODO(pwnall): upgrade to the OAuth 2 MAC tokens algorithm string = method.toUpperCase() + '&' + Dropbox.Util.Xhr.urlEncodeValue(url) + '&' + Dropbox.Util.Xhr.urlEncodeValue(Dropbox.Util.Xhr.urlEncode(params)) macParams.mac = Dropbox.Util.hmac string, @_tokenKey macParams # @private # Use {Dropbox.Client#appHash} instead. # # @return {String} a string that uniquely identifies the application, based # on its OAuth client id appHash: -> return @_appHash if @_appHash @_appHash = Dropbox.Util.sha1('oauth2-' + @_id).replace(/[\/+=]/g, '') # Drops all user-specific OAuth information. # # @private # Use {Dropbox.Client#reset} instead. # # After this method is called, the Oauth instance will be in the # {Dropbox.Client.RESET} step. # # @return {Dropbox.Util.Oauth} this, for easy call chaining reset: -> @_stateParam = null @_authCode = null @_token = <PASSWORD> @_tokenKey = null @_tokenKid = null @ # The timestamp used for an OAuth 2 request. # # @private # This method is separated out for testing purposes. # # @return {Number} a timestamp suitable for use in computing OAuth 2 MAC # authenticators @timestamp: -> Math.floor(Date.now() / 1000) # Generates a random OAuth 2 authentication state parameter value. # # This is used for authentication drivers that do not implement # Dropbox.AuthDriver#getStateParam. # # @return {String} a randomly generated parameter @randomAuthStateParam: -> ['oas', Date.now().toString(36), Math.random().toString(36)].join '_' # Date.now() workaround for Internet Explorer 8. unless Date.now? Dropbox.Util.Oauth.timestamp = -> Math.floor((new Date()).getTime() / 1000)
true
# Stripped-down OAuth 2 implementation that works with the Dropbox API server. class Dropbox.Util.Oauth # Creates an Oauth instance that manages an application's key and token data. # # @private # This constructor is called by {Dropbox.Client}. This class should not be # instantiated directly. # # @param {Object} options the application type and API key; alternatively, # the result of a previous {Dropbox.Util.Oauth#credentials} call can be # passed in to create an identical {Dropbox.Util.Oauth} instance # @option options {String} key the Dropbox application's key (client # identifier, in OAuth2 vocabulary) # @option options {String} secret the Dropbox application's secret (client # secret, in OAuth vocabulary); browser-side applications should not use # this option # @option options {String} token (optional) the user's OAuth 2.0 access token constructor: (options) -> @_id = null @_secret = null @_stateParam = null @_authCode = null @_token = null @_tokenKey = null @_tokenKid = null @_error = null @_appHash = null @_loaded = null @setCredentials options # Resets the credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#setCredentials} instead. # # @param {Object} options same as for #{Dropbox.Util.Oauth#constructor} # @return {Dropbox.Util.Oauth} this, for easy call chaining # # @see Dropbox.Util.Oauth#constructor setCredentials: (options) -> if options.key @_id = options.key else unless options.token throw new Error 'No API key supplied' @_id = null @_secret = options.secret or null @_appHash = null @_error = null @_loaded = true @reset() if options.token @_token = options.token if options.tokenKey @_tokenKey = options.tokenKey @_tokenKid = options.tokenKid else if options.oauthCode @_authCode = options.oauthCode else if options.oauthStateParam @_stateParam = options.oauthStateParam @ # The credentials used by this Oauth instance. # # @private # Use {Dropbox.Client#credentials} instead. # # @return {Object<String, String>} an object that can be passed into # {Dropbox.Util.Oauth#constructor} or into {Dropbox.Util.Oauth#reset} to # obtain a new instance that uses the same credentials; the object can be # serialized using JSON credentials: -> returnValue = {} returnValue.key = @_PI:KEY:<KEY>END_PI if @_id returnValue.secret = @_secret if @_secret if @_token isnt null returnValue.token = @_token if @_tokenKey returnValue.tokenKey = PI:KEY:<KEY>END_PItokenKey returnValue.tokenKid = @_tokenKid else if @_authCode isnt null returnValue.oauthCode = @_authCode else if @_stateParam isnt null returnValue.oauthStateParam = @_stateParam returnValue # The authentication process step that this instance's credentials are for # # @private # Use {Dropbox.Client#authStep} instead. # # @return {Number} one of the constants defined on {Dropbox.Client}, such as # {Dropbox.Client.DONE} step: -> if @_token isnt null Dropbox.Client.DONE else if @_authCode isnt null Dropbox.Client.AUTHORIZED else if @_stateParam isnt null if @_loaded Dropbox.Client.PARAM_LOADED else Dropbox.Client.PARAM_SET else if @_error isnt null Dropbox.Client.ERROR else Dropbox.Client.RESET # Sets the "state" parameter value for the following /authorize request. # # @private # Use {Dropbox.Client#authorize} instead. # # @param {String} stateParam the value of the "state" parameter # @return {Dropbox.Util.OAuth} this, for easy call chaining setAuthStateParam: (stateParam) -> if @_id is null throw new Error('No API key supplied, cannot do authorization') @reset() @_loaded = false @_stateParam = stateParam @ # Verifies the "state" query parameter in an /authorize redirect. # # If this method returns false, the /authorize redirect should be ignored. # # @param {String} stateParam the value of the "state" query parameter in the # request caused by an /authorize HTTP redirect # @return {Boolean} true if the given value matches the "state" parameter # sent to /authorize; false if no /authorize redirect was expected, or if # the value doesn't match checkAuthStateParam: (stateParam) -> (@_stateParam is stateParam) and (@_stateParam isnt null) # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Util.Oauth#checkAuthStateParam} instead. # # @return {String} the "state" query parameter set by setAuthStateParam authStateParam: -> @_stateParam # @private # This should only be called by {Dropbox.Client#authenticate}. Use # {Dropbox.Client#error} instead. error: -> @_error # Assimilates the information in an /authorize redirect's query parameters. # # The parameters may contain an access code, which will bring the Oauth # instance in the {Dropbox.Client.AUTHORIZED} state, or may contain an access # token, which will bring the Oauth instance in the {Dropbox.Client.DONE} # state. # # @private # This should only be called by {Dropbox.Client#authenticate}. OAuth drivers # should pass the redirect parameters to the callback of # {Dropbox.AuthDriver#doAuthorize} or {Dropbox.AuthDriver#resumeAuthorize}. # # @param {Object<String, String>} queryParams the query parameters that # contain an authorization code or access token; these should be query # parameters received from an /authorize redirect # @return {Boolean} true if the query parameters contained information about # an OAuth 2 authorization code or access token; false if no useful # information was found and this instance's state was not changed # # @see http://tools.ietf.org/html/rfc6749#section-4.1.2 RFC 6749 Section 4.1.2 # @see http://tools.ietf.org/html/rfc6750#section-4 RFC 6750 Section 4 # @see http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-03 processRedirectParams: (queryParams) -> if queryParams.error if @_id is null throw new Error('No API key supplied, cannot process errors') @reset() @_error = new Dropbox.AuthError(queryParams) return true if queryParams.code if @_id is null throw new Error('No API key supplied, cannot do Authorization Codes') @reset() @_loaded = false @_authCode = queryParams.code return true tokenType = queryParams.token_type if tokenType # NOTE: the API server used to use 'bearer' instead of 'Bearer' as the # token_type; the OAuth spec is hard to follow, so it's better to # be permissive tokenType = tokenType.toLowerCase() if tokenType isnt 'bearer' and tokenType isnt 'mac' throw new Error("Unimplemented token type #{tokenType}") @reset() @_loaded = false if tokenType is 'mac' if queryParams.mac_algorithm isnt 'hmac-sha-1' throw new Error( "Unimplemented MAC algorithms #{queryParams.mac_algorithm}") @_tokenKey = queryParams.mac_key @_tokenKid = queryParams.kid @_token = queryParams.access_token return true false # Computes the value of the OAuth 2-specified Authorization HTTP header. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by this method) is the recommended # method, and form parameters (implemented by addAuthParams) is the fallback # method. The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters # @return {String} the value to be used for the Authorization HTTP header authHeader: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) userPassword = if @_secret is null Dropbox.Util.btoa("#{@_id}:") else Dropbox.Util.btoa("#{@_id}:#{@_secret}") "Basic #{userPassword}" else if @_tokenKey is null # RFC 6750: Bearer Tokens. "Bearer #{@_token}" else # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params "MAC kid=#{macParams.kid} ts=#{macParams.ts} " + "access_token=#{@_token} mac=#{macParams.mac}" # Generates OAuth-required form parameters. # # OAuth 2 supports two methods of passing authorization information. The # Authorization header (implemented by authHeader) is the recommended method, # and form parameters (implemented by this method) is the fallback method. # The fallback method is useful for avoiding CORS preflight requests. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} params an associative array (hash) containing the HTTP # request parameters; this parameter will be mutated # @return {Object} the value of the params argument addAuthParams: (method, url, params) -> if @_token is null # RFC 6749: OAuth 2.0 (Client Authentication, Protocol Endpoints) params.client_id = @_id if @_secret isnt null params.client_secret = @_secret else if @_tokenKey isnt null # IETF draft-ietf-oauth-v2-http-mac macParams = @macParams method, url, params params.kid = macParams.kid params.ts = macParams.ts params.mac = macParams.mac # RFC 6750: Bearer Tokens and IETF draft-ietf-oauth-v2-http-mac params.access_token = @_token params # The query parameters to be used in an OAuth 2 /authorize URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {String} responseType one of the /authorize response types # implemented by dropbox.js # @param {?String} redirectUrl the URL that the user's browser should be # redirected to in order to perform an /authorize request # @return {Object<String, String>} the query parameters for the # /authorize URL # # @see Dropbox.AuthDriver#authType # @see RFC 6749 for the authorization process in OAuth 2.0 authorizeUrlParams: (responseType, redirectUrl) -> if responseType isnt 'token' and responseType isnt 'code' throw new Error("Unimplemented /authorize response type #{responseType}") # NOTE: these parameters will never contain the client secret params = client_id: @_id, state: @_stateParam, response_type: responseType params.redirect_uri = redirectUrl if redirectUrl params # The query parameters to be used in an /oauth2/token URL. # # @private # This should only be called by {Dropbox.Client#authenticate}. # # @param {?String} redirectUrl the URL that the user's browser was redirected # to after performing the /oauth2/authorize request; this must be the same # as the redirectUrl parameter passed to authorizeUrlParams # @return {Object<String, String>} the query parameters for the /oauth2/token # URL accessTokenParams: (redirectUrl) -> params = { grant_type: 'authorization_code', code: @_authCode } params.redirect_uri = redirectUrl if redirectUrl params # Extracts the query parameters in an /authorize redirect URL. # # This is provided as a helper for dropbox.js OAuth drivers. It is not a # general-purpose URL parser, but it will handle the URLs generated by the # Dropbox API server. # # @param {String} url a redirect URL generated by Dropbox's OAuth # authorization page # @return {Object<String, String>} the OAuth 2 parameters passed in the URL; # this should be passed to the callback of {Dropbox.AuthDriver#doAuthorize} # or {Dropbox.AuthDriver#resumeAuthorize} @queryParamsFromUrl: (url) -> match = /^[^?#]+(\?([^\#]*))?(\#(.*))?$/.exec url return {} unless match query = match[2] or '' fragment = match[4] or '' fragmentOffset = fragment.indexOf '?' if fragmentOffset isnt -1 fragment = fragment.substring fragmentOffset + 1 params = {} for kvp in query.split('&').concat fragment.split('&') offset = kvp.indexOf '=' continue if offset is -1 params[decodeURIComponent(kvp.substring(0, offset))] = decodeURIComponent kvp.substring(offset + 1) params # The parameters of an OAuth 2 MAC authenticator. # # @private # This is called internally by addHeader and addAuthParams when OAuth 2 MAC # tokens are in use. # # @param {String} method the HTTP method used to make the request ('GET', # 'POST', etc) # @param {String} url the HTTP URL (e.g. "http://www.example.com/photos") # that receives the request # @param {Object} queryParams an associative array (hash) containing the # query parameters in the HTTP request URL # @return {Object<String, String>} the MAC authenticator attributes macParams: (method, url, params) -> macParams = { kid: @_tokenKid, ts: Dropbox.Util.Oauth.timestamp() } # TODO(pwnall): upgrade to the OAuth 2 MAC tokens algorithm string = method.toUpperCase() + '&' + Dropbox.Util.Xhr.urlEncodeValue(url) + '&' + Dropbox.Util.Xhr.urlEncodeValue(Dropbox.Util.Xhr.urlEncode(params)) macParams.mac = Dropbox.Util.hmac string, @_tokenKey macParams # @private # Use {Dropbox.Client#appHash} instead. # # @return {String} a string that uniquely identifies the application, based # on its OAuth client id appHash: -> return @_appHash if @_appHash @_appHash = Dropbox.Util.sha1('oauth2-' + @_id).replace(/[\/+=]/g, '') # Drops all user-specific OAuth information. # # @private # Use {Dropbox.Client#reset} instead. # # After this method is called, the Oauth instance will be in the # {Dropbox.Client.RESET} step. # # @return {Dropbox.Util.Oauth} this, for easy call chaining reset: -> @_stateParam = null @_authCode = null @_token = PI:PASSWORD:<PASSWORD>END_PI @_tokenKey = null @_tokenKid = null @ # The timestamp used for an OAuth 2 request. # # @private # This method is separated out for testing purposes. # # @return {Number} a timestamp suitable for use in computing OAuth 2 MAC # authenticators @timestamp: -> Math.floor(Date.now() / 1000) # Generates a random OAuth 2 authentication state parameter value. # # This is used for authentication drivers that do not implement # Dropbox.AuthDriver#getStateParam. # # @return {String} a randomly generated parameter @randomAuthStateParam: -> ['oas', Date.now().toString(36), Math.random().toString(36)].join '_' # Date.now() workaround for Internet Explorer 8. unless Date.now? Dropbox.Util.Oauth.timestamp = -> Math.floor((new Date()).getTime() / 1000)
[ { "context": "h'\n\nuserAgent = 'sdmx-rest4js (https://github.com/sosna/sdmx-rest4js)'\n\ncheckStatus = (query, response) -", "end": 1154, "score": 0.999626636505127, "start": 1149, "tag": "USERNAME", "value": "sosna" }, { "context": "ely\n# sdmxrest.getDataQuery({flow: 'EXR', key:...
src/index.coffee
sosna/sdmx-rest.js
16
{DataQuery} = require './data/data-query' {DataFormat} = require './data/data-format' {DataDetail} = require './data/data-detail' {MetadataQuery} = require './metadata/metadata-query' {MetadataFormat} = require './metadata/metadata-format' {MetadataDetail} = require './metadata/metadata-detail' {MetadataReferences} = require './metadata/metadata-references' {MetadataType} = require './metadata/metadata-type' {AvailabilityQuery} = require './avail/availability-query' {AvailabilityMode} = require './avail/availability-mode' {AvailabilityReferences} = require './avail/availability-references' {SchemaQuery} = require './schema/schema-query' {SchemaContext} = require './schema/schema-context' {SchemaFormat} = require './schema/schema-format' {Service} = require './service/service' {services} = require './service/service' {UrlGenerator} = require './utils/url-generator' {ApiVersion} = require './utils/api-version' {ApiResources} = require './utils/api-version' SdmxPatterns = require './utils/sdmx-patterns' promise = require 'es6-promise' promise.polyfill() fetch = require 'isomorphic-fetch' userAgent = 'sdmx-rest4js (https://github.com/sosna/sdmx-rest4js)' checkStatus = (query, response) -> throw ReferenceError 'Not a valid response' unless response code = response.status unless 100 <= code < 400 or (code is 404 and query.updatedAfter) throw RangeError "Request failed with error code #{code}" isFormat = (input, expected) -> out = false for v in Object.values expected out = true if v is input out isDataFormat = (format) -> isFormat(format, DataFormat) isMetadataFormat = (format) -> isFormat(format, MetadataFormat) isSchemaFormat = (format) -> isFormat(format, SchemaFormat) isGenericFormat = (format) -> formats = [ 'application/xml' 'application/json' 'text/csv' 'text/xml' ] format in formats isRequestedFormat = (requested, received) -> requested.indexOf(received) > -1 checkMediaType = (requested, response) -> fmt = response.headers.get('content-type') fmt = if fmt then fmt.replace /; version=/, ';version=' else fmt unless isDataFormat(fmt) or \ isMetadataFormat(fmt) or \ isGenericFormat(fmt) or \ isSchemaFormat(fmt) throw RangeError "Not an SDMX format: #{fmt}" unless isRequestedFormat(requested, fmt) throw RangeError "Wrong format: requested #{requested} but got #{fmt}" addHeaders = (opts, s, type) -> opts ?= {} headers = {} headers[key.toLowerCase()] = opts.headers[key] for own key of opts.headers unless headers.accept headers.accept = switch type when 'data' then s.format when 'structure' then s.structureFormat when 'schema' then s.schemaFormat headers.accept = '*/*' unless headers.accept headers['user-agent'] = userAgent unless headers['user-agent'] opts.headers = headers opts guessService = (u) -> s = (Service[k] for own k of Service when u.indexOf(Service[k].url) > -1) return s[0] ? {} # # Get an SDMX 2.1 RESTful web service against which queries can be executed. # # This library offers a few predefined services, which you can access using the # service identifier. # # @example Get a predefined service # sdmxrest.getService('ECB') # # In case the service to be accessed is not yet predefined, an object with the # information necessary to create the service can be passed as parameter. # # @example Create a service # sdmxrest.getService({url: 'http://ws-entry-point'}) # # The expected properties for the object are: # - *url* - the entry point of the SDMX 2.1 RESTful web service # - *api* (optional) - the version of the SDMX 2.1 RESTful API supported by # the service. If not supplied, it will default to the most recent version of # the SDMX RESTful API # - *id* (optional) - an identifier for the web service # - *name* (optional) - a label for the web service # # @param [Object|String] input the ID of a predefined service or an object with # the information about the service to be instantiated # # @throw an error in case a) a string is supplied and it is not the ID of a # predefined service or b) an object is supplied and it does not contain a # valid *url* property. # getService = (input) -> if typeof input is 'string' throw ReferenceError "#{input} is not in the list of predefined services" \ unless Service[input] Service[input] else if input instanceof Object and \ Object.prototype.toString.call(input) is '[object Object]' Service.from input else throw TypeError "Invalid type of #{input}. Expected an object or a string" # # Get an SDMX 2.1 RESTful data query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *firstNObs* (optional) - the number of observations to be returned, # starting from the first observation # - *lastNObs* (optional) - the number of observations to be returned, # starting from the last observation # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level (default TIME_PERIOD). # - *detail* (optional) - the desired amount of information to be returned # (default: full). # - *history* (optional) - Whether previous versions of the data should be # returned (default: false). # # @example Create a query for all data belonging to the EXR dataflow # sdmxrest.getDataQuery({flow: 'EXR'}) # # @example Create a query for EXR data, matching values A and Q for the 1st # dimension, any value for the 2nd dimension, EUR, SP00 and A for the 3rd, 4th # and 5th dimensions respectively # sdmxrest.getDataQuery({flow: 'EXR', key: 'A+Q..EUR.SP00.A'}) # # @example Create a query for the last observation of the EXR data matching the # supplied key # sdmxrest.getDataQuery({flow: 'EXR', key: 'A.CHF.EUR.SP00.A', lastNObs: 1}) # # @example Create a query to get what has changed for the matching data since # the supplied point in time # sdmxrest.getDataQuery({flow: 'EXR', key: 'A.NOK.EUR.SP00.A', # updatedAfter: '2016-03-17T14:38:00Z'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getDataQuery = (input) -> return DataQuery.from input # # Get an SDMX 2.1 RESTful metadata query. # # The expected properties (and their default values) are: # - *resource*: **Mandatory** - the type of structural metadata to be returned # - *agency* (optional) - the agency maintaining the metadata to be returned # (default: all) # - *id* (optional) - the id of the metadata to be returned (default: all) # - *version* (optional) - the version of the metadata to be returned # (default: latest) # - *item* (optional) - for item schemes query, the id of the item to be # returned (default: all) # - *detail* (optional) - the desired amount of information to be returned # (default: full) # - *references* (optional) - whether to return the artefacts referenced by, # or that use, the metadata to be returned (default: none) # # @example Create a query for all codelists maintained by the ECB # sdmxrest.getMetadataQuery({resource: 'codelist', agency: 'ECB'}) # # @example Create a query for the BOP data structure maintained by the IMF, # along with all the codelists and concepts used in the data structure # sdmxrest.getMetadataQuery({resource: 'datastructure', agency: 'IMF', # id: 'BOP', references: 'descendants'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory resource is not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getMetadataQuery = (input) -> return MetadataQuery.from input # # Get an SDMX 2.1 RESTful availability query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *component* (optional) - the id of the dimension for which to obtain # availability information (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *mode* (optional) - the possible processing modes (default: exact) # - *references* (optional) - the references to be returned (default: none) # # @example Create an availability query for the EXR dataflow # sdmxrest.getAvailabilityQuery({flow: 'EXR'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getAvailabilityQuery = (input) -> return AvailabilityQuery.from input # # Get an SDMX 2.1 RESTful schema query. # # The expected properties (and their default values) are: # - *context*: **Mandatory** - the constraints that need to be taken into # account, when generating the schema # - *agency*: **Mandatory** - the maintenance agency # - *id*: **Mandatory** - the artefact id # - *version* (optional) - the artefact version (default: latest) # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level. # - *explicit* (optional) - For cross-sectional data validation, indicates # whether observations are strongly typed (default: false) # # @example Create a schema query for the CBS schema # sdmxrest.getSchemaQuery({context: 'dataflow', 'id': 'CBS', 'agency': 'BIS'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory properties are not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getSchemaQuery = (input) -> return SchemaQuery.from input # # Get the SDMX 2.1 RESTful URL representing the query to be executed against the # supplied service. # # @example Get the URL representing the query to be executed against the # supplied service # sdmxrest.getUrl({flow: 'EXR', key: 'A.CHF.EUR.SP00.A'}, 'ECB') # # @param [Object] query the query to be executed # @param [Object|String] service the service against which the query should be # executed # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # getUrl = (query, service) -> throw ReferenceError 'Not a valid service' unless service throw ReferenceError 'Not a valid query' unless query s = getService service q = if (query.mode? or \ (query.flow? and query.references?) or \ (query.flow? and query.component?)) getAvailabilityQuery query else if query.flow? getDataQuery query else if query.resource? getMetadataQuery query else if query.context? getSchemaQuery query throw Error 'Not a valid query' unless q return new UrlGenerator().getUrl q, s # # Executes the supplied query against the supplied service and returns a # Promise. # # At the difference with the request() function, request2() will # include the response headers and additional information such as the status. # # @see #request for additional information about the required parameters. # request2 = (params...) -> q = params[0] s = if typeof q is 'string' then guessService q else getService params[1] u = if typeof q is 'string' then q else getUrl q, s o = if typeof q is 'string' then params[1] else params[2] t = null if u.indexOf('/data/') > -1 t = 'data' else if u.indexOf('/schema/') > -1 t = 'schema' else t = 'structure' requestOptions = addHeaders o, s, t fetch(u, requestOptions) .then((response) -> response) # # Executes the supplied query against the supplied service and returns a # Promise. # # The returned Promise should be handled using the *then* and *catch* methods # offered by a Promise. # # @example Executes the supplied query against the supplied service # sdmxrest.request({flow: 'EXR', key: 'A.CHF.EUR.SP00.A'}, 'ECB') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Executes the supplied query against the supplied service, asking the # service to return a compressed SDMX-JSON message. # sdmxrest.request({flow: 'EXR', key: 'A.CHF.EUR.SP00.A'}, 'ECB', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # In case you already have an SDMX 2.1 RESTful query string, you can also use it # with execute(). # # @example Fetches the supplied URL # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Fetches the supplied URL, asking the service to return a compressed # SDMX-JSON message # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @param [Object|String] query the query to be executed # @param [Object|String] service the service against which the query should be # executed. This should not be set in case an SDMX 2.1 query string is passed # as 1st parameter # @param [Object] opts additional options for the request. See the whatwg fetch # specification for additional information. # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # request = (params...) -> request2(params...).then((response) -> checkStatus params[0], response response.text()) module.exports = getService: getService services: services getDataQuery: getDataQuery getMetadataQuery: getMetadataQuery getAvailabilityQuery: getAvailabilityQuery getSchemaQuery: getSchemaQuery getUrl: getUrl request: request request2: request2 checkStatus: checkStatus checkMediaType: checkMediaType data: DataFormat: DataFormat DataDetail: DataDetail metadata: MetadataFormat: MetadataFormat MetadataDetail: MetadataDetail MetadataReferences: MetadataReferences MetadataType: MetadataType availability: AvailabilityMode: AvailabilityMode AvailabilityReferences: AvailabilityReferences utils: ApiVersion: ApiVersion ApiResources: ApiResources SdmxPatterns: SdmxPatterns schema: SchemaContext: SchemaContext SchemaFormat: SchemaFormat
40850
{DataQuery} = require './data/data-query' {DataFormat} = require './data/data-format' {DataDetail} = require './data/data-detail' {MetadataQuery} = require './metadata/metadata-query' {MetadataFormat} = require './metadata/metadata-format' {MetadataDetail} = require './metadata/metadata-detail' {MetadataReferences} = require './metadata/metadata-references' {MetadataType} = require './metadata/metadata-type' {AvailabilityQuery} = require './avail/availability-query' {AvailabilityMode} = require './avail/availability-mode' {AvailabilityReferences} = require './avail/availability-references' {SchemaQuery} = require './schema/schema-query' {SchemaContext} = require './schema/schema-context' {SchemaFormat} = require './schema/schema-format' {Service} = require './service/service' {services} = require './service/service' {UrlGenerator} = require './utils/url-generator' {ApiVersion} = require './utils/api-version' {ApiResources} = require './utils/api-version' SdmxPatterns = require './utils/sdmx-patterns' promise = require 'es6-promise' promise.polyfill() fetch = require 'isomorphic-fetch' userAgent = 'sdmx-rest4js (https://github.com/sosna/sdmx-rest4js)' checkStatus = (query, response) -> throw ReferenceError 'Not a valid response' unless response code = response.status unless 100 <= code < 400 or (code is 404 and query.updatedAfter) throw RangeError "Request failed with error code #{code}" isFormat = (input, expected) -> out = false for v in Object.values expected out = true if v is input out isDataFormat = (format) -> isFormat(format, DataFormat) isMetadataFormat = (format) -> isFormat(format, MetadataFormat) isSchemaFormat = (format) -> isFormat(format, SchemaFormat) isGenericFormat = (format) -> formats = [ 'application/xml' 'application/json' 'text/csv' 'text/xml' ] format in formats isRequestedFormat = (requested, received) -> requested.indexOf(received) > -1 checkMediaType = (requested, response) -> fmt = response.headers.get('content-type') fmt = if fmt then fmt.replace /; version=/, ';version=' else fmt unless isDataFormat(fmt) or \ isMetadataFormat(fmt) or \ isGenericFormat(fmt) or \ isSchemaFormat(fmt) throw RangeError "Not an SDMX format: #{fmt}" unless isRequestedFormat(requested, fmt) throw RangeError "Wrong format: requested #{requested} but got #{fmt}" addHeaders = (opts, s, type) -> opts ?= {} headers = {} headers[key.toLowerCase()] = opts.headers[key] for own key of opts.headers unless headers.accept headers.accept = switch type when 'data' then s.format when 'structure' then s.structureFormat when 'schema' then s.schemaFormat headers.accept = '*/*' unless headers.accept headers['user-agent'] = userAgent unless headers['user-agent'] opts.headers = headers opts guessService = (u) -> s = (Service[k] for own k of Service when u.indexOf(Service[k].url) > -1) return s[0] ? {} # # Get an SDMX 2.1 RESTful web service against which queries can be executed. # # This library offers a few predefined services, which you can access using the # service identifier. # # @example Get a predefined service # sdmxrest.getService('ECB') # # In case the service to be accessed is not yet predefined, an object with the # information necessary to create the service can be passed as parameter. # # @example Create a service # sdmxrest.getService({url: 'http://ws-entry-point'}) # # The expected properties for the object are: # - *url* - the entry point of the SDMX 2.1 RESTful web service # - *api* (optional) - the version of the SDMX 2.1 RESTful API supported by # the service. If not supplied, it will default to the most recent version of # the SDMX RESTful API # - *id* (optional) - an identifier for the web service # - *name* (optional) - a label for the web service # # @param [Object|String] input the ID of a predefined service or an object with # the information about the service to be instantiated # # @throw an error in case a) a string is supplied and it is not the ID of a # predefined service or b) an object is supplied and it does not contain a # valid *url* property. # getService = (input) -> if typeof input is 'string' throw ReferenceError "#{input} is not in the list of predefined services" \ unless Service[input] Service[input] else if input instanceof Object and \ Object.prototype.toString.call(input) is '[object Object]' Service.from input else throw TypeError "Invalid type of #{input}. Expected an object or a string" # # Get an SDMX 2.1 RESTful data query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *firstNObs* (optional) - the number of observations to be returned, # starting from the first observation # - *lastNObs* (optional) - the number of observations to be returned, # starting from the last observation # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level (default TIME_PERIOD). # - *detail* (optional) - the desired amount of information to be returned # (default: full). # - *history* (optional) - Whether previous versions of the data should be # returned (default: false). # # @example Create a query for all data belonging to the EXR dataflow # sdmxrest.getDataQuery({flow: 'EXR'}) # # @example Create a query for EXR data, matching values A and Q for the 1st # dimension, any value for the 2nd dimension, EUR, SP00 and A for the 3rd, 4th # and 5th dimensions respectively # sdmxrest.getDataQuery({flow: 'EXR', key: '<KEY>'}) # # @example Create a query for the last observation of the EXR data matching the # supplied key # sdmxrest.getDataQuery({flow: 'EXR', key: '<KEY>', lastNObs: 1}) # # @example Create a query to get what has changed for the matching data since # the supplied point in time # sdmxrest.getDataQuery({flow: 'EXR', key: '<KEY>', # updatedAfter: '2016-03-17T14:38:00Z'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getDataQuery = (input) -> return DataQuery.from input # # Get an SDMX 2.1 RESTful metadata query. # # The expected properties (and their default values) are: # - *resource*: **Mandatory** - the type of structural metadata to be returned # - *agency* (optional) - the agency maintaining the metadata to be returned # (default: all) # - *id* (optional) - the id of the metadata to be returned (default: all) # - *version* (optional) - the version of the metadata to be returned # (default: latest) # - *item* (optional) - for item schemes query, the id of the item to be # returned (default: all) # - *detail* (optional) - the desired amount of information to be returned # (default: full) # - *references* (optional) - whether to return the artefacts referenced by, # or that use, the metadata to be returned (default: none) # # @example Create a query for all codelists maintained by the ECB # sdmxrest.getMetadataQuery({resource: 'codelist', agency: 'ECB'}) # # @example Create a query for the BOP data structure maintained by the IMF, # along with all the codelists and concepts used in the data structure # sdmxrest.getMetadataQuery({resource: 'datastructure', agency: 'IMF', # id: 'BOP', references: 'descendants'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory resource is not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getMetadataQuery = (input) -> return MetadataQuery.from input # # Get an SDMX 2.1 RESTful availability query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *component* (optional) - the id of the dimension for which to obtain # availability information (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *mode* (optional) - the possible processing modes (default: exact) # - *references* (optional) - the references to be returned (default: none) # # @example Create an availability query for the EXR dataflow # sdmxrest.getAvailabilityQuery({flow: 'EXR'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getAvailabilityQuery = (input) -> return AvailabilityQuery.from input # # Get an SDMX 2.1 RESTful schema query. # # The expected properties (and their default values) are: # - *context*: **Mandatory** - the constraints that need to be taken into # account, when generating the schema # - *agency*: **Mandatory** - the maintenance agency # - *id*: **Mandatory** - the artefact id # - *version* (optional) - the artefact version (default: latest) # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level. # - *explicit* (optional) - For cross-sectional data validation, indicates # whether observations are strongly typed (default: false) # # @example Create a schema query for the CBS schema # sdmxrest.getSchemaQuery({context: 'dataflow', 'id': 'CBS', 'agency': 'BIS'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory properties are not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getSchemaQuery = (input) -> return SchemaQuery.from input # # Get the SDMX 2.1 RESTful URL representing the query to be executed against the # supplied service. # # @example Get the URL representing the query to be executed against the # supplied service # sdmxrest.getUrl({flow: 'EXR', key: '<KEY>'}, 'ECB') # # @param [Object] query the query to be executed # @param [Object|String] service the service against which the query should be # executed # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # getUrl = (query, service) -> throw ReferenceError 'Not a valid service' unless service throw ReferenceError 'Not a valid query' unless query s = getService service q = if (query.mode? or \ (query.flow? and query.references?) or \ (query.flow? and query.component?)) getAvailabilityQuery query else if query.flow? getDataQuery query else if query.resource? getMetadataQuery query else if query.context? getSchemaQuery query throw Error 'Not a valid query' unless q return new UrlGenerator().getUrl q, s # # Executes the supplied query against the supplied service and returns a # Promise. # # At the difference with the request() function, request2() will # include the response headers and additional information such as the status. # # @see #request for additional information about the required parameters. # request2 = (params...) -> q = params[0] s = if typeof q is 'string' then guessService q else getService params[1] u = if typeof q is 'string' then q else getUrl q, s o = if typeof q is 'string' then params[1] else params[2] t = null if u.indexOf('/data/') > -1 t = 'data' else if u.indexOf('/schema/') > -1 t = 'schema' else t = 'structure' requestOptions = addHeaders o, s, t fetch(u, requestOptions) .then((response) -> response) # # Executes the supplied query against the supplied service and returns a # Promise. # # The returned Promise should be handled using the *then* and *catch* methods # offered by a Promise. # # @example Executes the supplied query against the supplied service # sdmxrest.request({flow: 'EXR', key: '<KEY>'}, 'ECB') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Executes the supplied query against the supplied service, asking the # service to return a compressed SDMX-JSON message. # sdmxrest.request({flow: 'EXR', key: '<KEY>'}, 'ECB', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # In case you already have an SDMX 2.1 RESTful query string, you can also use it # with execute(). # # @example Fetches the supplied URL # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Fetches the supplied URL, asking the service to return a compressed # SDMX-JSON message # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @param [Object|String] query the query to be executed # @param [Object|String] service the service against which the query should be # executed. This should not be set in case an SDMX 2.1 query string is passed # as 1st parameter # @param [Object] opts additional options for the request. See the whatwg fetch # specification for additional information. # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # request = (params...) -> request2(params...).then((response) -> checkStatus params[0], response response.text()) module.exports = getService: getService services: services getDataQuery: getDataQuery getMetadataQuery: getMetadataQuery getAvailabilityQuery: getAvailabilityQuery getSchemaQuery: getSchemaQuery getUrl: getUrl request: request request2: request2 checkStatus: checkStatus checkMediaType: checkMediaType data: DataFormat: DataFormat DataDetail: DataDetail metadata: MetadataFormat: MetadataFormat MetadataDetail: MetadataDetail MetadataReferences: MetadataReferences MetadataType: MetadataType availability: AvailabilityMode: AvailabilityMode AvailabilityReferences: AvailabilityReferences utils: ApiVersion: ApiVersion ApiResources: ApiResources SdmxPatterns: SdmxPatterns schema: SchemaContext: SchemaContext SchemaFormat: SchemaFormat
true
{DataQuery} = require './data/data-query' {DataFormat} = require './data/data-format' {DataDetail} = require './data/data-detail' {MetadataQuery} = require './metadata/metadata-query' {MetadataFormat} = require './metadata/metadata-format' {MetadataDetail} = require './metadata/metadata-detail' {MetadataReferences} = require './metadata/metadata-references' {MetadataType} = require './metadata/metadata-type' {AvailabilityQuery} = require './avail/availability-query' {AvailabilityMode} = require './avail/availability-mode' {AvailabilityReferences} = require './avail/availability-references' {SchemaQuery} = require './schema/schema-query' {SchemaContext} = require './schema/schema-context' {SchemaFormat} = require './schema/schema-format' {Service} = require './service/service' {services} = require './service/service' {UrlGenerator} = require './utils/url-generator' {ApiVersion} = require './utils/api-version' {ApiResources} = require './utils/api-version' SdmxPatterns = require './utils/sdmx-patterns' promise = require 'es6-promise' promise.polyfill() fetch = require 'isomorphic-fetch' userAgent = 'sdmx-rest4js (https://github.com/sosna/sdmx-rest4js)' checkStatus = (query, response) -> throw ReferenceError 'Not a valid response' unless response code = response.status unless 100 <= code < 400 or (code is 404 and query.updatedAfter) throw RangeError "Request failed with error code #{code}" isFormat = (input, expected) -> out = false for v in Object.values expected out = true if v is input out isDataFormat = (format) -> isFormat(format, DataFormat) isMetadataFormat = (format) -> isFormat(format, MetadataFormat) isSchemaFormat = (format) -> isFormat(format, SchemaFormat) isGenericFormat = (format) -> formats = [ 'application/xml' 'application/json' 'text/csv' 'text/xml' ] format in formats isRequestedFormat = (requested, received) -> requested.indexOf(received) > -1 checkMediaType = (requested, response) -> fmt = response.headers.get('content-type') fmt = if fmt then fmt.replace /; version=/, ';version=' else fmt unless isDataFormat(fmt) or \ isMetadataFormat(fmt) or \ isGenericFormat(fmt) or \ isSchemaFormat(fmt) throw RangeError "Not an SDMX format: #{fmt}" unless isRequestedFormat(requested, fmt) throw RangeError "Wrong format: requested #{requested} but got #{fmt}" addHeaders = (opts, s, type) -> opts ?= {} headers = {} headers[key.toLowerCase()] = opts.headers[key] for own key of opts.headers unless headers.accept headers.accept = switch type when 'data' then s.format when 'structure' then s.structureFormat when 'schema' then s.schemaFormat headers.accept = '*/*' unless headers.accept headers['user-agent'] = userAgent unless headers['user-agent'] opts.headers = headers opts guessService = (u) -> s = (Service[k] for own k of Service when u.indexOf(Service[k].url) > -1) return s[0] ? {} # # Get an SDMX 2.1 RESTful web service against which queries can be executed. # # This library offers a few predefined services, which you can access using the # service identifier. # # @example Get a predefined service # sdmxrest.getService('ECB') # # In case the service to be accessed is not yet predefined, an object with the # information necessary to create the service can be passed as parameter. # # @example Create a service # sdmxrest.getService({url: 'http://ws-entry-point'}) # # The expected properties for the object are: # - *url* - the entry point of the SDMX 2.1 RESTful web service # - *api* (optional) - the version of the SDMX 2.1 RESTful API supported by # the service. If not supplied, it will default to the most recent version of # the SDMX RESTful API # - *id* (optional) - an identifier for the web service # - *name* (optional) - a label for the web service # # @param [Object|String] input the ID of a predefined service or an object with # the information about the service to be instantiated # # @throw an error in case a) a string is supplied and it is not the ID of a # predefined service or b) an object is supplied and it does not contain a # valid *url* property. # getService = (input) -> if typeof input is 'string' throw ReferenceError "#{input} is not in the list of predefined services" \ unless Service[input] Service[input] else if input instanceof Object and \ Object.prototype.toString.call(input) is '[object Object]' Service.from input else throw TypeError "Invalid type of #{input}. Expected an object or a string" # # Get an SDMX 2.1 RESTful data query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *firstNObs* (optional) - the number of observations to be returned, # starting from the first observation # - *lastNObs* (optional) - the number of observations to be returned, # starting from the last observation # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level (default TIME_PERIOD). # - *detail* (optional) - the desired amount of information to be returned # (default: full). # - *history* (optional) - Whether previous versions of the data should be # returned (default: false). # # @example Create a query for all data belonging to the EXR dataflow # sdmxrest.getDataQuery({flow: 'EXR'}) # # @example Create a query for EXR data, matching values A and Q for the 1st # dimension, any value for the 2nd dimension, EUR, SP00 and A for the 3rd, 4th # and 5th dimensions respectively # sdmxrest.getDataQuery({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'}) # # @example Create a query for the last observation of the EXR data matching the # supplied key # sdmxrest.getDataQuery({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI', lastNObs: 1}) # # @example Create a query to get what has changed for the matching data since # the supplied point in time # sdmxrest.getDataQuery({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI', # updatedAfter: '2016-03-17T14:38:00Z'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getDataQuery = (input) -> return DataQuery.from input # # Get an SDMX 2.1 RESTful metadata query. # # The expected properties (and their default values) are: # - *resource*: **Mandatory** - the type of structural metadata to be returned # - *agency* (optional) - the agency maintaining the metadata to be returned # (default: all) # - *id* (optional) - the id of the metadata to be returned (default: all) # - *version* (optional) - the version of the metadata to be returned # (default: latest) # - *item* (optional) - for item schemes query, the id of the item to be # returned (default: all) # - *detail* (optional) - the desired amount of information to be returned # (default: full) # - *references* (optional) - whether to return the artefacts referenced by, # or that use, the metadata to be returned (default: none) # # @example Create a query for all codelists maintained by the ECB # sdmxrest.getMetadataQuery({resource: 'codelist', agency: 'ECB'}) # # @example Create a query for the BOP data structure maintained by the IMF, # along with all the codelists and concepts used in the data structure # sdmxrest.getMetadataQuery({resource: 'datastructure', agency: 'IMF', # id: 'BOP', references: 'descendants'}) # # @param [Object] input an object with the desired filters for the query # # @throw an error in case a) the mandatory resource is not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getMetadataQuery = (input) -> return MetadataQuery.from input # # Get an SDMX 2.1 RESTful availability query. # # The expected properties (and their default values) are: # - *flow*: **Mandatory** - the id of the dataflow of the data to be returned # - *key* (optional) - the key of the data to be returned (default: all) # - *provider* (optional) - the provider of the data (default: all) # - *component* (optional) - the id of the dimension for which to obtain # availability information (default: all) # - *start* (optional) - the start period for which data should be returned # - *end* (optional) - the end period for which data should be returned # - *updatedAfter* (optional) - instructs the service to return what has # changed since the supplied time stamp. # - *mode* (optional) - the possible processing modes (default: exact) # - *references* (optional) - the references to be returned (default: none) # # @example Create an availability query for the EXR dataflow # sdmxrest.getAvailabilityQuery({flow: 'EXR'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory flow is not supplied or b) a value # not compliant with the SDMX 2.1 RESTful specification is supplied for one of # the properties. # getAvailabilityQuery = (input) -> return AvailabilityQuery.from input # # Get an SDMX 2.1 RESTful schema query. # # The expected properties (and their default values) are: # - *context*: **Mandatory** - the constraints that need to be taken into # account, when generating the schema # - *agency*: **Mandatory** - the maintenance agency # - *id*: **Mandatory** - the artefact id # - *version* (optional) - the artefact version (default: latest) # - *obsDimension* (optional) - the ID of the dimension to be attached at the # observation level. # - *explicit* (optional) - For cross-sectional data validation, indicates # whether observations are strongly typed (default: false) # # @example Create a schema query for the CBS schema # sdmxrest.getSchemaQuery({context: 'dataflow', 'id': 'CBS', 'agency': 'BIS'}) # # @param [Object] input an object with the desired characteristics of the query # # @throw an error in case a) the mandatory properties are not supplied or # b) a value not compliant with the SDMX 2.1 RESTful specification is supplied # for one of the properties. # getSchemaQuery = (input) -> return SchemaQuery.from input # # Get the SDMX 2.1 RESTful URL representing the query to be executed against the # supplied service. # # @example Get the URL representing the query to be executed against the # supplied service # sdmxrest.getUrl({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'}, 'ECB') # # @param [Object] query the query to be executed # @param [Object|String] service the service against which the query should be # executed # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # getUrl = (query, service) -> throw ReferenceError 'Not a valid service' unless service throw ReferenceError 'Not a valid query' unless query s = getService service q = if (query.mode? or \ (query.flow? and query.references?) or \ (query.flow? and query.component?)) getAvailabilityQuery query else if query.flow? getDataQuery query else if query.resource? getMetadataQuery query else if query.context? getSchemaQuery query throw Error 'Not a valid query' unless q return new UrlGenerator().getUrl q, s # # Executes the supplied query against the supplied service and returns a # Promise. # # At the difference with the request() function, request2() will # include the response headers and additional information such as the status. # # @see #request for additional information about the required parameters. # request2 = (params...) -> q = params[0] s = if typeof q is 'string' then guessService q else getService params[1] u = if typeof q is 'string' then q else getUrl q, s o = if typeof q is 'string' then params[1] else params[2] t = null if u.indexOf('/data/') > -1 t = 'data' else if u.indexOf('/schema/') > -1 t = 'schema' else t = 'structure' requestOptions = addHeaders o, s, t fetch(u, requestOptions) .then((response) -> response) # # Executes the supplied query against the supplied service and returns a # Promise. # # The returned Promise should be handled using the *then* and *catch* methods # offered by a Promise. # # @example Executes the supplied query against the supplied service # sdmxrest.request({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'}, 'ECB') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Executes the supplied query against the supplied service, asking the # service to return a compressed SDMX-JSON message. # sdmxrest.request({flow: 'EXR', key: 'PI:KEY:<KEY>END_PI'}, 'ECB', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # In case you already have an SDMX 2.1 RESTful query string, you can also use it # with execute(). # # @example Fetches the supplied URL # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR') # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @example Fetches the supplied URL, asking the service to return a compressed # SDMX-JSON message # sdmxrest.request('http://sdw-wsrest.ecb.europa.eu/service/data/EXR', # {headers: {accept: DataFormat.SDMX_JSON, accept-encoding: "gzip"}}) # .then(function(data) {console.log(data);}) # .catch(function(error) {console.log(error);}); # # @param [Object|String] query the query to be executed # @param [Object|String] service the service against which the query should be # executed. This should not be set in case an SDMX 2.1 query string is passed # as 1st parameter # @param [Object] opts additional options for the request. See the whatwg fetch # specification for additional information. # # @throw an error in case the query and/or the service are not valid. # # @see #getDataQuery # @see #getMetadataQuery # @see #getService # request = (params...) -> request2(params...).then((response) -> checkStatus params[0], response response.text()) module.exports = getService: getService services: services getDataQuery: getDataQuery getMetadataQuery: getMetadataQuery getAvailabilityQuery: getAvailabilityQuery getSchemaQuery: getSchemaQuery getUrl: getUrl request: request request2: request2 checkStatus: checkStatus checkMediaType: checkMediaType data: DataFormat: DataFormat DataDetail: DataDetail metadata: MetadataFormat: MetadataFormat MetadataDetail: MetadataDetail MetadataReferences: MetadataReferences MetadataType: MetadataType availability: AvailabilityMode: AvailabilityMode AvailabilityReferences: AvailabilityReferences utils: ApiVersion: ApiVersion ApiResources: ApiResources SdmxPatterns: SdmxPatterns schema: SchemaContext: SchemaContext SchemaFormat: SchemaFormat
[ { "context": "de headers allcaps prude plaintext\n#\n# Author:\n# yves trublin\n\nmodule.exports = (robot) ->\n robot.hear /lorem(", "end": 310, "score": 0.9990768432617188, "start": 298, "tag": "NAME", "value": "yves trublin" } ]
src/lorem-ipsum.coffee
PHSDigitalAgency/hubot-loremipsum
0
# Description: # Generate Lorem Ipsum from loripsum.net API # # Dependencies: # None # # Configuration: # None # # Commands: # hubot lorem - Generate Lorem Ipsum - eg: lorem (integer) short|medium|long|verylong decorate link ul ol dl bq code headers allcaps prude plaintext # # Author: # yves trublin module.exports = (robot) -> robot.hear /lorem( ipsum)? (.*)$/i, (msg) -> args = encodeURIComponent(msg.match[2]).split("%20").join("/") robot.http("http://loripsum.net/api/#{args}") .get() (err, res, body) -> msg.send "#{body}"
213708
# Description: # Generate Lorem Ipsum from loripsum.net API # # Dependencies: # None # # Configuration: # None # # Commands: # hubot lorem - Generate Lorem Ipsum - eg: lorem (integer) short|medium|long|verylong decorate link ul ol dl bq code headers allcaps prude plaintext # # Author: # <NAME> module.exports = (robot) -> robot.hear /lorem( ipsum)? (.*)$/i, (msg) -> args = encodeURIComponent(msg.match[2]).split("%20").join("/") robot.http("http://loripsum.net/api/#{args}") .get() (err, res, body) -> msg.send "#{body}"
true
# Description: # Generate Lorem Ipsum from loripsum.net API # # Dependencies: # None # # Configuration: # None # # Commands: # hubot lorem - Generate Lorem Ipsum - eg: lorem (integer) short|medium|long|verylong decorate link ul ol dl bq code headers allcaps prude plaintext # # Author: # PI:NAME:<NAME>END_PI module.exports = (robot) -> robot.hear /lorem( ipsum)? (.*)$/i, (msg) -> args = encodeURIComponent(msg.match[2]).split("%20").join("/") robot.http("http://loripsum.net/api/#{args}") .get() (err, res, body) -> msg.send "#{body}"
[ { "context": "ync @OAUTH2_REDEEM_URL, data,\n username: @OAUTH2_CLIENT_ID\n password: @OAUTH2_CLIENT_SECRET", "end": 2117, "score": 0.5682895183563232, "start": 2112, "tag": "USERNAME", "value": "AUTH2" }, { "context": " username: @OAUTH2_CLIENT_ID\n password...
api/services/provider.coffee
twhtanghk/oauth2_code
0
_ = require 'lodash' uuid = require 'node-uuid' url = require 'url' Promise = require 'bluebird' http = Promise.promisifyAll require 'needle' class Provider constructor: (opts = sails.config.oauth2) -> _.extend @, _.pick opts, [ 'OAUTH2_CLIENT_ID' 'OAUTH2_CLIENT_SECRET' 'OAUTH2_SCOPE' 'OAUTH2_LOGIN_URL' 'OAUTH2_REDEEM_URL' 'OAUTH2_VALIDATE_URL' 'OAUTH2_CALLBACK_URL' ] # promise to return authenticated user or null if forwarded to oauth2 provider isAuth: (req, res) -> path = url.parse(req.url).pathname switch true when path == '/oauth2/sign_in' req.session.user = null req.session.nextUrl = '/' @login req, res when path == '/oauth2/start' req.session.nextUrl = req.url @login req, res when path == '/oauth2/callback' @redeem req, res else # forward to upstream req.session.nextUrl = req.url @login req, res .then (user) => if user @afterAuth req user # promise to return current login user or null if forwarded to oauth2 provider login: (req, res) -> user = req.session.user if user return Promise.resolve user req.session.state = uuid() path = _.extend url.parse(@OAUTH2_LOGIN_URL), query: response_type: 'code' client_id: @OAUTH2_CLIENT_ID redirect_uri: @OAUTH2_CALLBACK_URL scope: @OAUTH2_SCOPE state: req.session.state res.redirect url.format path Promise.resolve() # promise to redirect to nextUrl when user starts authentication from if # 1. success in making token request # 2. success in verifying user # 3. redirect ot nextUrl redeem: (req, res) -> if req.query.state != req.session.state return Promise.reject 'oauth2 state mismatch' data = grant_type: 'authorization_code' code: req.query.code redirect_uri: @OAUTH2_CALLBACK_URL client_id: @OAUTH2_CLIENT_ID http .postAsync @OAUTH2_REDEEM_URL, data, username: @OAUTH2_CLIENT_ID password: @OAUTH2_CLIENT_SECRET accept: 'application/json' .then @token .then @validate .then (user) -> req.session.user = user res.redirect req.session.nextUrl # promise to return user by verifying token via oauth2 provider validate: (token) => http .getAsync @OAUTH2_VALIDATE_URL, headers: Authorization: "Bearer #{token}" .then @user .then @email .then (user) -> _.extend user, token: token # provider specific method to get token from oauth2 provider response token: (res) -> if res.body.error return Promise.reject res.body.error res.body.access_token # provider specific method to get user details (name, email, url) from oauth2 provider response user: (res) -> if res.body.error return Promise.reject res.body.error res.body.user # validate if user email matched the specified pattern email: (user) -> matched = _.some sails.config.email, (pattern) -> new RegExp pattern .test user.email if not matched return Promise.reject "#{user.email} not matched with defined email domain" user # customized method to pass user details after user authenticated afterAuth: (req) -> req.headers['X-Forwarded-User'] = req.session.user.username req.headers['X-Forwarded-Email'] = req.session.user.email req.headers['X-Forwarded-Access-Token'] = req.session.user.token module.exports = Provider
159158
_ = require 'lodash' uuid = require 'node-uuid' url = require 'url' Promise = require 'bluebird' http = Promise.promisifyAll require 'needle' class Provider constructor: (opts = sails.config.oauth2) -> _.extend @, _.pick opts, [ 'OAUTH2_CLIENT_ID' 'OAUTH2_CLIENT_SECRET' 'OAUTH2_SCOPE' 'OAUTH2_LOGIN_URL' 'OAUTH2_REDEEM_URL' 'OAUTH2_VALIDATE_URL' 'OAUTH2_CALLBACK_URL' ] # promise to return authenticated user or null if forwarded to oauth2 provider isAuth: (req, res) -> path = url.parse(req.url).pathname switch true when path == '/oauth2/sign_in' req.session.user = null req.session.nextUrl = '/' @login req, res when path == '/oauth2/start' req.session.nextUrl = req.url @login req, res when path == '/oauth2/callback' @redeem req, res else # forward to upstream req.session.nextUrl = req.url @login req, res .then (user) => if user @afterAuth req user # promise to return current login user or null if forwarded to oauth2 provider login: (req, res) -> user = req.session.user if user return Promise.resolve user req.session.state = uuid() path = _.extend url.parse(@OAUTH2_LOGIN_URL), query: response_type: 'code' client_id: @OAUTH2_CLIENT_ID redirect_uri: @OAUTH2_CALLBACK_URL scope: @OAUTH2_SCOPE state: req.session.state res.redirect url.format path Promise.resolve() # promise to redirect to nextUrl when user starts authentication from if # 1. success in making token request # 2. success in verifying user # 3. redirect ot nextUrl redeem: (req, res) -> if req.query.state != req.session.state return Promise.reject 'oauth2 state mismatch' data = grant_type: 'authorization_code' code: req.query.code redirect_uri: @OAUTH2_CALLBACK_URL client_id: @OAUTH2_CLIENT_ID http .postAsync @OAUTH2_REDEEM_URL, data, username: @OAUTH2_CLIENT_ID password: <PASSWORD> accept: 'application/json' .then @token .then @validate .then (user) -> req.session.user = user res.redirect req.session.nextUrl # promise to return user by verifying token via oauth2 provider validate: (token) => http .getAsync @OAUTH2_VALIDATE_URL, headers: Authorization: "Bearer #{token}" .then @user .then @email .then (user) -> _.extend user, token: token # provider specific method to get token from oauth2 provider response token: (res) -> if res.body.error return Promise.reject res.body.error res.body.access_token # provider specific method to get user details (name, email, url) from oauth2 provider response user: (res) -> if res.body.error return Promise.reject res.body.error res.body.user # validate if user email matched the specified pattern email: (user) -> matched = _.some sails.config.email, (pattern) -> new RegExp pattern .test user.email if not matched return Promise.reject "#{user.email} not matched with defined email domain" user # customized method to pass user details after user authenticated afterAuth: (req) -> req.headers['X-Forwarded-User'] = req.session.user.username req.headers['X-Forwarded-Email'] = req.session.user.email req.headers['X-Forwarded-Access-Token'] = req.session.user.token module.exports = Provider
true
_ = require 'lodash' uuid = require 'node-uuid' url = require 'url' Promise = require 'bluebird' http = Promise.promisifyAll require 'needle' class Provider constructor: (opts = sails.config.oauth2) -> _.extend @, _.pick opts, [ 'OAUTH2_CLIENT_ID' 'OAUTH2_CLIENT_SECRET' 'OAUTH2_SCOPE' 'OAUTH2_LOGIN_URL' 'OAUTH2_REDEEM_URL' 'OAUTH2_VALIDATE_URL' 'OAUTH2_CALLBACK_URL' ] # promise to return authenticated user or null if forwarded to oauth2 provider isAuth: (req, res) -> path = url.parse(req.url).pathname switch true when path == '/oauth2/sign_in' req.session.user = null req.session.nextUrl = '/' @login req, res when path == '/oauth2/start' req.session.nextUrl = req.url @login req, res when path == '/oauth2/callback' @redeem req, res else # forward to upstream req.session.nextUrl = req.url @login req, res .then (user) => if user @afterAuth req user # promise to return current login user or null if forwarded to oauth2 provider login: (req, res) -> user = req.session.user if user return Promise.resolve user req.session.state = uuid() path = _.extend url.parse(@OAUTH2_LOGIN_URL), query: response_type: 'code' client_id: @OAUTH2_CLIENT_ID redirect_uri: @OAUTH2_CALLBACK_URL scope: @OAUTH2_SCOPE state: req.session.state res.redirect url.format path Promise.resolve() # promise to redirect to nextUrl when user starts authentication from if # 1. success in making token request # 2. success in verifying user # 3. redirect ot nextUrl redeem: (req, res) -> if req.query.state != req.session.state return Promise.reject 'oauth2 state mismatch' data = grant_type: 'authorization_code' code: req.query.code redirect_uri: @OAUTH2_CALLBACK_URL client_id: @OAUTH2_CLIENT_ID http .postAsync @OAUTH2_REDEEM_URL, data, username: @OAUTH2_CLIENT_ID password: PI:PASSWORD:<PASSWORD>END_PI accept: 'application/json' .then @token .then @validate .then (user) -> req.session.user = user res.redirect req.session.nextUrl # promise to return user by verifying token via oauth2 provider validate: (token) => http .getAsync @OAUTH2_VALIDATE_URL, headers: Authorization: "Bearer #{token}" .then @user .then @email .then (user) -> _.extend user, token: token # provider specific method to get token from oauth2 provider response token: (res) -> if res.body.error return Promise.reject res.body.error res.body.access_token # provider specific method to get user details (name, email, url) from oauth2 provider response user: (res) -> if res.body.error return Promise.reject res.body.error res.body.user # validate if user email matched the specified pattern email: (user) -> matched = _.some sails.config.email, (pattern) -> new RegExp pattern .test user.email if not matched return Promise.reject "#{user.email} not matched with defined email domain" user # customized method to pass user details after user authenticated afterAuth: (req) -> req.headers['X-Forwarded-User'] = req.session.user.username req.headers['X-Forwarded-Email'] = req.session.user.email req.headers['X-Forwarded-Access-Token'] = req.session.user.token module.exports = Provider
[ { "context": "empty()\n passed = yes\n pool.set [{ name: 'bob' }]\n expect(passed).to.be.true()\n \n it 'shou", "end": 483, "score": 0.9985114336013794, "start": 480, "tag": "NAME", "value": "bob" }, { "context": "\n func added, removed\n pool.set [{ name: 'bob' ...
test/diff-pool.coffee
metocean/redwire-consul
0
expect = require('chai').expect DiffPool = require '../src/diff-pool' describe 'Diff Pool', -> it 'should handle an empty array', -> passed = yes pool = new DiffPool (added, removed) -> passed = no pool.set [] expect(passed).to.be.true() it 'should pass new items in added', -> passed = no pool = new DiffPool (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.be.empty() passed = yes pool.set [{ name: 'bob' }] expect(passed).to.be.true() it 'should pass removed items in removed', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'bob' }] passed = no func = (added, removed) -> expect(added).to.be.empty() expect(removed).to.have.length.of 1 passed = yes pool.set [] expect(passed).to.be.true() it 'should not callback on duplicate items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'bob' }] passed = yes func = (added, removed) -> passed = no pool.set [{ name: 'bob' }] expect(passed).to.be.true() it 'should handle added items at the same time as removed items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'bob' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: 'sue' }] expect(passed).to.be.true() it 'should handle more than one diff in a row', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'bob' }, { name: 'sue' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: 'sue' }, { name: 'mary' }] expect(passed).to.be.true() passed = no pool.set [{ name: 'bob' }, { name: 'mary' }] expect(passed).to.be.true() it 'should keep members updated', -> pool = new DiffPool -> pool.set [{ name: 'bob' }, { name: 'sue' }] expect(pool.members()).to.have.length.of 2 pool.set [{ name: 'bob' }, { name: 'sue' }, { name: 'mary' }] expect(pool.members()).to.have.length.of 3 pool.set [] expect(pool.members()).to.be.empty()
24787
expect = require('chai').expect DiffPool = require '../src/diff-pool' describe 'Diff Pool', -> it 'should handle an empty array', -> passed = yes pool = new DiffPool (added, removed) -> passed = no pool.set [] expect(passed).to.be.true() it 'should pass new items in added', -> passed = no pool = new DiffPool (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.be.empty() passed = yes pool.set [{ name: '<NAME>' }] expect(passed).to.be.true() it 'should pass removed items in removed', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: '<NAME>' }] passed = no func = (added, removed) -> expect(added).to.be.empty() expect(removed).to.have.length.of 1 passed = yes pool.set [] expect(passed).to.be.true() it 'should not callback on duplicate items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: '<NAME>' }] passed = yes func = (added, removed) -> passed = no pool.set [{ name: '<NAME>' }] expect(passed).to.be.true() it 'should handle added items at the same time as removed items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: '<NAME>' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: '<NAME>' }] expect(passed).to.be.true() it 'should handle more than one diff in a row', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: '<NAME>' }, { name: '<NAME>' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: '<NAME>' }, { name: '<NAME>' }] expect(passed).to.be.true() passed = no pool.set [{ name: '<NAME>' }, { name: '<NAME>' }] expect(passed).to.be.true() it 'should keep members updated', -> pool = new DiffPool -> pool.set [{ name: '<NAME>' }, { name: '<NAME>' }] expect(pool.members()).to.have.length.of 2 pool.set [{ name: '<NAME>' }, { name: '<NAME>' }, { name: '<NAME>' }] expect(pool.members()).to.have.length.of 3 pool.set [] expect(pool.members()).to.be.empty()
true
expect = require('chai').expect DiffPool = require '../src/diff-pool' describe 'Diff Pool', -> it 'should handle an empty array', -> passed = yes pool = new DiffPool (added, removed) -> passed = no pool.set [] expect(passed).to.be.true() it 'should pass new items in added', -> passed = no pool = new DiffPool (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.be.empty() passed = yes pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] expect(passed).to.be.true() it 'should pass removed items in removed', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] passed = no func = (added, removed) -> expect(added).to.be.empty() expect(removed).to.have.length.of 1 passed = yes pool.set [] expect(passed).to.be.true() it 'should not callback on duplicate items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] passed = yes func = (added, removed) -> passed = no pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] expect(passed).to.be.true() it 'should handle added items at the same time as removed items', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: 'PI:NAME:<NAME>END_PI' }] expect(passed).to.be.true() it 'should handle more than one diff in a row', -> func = -> pool = new DiffPool (added, removed) -> func added, removed pool.set [{ name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }] passed = no func = (added, removed) -> expect(added).to.have.length.of 1 expect(removed).to.have.length.of 1 passed = yes pool.set [{ name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }] expect(passed).to.be.true() passed = no pool.set [{ name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }] expect(passed).to.be.true() it 'should keep members updated', -> pool = new DiffPool -> pool.set [{ name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }] expect(pool.members()).to.have.length.of 2 pool.set [{ name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }, { name: 'PI:NAME:<NAME>END_PI' }] expect(pool.members()).to.have.length.of 3 pool.set [] expect(pool.members()).to.be.empty()
[ { "context": "SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef'\n SettingsHelper.setCu", "end": 912, "score": 0.6074473857879639, "start": 906, "tag": "KEY", "value": "456789" }, { "context": "etCredentials 'foo@bar.baz', '0123456789abcdef0123456789...
spec/views/claim-core-view-spec.coffee
lukehoban/spark-dev
1
{WorkspaceView} = require 'atom' $ = require('atom').$ SettingsHelper = require '../../lib/utils/settings-helper' SparkStub = require('spark-dev-spec-stubs').spark spark = require 'spark' describe 'Claim Core View', -> activationPromise = null originalProfile = null sparkIde = null claimCoreView = null beforeEach -> atom.workspaceView = new WorkspaceView activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) -> sparkIde = mainModule sparkIde.claimCoreView = null originalProfile = SettingsHelper.getProfile() # For tests not to mess up our profile, we have to switch to test one... SettingsHelper.setProfile 'spark-dev-test' waitsForPromise -> activationPromise afterEach -> SettingsHelper.setProfile originalProfile describe '', -> beforeEach -> SettingsHelper.setCredentials 'foo@bar.baz', '0123456789abcdef0123456789abcdef' SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo' afterEach -> SettingsHelper.clearCurrentCore() SettingsHelper.clearCredentials() it 'checks if empty name would cause an error', -> SparkStub.stubSuccess spark, 'claimCore' sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '' spyOn claimCoreView, 'close' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(false) claimCoreView.trigger 'core:confirm' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(true) expect(claimCoreView.close).not.toHaveBeenCalled() sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '0123456789abcdef0123456789abcdef' spyOn claimCoreView, 'close' spyOn atom.workspaceView, 'trigger' spyOn SettingsHelper, 'setCurrentCore' claimCoreView.trigger 'core:confirm' waitsFor -> !claimCoreView.claimPromise runs -> expect(SettingsHelper.setCurrentCore).toHaveBeenCalled() expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('0123456789abcdef0123456789abcdef', null) expect(atom.workspaceView.trigger).toHaveBeenCalled() expect(atom.workspaceView.trigger.calls.length).toEqual(2) expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status') expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu') expect(claimCoreView.close).toHaveBeenCalled() jasmine.unspy claimCoreView, 'close' jasmine.unspy atom.workspaceView, 'trigger' jasmine.unspy SettingsHelper, 'setCurrentCore' claimCoreView.close()
161040
{WorkspaceView} = require 'atom' $ = require('atom').$ SettingsHelper = require '../../lib/utils/settings-helper' SparkStub = require('spark-dev-spec-stubs').spark spark = require 'spark' describe 'Claim Core View', -> activationPromise = null originalProfile = null sparkIde = null claimCoreView = null beforeEach -> atom.workspaceView = new WorkspaceView activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) -> sparkIde = mainModule sparkIde.claimCoreView = null originalProfile = SettingsHelper.getProfile() # For tests not to mess up our profile, we have to switch to test one... SettingsHelper.setProfile 'spark-dev-test' waitsForPromise -> activationPromise afterEach -> SettingsHelper.setProfile originalProfile describe '', -> beforeEach -> SettingsHelper.setCredentials 'foo@bar.baz', '0123<KEY>abcdef0123<KEY>' SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo' afterEach -> SettingsHelper.clearCurrentCore() SettingsHelper.clearCredentials() it 'checks if empty name would cause an error', -> SparkStub.stubSuccess spark, 'claimCore' sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '' spyOn claimCoreView, 'close' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(false) claimCoreView.trigger 'core:confirm' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(true) expect(claimCoreView.close).not.toHaveBeenCalled() sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '0123456789abcdef01234<KEY>9<KEY>' spyOn claimCoreView, 'close' spyOn atom.workspaceView, 'trigger' spyOn SettingsHelper, 'setCurrentCore' claimCoreView.trigger 'core:confirm' waitsFor -> !claimCoreView.claimPromise runs -> expect(SettingsHelper.setCurrentCore).toHaveBeenCalled() expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('0123456789abcdef0123456789abcdef', null) expect(atom.workspaceView.trigger).toHaveBeenCalled() expect(atom.workspaceView.trigger.calls.length).toEqual(2) expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status') expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu') expect(claimCoreView.close).toHaveBeenCalled() jasmine.unspy claimCoreView, 'close' jasmine.unspy atom.workspaceView, 'trigger' jasmine.unspy SettingsHelper, 'setCurrentCore' claimCoreView.close()
true
{WorkspaceView} = require 'atom' $ = require('atom').$ SettingsHelper = require '../../lib/utils/settings-helper' SparkStub = require('spark-dev-spec-stubs').spark spark = require 'spark' describe 'Claim Core View', -> activationPromise = null originalProfile = null sparkIde = null claimCoreView = null beforeEach -> atom.workspaceView = new WorkspaceView activationPromise = atom.packages.activatePackage('spark-dev').then ({mainModule}) -> sparkIde = mainModule sparkIde.claimCoreView = null originalProfile = SettingsHelper.getProfile() # For tests not to mess up our profile, we have to switch to test one... SettingsHelper.setProfile 'spark-dev-test' waitsForPromise -> activationPromise afterEach -> SettingsHelper.setProfile originalProfile describe '', -> beforeEach -> SettingsHelper.setCredentials 'foo@bar.baz', '0123PI:KEY:<KEY>END_PIabcdef0123PI:KEY:<KEY>END_PI' SettingsHelper.setCurrentCore '0123456789abcdef0123456789abcdef', 'Foo' afterEach -> SettingsHelper.clearCurrentCore() SettingsHelper.clearCredentials() it 'checks if empty name would cause an error', -> SparkStub.stubSuccess spark, 'claimCore' sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '' spyOn claimCoreView, 'close' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(false) claimCoreView.trigger 'core:confirm' expect(atom.workspaceView.find('#spark-dev-claim-core-view .editor:eq(0)').hasClass('editor-error')).toBe(true) expect(claimCoreView.close).not.toHaveBeenCalled() sparkIde.claimCore() claimCoreView = sparkIde.claimCoreView editor = claimCoreView.miniEditor.getEditor() editor.setText '0123456789abcdef01234PI:KEY:<KEY>END_PI9PI:KEY:<KEY>END_PI' spyOn claimCoreView, 'close' spyOn atom.workspaceView, 'trigger' spyOn SettingsHelper, 'setCurrentCore' claimCoreView.trigger 'core:confirm' waitsFor -> !claimCoreView.claimPromise runs -> expect(SettingsHelper.setCurrentCore).toHaveBeenCalled() expect(SettingsHelper.setCurrentCore).toHaveBeenCalledWith('0123456789abcdef0123456789abcdef', null) expect(atom.workspaceView.trigger).toHaveBeenCalled() expect(atom.workspaceView.trigger.calls.length).toEqual(2) expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-core-status') expect(atom.workspaceView.trigger).toHaveBeenCalledWith('spark-dev:update-menu') expect(claimCoreView.close).toHaveBeenCalled() jasmine.unspy claimCoreView, 'close' jasmine.unspy atom.workspaceView, 'trigger' jasmine.unspy SettingsHelper, 'setCurrentCore' claimCoreView.close()
[ { "context": " CleverStyle Music\n * @category app\n * @author Nazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright Copyright (c", "end": 85, "score": 0.9998961687088013, "start": 69, "tag": "NAME", "value": "Nazar Mokrynskyi" }, { "context": " * @category app\n * @author N...
js/ac.sound_processing.coffee
mariot/Klif-Mozika
0
###* * @package CleverStyle Music * @category app * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2014-2015, Nazar Mokrynskyi * @license MIT License, see license.txt ### window.AudioContext = AudioContext || webkitAudioContext music_settings = cs.music_settings cs.sound_processing = do -> frequencies_to_control = [32, 64, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] #kHz frequencies_types = ['lowshelf', 'lowshelf', 'lowshelf', 'peaking', 'peaking', 'peaking', 'peaking', 'highshelf', 'highshelf', 'highshelf'] gain_levels = music_settings.equalizer_gain_levels || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] create_equalizer = (audio) -> frequencies = [] audio.frequencies = frequencies for frequency, index in frequencies_to_control frequencies[index] = audio.context.createBiquadFilter() frequencies[index].frequency.value = frequency frequencies[index].type = frequencies_types[index] frequencies[index].gain.value = gain_levels[index] frequencies[index].Q.value = 1 audio.source.connect(frequencies[index]) audio.source = frequencies[index] return update_equalizer = (audio) -> frequencies = audio.frequencies for frequency, index in frequencies_to_control frequencies[index].gain.value = gain_levels[index] return reverb_impulse_responses_files = [ 'Block Inside' 'Cement Blocks' 'Chamber' 'Chateau de Logne, Outside' 'Derlon Sanctuary' 'Five Columns' 'Five Columns Long' 'Greek 7 Echo Hall' 'Hall' 'Highly Damped Large Room' 'In The Silo Revised' 'Inverse Room' 'Large Wide Echo Hall' 'Masonic Lodge' 'Musikvereinsaal' 'Narrow Bumpy Space' 'On a Star' 'Parking Garage' 'Plate' 'Rich Plate' 'Rich Split' 'Ruby Room' 'Scala Milan Opera Hall' 'St Nicolaes Church' 'Trig Room' 'Vocal Duo' ] reverb_impulse_response_current = music_settings.reverb_mode reverb_impulse_response_new = music_settings.reverb_mode reverb_impulse_response_load = (filename, callback) -> if !filename callback() return context = new AudioContext url = "/audio/reverb_impulse_responses/#{filename}.ogg" # Load buffer asynchronously request = new XMLHttpRequest() request.open('GET', url, true) request.responseType = 'blob' request.onload = -> file_reader = new FileReader(); file_reader.onload = -> # Asynchronously decode the audio file data in request.response context.decodeAudioData( @result (buffer) -> if !buffer callback() return callback(buffer) return ) file_reader.readAsArrayBuffer(request.response); return request.onerror = -> callback() request.send() return # Compressor for smoother sound peaks create_compressor = (audio) -> compressor = audio.context.createDynamicsCompressor() audio.compressor = compressor compressor.knee.value = 40 # [0..40] Range above threshold in dB where compression will be smoothly applied compressor.threshold.value = -10 # [-100..0] Threshold in dB about which compression will start compressor.ratio.value = 5 # [1..20] Specified number of dB over the threshold at input will become 1 dB on output audio.source.connect(compressor) audio.source = compressor return # Reverb for surround effect create_reverb = (audio) -> reverb = audio.context.createConvolver() audio.reverb = reverb setTimeout (-> reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> reverb.buffer = buffer ) ), 0 audio.source.connect(reverb) audio.source = reverb return update_reverb = (audio) -> if reverb_impulse_response_new == reverb_impulse_response_current return setTimeout (-> reverb_impulse_response_current = reverb_impulse_response_new reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> audio.reverb.buffer = buffer ) ), 0 add_to_element : (element) -> if music_settings.low_performance return audio = {} element.audio_processing = audio audio.context = new AudioContext audio.context.mozAudioChannelType = 'content' audio.source = audio.context.createMediaElementSource(unwrap(element)) create_reverb(audio) create_equalizer(audio) create_compressor(audio) audio.source.connect(audio.context.destination) update_element : (element) -> audio = element.audio_processing update_equalizer(audio) update_reverb(audio) get_gain_levels : -> gain_levels set_gain_levels : (new_gain_levels) -> gain_levels = new_gain_levels music_settings.equalizer_gain_levels = new_gain_levels cs.bus.trigger('sound-processing/update') get_reverb_mode : -> reverb_impulse_response_current get_reverb_modes : -> reverb_impulse_responses_files set_reverb_mode : (mode) -> reverb_impulse_response_new = mode music_settings.reverb_mode = mode cs.bus.trigger('sound-processing/update')
65897
###* * @package CleverStyle Music * @category app * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2014-2015, <NAME> * @license MIT License, see license.txt ### window.AudioContext = AudioContext || webkitAudioContext music_settings = cs.music_settings cs.sound_processing = do -> frequencies_to_control = [32, 64, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] #kHz frequencies_types = ['lowshelf', 'lowshelf', 'lowshelf', 'peaking', 'peaking', 'peaking', 'peaking', 'highshelf', 'highshelf', 'highshelf'] gain_levels = music_settings.equalizer_gain_levels || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] create_equalizer = (audio) -> frequencies = [] audio.frequencies = frequencies for frequency, index in frequencies_to_control frequencies[index] = audio.context.createBiquadFilter() frequencies[index].frequency.value = frequency frequencies[index].type = frequencies_types[index] frequencies[index].gain.value = gain_levels[index] frequencies[index].Q.value = 1 audio.source.connect(frequencies[index]) audio.source = frequencies[index] return update_equalizer = (audio) -> frequencies = audio.frequencies for frequency, index in frequencies_to_control frequencies[index].gain.value = gain_levels[index] return reverb_impulse_responses_files = [ 'Block Inside' 'Cement Blocks' 'Chamber' 'Chateau de Logne, Outside' 'Derlon Sanctuary' 'Five Columns' 'Five Columns Long' 'Greek 7 Echo Hall' 'Hall' 'Highly Damped Large Room' 'In The Silo Revised' 'Inverse Room' 'Large Wide Echo Hall' 'Masonic Lodge' 'Musikvereinsaal' 'Narrow Bumpy Space' 'On a Star' 'Parking Garage' 'Plate' 'Rich Plate' 'Rich Split' 'Ruby Room' 'Scala Milan Opera Hall' 'St Nicolaes Church' 'Trig Room' 'Vocal Duo' ] reverb_impulse_response_current = music_settings.reverb_mode reverb_impulse_response_new = music_settings.reverb_mode reverb_impulse_response_load = (filename, callback) -> if !filename callback() return context = new AudioContext url = "/audio/reverb_impulse_responses/#{filename}.ogg" # Load buffer asynchronously request = new XMLHttpRequest() request.open('GET', url, true) request.responseType = 'blob' request.onload = -> file_reader = new FileReader(); file_reader.onload = -> # Asynchronously decode the audio file data in request.response context.decodeAudioData( @result (buffer) -> if !buffer callback() return callback(buffer) return ) file_reader.readAsArrayBuffer(request.response); return request.onerror = -> callback() request.send() return # Compressor for smoother sound peaks create_compressor = (audio) -> compressor = audio.context.createDynamicsCompressor() audio.compressor = compressor compressor.knee.value = 40 # [0..40] Range above threshold in dB where compression will be smoothly applied compressor.threshold.value = -10 # [-100..0] Threshold in dB about which compression will start compressor.ratio.value = 5 # [1..20] Specified number of dB over the threshold at input will become 1 dB on output audio.source.connect(compressor) audio.source = compressor return # Reverb for surround effect create_reverb = (audio) -> reverb = audio.context.createConvolver() audio.reverb = reverb setTimeout (-> reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> reverb.buffer = buffer ) ), 0 audio.source.connect(reverb) audio.source = reverb return update_reverb = (audio) -> if reverb_impulse_response_new == reverb_impulse_response_current return setTimeout (-> reverb_impulse_response_current = reverb_impulse_response_new reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> audio.reverb.buffer = buffer ) ), 0 add_to_element : (element) -> if music_settings.low_performance return audio = {} element.audio_processing = audio audio.context = new AudioContext audio.context.mozAudioChannelType = 'content' audio.source = audio.context.createMediaElementSource(unwrap(element)) create_reverb(audio) create_equalizer(audio) create_compressor(audio) audio.source.connect(audio.context.destination) update_element : (element) -> audio = element.audio_processing update_equalizer(audio) update_reverb(audio) get_gain_levels : -> gain_levels set_gain_levels : (new_gain_levels) -> gain_levels = new_gain_levels music_settings.equalizer_gain_levels = new_gain_levels cs.bus.trigger('sound-processing/update') get_reverb_mode : -> reverb_impulse_response_current get_reverb_modes : -> reverb_impulse_responses_files set_reverb_mode : (mode) -> reverb_impulse_response_new = mode music_settings.reverb_mode = mode cs.bus.trigger('sound-processing/update')
true
###* * @package CleverStyle Music * @category app * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2014-2015, PI:NAME:<NAME>END_PI * @license MIT License, see license.txt ### window.AudioContext = AudioContext || webkitAudioContext music_settings = cs.music_settings cs.sound_processing = do -> frequencies_to_control = [32, 64, 125, 250, 500, 1000, 2000, 4000, 8000, 16000] #kHz frequencies_types = ['lowshelf', 'lowshelf', 'lowshelf', 'peaking', 'peaking', 'peaking', 'peaking', 'highshelf', 'highshelf', 'highshelf'] gain_levels = music_settings.equalizer_gain_levels || [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] create_equalizer = (audio) -> frequencies = [] audio.frequencies = frequencies for frequency, index in frequencies_to_control frequencies[index] = audio.context.createBiquadFilter() frequencies[index].frequency.value = frequency frequencies[index].type = frequencies_types[index] frequencies[index].gain.value = gain_levels[index] frequencies[index].Q.value = 1 audio.source.connect(frequencies[index]) audio.source = frequencies[index] return update_equalizer = (audio) -> frequencies = audio.frequencies for frequency, index in frequencies_to_control frequencies[index].gain.value = gain_levels[index] return reverb_impulse_responses_files = [ 'Block Inside' 'Cement Blocks' 'Chamber' 'Chateau de Logne, Outside' 'Derlon Sanctuary' 'Five Columns' 'Five Columns Long' 'Greek 7 Echo Hall' 'Hall' 'Highly Damped Large Room' 'In The Silo Revised' 'Inverse Room' 'Large Wide Echo Hall' 'Masonic Lodge' 'Musikvereinsaal' 'Narrow Bumpy Space' 'On a Star' 'Parking Garage' 'Plate' 'Rich Plate' 'Rich Split' 'Ruby Room' 'Scala Milan Opera Hall' 'St Nicolaes Church' 'Trig Room' 'Vocal Duo' ] reverb_impulse_response_current = music_settings.reverb_mode reverb_impulse_response_new = music_settings.reverb_mode reverb_impulse_response_load = (filename, callback) -> if !filename callback() return context = new AudioContext url = "/audio/reverb_impulse_responses/#{filename}.ogg" # Load buffer asynchronously request = new XMLHttpRequest() request.open('GET', url, true) request.responseType = 'blob' request.onload = -> file_reader = new FileReader(); file_reader.onload = -> # Asynchronously decode the audio file data in request.response context.decodeAudioData( @result (buffer) -> if !buffer callback() return callback(buffer) return ) file_reader.readAsArrayBuffer(request.response); return request.onerror = -> callback() request.send() return # Compressor for smoother sound peaks create_compressor = (audio) -> compressor = audio.context.createDynamicsCompressor() audio.compressor = compressor compressor.knee.value = 40 # [0..40] Range above threshold in dB where compression will be smoothly applied compressor.threshold.value = -10 # [-100..0] Threshold in dB about which compression will start compressor.ratio.value = 5 # [1..20] Specified number of dB over the threshold at input will become 1 dB on output audio.source.connect(compressor) audio.source = compressor return # Reverb for surround effect create_reverb = (audio) -> reverb = audio.context.createConvolver() audio.reverb = reverb setTimeout (-> reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> reverb.buffer = buffer ) ), 0 audio.source.connect(reverb) audio.source = reverb return update_reverb = (audio) -> if reverb_impulse_response_new == reverb_impulse_response_current return setTimeout (-> reverb_impulse_response_current = reverb_impulse_response_new reverb_impulse_response_load( reverb_impulse_response_current (buffer) -> audio.reverb.buffer = buffer ) ), 0 add_to_element : (element) -> if music_settings.low_performance return audio = {} element.audio_processing = audio audio.context = new AudioContext audio.context.mozAudioChannelType = 'content' audio.source = audio.context.createMediaElementSource(unwrap(element)) create_reverb(audio) create_equalizer(audio) create_compressor(audio) audio.source.connect(audio.context.destination) update_element : (element) -> audio = element.audio_processing update_equalizer(audio) update_reverb(audio) get_gain_levels : -> gain_levels set_gain_levels : (new_gain_levels) -> gain_levels = new_gain_levels music_settings.equalizer_gain_levels = new_gain_levels cs.bus.trigger('sound-processing/update') get_reverb_mode : -> reverb_impulse_response_current get_reverb_modes : -> reverb_impulse_responses_files set_reverb_mode : (mode) -> reverb_impulse_response_new = mode music_settings.reverb_mode = mode cs.bus.trigger('sound-processing/update')
[ { "context": "()\n\t\t\t\"../../models/User\": { User: @UserModel }\n\t\t@user =\n\t\t\t_id: ObjectId()\n\t\t\temail: @email = \"USER", "end": 1961, "score": 0.6065766215324402, "start": 1961, "tag": "USERNAME", "value": "" }, { "context": "\n\t\t@user =\n\t\t\t_id: ObjectId()\n\t\t\...
test/unit/coffee/Authentication/AuthenticationControllerTests.coffee
shyoshyo/web-sharelatex
1
sinon = require('sinon') chai = require('chai') sinonChai = require "sinon-chai" chai.use sinonChai should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> tk.freeze(Date.now()) @UserModel = findOne: sinon.stub() @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserUpdater" : @UserUpdater = {updateUser:sinon.stub()} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": { siteUrl: 'http://www.foo.bar' } "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) "../../infrastructure/Modules": @Modules = {hooks: {fire: sinon.stub().callsArgWith(2, null, [])}} "../SudoMode/SudoModeHandler": @SudoModeHandler = {activateSudoMode: sinon.stub().callsArgWith(1, null)} "../Notifications/NotificationsBuilder": @NotificationsBuilder = ipMatcherAffiliation: sinon.stub() "../V1/V1Api": @V1Api = request: sinon.stub() "../../models/User": { User: @UserModel } @user = _id: ObjectId() email: @email = "USER@example.com" first_name: "bob" last_name: "brown" referal_id: 1234 isAdmin: false @password = "banana" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: 'a' last_name: 'b' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: 'b' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @AuthenticationController.finishLogin = sinon.stub() @passport.authenticate.callsArgWith(1, null, @user, @info) @err = new Error('woops') it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 1 @AuthenticationController.finishLogin.calledWith(@user).should.equal true describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, []) # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: @password session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the preDoPassportLogin hooks produce an info object", -> beforeEach -> @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [null, {redir: '/somewhere'}, null]) it "should stop early and call done with this info object", (done) -> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, false, {redir: '/somewhere'}).should.equal true @LoginRateLimiter.processLoginRequest.callCount.should.equal 0 done() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true describe '_loginAsyncHandlers', -> beforeEach -> @UserHandler.setupLoginData = sinon.stub() @LoginRateLimiter.recordSuccessfulLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @AnalyticsManager.recordEvent = sinon.stub() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController._loginAsyncHandlers(@req, @user) it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@user.email).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @user.email, user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "user@sharelatex.com" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "user@sharelatex.com" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireOauth", -> beforeEach -> @res.send = sinon.stub() @res.status = sinon.stub().returns(@res) @middleware = @AuthenticationController.requireOauth() describe "when token not provided", -> beforeEach -> @middleware(@req, @res, @next) it "should return 401 error", -> @res.status.should.have.been.calledWith 401 describe "when token provided", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "foo" @middleware(@req, @res, @next) it "should make request to v1 api with token", -> @V1Api.request.should.have.been.calledWith { expectedStatusCodes: [401] json: token: "foo" method: "POST" uri: "/api/v1/sharelatex/oauth_authorize" } describe "when v1 api returns error", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "foo" @middleware(@req, @res, @next) it "should return status", -> @next.should.have.been.calledWith "error" describe "when v1 api status code is not 200", -> beforeEach -> @V1Api.request = sinon.stub().yields(null, {statusCode: 401}, {}) @req.token = "foo" @middleware(@req, @res, @next) it "should return status", -> @res.status.should.have.been.calledWith 401 describe "when v1 api returns authorized profile and access token", -> beforeEach -> @oauth_authorize = access_token: "access_token" user_profile: id: "overleaf-id" @V1Api.request = sinon.stub().yields(null, {statusCode: 200}, @oauth_authorize) @req.token = "foo" describe "in all cases", -> beforeEach -> @middleware(@req, @res, @next) it "should find user", -> @UserModel.findOne.should.have.been.calledWithMatch { "overleaf.id": "overleaf-id" } describe "when user find returns error", -> beforeEach -> @UserModel.findOne = sinon.stub().yields("error") @middleware(@req, @res, @next) it "should return error", -> @next.should.have.been.calledWith "error" describe "when user is not found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, null) @middleware(@req, @res, @next) it "should return unauthorized", -> @res.status.should.have.been.calledWith 401 describe "when user is found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, "user") @middleware(@req, @res, @next) it "should add user to request", -> @req.oauth_user.should.equal "user" it "should add access_token to request", -> @req.oauth.access_token.should.equal "access_token" describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @setRedirect = sinon.spy(@AuthenticationController, 'setRedirectInSession') afterEach -> @setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe 'setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController.setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController.setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" it 'should not allow open redirects', -> @AuthenticationController.setRedirectInSession(@req, 'https://evil.com') expect(@req.session.postLoginRedirect).to.be.undefined describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> it 'should get redirect property from session', -> @req = session: { postLoginRedirect: '/a?b=c' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" it 'should not allow open redirects', -> @req = session: { postLoginRedirect: 'https://evil.com' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null it 'handle null values', -> @req = session: {} expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null describe '_getSafeRedirectPath', -> it 'sanitize redirect path to prevent open redirects', -> expect( @AuthenticationController._getSafeRedirectPath('https://evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//ol.com/evil') ).to.equal '/evil' expect( @AuthenticationController._getSafeRedirectPath('////evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('%2F%2Fevil.com') ).to.equal '/%2F%2Fevil.com' expect( @AuthenticationController._getSafeRedirectPath('.evil.com') ).to.equal '/.evil.com' describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined describe 'finishLogin', -> # - get redirect # - async handlers # - afterLoginSessionSetup # - clear redirect # - issue redir, two ways beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page' @AuthenticationController._loginAsyncHandlers = sinon.stub() @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null) @AuthenticationController._clearRedirectFromSession = sinon.stub() @req.headers = {accept: 'application/json, whatever'} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should extract the redirect from the session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true it 'should call the async handlers', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1 expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true it 'should call afterLoginSessionSetup', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1 expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true it 'should clear redirect from session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true it 'should issue a json response with a redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 1 expect(@res.redirect.callCount).to.equal 0 expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true describe 'with a non-json request', -> beforeEach -> @req.headers = {} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should issue a plain redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 0 expect(@res.redirect.callCount).to.equal 1 expect(@res.redirect.calledWith('/some/page')).to.equal true
24744
sinon = require('sinon') chai = require('chai') sinonChai = require "sinon-chai" chai.use sinonChai should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> tk.freeze(Date.now()) @UserModel = findOne: sinon.stub() @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserUpdater" : @UserUpdater = {updateUser:sinon.stub()} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": { siteUrl: 'http://www.foo.bar' } "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) "../../infrastructure/Modules": @Modules = {hooks: {fire: sinon.stub().callsArgWith(2, null, [])}} "../SudoMode/SudoModeHandler": @SudoModeHandler = {activateSudoMode: sinon.stub().callsArgWith(1, null)} "../Notifications/NotificationsBuilder": @NotificationsBuilder = ipMatcherAffiliation: sinon.stub() "../V1/V1Api": @V1Api = request: sinon.stub() "../../models/User": { User: @UserModel } @user = _id: ObjectId() email: @email = "<EMAIL>" first_name: "<NAME>" last_name: "<NAME>" referal_id: 1234 isAdmin: false @password = "<PASSWORD>" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: '<NAME>' last_name: '<NAME>' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: '<NAME>' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @AuthenticationController.finishLogin = sinon.stub() @passport.authenticate.callsArgWith(1, null, @user, @info) @err = new Error('woops') it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 1 @AuthenticationController.finishLogin.calledWith(@user).should.equal true describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, []) # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: <PASSWORD> session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the preDoPassportLogin hooks produce an info object", -> beforeEach -> @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [null, {redir: '/somewhere'}, null]) it "should stop early and call done with this info object", (done) -> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, false, {redir: '/somewhere'}).should.equal true @LoginRateLimiter.processLoginRequest.callCount.should.equal 0 done() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true describe '_loginAsyncHandlers', -> beforeEach -> @UserHandler.setupLoginData = sinon.stub() @LoginRateLimiter.recordSuccessfulLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @AnalyticsManager.recordEvent = sinon.stub() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController._loginAsyncHandlers(@req, @user) it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@user.email).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @user.email, user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "<EMAIL>" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "<EMAIL>" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireOauth", -> beforeEach -> @res.send = sinon.stub() @res.status = sinon.stub().returns(@res) @middleware = @AuthenticationController.requireOauth() describe "when token not provided", -> beforeEach -> @middleware(@req, @res, @next) it "should return 401 error", -> @res.status.should.have.been.calledWith 401 describe "when token provided", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "<KEY>" @middleware(@req, @res, @next) it "should make request to v1 api with token", -> @V1Api.request.should.have.been.calledWith { expectedStatusCodes: [401] json: token: "foo" method: "POST" uri: "/api/v1/sharelatex/oauth_authorize" } describe "when v1 api returns error", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "foo" @middleware(@req, @res, @next) it "should return status", -> @next.should.have.been.calledWith "error" describe "when v1 api status code is not 200", -> beforeEach -> @V1Api.request = sinon.stub().yields(null, {statusCode: 401}, {}) @req.token = "<KEY>" @middleware(@req, @res, @next) it "should return status", -> @res.status.should.have.been.calledWith 401 describe "when v1 api returns authorized profile and access token", -> beforeEach -> @oauth_authorize = access_token: "access_token" user_profile: id: "overleaf-id" @V1Api.request = sinon.stub().yields(null, {statusCode: 200}, @oauth_authorize) @req.token = "foo" describe "in all cases", -> beforeEach -> @middleware(@req, @res, @next) it "should find user", -> @UserModel.findOne.should.have.been.calledWithMatch { "overleaf.id": "overleaf-id" } describe "when user find returns error", -> beforeEach -> @UserModel.findOne = sinon.stub().yields("error") @middleware(@req, @res, @next) it "should return error", -> @next.should.have.been.calledWith "error" describe "when user is not found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, null) @middleware(@req, @res, @next) it "should return unauthorized", -> @res.status.should.have.been.calledWith 401 describe "when user is found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, "user") @middleware(@req, @res, @next) it "should add user to request", -> @req.oauth_user.should.equal "user" it "should add access_token to request", -> @req.oauth.access_token.should.equal "access_token" describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @setRedirect = sinon.spy(@AuthenticationController, 'setRedirectInSession') afterEach -> @setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe 'setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController.setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController.setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" it 'should not allow open redirects', -> @AuthenticationController.setRedirectInSession(@req, 'https://evil.com') expect(@req.session.postLoginRedirect).to.be.undefined describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> it 'should get redirect property from session', -> @req = session: { postLoginRedirect: '/a?b=c' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" it 'should not allow open redirects', -> @req = session: { postLoginRedirect: 'https://evil.com' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null it 'handle null values', -> @req = session: {} expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null describe '_getSafeRedirectPath', -> it 'sanitize redirect path to prevent open redirects', -> expect( @AuthenticationController._getSafeRedirectPath('https://evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//ol.com/evil') ).to.equal '/evil' expect( @AuthenticationController._getSafeRedirectPath('////evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('%2F%2Fevil.com') ).to.equal '/%2F%2Fevil.com' expect( @AuthenticationController._getSafeRedirectPath('.evil.com') ).to.equal '/.evil.com' describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined describe 'finishLogin', -> # - get redirect # - async handlers # - afterLoginSessionSetup # - clear redirect # - issue redir, two ways beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page' @AuthenticationController._loginAsyncHandlers = sinon.stub() @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null) @AuthenticationController._clearRedirectFromSession = sinon.stub() @req.headers = {accept: 'application/json, whatever'} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should extract the redirect from the session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true it 'should call the async handlers', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1 expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true it 'should call afterLoginSessionSetup', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1 expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true it 'should clear redirect from session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true it 'should issue a json response with a redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 1 expect(@res.redirect.callCount).to.equal 0 expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true describe 'with a non-json request', -> beforeEach -> @req.headers = {} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should issue a plain redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 0 expect(@res.redirect.callCount).to.equal 1 expect(@res.redirect.calledWith('/some/page')).to.equal true
true
sinon = require('sinon') chai = require('chai') sinonChai = require "sinon-chai" chai.use sinonChai should = chai.should() expect = chai.expect modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js" SandboxedModule = require('sandboxed-module') events = require "events" tk = require("timekeeper") MockRequest = require("../helpers/MockRequest") MockResponse = require("../helpers/MockResponse") ObjectId = require("mongojs").ObjectId describe "AuthenticationController", -> beforeEach -> tk.freeze(Date.now()) @UserModel = findOne: sinon.stub() @AuthenticationController = SandboxedModule.require modulePath, requires: "./AuthenticationManager": @AuthenticationManager = {} "../User/UserUpdater" : @UserUpdater = {updateUser:sinon.stub()} "metrics-sharelatex": @Metrics = { inc: sinon.stub() } "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() } "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()} "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() } "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() } "settings-sharelatex": { siteUrl: 'http://www.foo.bar' } "passport": @passport = authenticate: sinon.stub().returns(sinon.stub()) "../User/UserSessionsManager": @UserSessionsManager = trackSession: sinon.stub() untrackSession: sinon.stub() revokeAllUserSessions: sinon.stub().callsArgWith(1, null) "../../infrastructure/Modules": @Modules = {hooks: {fire: sinon.stub().callsArgWith(2, null, [])}} "../SudoMode/SudoModeHandler": @SudoModeHandler = {activateSudoMode: sinon.stub().callsArgWith(1, null)} "../Notifications/NotificationsBuilder": @NotificationsBuilder = ipMatcherAffiliation: sinon.stub() "../V1/V1Api": @V1Api = request: sinon.stub() "../../models/User": { User: @UserModel } @user = _id: ObjectId() email: @email = "PI:EMAIL:<EMAIL>END_PI" first_name: "PI:NAME:<NAME>END_PI" last_name: "PI:NAME:<NAME>END_PI" referal_id: 1234 isAdmin: false @password = "PI:PASSWORD:<PASSWORD>END_PI" @req = new MockRequest() @res = new MockResponse() @callback = @next = sinon.stub() afterEach -> tk.reset() describe 'isUserLoggedIn', () -> beforeEach -> @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId') afterEach -> @stub.restore() it 'should do the right thing in all cases', () -> @AuthenticationController.getLoggedInUserId.returns('some_id') expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true @AuthenticationController.getLoggedInUserId.returns(null) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(false) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false @AuthenticationController.getLoggedInUserId.returns(undefined) expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false describe 'setInSessionUser', () -> beforeEach -> @user = { _id: 'id' first_name: 'PI:NAME:<NAME>END_PI' last_name: 'PI:NAME:<NAME>END_PI' email: 'c' } @req.session.passport = {user: @user} @req.session.user = @user it 'should update the right properties', () -> @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'}) expectedUser = { _id: 'id' first_name: 'new_first_name' last_name: 'PI:NAME:<NAME>END_PI' email: 'new_email' } expect(@req.session.passport.user).to.deep.equal(expectedUser) expect(@req.session.user).to.deep.equal(expectedUser) describe 'passportLogin', -> beforeEach -> @info = null @req.login = sinon.stub().callsArgWith(1, null) @res.json = sinon.stub() @req.session = @session = { passport: {user: @user}, postLoginRedirect: "/path/to/redir/to" } @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @AuthenticationController.finishLogin = sinon.stub() @passport.authenticate.callsArgWith(1, null, @user, @info) @err = new Error('woops') it 'should call passport.authenticate', () -> @AuthenticationController.passportLogin @req, @res, @next @passport.authenticate.callCount.should.equal 1 describe 'when authenticate produces an error', -> beforeEach -> @passport.authenticate.callsArgWith(1, @err) it 'should return next with an error', () -> @AuthenticationController.passportLogin @req, @res, @next @next.calledWith(@err).should.equal true describe 'when authenticate produces a user', -> beforeEach -> @req.session.postLoginRedirect = 'some_redirect' @passport.authenticate.callsArgWith(1, null, @user, @info) afterEach -> delete @req.session.postLoginRedirect it 'should call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 1 @AuthenticationController.finishLogin.calledWith(@user).should.equal true describe 'when authenticate does not produce a user', -> beforeEach -> @info = {text: 'a', type: 'b'} @passport.authenticate.callsArgWith(1, null, false, @info) it 'should not call finishLogin', () -> @AuthenticationController.passportLogin @req, @res, @next @AuthenticationController.finishLogin.callCount.should.equal 0 it 'should not send a json response with redirect', () -> @AuthenticationController.passportLogin @req, @res, @next @res.json.callCount.should.equal 1 @res.json.calledWith({message: @info}).should.equal true expect(@res.json.lastCall.args[0].redir?).to.equal false describe 'afterLoginSessionSetup', -> beforeEach -> @req.login = sinon.stub().callsArgWith(1, null) @req.session = @session = {passport: {user: @user}} @req.session = passport: {user: {_id: "one"}} @req.session.destroy = sinon.stub().callsArgWith(0, null) @req.session.save = sinon.stub().callsArgWith(0, null) @req.sessionStore = {generate: sinon.stub()} @UserSessionsManager.trackSession = sinon.stub() @call = (callback) => @AuthenticationController.afterLoginSessionSetup @req, @user, callback it 'should not produce an error', (done) -> @call (err) => expect(err).to.equal null done() it 'should call req.login', (done) -> @call (err) => @req.login.callCount.should.equal 1 done() it 'should call req.session.save', (done) -> @call (err) => @req.session.save.callCount.should.equal 1 done() it 'should call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 1 done() describe 'when req.session.save produces an error', -> beforeEach -> @req.session.save = sinon.stub().callsArgWith(0, new Error('woops')) it 'should produce an error', (done) -> @call (err) => expect(err).to.not.be.oneOf [null, undefined] expect(err).to.be.instanceof Error done() it 'should not call UserSessionsManager.trackSession', (done) -> @call (err) => @UserSessionsManager.trackSession.callCount.should.equal 0 done() describe 'getSessionUser', -> it 'should get the user object from session', -> @req.session = passport: user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} it 'should work with legacy sessions', -> @req.session = user: {_id: 'one'} user = @AuthenticationController.getSessionUser(@req) expect(user).to.deep.equal {_id: 'one'} describe "doPassportLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, []) # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2) @req.body = email: @email password: PI:PASSWORD:<PASSWORD>END_PI session: postLoginRedirect: "/path/to/redir/to" @cb = sinon.stub() describe "when the preDoPassportLogin hooks produce an info object", -> beforeEach -> @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [null, {redir: '/somewhere'}, null]) it "should stop early and call done with this info object", (done) -> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, false, {redir: '/somewhere'}).should.equal true @LoginRateLimiter.processLoginRequest.callCount.should.equal 0 done() describe "when the users rate limit", -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false) it "should block the request if the limit has been exceeded", (done)-> @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) @cb.callCount.should.equal 1 @cb.calledWith(null, null).should.equal true done() describe 'when the user is authenticated', -> beforeEach -> @cb = sinon.stub() @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user) @req.sessionID = Math.random() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should attempt to authorise the user", -> @AuthenticationManager.authenticate .calledWith(email: @email.toLowerCase(), @password) .should.equal true it "should establish the user's session", -> @cb.calledWith(null, @user).should.equal true describe '_loginAsyncHandlers', -> beforeEach -> @UserHandler.setupLoginData = sinon.stub() @LoginRateLimiter.recordSuccessfulLogin = sinon.stub() @AuthenticationController._recordSuccessfulLogin = sinon.stub() @AnalyticsManager.recordEvent = sinon.stub() @AnalyticsManager.identifyUser = sinon.stub() @AuthenticationController._loginAsyncHandlers(@req, @user) it "should call identifyUser", -> @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true it "should setup the user data in the background", -> @UserHandler.setupLoginData.calledWith(@user).should.equal true it "should set res.session.justLoggedIn", -> @req.session.justLoggedIn.should.equal true it "should record the successful login", -> @AuthenticationController._recordSuccessfulLogin .calledWith(@user._id) .should.equal true it "should tell the rate limiter that there was a success for that email", -> @LoginRateLimiter.recordSuccessfulLogin.calledWith(@user.email).should.equal true it "should log the successful login", -> @logger.log .calledWith(email: @user.email, user_id: @user._id.toString(), "successful log in") .should.equal true it "should track the login event", -> @AnalyticsManager.recordEvent .calledWith(@user._id, "user-logged-in") .should.equal true describe 'when the user is not authenticated', -> beforeEach -> @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true) @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null) @cb = sinon.stub() @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb) it "should not establish the login", -> @cb.callCount.should.equal 1 @cb.calledWith(null, false) # @res.body.should.exist expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type'] # message: # text: 'Your email or password were incorrect. Please try again', # type: 'error' it "should not setup the user data in the background", -> @UserHandler.setupLoginData.called.should.equal false it "should record a failed login", -> @AuthenticationController._recordFailedLogin.called.should.equal true it "should log the failed login", -> @logger.log .calledWith(email: @email.toLowerCase(), "failed log in") .should.equal true describe "getLoggedInUserId", -> beforeEach -> @req = session :{} it "should return the user id from the session", ()-> @user_id = "2134" @req.session.user = _id:@user_id result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it 'should return user for passport session', () -> @user_id = "2134" @req.session = { passport: { user: { _id:@user_id } } } result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal @user_id it "should return null if there is no user on the session", ()-> result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no session", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null it "should return null if there is no req", ()-> @req = {} result = @AuthenticationController.getLoggedInUserId @req expect(result).to.equal null describe "requireLogin", -> beforeEach -> @user = _id: "user-id-123" email: "PI:EMAIL:<EMAIL>END_PI" @middleware = @AuthenticationController.requireLogin() describe "when the user is logged in", -> beforeEach -> @req.session = user: @user = { _id: "user-id-123" email: "PI:EMAIL:<EMAIL>END_PI" } @middleware(@req, @res, @next) it "should call the next method in the chain", -> @next.called.should.equal true describe "when the user is not logged in", -> beforeEach -> @req.session = {} @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub() @req.query = {} @middleware(@req, @res, @next) it "should redirect to the register or login page", -> @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true describe "requireOauth", -> beforeEach -> @res.send = sinon.stub() @res.status = sinon.stub().returns(@res) @middleware = @AuthenticationController.requireOauth() describe "when token not provided", -> beforeEach -> @middleware(@req, @res, @next) it "should return 401 error", -> @res.status.should.have.been.calledWith 401 describe "when token provided", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "PI:KEY:<KEY>END_PI" @middleware(@req, @res, @next) it "should make request to v1 api with token", -> @V1Api.request.should.have.been.calledWith { expectedStatusCodes: [401] json: token: "foo" method: "POST" uri: "/api/v1/sharelatex/oauth_authorize" } describe "when v1 api returns error", -> beforeEach -> @V1Api.request = sinon.stub().yields("error", {}, {}) @req.token = "foo" @middleware(@req, @res, @next) it "should return status", -> @next.should.have.been.calledWith "error" describe "when v1 api status code is not 200", -> beforeEach -> @V1Api.request = sinon.stub().yields(null, {statusCode: 401}, {}) @req.token = "PI:KEY:<KEY>END_PI" @middleware(@req, @res, @next) it "should return status", -> @res.status.should.have.been.calledWith 401 describe "when v1 api returns authorized profile and access token", -> beforeEach -> @oauth_authorize = access_token: "access_token" user_profile: id: "overleaf-id" @V1Api.request = sinon.stub().yields(null, {statusCode: 200}, @oauth_authorize) @req.token = "foo" describe "in all cases", -> beforeEach -> @middleware(@req, @res, @next) it "should find user", -> @UserModel.findOne.should.have.been.calledWithMatch { "overleaf.id": "overleaf-id" } describe "when user find returns error", -> beforeEach -> @UserModel.findOne = sinon.stub().yields("error") @middleware(@req, @res, @next) it "should return error", -> @next.should.have.been.calledWith "error" describe "when user is not found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, null) @middleware(@req, @res, @next) it "should return unauthorized", -> @res.status.should.have.been.calledWith 401 describe "when user is found", -> beforeEach -> @UserModel.findOne = sinon.stub().yields(null, "user") @middleware(@req, @res, @next) it "should add user to request", -> @req.oauth_user.should.equal "user" it "should add access_token to request", -> @req.oauth.access_token.should.equal "access_token" describe "requireGlobalLogin", -> beforeEach -> @req.headers = {} @AuthenticationController.httpAuth = sinon.stub() @setRedirect = sinon.spy(@AuthenticationController, 'setRedirectInSession') afterEach -> @setRedirect.restore() describe "with white listed url", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with white listed url and a query string", -> beforeEach -> @AuthenticationController.addEndpointToLoginWhitelist "/login" @req._parsedUrl.pathname = "/login" @req.url = "/login?query=something" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with http auth", -> beforeEach -> @req.headers["authorization"] = "Mock Basic Auth" @AuthenticationController.requireGlobalLogin @req, @res, @next it "should pass the request onto httpAuth", -> @AuthenticationController.httpAuth .calledWith(@req, @res, @next) .should.equal true describe "with a user session", -> beforeEach -> @req.session = user: {"mock": "user", "_id": "some_id"} @AuthenticationController.requireGlobalLogin @req, @res, @next it "should call next() directly", -> @next.called.should.equal true describe "with no login credentials", -> beforeEach -> @req.session = {} @AuthenticationController.requireGlobalLogin @req, @res, @next it 'should have called setRedirectInSession', -> @setRedirect.callCount.should.equal 1 it "should redirect to the /login page", -> @res.redirectedTo.should.equal "/login" describe "_redirectToLoginOrRegisterPage", -> beforeEach -> @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false }) @req.session = {} @AuthenticationController._redirectToRegisterPage = sinon.stub() @AuthenticationController._redirectToLoginPage = sinon.stub() @req.query = {} describe "they have come directly to the url", -> beforeEach -> @req.query = {} @middleware(@req, @res, @next) it "should redirect to the login page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true describe "they have come via a templates link", -> beforeEach -> @req.query.zipUrl = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "they have been invited to a project", -> beforeEach -> @req.query.project_name = "something" @middleware(@req, @res, @next) it "should redirect to the register page", -> @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false describe "_redirectToRegisterPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToRegisterPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/register?extra_query=foo" it "should log out a message", -> @logger.log .calledWith(url: @url, "user not logged in so redirecting to register page") .should.equal true describe "_redirectToLoginPage", -> beforeEach -> @req.path = "/target/url" @req.query = extra_query: "foo" @AuthenticationController._redirectToLoginPage(@req, @res) it "should redirect to the register page with a query string attached", -> @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo' @res.redirectedTo.should.equal "/login?extra_query=foo" describe "_recordSuccessfulLogin", -> beforeEach -> @UserUpdater.updateUser = sinon.stub().callsArg(2) @AuthenticationController._recordSuccessfulLogin(@user._id, @callback) it "should increment the user.login.success metric", -> @Metrics.inc .calledWith("user.login.success") .should.equal true it "should update the user's login count and last logged in date", -> @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1 it "should call the callback", -> @callback.called.should.equal true describe "_recordFailedLogin", -> beforeEach -> @AuthenticationController._recordFailedLogin(@callback) it "should increment the user.login.failed metric", -> @Metrics.inc .calledWith("user.login.failed") .should.equal true it "should call the callback", -> @callback.called.should.equal true describe 'setRedirectInSession', -> beforeEach -> @req = {session: {}} @req.path = "/somewhere" @req.query = {one: "1"} it 'should set redirect property on session', -> @AuthenticationController.setRedirectInSession(@req) expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1" it 'should set the supplied value', -> @AuthenticationController.setRedirectInSession(@req, '/somewhere/specific') expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific" it 'should not allow open redirects', -> @AuthenticationController.setRedirectInSession(@req, 'https://evil.com') expect(@req.session.postLoginRedirect).to.be.undefined describe 'with a png', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/something.png') expect(@req.session.postLoginRedirect).to.equal undefined describe 'with a js path', -> beforeEach -> @req = {session: {}} it 'should not set the redirect', -> @AuthenticationController.setRedirectInSession(@req, '/js/something.js') expect(@req.session.postLoginRedirect).to.equal undefined describe '_getRedirectFromSession', -> it 'should get redirect property from session', -> @req = session: { postLoginRedirect: '/a?b=c' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c" it 'should not allow open redirects', -> @req = session: { postLoginRedirect: 'https://evil.com' } expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null it 'handle null values', -> @req = session: {} expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null describe '_getSafeRedirectPath', -> it 'sanitize redirect path to prevent open redirects', -> expect( @AuthenticationController._getSafeRedirectPath('https://evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('//ol.com/evil') ).to.equal '/evil' expect( @AuthenticationController._getSafeRedirectPath('////evil.com') ).to.be.undefined expect( @AuthenticationController._getSafeRedirectPath('%2F%2Fevil.com') ).to.equal '/%2F%2Fevil.com' expect( @AuthenticationController._getSafeRedirectPath('.evil.com') ).to.equal '/.evil.com' describe '_clearRedirectFromSession', -> beforeEach -> @req = {session: {postLoginRedirect: "/a?b=c"}} it 'should remove the redirect property from session', -> @AuthenticationController._clearRedirectFromSession(@req) expect(@req.session.postLoginRedirect).to.equal undefined describe 'finishLogin', -> # - get redirect # - async handlers # - afterLoginSessionSetup # - clear redirect # - issue redir, two ways beforeEach -> @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page' @AuthenticationController._loginAsyncHandlers = sinon.stub() @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null) @AuthenticationController._clearRedirectFromSession = sinon.stub() @req.headers = {accept: 'application/json, whatever'} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should extract the redirect from the session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true it 'should call the async handlers', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1 expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true it 'should call afterLoginSessionSetup', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1 expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true it 'should clear redirect from session', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1 expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true it 'should issue a json response with a redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 1 expect(@res.redirect.callCount).to.equal 0 expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true describe 'with a non-json request', -> beforeEach -> @req.headers = {} @res.json = sinon.stub() @res.redirect = sinon.stub() it 'should issue a plain redirect', () -> @AuthenticationController.finishLogin(@user, @req, @res, @next) expect(@res.json.callCount).to.equal 0 expect(@res.redirect.callCount).to.equal 1 expect(@res.redirect.calledWith('/some/page')).to.equal true
[ { "context": "toLowerCase()) === 0 \n# || data.name.indexOf(\" reau \") !== -1 \n# || data.content.toLowerCase().in", "end": 828, "score": 0.9532831907272339, "start": 824, "tag": "NAME", "value": "reau" } ]
example/inline_function.coffee
FGRibreau/node-ast-inlining
1
inliner = require '../index' # or # inliner = require 'ast-inlining' f = testInput: (data) -> # Method calls that will be inlined a._startWith(data.content, 'ipsum') || f._contains(data.name, 'reau') || a._startWith(data.content, 'Lorem') _substr: (where, what) -> where.indexOf(what) != -1 _contains: (where, what) -> f._substr(where, ' '+what+' ') # case sensitive _csstartWith: (where, what) -> where.indexOf(what) == 0 a = _startWith: (where, what) -> f._csstartWith(where.toLowerCase(), what.toLowerCase()) # Inline calls f.testInputInlined = inliner.inline_function(f.testInput, f:f, a:a) console.log f.testInputInlined.toString() ### # function anon_0(data) { # return data.content.toLowerCase().indexOf("ipsum".toLowerCase()) === 0 # || data.name.indexOf(" reau ") !== -1 # || data.content.toLowerCase().indexOf("Lorem".toLowerCase()) === 0; # } ###
225144
inliner = require '../index' # or # inliner = require 'ast-inlining' f = testInput: (data) -> # Method calls that will be inlined a._startWith(data.content, 'ipsum') || f._contains(data.name, 'reau') || a._startWith(data.content, 'Lorem') _substr: (where, what) -> where.indexOf(what) != -1 _contains: (where, what) -> f._substr(where, ' '+what+' ') # case sensitive _csstartWith: (where, what) -> where.indexOf(what) == 0 a = _startWith: (where, what) -> f._csstartWith(where.toLowerCase(), what.toLowerCase()) # Inline calls f.testInputInlined = inliner.inline_function(f.testInput, f:f, a:a) console.log f.testInputInlined.toString() ### # function anon_0(data) { # return data.content.toLowerCase().indexOf("ipsum".toLowerCase()) === 0 # || data.name.indexOf(" <NAME> ") !== -1 # || data.content.toLowerCase().indexOf("Lorem".toLowerCase()) === 0; # } ###
true
inliner = require '../index' # or # inliner = require 'ast-inlining' f = testInput: (data) -> # Method calls that will be inlined a._startWith(data.content, 'ipsum') || f._contains(data.name, 'reau') || a._startWith(data.content, 'Lorem') _substr: (where, what) -> where.indexOf(what) != -1 _contains: (where, what) -> f._substr(where, ' '+what+' ') # case sensitive _csstartWith: (where, what) -> where.indexOf(what) == 0 a = _startWith: (where, what) -> f._csstartWith(where.toLowerCase(), what.toLowerCase()) # Inline calls f.testInputInlined = inliner.inline_function(f.testInput, f:f, a:a) console.log f.testInputInlined.toString() ### # function anon_0(data) { # return data.content.toLowerCase().indexOf("ipsum".toLowerCase()) === 0 # || data.name.indexOf(" PI:NAME:<NAME>END_PI ") !== -1 # || data.content.toLowerCase().indexOf("Lorem".toLowerCase()) === 0; # } ###
[ { "context": "els first.'\n 'server_msg.wrong_password': 'Wrong channel password!'\n 'server_msg.cannot_leave_own_channel': 'S", "end": 775, "score": 0.9991416931152344, "start": 753, "tag": "PASSWORD", "value": "Wrong channel password" }, { "context": "'Channel name'\n...
src/webclient/translate_module.coffee
Atanamo/IRC-Gateway
0
class Translation # English translated texts TEXTS_EN = { 'server_msg.invalid_input': 'Invalid input!' 'server_msg.illegal_length_of_channel_name': 'The requested channel name is too short or too long!' 'server_msg.channel_password_too_short': 'The requested channel password is too short!' 'server_msg.channel_password_too_long': 'The requested channel password is too long!' 'server_msg.invalid_user_data': 'Invalid user data!' 'server_msg.unknown_user': 'Unknown user!' 'server_msg.invalid_token': 'Invalid token!' 'server_msg.reached_channel_limit': 'You reached the limit for self-created channels! Please delete other channels first.' 'server_msg.wrong_password': 'Wrong channel password!' 'server_msg.cannot_leave_own_channel': 'Self-created channels can not be leaved!' 'server_msg.can_only_delete_own_channels': 'A channel can only be deleted, if it has been created by yourself!' 'server_msg.can_only_delete_empty_channels': 'A channel can only be deleted, if no other users are joined to it (even if offline)!' 'server_msg.recognized_flooding_attack': 'You were kicked from the server because of spamming suspicion!' 'manage_msg.loading_start': 'Loading...' 'manage_msg.connect_success': 'Connection established!' 'manage_msg.connect_error': 'Connection error: $error$' 'manage_msg.connect_lost': 'Connection lost! Server may quit' 'manage_msg.auth_start': 'Authenticating...' 'manage_msg.auth_success': 'Authentication successful!' 'manage_msg.auth_failed': 'Authentication failed! $reason$' 'manage_msg.welcome_message': 'Welcome message: $message$' 'manage_msg.channel_join_failed': 'Channel join failed! $reason$' 'confirm_dialog.leave_channel': 'Really want to leave the channel?' 'confirm_dialog.delete_channel': 'Really want to delete the channel?\nChat history would be lost.' 'msg.server_connection_lost': 'Error: Lost connection to server! Waiting for reconnect...' 'msg.channel_joined': 'Joined \'$channel$\'' 'msg.channel_left': 'Left \'$channel$\'' 'msg.channel_deleted': 'Channel \'$channel$\' has been deleted' 'msg.initial_channel_topic': 'Channel topic: $topic$' 'msg.new_channel_topic.authorless': 'New channel topic: $topic$' 'msg.new_channel_topic.authored': '$author$ set new channel topic: $topic$' 'msg.user_changed_name': '$user$ changes his name to $new_name$' 'msg.user_joined_channel': '$user$ joined the channel' 'msg.user_left_channel.part.reasoned': '$user$ left the channel, reason: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ left the channel' 'msg.user_left_channel.quit.reasoned': '$user$ has quit, message: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ has quit' 'msg.user_left_channel.close.reasoned': '$user$ left by closing the channel tab, reason: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ left by closing the channel tab' 'msg.user_kicked_from_channel': '$user$ has been kicked from channel by $actor$, reason: $reason$' 'msg.user_killed_from_server': '$user$ has been kicked from server by $actor$, reason: $reason$' 'msg.user_list_changed': 'The list of users has changed because of an unknown event for user $user$' 'msg.actor_changed_a_mode': '$actor$ set channel mode $mode_event$' 'info.start_of_chat_history': 'Start of chat history ($start$ - $end$)' 'info.end_of_chat_history': 'End of chat history ($start$ - $end$)' 'info.unknown': 'unknown' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Players online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Join or create channel' 'label.channel_creation_options': 'Further options for new channel' 'label.channel_name': 'Channel name' 'label.channel_password': 'Channel password' 'label.channel_flag_public': 'Hide joined users' 'label.channel_flag_irc': 'Mirror channel to IRC' 'label.button.close_channel': 'Close' 'label.button.leave_channel': 'Leave channel' 'label.button.delete_channel': 'Delete channel' } # German translated texts TEXTS_DE = { 'server_msg.invalid_input': 'Ung&uuml;ltige Eingaben!' 'server_msg.illegal_length_of_channel_name': 'Der angeforderte Channel-Name ist zu kurz oder zu lang!' 'server_msg.channel_password_too_short': 'Das angeforderte Channel-Passwort ist zu kurz!' 'server_msg.channel_password_too_long': 'Das angeforderte Channel-Passwort ist zu lang!' 'server_msg.invalid_user_data': 'Ung&uuml;ltige Benutzerdaten!' 'server_msg.unknown_user': 'Unbekannter Benutzer!' 'server_msg.invalid_token': 'Ung&uuml;ltiges Token!' 'server_msg.reached_channel_limit': 'Du hast das Limit f&uuml;r selbst erstellte Channels erreicht! L&ouml;sche bitte bestehende Channels vorher.' 'server_msg.wrong_password': 'Das Channel-Passwort ist falsch!' 'server_msg.cannot_leave_own_channels': 'Selbst erstellte Channels k&ouml;nnen nicht verlassen werden!' 'server_msg.can_only_delete_own_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn sie selbst erstellt wurden!' 'server_msg.can_only_delete_empty_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn keine anderen User beigetreten sind (selbst wenn offline)!' 'server_msg.recognized_flooding_attack': 'Du wurdest wegen Spamming-Verdachts vom Server geworfen!' 'manage_msg.loading_start': 'Initialisierung l&auml;uft...' 'manage_msg.connect_success': 'Verbindung zum Server hergestellt!' 'manage_msg.connect_error': 'Verbindungsabbruch: $error$' 'manage_msg.connect_lost': 'Verbindung zum Server abgerissen! Server wurde eventuell beendet.' 'manage_msg.auth_start': 'Anmeldung l&auml;uft...' 'manage_msg.auth_success': 'Anmeldung erfolgreich!' 'manage_msg.auth_failed': 'Anmeldung fehlgeschlagen! $reason$' 'manage_msg.welcome_message': 'Willkommensnachricht: $message$' 'manage_msg.channel_join_failed': 'Channel-Beitritt fehlgeschlagen! $reason$' 'confirm_dialog.leave_channel': 'Soll der Channel wirklich verlassen werden?' 'confirm_dialog.delete_channel': 'Soll der Channel wirklich gel&ouml;scht werden?\nChatverl&auml;ufe w&uuml;rden verloren gehen.' 'msg.server_connection_lost': 'Fehler: Verbindung zum Server abgerissen! Warten auf Reconnect...' 'msg.channel_joined': 'Channel \'$channel$\' beigetreten' 'msg.channel_left': 'Channel \'$channel$\' verlassen' 'msg.channel_deleted': 'Channel \'$channel$\' wurde gel&ouml;scht' 'msg.initial_channel_topic': 'Channel-Thema: $topic$' 'msg.new_channel_topic.authorless': 'Ein neues Channel-Thema wurde gesetzt: $topic$' 'msg.new_channel_topic.authored': '$author$ hat ein neues Channel-Thema gesetzt: $topic$' 'msg.user_changed_name': '$user$ nennt sich nun $new_name$' 'msg.user_joined_channel': '$user$ ist dem Channel beigetreten' 'msg.user_left_channel.part.reasoned': '$user$ hat den Channel verlassen, Grund: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ hat den Channel verlassen' 'msg.user_left_channel.quit.reasoned': '$user$ ist offline gegangen: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ ist offline gegangen' 'msg.user_left_channel.close.reasoned': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen, Grund: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen' 'msg.user_kicked_from_channel': '$user$ wurde von $actor$ aus dem Channel gekickt, Grund: $reason$' 'msg.user_killed_from_server': '$user$ wurde von $actor$ vom Server geworfen, Grund: $reason$' 'msg.user_list_changed': 'Die Userliste hat sich wegen einem Ereignis zu Benutzer $user$ aktualisiert' 'msg.actor_changed_a_mode': '$actor$ setzt Channel-Modus: $mode_event$' 'info.start_of_chat_history': 'Beginn des Chatverlaufs ($start$ - $end$)' 'info.end_of_chat_history': 'Ende des Chatverlaufs ($start$ - $end$)' 'info.unknown': 'Unbekannt' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Spieler online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Channel beitreten oder neu erstellen' 'label.channel_creation_options': 'Zusatzoptionen f&uuml;r neuen Channel' 'label.channel_name': 'Channel-Name' 'label.channel_password': 'Channel-Passwort' 'label.channel_flag_public': 'Beigetretene User verstecken' 'label.channel_flag_irc': 'Channel ins IRC spiegeln' 'label.button.close_channel': 'Schlie&szlig;en' 'label.button.leave_channel': 'Channel verlassen' 'label.button.delete_channel': 'Channel l&ouml;schen' } # Currently used translations localTexts = TEXTS_EN # Helper textarea, to decode html entities to result text converterTextArea = document.createElement('textarea') # Returns the plaintext output for the given text, having all html entities to be resolved to real characters @_toDecoded: (textWithEscapes) -> converterTextArea.innerHTML = textWithEscapes # Write/fill as html return converterTextArea.value # Read as value - this is the browser interpreted result of the html # Returns the translations for a text with given key and replaces placeholders by given data @get: (key, data) -> text = localTexts[key] or "{Missing text for key: #{key}}" if data? for name, val of data text = text.replace("$#{name}$", val) return @_toDecoded(text) # Returns the translations for the given server message @getForServerMessage: (message) -> key_part = message.toLowerCase().replace(/[ ]/g, '_') text = localTexts["server_msg.#{key_part}"] or message return @_toDecoded(text) # Returns the browser language code @getLangCode: -> return navigator.language or navigator.userLanguage # Sets up the translations to use by browser language @setup: -> langCode = @getLangCode() if langCode is 'de' localTexts = TEXTS_DE else localTexts = TEXTS_EN ## Export class module.exports = Translation
74673
class Translation # English translated texts TEXTS_EN = { 'server_msg.invalid_input': 'Invalid input!' 'server_msg.illegal_length_of_channel_name': 'The requested channel name is too short or too long!' 'server_msg.channel_password_too_short': 'The requested channel password is too short!' 'server_msg.channel_password_too_long': 'The requested channel password is too long!' 'server_msg.invalid_user_data': 'Invalid user data!' 'server_msg.unknown_user': 'Unknown user!' 'server_msg.invalid_token': 'Invalid token!' 'server_msg.reached_channel_limit': 'You reached the limit for self-created channels! Please delete other channels first.' 'server_msg.wrong_password': '<PASSWORD>!' 'server_msg.cannot_leave_own_channel': 'Self-created channels can not be leaved!' 'server_msg.can_only_delete_own_channels': 'A channel can only be deleted, if it has been created by yourself!' 'server_msg.can_only_delete_empty_channels': 'A channel can only be deleted, if no other users are joined to it (even if offline)!' 'server_msg.recognized_flooding_attack': 'You were kicked from the server because of spamming suspicion!' 'manage_msg.loading_start': 'Loading...' 'manage_msg.connect_success': 'Connection established!' 'manage_msg.connect_error': 'Connection error: $error$' 'manage_msg.connect_lost': 'Connection lost! Server may quit' 'manage_msg.auth_start': 'Authenticating...' 'manage_msg.auth_success': 'Authentication successful!' 'manage_msg.auth_failed': 'Authentication failed! $reason$' 'manage_msg.welcome_message': 'Welcome message: $message$' 'manage_msg.channel_join_failed': 'Channel join failed! $reason$' 'confirm_dialog.leave_channel': 'Really want to leave the channel?' 'confirm_dialog.delete_channel': 'Really want to delete the channel?\nChat history would be lost.' 'msg.server_connection_lost': 'Error: Lost connection to server! Waiting for reconnect...' 'msg.channel_joined': 'Joined \'$channel$\'' 'msg.channel_left': 'Left \'$channel$\'' 'msg.channel_deleted': 'Channel \'$channel$\' has been deleted' 'msg.initial_channel_topic': 'Channel topic: $topic$' 'msg.new_channel_topic.authorless': 'New channel topic: $topic$' 'msg.new_channel_topic.authored': '$author$ set new channel topic: $topic$' 'msg.user_changed_name': '$user$ changes his name to $new_name$' 'msg.user_joined_channel': '$user$ joined the channel' 'msg.user_left_channel.part.reasoned': '$user$ left the channel, reason: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ left the channel' 'msg.user_left_channel.quit.reasoned': '$user$ has quit, message: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ has quit' 'msg.user_left_channel.close.reasoned': '$user$ left by closing the channel tab, reason: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ left by closing the channel tab' 'msg.user_kicked_from_channel': '$user$ has been kicked from channel by $actor$, reason: $reason$' 'msg.user_killed_from_server': '$user$ has been kicked from server by $actor$, reason: $reason$' 'msg.user_list_changed': 'The list of users has changed because of an unknown event for user $user$' 'msg.actor_changed_a_mode': '$actor$ set channel mode $mode_event$' 'info.start_of_chat_history': 'Start of chat history ($start$ - $end$)' 'info.end_of_chat_history': 'End of chat history ($start$ - $end$)' 'info.unknown': 'unknown' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Players online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Join or create channel' 'label.channel_creation_options': 'Further options for new channel' 'label.channel_name': 'Channel name' 'label.channel_password': '<PASSWORD>' 'label.channel_flag_public': 'Hide joined users' 'label.channel_flag_irc': 'Mirror channel to IRC' 'label.button.close_channel': 'Close' 'label.button.leave_channel': 'Leave channel' 'label.button.delete_channel': 'Delete channel' } # German translated texts TEXTS_DE = { 'server_msg.invalid_input': 'Ung&uuml;ltige Eingaben!' 'server_msg.illegal_length_of_channel_name': 'Der angeforderte Channel-Name ist zu kurz oder zu lang!' 'server_msg.channel_password_too_short': 'Das angeforderte Channel-Passwort ist zu kurz!' 'server_msg.channel_password_too_long': 'Das angeforderte Channel-Passwort ist zu lang!' 'server_msg.invalid_user_data': 'Ung&uuml;ltige Benutzerdaten!' 'server_msg.unknown_user': 'Unbekannter Benutzer!' 'server_msg.invalid_token': 'Ung&uuml;ltiges Token!' 'server_msg.reached_channel_limit': 'Du hast das Limit f&uuml;r selbst erstellte Channels erreicht! L&ouml;sche bitte bestehende Channels vorher.' 'server_msg.wrong_password': 'Das Channel-Passwort ist <PASSWORD>!' 'server_msg.cannot_leave_own_channels': 'Selbst erstellte Channels k&ouml;nnen nicht verlassen werden!' 'server_msg.can_only_delete_own_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn sie selbst erstellt wurden!' 'server_msg.can_only_delete_empty_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn keine anderen User beigetreten sind (selbst wenn offline)!' 'server_msg.recognized_flooding_attack': 'Du wurdest wegen Spamming-Verdachts vom Server geworfen!' 'manage_msg.loading_start': 'Initialisierung l&auml;uft...' 'manage_msg.connect_success': 'Verbindung zum Server hergestellt!' 'manage_msg.connect_error': 'Verbindungsabbruch: $error$' 'manage_msg.connect_lost': 'Verbindung zum Server abgerissen! Server wurde eventuell beendet.' 'manage_msg.auth_start': 'Anmeldung l&auml;uft...' 'manage_msg.auth_success': 'Anmeldung erfolgreich!' 'manage_msg.auth_failed': 'Anmeldung fehlgeschlagen! $reason$' 'manage_msg.welcome_message': 'Willkommensnachricht: $message$' 'manage_msg.channel_join_failed': 'Channel-Beitritt fehlgeschlagen! $reason$' 'confirm_dialog.leave_channel': 'Soll der Channel wirklich verlassen werden?' 'confirm_dialog.delete_channel': 'Soll der Channel wirklich gel&ouml;scht werden?\nChatverl&auml;ufe w&uuml;rden verloren gehen.' 'msg.server_connection_lost': 'Fehler: Verbindung zum Server abgerissen! Warten auf Reconnect...' 'msg.channel_joined': 'Channel \'$channel$\' beigetreten' 'msg.channel_left': 'Channel \'$channel$\' verlassen' 'msg.channel_deleted': 'Channel \'$channel$\' wurde gel&ouml;scht' 'msg.initial_channel_topic': 'Channel-Thema: $topic$' 'msg.new_channel_topic.authorless': 'Ein neues Channel-Thema wurde gesetzt: $topic$' 'msg.new_channel_topic.authored': '$author$ hat ein neues Channel-Thema gesetzt: $topic$' 'msg.user_changed_name': '$user$ nennt sich nun $new_name$' 'msg.user_joined_channel': '$user$ ist dem Channel beigetreten' 'msg.user_left_channel.part.reasoned': '$user$ hat den Channel verlassen, Grund: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ hat den Channel verlassen' 'msg.user_left_channel.quit.reasoned': '$user$ ist offline gegangen: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ ist offline gegangen' 'msg.user_left_channel.close.reasoned': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen, Grund: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen' 'msg.user_kicked_from_channel': '$user$ wurde von $actor$ aus dem Channel gekickt, Grund: $reason$' 'msg.user_killed_from_server': '$user$ wurde von $actor$ vom Server geworfen, Grund: $reason$' 'msg.user_list_changed': 'Die Userliste hat sich wegen einem Ereignis zu Benutzer $user$ aktualisiert' 'msg.actor_changed_a_mode': '$actor$ setzt Channel-Modus: $mode_event$' 'info.start_of_chat_history': 'Beginn des Chatverlaufs ($start$ - $end$)' 'info.end_of_chat_history': 'Ende des Chatverlaufs ($start$ - $end$)' 'info.unknown': 'Unbekannt' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Spieler online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Channel beitreten oder neu erstellen' 'label.channel_creation_options': 'Zusatzoptionen f&uuml;r neuen Channel' 'label.channel_name': 'Channel-Name' 'label.channel_password': '<PASSWORD>' 'label.channel_flag_public': 'Beigetretene User verstecken' 'label.channel_flag_irc': 'Channel ins IRC spiegeln' 'label.button.close_channel': 'Schlie&szlig;en' 'label.button.leave_channel': 'Channel verlassen' 'label.button.delete_channel': 'Channel l&ouml;schen' } # Currently used translations localTexts = TEXTS_EN # Helper textarea, to decode html entities to result text converterTextArea = document.createElement('textarea') # Returns the plaintext output for the given text, having all html entities to be resolved to real characters @_toDecoded: (textWithEscapes) -> converterTextArea.innerHTML = textWithEscapes # Write/fill as html return converterTextArea.value # Read as value - this is the browser interpreted result of the html # Returns the translations for a text with given key and replaces placeholders by given data @get: (key, data) -> text = localTexts[key] or "{Missing text for key: #{key}}" if data? for name, val of data text = text.replace("$#{name}$", val) return @_toDecoded(text) # Returns the translations for the given server message @getForServerMessage: (message) -> key_part = message.toLowerCase().replace(/[ ]/g, '_') text = localTexts["server_msg.#{key_part}"] or message return @_toDecoded(text) # Returns the browser language code @getLangCode: -> return navigator.language or navigator.userLanguage # Sets up the translations to use by browser language @setup: -> langCode = @getLangCode() if langCode is 'de' localTexts = TEXTS_DE else localTexts = TEXTS_EN ## Export class module.exports = Translation
true
class Translation # English translated texts TEXTS_EN = { 'server_msg.invalid_input': 'Invalid input!' 'server_msg.illegal_length_of_channel_name': 'The requested channel name is too short or too long!' 'server_msg.channel_password_too_short': 'The requested channel password is too short!' 'server_msg.channel_password_too_long': 'The requested channel password is too long!' 'server_msg.invalid_user_data': 'Invalid user data!' 'server_msg.unknown_user': 'Unknown user!' 'server_msg.invalid_token': 'Invalid token!' 'server_msg.reached_channel_limit': 'You reached the limit for self-created channels! Please delete other channels first.' 'server_msg.wrong_password': 'PI:PASSWORD:<PASSWORD>END_PI!' 'server_msg.cannot_leave_own_channel': 'Self-created channels can not be leaved!' 'server_msg.can_only_delete_own_channels': 'A channel can only be deleted, if it has been created by yourself!' 'server_msg.can_only_delete_empty_channels': 'A channel can only be deleted, if no other users are joined to it (even if offline)!' 'server_msg.recognized_flooding_attack': 'You were kicked from the server because of spamming suspicion!' 'manage_msg.loading_start': 'Loading...' 'manage_msg.connect_success': 'Connection established!' 'manage_msg.connect_error': 'Connection error: $error$' 'manage_msg.connect_lost': 'Connection lost! Server may quit' 'manage_msg.auth_start': 'Authenticating...' 'manage_msg.auth_success': 'Authentication successful!' 'manage_msg.auth_failed': 'Authentication failed! $reason$' 'manage_msg.welcome_message': 'Welcome message: $message$' 'manage_msg.channel_join_failed': 'Channel join failed! $reason$' 'confirm_dialog.leave_channel': 'Really want to leave the channel?' 'confirm_dialog.delete_channel': 'Really want to delete the channel?\nChat history would be lost.' 'msg.server_connection_lost': 'Error: Lost connection to server! Waiting for reconnect...' 'msg.channel_joined': 'Joined \'$channel$\'' 'msg.channel_left': 'Left \'$channel$\'' 'msg.channel_deleted': 'Channel \'$channel$\' has been deleted' 'msg.initial_channel_topic': 'Channel topic: $topic$' 'msg.new_channel_topic.authorless': 'New channel topic: $topic$' 'msg.new_channel_topic.authored': '$author$ set new channel topic: $topic$' 'msg.user_changed_name': '$user$ changes his name to $new_name$' 'msg.user_joined_channel': '$user$ joined the channel' 'msg.user_left_channel.part.reasoned': '$user$ left the channel, reason: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ left the channel' 'msg.user_left_channel.quit.reasoned': '$user$ has quit, message: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ has quit' 'msg.user_left_channel.close.reasoned': '$user$ left by closing the channel tab, reason: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ left by closing the channel tab' 'msg.user_kicked_from_channel': '$user$ has been kicked from channel by $actor$, reason: $reason$' 'msg.user_killed_from_server': '$user$ has been kicked from server by $actor$, reason: $reason$' 'msg.user_list_changed': 'The list of users has changed because of an unknown event for user $user$' 'msg.actor_changed_a_mode': '$actor$ set channel mode $mode_event$' 'info.start_of_chat_history': 'Start of chat history ($start$ - $end$)' 'info.end_of_chat_history': 'End of chat history ($start$ - $end$)' 'info.unknown': 'unknown' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Players online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Join or create channel' 'label.channel_creation_options': 'Further options for new channel' 'label.channel_name': 'Channel name' 'label.channel_password': 'PI:PASSWORD:<PASSWORD>END_PI' 'label.channel_flag_public': 'Hide joined users' 'label.channel_flag_irc': 'Mirror channel to IRC' 'label.button.close_channel': 'Close' 'label.button.leave_channel': 'Leave channel' 'label.button.delete_channel': 'Delete channel' } # German translated texts TEXTS_DE = { 'server_msg.invalid_input': 'Ung&uuml;ltige Eingaben!' 'server_msg.illegal_length_of_channel_name': 'Der angeforderte Channel-Name ist zu kurz oder zu lang!' 'server_msg.channel_password_too_short': 'Das angeforderte Channel-Passwort ist zu kurz!' 'server_msg.channel_password_too_long': 'Das angeforderte Channel-Passwort ist zu lang!' 'server_msg.invalid_user_data': 'Ung&uuml;ltige Benutzerdaten!' 'server_msg.unknown_user': 'Unbekannter Benutzer!' 'server_msg.invalid_token': 'Ung&uuml;ltiges Token!' 'server_msg.reached_channel_limit': 'Du hast das Limit f&uuml;r selbst erstellte Channels erreicht! L&ouml;sche bitte bestehende Channels vorher.' 'server_msg.wrong_password': 'Das Channel-Passwort ist PI:PASSWORD:<PASSWORD>END_PI!' 'server_msg.cannot_leave_own_channels': 'Selbst erstellte Channels k&ouml;nnen nicht verlassen werden!' 'server_msg.can_only_delete_own_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn sie selbst erstellt wurden!' 'server_msg.can_only_delete_empty_channels': 'Channels k&ouml;nnen nur gel&ouml;scht werden, wenn keine anderen User beigetreten sind (selbst wenn offline)!' 'server_msg.recognized_flooding_attack': 'Du wurdest wegen Spamming-Verdachts vom Server geworfen!' 'manage_msg.loading_start': 'Initialisierung l&auml;uft...' 'manage_msg.connect_success': 'Verbindung zum Server hergestellt!' 'manage_msg.connect_error': 'Verbindungsabbruch: $error$' 'manage_msg.connect_lost': 'Verbindung zum Server abgerissen! Server wurde eventuell beendet.' 'manage_msg.auth_start': 'Anmeldung l&auml;uft...' 'manage_msg.auth_success': 'Anmeldung erfolgreich!' 'manage_msg.auth_failed': 'Anmeldung fehlgeschlagen! $reason$' 'manage_msg.welcome_message': 'Willkommensnachricht: $message$' 'manage_msg.channel_join_failed': 'Channel-Beitritt fehlgeschlagen! $reason$' 'confirm_dialog.leave_channel': 'Soll der Channel wirklich verlassen werden?' 'confirm_dialog.delete_channel': 'Soll der Channel wirklich gel&ouml;scht werden?\nChatverl&auml;ufe w&uuml;rden verloren gehen.' 'msg.server_connection_lost': 'Fehler: Verbindung zum Server abgerissen! Warten auf Reconnect...' 'msg.channel_joined': 'Channel \'$channel$\' beigetreten' 'msg.channel_left': 'Channel \'$channel$\' verlassen' 'msg.channel_deleted': 'Channel \'$channel$\' wurde gel&ouml;scht' 'msg.initial_channel_topic': 'Channel-Thema: $topic$' 'msg.new_channel_topic.authorless': 'Ein neues Channel-Thema wurde gesetzt: $topic$' 'msg.new_channel_topic.authored': '$author$ hat ein neues Channel-Thema gesetzt: $topic$' 'msg.user_changed_name': '$user$ nennt sich nun $new_name$' 'msg.user_joined_channel': '$user$ ist dem Channel beigetreten' 'msg.user_left_channel.part.reasoned': '$user$ hat den Channel verlassen, Grund: $reason$' 'msg.user_left_channel.part.reasonless': '$user$ hat den Channel verlassen' 'msg.user_left_channel.quit.reasoned': '$user$ ist offline gegangen: $reason$' 'msg.user_left_channel.quit.reasonless': '$user$ ist offline gegangen' 'msg.user_left_channel.close.reasoned': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen, Grund: $reason$' # Should not be required 'msg.user_left_channel.close.reasonless': '$user$ hat den Channel durch Schlie&szlig;en des Tabs verlassen' 'msg.user_kicked_from_channel': '$user$ wurde von $actor$ aus dem Channel gekickt, Grund: $reason$' 'msg.user_killed_from_server': '$user$ wurde von $actor$ vom Server geworfen, Grund: $reason$' 'msg.user_list_changed': 'Die Userliste hat sich wegen einem Ereignis zu Benutzer $user$ aktualisiert' 'msg.actor_changed_a_mode': '$actor$ setzt Channel-Modus: $mode_event$' 'info.start_of_chat_history': 'Beginn des Chatverlaufs ($start$ - $end$)' 'info.end_of_chat_history': 'Ende des Chatverlaufs ($start$ - $end$)' 'info.unknown': 'Unbekannt' 'label.server_tab': 'Server' 'label.current_number_of_players': 'Spieler online' 'label.irc_channel_name': 'IRC' 'label.channel_join_options': 'Channel beitreten oder neu erstellen' 'label.channel_creation_options': 'Zusatzoptionen f&uuml;r neuen Channel' 'label.channel_name': 'Channel-Name' 'label.channel_password': 'PI:PASSWORD:<PASSWORD>END_PI' 'label.channel_flag_public': 'Beigetretene User verstecken' 'label.channel_flag_irc': 'Channel ins IRC spiegeln' 'label.button.close_channel': 'Schlie&szlig;en' 'label.button.leave_channel': 'Channel verlassen' 'label.button.delete_channel': 'Channel l&ouml;schen' } # Currently used translations localTexts = TEXTS_EN # Helper textarea, to decode html entities to result text converterTextArea = document.createElement('textarea') # Returns the plaintext output for the given text, having all html entities to be resolved to real characters @_toDecoded: (textWithEscapes) -> converterTextArea.innerHTML = textWithEscapes # Write/fill as html return converterTextArea.value # Read as value - this is the browser interpreted result of the html # Returns the translations for a text with given key and replaces placeholders by given data @get: (key, data) -> text = localTexts[key] or "{Missing text for key: #{key}}" if data? for name, val of data text = text.replace("$#{name}$", val) return @_toDecoded(text) # Returns the translations for the given server message @getForServerMessage: (message) -> key_part = message.toLowerCase().replace(/[ ]/g, '_') text = localTexts["server_msg.#{key_part}"] or message return @_toDecoded(text) # Returns the browser language code @getLangCode: -> return navigator.language or navigator.userLanguage # Sets up the translations to use by browser language @setup: -> langCode = @getLangCode() if langCode is 'de' localTexts = TEXTS_DE else localTexts = TEXTS_EN ## Export class module.exports = Translation
[ { "context": "w Tests for template-curly-spacing rule.\n# @author Toru Nagashima\n###\n\n'use strict'\n\n#-----------------------------", "end": 84, "score": 0.9998725056648254, "start": 70, "tag": "NAME", "value": "Toru Nagashima" } ]
src/tests/rules/template-curly-spacing.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for template-curly-spacing rule. # @author Toru Nagashima ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/template-curly-spacing' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'template-curly-spacing', rule, valid: [ '{ foo }' '"#{foo} #{bar}"' , code: '"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: '"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , 'tag"#{foo} #{bar}"' , code: 'tag"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: 'tag"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , '"#{}"' ] invalid: [ code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{foo} #{bar}"' output: '"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 2 , message: "Expected space(s) before '}'.", column: 7 , message: 'Expected space(s) after \'#{\'.', column: 9 , message: "Expected space(s) before '}'.", column: 14 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{foo} #{bar}"' output: 'tag"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 5 , message: "Expected space(s) before '}'.", column: 10 , message: 'Expected space(s) after \'#{\'.', column: 12 , message: "Expected space(s) before '}'.", column: 17 ] ]
84936
###* # @fileoverview Tests for template-curly-spacing rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/template-curly-spacing' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'template-curly-spacing', rule, valid: [ '{ foo }' '"#{foo} #{bar}"' , code: '"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: '"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , 'tag"#{foo} #{bar}"' , code: 'tag"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: 'tag"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , '"#{}"' ] invalid: [ code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{foo} #{bar}"' output: '"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 2 , message: "Expected space(s) before '}'.", column: 7 , message: 'Expected space(s) after \'#{\'.', column: 9 , message: "Expected space(s) before '}'.", column: 14 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{foo} #{bar}"' output: 'tag"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 5 , message: "Expected space(s) before '}'.", column: 10 , message: 'Expected space(s) after \'#{\'.', column: 12 , message: "Expected space(s) before '}'.", column: 17 ] ]
true
###* # @fileoverview Tests for template-curly-spacing rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/template-curly-spacing' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'template-curly-spacing', rule, valid: [ '{ foo }' '"#{foo} #{bar}"' , code: '"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: '"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , 'tag"#{foo} #{bar}"' , code: 'tag"#{foo} #{bar} #{\n baz\n}"', options: ['never'] , code: 'tag"#{ foo } #{ bar } #{\n baz\n}"', options: ['always'] , '"#{}"' ] invalid: [ code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{ foo } #{ bar }"' output: '"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 2 , message: "Unexpected space(s) before '}'.", column: 9 , message: 'Unexpected space(s) after \'#{\'.', column: 11 , message: "Unexpected space(s) before '}'.", column: 18 ] , code: '"#{foo} #{bar}"' output: '"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 2 , message: "Expected space(s) before '}'.", column: 7 , message: 'Expected space(s) after \'#{\'.', column: 9 , message: "Expected space(s) before '}'.", column: 14 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{ foo } #{ bar }"' output: 'tag"#{foo} #{bar}"' options: ['never'] errors: [ message: 'Unexpected space(s) after \'#{\'.', column: 5 , message: "Unexpected space(s) before '}'.", column: 12 , message: 'Unexpected space(s) after \'#{\'.', column: 14 , message: "Unexpected space(s) before '}'.", column: 21 ] , code: 'tag"#{foo} #{bar}"' output: 'tag"#{ foo } #{ bar }"' options: ['always'] errors: [ message: 'Expected space(s) after \'#{\'.', column: 5 , message: "Expected space(s) before '}'.", column: 10 , message: 'Expected space(s) after \'#{\'.', column: 12 , message: "Expected space(s) before '}'.", column: 17 ] ]
[ { "context": " throw err if err\n tx.insert(\"people\", {name: 'Stephen', location: 'Montreal'}).execute()\n tx.select(", "end": 272, "score": 0.9995850920677185, "start": 265, "tag": "NAME", "value": "Stephen" }, { "context": " visible\")\n t.deepEqual(res.rows[0], {name:...
test/integration/transaction.test.coffee
kamholz/gesundheit
0
#!/usr/bin/env coffee helpers = require('./helpers') tables = people: {name: 'varchar(255)', location: 'varchar(255)'} helpers.eachEngine "Transactions", tables, (db, t) -> t.plan(3) db.begin (err, tx) -> throw err if err tx.insert("people", {name: 'Stephen', location: 'Montreal'}).execute() tx.select('people').execute (err, res) -> throw err if err console.log('selected') t.equal(res?.rows.length, 1, "Inserted data is visible") t.deepEqual(res.rows[0], {name: 'Stephen', location: 'Montreal'}) # Select from people on a differenct connection tx.engine.select("people").execute (err, res) -> throw err if err t.ok(!(res?.rows.length), "Transaction is isolated")
115170
#!/usr/bin/env coffee helpers = require('./helpers') tables = people: {name: 'varchar(255)', location: 'varchar(255)'} helpers.eachEngine "Transactions", tables, (db, t) -> t.plan(3) db.begin (err, tx) -> throw err if err tx.insert("people", {name: '<NAME>', location: 'Montreal'}).execute() tx.select('people').execute (err, res) -> throw err if err console.log('selected') t.equal(res?.rows.length, 1, "Inserted data is visible") t.deepEqual(res.rows[0], {name: '<NAME>', location: 'Montreal'}) # Select from people on a differenct connection tx.engine.select("people").execute (err, res) -> throw err if err t.ok(!(res?.rows.length), "Transaction is isolated")
true
#!/usr/bin/env coffee helpers = require('./helpers') tables = people: {name: 'varchar(255)', location: 'varchar(255)'} helpers.eachEngine "Transactions", tables, (db, t) -> t.plan(3) db.begin (err, tx) -> throw err if err tx.insert("people", {name: 'PI:NAME:<NAME>END_PI', location: 'Montreal'}).execute() tx.select('people').execute (err, res) -> throw err if err console.log('selected') t.equal(res?.rows.length, 1, "Inserted data is visible") t.deepEqual(res.rows[0], {name: 'PI:NAME:<NAME>END_PI', location: 'Montreal'}) # Select from people on a differenct connection tx.engine.select("people").execute (err, res) -> throw err if err t.ok(!(res?.rows.length), "Transaction is isolated")
[ { "context": "lytics'\nanalytics = new GoogleAnalytics account: 'UA-1224199-33'\n\nmodule.exports = window.app = { api, navigation", "end": 1564, "score": 0.9803232550621033, "start": 1551, "tag": "KEY", "value": "UA-1224199-33" } ]
app/main.coffee
zooniverse/Cyclone-Center
2
translate = require 't7e' enUs = require './lib/en-us' translate.load enUs Api = require 'zooniverse/lib/api' api = if window.location.hostname is 'www.cyclonecenter.org' new Api project: 'cyclone_center', host: 'https://www.cyclonecenter.org', path: '/_ouroboros_api/proxy' else new Api project: 'cyclone_center' Subject = require 'zooniverse/models/subject' Subject.group = true $app = $('#app') $footerContainer = $('#footer-container') Navigation = require './controllers/navigation' navigation = new Navigation navigation.el.prependTo document.body StackOfPages = require 'stack-of-pages' stack = new StackOfPages '#/': require './controllers/home' '#/about/*': require './controllers/about' '#/classify': require './controllers/classify' '#/profile': require './controllers/profile' $(stack.el).appendTo $app LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs it: label: 'Italiano' zh_tw: label: '繁體中文', strings: './translations/zh-tw.json' languageManager.on 'change-language', (e, code, strings) -> translate.load strings translate.refresh() TopBar = require 'zooniverse/controllers/top-bar' topBar = new TopBar topBar.el.appendTo navigation.el Footer = require 'zooniverse/controllers/footer' footer = new Footer footer.el.appendTo $footerContainer User = require 'zooniverse/models/user' User.fetch() GoogleAnalytics = require 'zooniverse/lib/google-analytics' analytics = new GoogleAnalytics account: 'UA-1224199-33' module.exports = window.app = { api, navigation, stack, topBar, analytics }
197810
translate = require 't7e' enUs = require './lib/en-us' translate.load enUs Api = require 'zooniverse/lib/api' api = if window.location.hostname is 'www.cyclonecenter.org' new Api project: 'cyclone_center', host: 'https://www.cyclonecenter.org', path: '/_ouroboros_api/proxy' else new Api project: 'cyclone_center' Subject = require 'zooniverse/models/subject' Subject.group = true $app = $('#app') $footerContainer = $('#footer-container') Navigation = require './controllers/navigation' navigation = new Navigation navigation.el.prependTo document.body StackOfPages = require 'stack-of-pages' stack = new StackOfPages '#/': require './controllers/home' '#/about/*': require './controllers/about' '#/classify': require './controllers/classify' '#/profile': require './controllers/profile' $(stack.el).appendTo $app LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs it: label: 'Italiano' zh_tw: label: '繁體中文', strings: './translations/zh-tw.json' languageManager.on 'change-language', (e, code, strings) -> translate.load strings translate.refresh() TopBar = require 'zooniverse/controllers/top-bar' topBar = new TopBar topBar.el.appendTo navigation.el Footer = require 'zooniverse/controllers/footer' footer = new Footer footer.el.appendTo $footerContainer User = require 'zooniverse/models/user' User.fetch() GoogleAnalytics = require 'zooniverse/lib/google-analytics' analytics = new GoogleAnalytics account: '<KEY>' module.exports = window.app = { api, navigation, stack, topBar, analytics }
true
translate = require 't7e' enUs = require './lib/en-us' translate.load enUs Api = require 'zooniverse/lib/api' api = if window.location.hostname is 'www.cyclonecenter.org' new Api project: 'cyclone_center', host: 'https://www.cyclonecenter.org', path: '/_ouroboros_api/proxy' else new Api project: 'cyclone_center' Subject = require 'zooniverse/models/subject' Subject.group = true $app = $('#app') $footerContainer = $('#footer-container') Navigation = require './controllers/navigation' navigation = new Navigation navigation.el.prependTo document.body StackOfPages = require 'stack-of-pages' stack = new StackOfPages '#/': require './controllers/home' '#/about/*': require './controllers/about' '#/classify': require './controllers/classify' '#/profile': require './controllers/profile' $(stack.el).appendTo $app LanguageManager = require 'zooniverse/lib/language-manager' languageManager = new LanguageManager translations: en: label: 'English', strings: enUs it: label: 'Italiano' zh_tw: label: '繁體中文', strings: './translations/zh-tw.json' languageManager.on 'change-language', (e, code, strings) -> translate.load strings translate.refresh() TopBar = require 'zooniverse/controllers/top-bar' topBar = new TopBar topBar.el.appendTo navigation.el Footer = require 'zooniverse/controllers/footer' footer = new Footer footer.el.appendTo $footerContainer User = require 'zooniverse/models/user' User.fetch() GoogleAnalytics = require 'zooniverse/lib/google-analytics' analytics = new GoogleAnalytics account: 'PI:KEY:<KEY>END_PI' module.exports = window.app = { api, navigation, stack, topBar, analytics }
[ { "context": " ]\n assert.deepEqual res.body.kommuner, [ 'Samnanger', 'Vaksdal', 'Osterøy', 'Bergen', 'Voss' ]\n ", "end": 1528, "score": 0.9916565418243408, "start": 1519, "tag": "NAME", "value": "Samnanger" }, { "context": "sert.deepEqual res.body.kommuner, [ 'Samnanger...
test/routes/api_v1-spec.coffee
Turistforeningen/Geoserver
10
assert = require 'assert' request = require 'supertest' resolve = require('path').resolve app = require '../../src/server' mongo = require '../../src/mongo' trail = require '../assets/trail.json' req = request app base = '/api/v1' describe '/', -> it 'should do return API documentation', (done) -> req.get "#{base}" .expect 200 .end done describe '/boundary/intersect', -> it 'should return 400 for invalid body', (done) -> req.post "#{base}/boundary/intersect" .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf1500004b', navn: 'Stølsheimen, Bergsdalen og Vossefjellene' } { _id: '52408144e7926dcf15000025', navn: 'Byfjellene i Bergen' } { _id: '52408144e7926dcf15000035', navn: 'Nordhordland' } ] assert.deepEqual res.body.kommuner, [ 'Samnanger', 'Vaksdal', 'Osterøy', 'Bergen', 'Voss' ] assert.deepEqual res.body.fylker, [ 'Hordaland' ] .end done it 'should return for complex LineString', (done) -> @timeout 10000 req.post "#{base}/boundary/intersect" .send trail .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf15000050', navn: 'Huldreheimen' } { _id: '52408144e7926dcf1500000c', navn: 'Jotunheimen' } { _id: '52408144e7926dcf1500003c', navn: 'Skarvheimen' } { _id: '52408144e7926dcf15000039', navn: 'Hardangervidda' } ] assert.deepEqual res.body.kommuner, [ 'Vang', 'Lærdal', 'Aurland', 'Hol', 'Ål', 'Ulvik' ] assert.deepEqual res.body.fylker, [ 'Oppland', 'Buskerud', 'Sogn og Fjordane', 'Hordaland' ] .end done describe '/line/analyze', -> url = "#{base}/line/analyze" it 'should return 400 for invalid body', (done) -> req.post url .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post url .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post url .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post url .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body, length: 64781 geojson: type: 'LineString' coordinates: [ [ 5.32907, 60.39826 ], [ 6.41474, 60.62869 ] ] properties: start: type: 'Point', coordinates: [ 5.32907, 60.39826 ] stop: type: 'Point', coordinates: [ 6.41474, 60.62869 ] .end done describe '/gpx/parse', -> url = "#{base}/gpx/parse" it 'should parse uploaded GPX file', (done) -> @timeout 5000 req.post url .attach 'files[]', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'totland.gpx' assert.equal res.body['files[]'][0].extension, 'gpx' assert.equal res.body['files[]'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['files[]'][0].geojson, 'object' .end done it 'should parse uploaded GPX file with arbitrary field name', (done) -> @timeout 5000 req.post url .attach 'gpx', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['gpx'].length, 1 assert.equal res.body['gpx'][0].fieldname, 'gpx' assert.equal res.body['gpx'][0].filename, 'totland.gpx' assert.equal res.body['gpx'][0].extension, 'gpx' assert.equal res.body['gpx'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['gpx'][0].geojson, 'object' .end done it 'should return error for non GPX file', (done) -> req.post url .attach 'files[]', resolve __dirname, '../data/file.json' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'file.json' assert.equal res.body['files[]'][0].extension, 'json' assert.equal res.body['files[]'][0].mimetype, 'application/json' assert.equal res.body['files[]'][0].geojson, null assert.equal res.body['files[]'][0].error, 'Invalid extension \'json\'' .end done
89474
assert = require 'assert' request = require 'supertest' resolve = require('path').resolve app = require '../../src/server' mongo = require '../../src/mongo' trail = require '../assets/trail.json' req = request app base = '/api/v1' describe '/', -> it 'should do return API documentation', (done) -> req.get "#{base}" .expect 200 .end done describe '/boundary/intersect', -> it 'should return 400 for invalid body', (done) -> req.post "#{base}/boundary/intersect" .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf1500004b', navn: 'Stølsheimen, Bergsdalen og Vossefjellene' } { _id: '52408144e7926dcf15000025', navn: 'Byfjellene i Bergen' } { _id: '52408144e7926dcf15000035', navn: 'Nordhordland' } ] assert.deepEqual res.body.kommuner, [ '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>' ] assert.deepEqual res.body.fylker, [ '<NAME>' ] .end done it 'should return for complex LineString', (done) -> @timeout 10000 req.post "#{base}/boundary/intersect" .send trail .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf15000050', navn: 'Huldreheimen' } { _id: '52408144e7926dcf1500000c', navn: 'Jotunheimen' } { _id: '52408144e7926dcf1500003c', navn: 'Skarvheimen' } { _id: '52408144e7926dcf15000039', navn: 'Hardangervidda' } ] assert.deepEqual res.body.kommuner, [ 'Vang', 'Lærdal', 'Aurland', 'Hol', 'Ål', 'Ulvik' ] assert.deepEqual res.body.fylker, [ '<NAME>', '<NAME>', '<NAME> <NAME>', 'Hordaland' ] .end done describe '/line/analyze', -> url = "#{base}/line/analyze" it 'should return 400 for invalid body', (done) -> req.post url .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post url .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post url .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post url .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body, length: 64781 geojson: type: 'LineString' coordinates: [ [ 5.32907, 60.39826 ], [ 6.41474, 60.62869 ] ] properties: start: type: 'Point', coordinates: [ 5.32907, 60.39826 ] stop: type: 'Point', coordinates: [ 6.41474, 60.62869 ] .end done describe '/gpx/parse', -> url = "#{base}/gpx/parse" it 'should parse uploaded GPX file', (done) -> @timeout 5000 req.post url .attach 'files[]', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'totland.gpx' assert.equal res.body['files[]'][0].extension, 'gpx' assert.equal res.body['files[]'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['files[]'][0].geojson, 'object' .end done it 'should parse uploaded GPX file with arbitrary field name', (done) -> @timeout 5000 req.post url .attach 'gpx', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['gpx'].length, 1 assert.equal res.body['gpx'][0].fieldname, 'gpx' assert.equal res.body['gpx'][0].filename, 'totland.gpx' assert.equal res.body['gpx'][0].extension, 'gpx' assert.equal res.body['gpx'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['gpx'][0].geojson, 'object' .end done it 'should return error for non GPX file', (done) -> req.post url .attach 'files[]', resolve __dirname, '../data/file.json' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'file.json' assert.equal res.body['files[]'][0].extension, 'json' assert.equal res.body['files[]'][0].mimetype, 'application/json' assert.equal res.body['files[]'][0].geojson, null assert.equal res.body['files[]'][0].error, 'Invalid extension \'json\'' .end done
true
assert = require 'assert' request = require 'supertest' resolve = require('path').resolve app = require '../../src/server' mongo = require '../../src/mongo' trail = require '../assets/trail.json' req = request app base = '/api/v1' describe '/', -> it 'should do return API documentation', (done) -> req.get "#{base}" .expect 200 .end done describe '/boundary/intersect', -> it 'should return 400 for invalid body', (done) -> req.post "#{base}/boundary/intersect" .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post "#{base}/boundary/intersect" .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf1500004b', navn: 'Stølsheimen, Bergsdalen og Vossefjellene' } { _id: '52408144e7926dcf15000025', navn: 'Byfjellene i Bergen' } { _id: '52408144e7926dcf15000035', navn: 'Nordhordland' } ] assert.deepEqual res.body.kommuner, [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI' ] assert.deepEqual res.body.fylker, [ 'PI:NAME:<NAME>END_PI' ] .end done it 'should return for complex LineString', (done) -> @timeout 10000 req.post "#{base}/boundary/intersect" .send trail .expect 200 .expect (res) -> assert.deepEqual res.body.områder, [ { _id: '52408144e7926dcf15000050', navn: 'Huldreheimen' } { _id: '52408144e7926dcf1500000c', navn: 'Jotunheimen' } { _id: '52408144e7926dcf1500003c', navn: 'Skarvheimen' } { _id: '52408144e7926dcf15000039', navn: 'Hardangervidda' } ] assert.deepEqual res.body.kommuner, [ 'Vang', 'Lærdal', 'Aurland', 'Hol', 'Ål', 'Ulvik' ] assert.deepEqual res.body.fylker, [ 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', 'Hordaland' ] .end done describe '/line/analyze', -> url = "#{base}/line/analyze" it 'should return 400 for invalid body', (done) -> req.post url .expect 400 .end done it 'should return 422 for invalid geometry type', (done) -> req.post url .send geojson: type: 'Foo' .expect 422 .end done it 'should return 422 for invalid geometry coordinates', (done) -> req.post url .send geojson: type: 'LineString', coordinates: 'Foobar' .expect 422 .end done it 'should return for simple LineString', (done) -> req.post url .send geojson: type: 'LineString', coordinates: [ [ 5.32907, 60.39826 ] [ 6.41474, 60.62869 ] ] .expect 200 .expect (res) -> assert.deepEqual res.body, length: 64781 geojson: type: 'LineString' coordinates: [ [ 5.32907, 60.39826 ], [ 6.41474, 60.62869 ] ] properties: start: type: 'Point', coordinates: [ 5.32907, 60.39826 ] stop: type: 'Point', coordinates: [ 6.41474, 60.62869 ] .end done describe '/gpx/parse', -> url = "#{base}/gpx/parse" it 'should parse uploaded GPX file', (done) -> @timeout 5000 req.post url .attach 'files[]', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'totland.gpx' assert.equal res.body['files[]'][0].extension, 'gpx' assert.equal res.body['files[]'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['files[]'][0].geojson, 'object' .end done it 'should parse uploaded GPX file with arbitrary field name', (done) -> @timeout 5000 req.post url .attach 'gpx', resolve __dirname, '../data/totland.gpx' .expect 200 .expect (res) -> assert.equal res.body['gpx'].length, 1 assert.equal res.body['gpx'][0].fieldname, 'gpx' assert.equal res.body['gpx'][0].filename, 'totland.gpx' assert.equal res.body['gpx'][0].extension, 'gpx' assert.equal res.body['gpx'][0].mimetype, 'application/gpx+xml' assert.equal typeof res.body['gpx'][0].geojson, 'object' .end done it 'should return error for non GPX file', (done) -> req.post url .attach 'files[]', resolve __dirname, '../data/file.json' .expect 200 .expect (res) -> assert.equal res.body['files[]'].length, 1 assert.equal res.body['files[]'][0].fieldname, 'files[]' assert.equal res.body['files[]'][0].filename, 'file.json' assert.equal res.body['files[]'][0].extension, 'json' assert.equal res.body['files[]'][0].mimetype, 'application/json' assert.equal res.body['files[]'][0].geojson, null assert.equal res.body['files[]'][0].error, 'Invalid extension \'json\'' .end done
[ { "context": " Classroom], done)\n beforeEach (done) -> loginJoe (@joe) => done()\n beforeEach init.course()\n beforeEac", "end": 326, "score": 0.9996342062950134, "start": 321, "tag": "USERNAME", "value": "(@joe" }, { "context": "('/db/course_instance')\n data = {\n name:...
spec/server/functional/course_instance.spec.coffee
teplyja1/codecombat
1
async = require 'async' config = require '../../../server_config' require '../common' stripe = require('stripe')(config.stripe.secretKey) init = require '../init' describe 'POST /db/course_instance', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course() beforeEach init.classroom() it 'creates a CourseInstance', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'Some Name' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() done() it 'returns the same CourseInstance if you POST twice', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'Some Name' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() firstID = body._id request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() secondID = body._id expect(firstID).toBe(secondID) done() it 'returns 404 if the Course does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'Some Name' courseID: '123456789012345678901234' classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'returns 404 if the Classroom does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'Some Name' courseID: test.course.id classroomID: '123456789012345678901234' } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'return 403 if the logged in user does not own the Classroom', (done) -> test = @ loginSam -> url = getURL('/db/course_instance') data = { name: 'Some Name' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'adds a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() ], makeTestIterator(@), done) it 'adds the CourseInstance id to the user', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() ], makeTestIterator(@), done) it 'return 403 if the member is not in the classroom', (done) -> async.eachSeries([ (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 403 if the user does not own the course instance and is not adding self', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> loginSam -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 200 if the user is a member of the classroom and is adding self', -> it 'return 402 if the course is not free and the user is not in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(402) cb() ], makeTestIterator(@), done) it 'works if the course is not free and the user is in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, addTestUserToPrepaid, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(200) cb() ], makeTestIterator(@), done) makeTestCourseNotFree = (test, cb) -> test.course.set('free', false) test.course.save cb addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToPrepaid = (test, cb) -> test.prepaid.set('redeemers', [{userID: test.user.get('_id')}]) test.prepaid.save cb describe 'DELETE /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'removes a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() ], makeTestIterator(@), done) it 'removes the CourseInstance from the User.courseInstances', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() removeTestUserFromCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(0) cb() ], makeTestIterator(@), done) addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() removeTestUserFromCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() makeTestIterator = (testObject) -> (func, callback) -> func(testObject, callback)
217512
async = require 'async' config = require '../../../server_config' require '../common' stripe = require('stripe')(config.stripe.secretKey) init = require '../init' describe 'POST /db/course_instance', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course() beforeEach init.classroom() it 'creates a CourseInstance', (done) -> test = @ url = getURL('/db/course_instance') data = { name: '<NAME>' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() done() it 'returns the same CourseInstance if you POST twice', (done) -> test = @ url = getURL('/db/course_instance') data = { name: '<NAME>' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() firstID = body._id request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() secondID = body._id expect(firstID).toBe(secondID) done() it 'returns 404 if the Course does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: '<NAME>' courseID: '123456789012345678901234' classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'returns 404 if the Classroom does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: '<NAME>' courseID: test.course.id classroomID: '123456789012345678901234' } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'return 403 if the logged in user does not own the Classroom', (done) -> test = @ loginSam -> url = getURL('/db/course_instance') data = { name: '<NAME>' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'adds a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() ], makeTestIterator(@), done) it 'adds the CourseInstance id to the user', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() ], makeTestIterator(@), done) it 'return 403 if the member is not in the classroom', (done) -> async.eachSeries([ (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 403 if the user does not own the course instance and is not adding self', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> loginSam -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 200 if the user is a member of the classroom and is adding self', -> it 'return 402 if the course is not free and the user is not in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(402) cb() ], makeTestIterator(@), done) it 'works if the course is not free and the user is in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, addTestUserToPrepaid, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(200) cb() ], makeTestIterator(@), done) makeTestCourseNotFree = (test, cb) -> test.course.set('free', false) test.course.save cb addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToPrepaid = (test, cb) -> test.prepaid.set('redeemers', [{userID: test.user.get('_id')}]) test.prepaid.save cb describe 'DELETE /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'removes a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() ], makeTestIterator(@), done) it 'removes the CourseInstance from the User.courseInstances', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() removeTestUserFromCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(0) cb() ], makeTestIterator(@), done) addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() removeTestUserFromCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() makeTestIterator = (testObject) -> (func, callback) -> func(testObject, callback)
true
async = require 'async' config = require '../../../server_config' require '../common' stripe = require('stripe')(config.stripe.secretKey) init = require '../init' describe 'POST /db/course_instance', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course() beforeEach init.classroom() it 'creates a CourseInstance', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'PI:NAME:<NAME>END_PI' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() done() it 'returns the same CourseInstance if you POST twice', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'PI:NAME:<NAME>END_PI' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() firstID = body._id request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.classroomID).toBeDefined() secondID = body._id expect(firstID).toBe(secondID) done() it 'returns 404 if the Course does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'PI:NAME:<NAME>END_PI' courseID: '123456789012345678901234' classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'returns 404 if the Classroom does not exist', (done) -> test = @ url = getURL('/db/course_instance') data = { name: 'PI:NAME:<NAME>END_PI' courseID: test.course.id classroomID: '123456789012345678901234' } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(404) done() it 'return 403 if the logged in user does not own the Classroom', (done) -> test = @ loginSam -> url = getURL('/db/course_instance') data = { name: 'PI:NAME:<NAME>END_PI' courseID: test.course.id classroomID: test.classroom.id } request.post {uri: url, json: data}, (err, res, body) -> expect(res.statusCode).toBe(403) done() describe 'POST /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'adds a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() ], makeTestIterator(@), done) it 'adds the CourseInstance id to the user', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() ], makeTestIterator(@), done) it 'return 403 if the member is not in the classroom', (done) -> async.eachSeries([ (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 403 if the user does not own the course instance and is not adding self', (done) -> async.eachSeries([ addTestUserToClassroom, (test, cb) -> loginSam -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(403) cb() ], makeTestIterator(@), done) it 'returns 200 if the user is a member of the classroom and is adding self', -> it 'return 402 if the course is not free and the user is not in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(402) cb() ], makeTestIterator(@), done) it 'works if the course is not free and the user is in a prepaid', (done) -> async.eachSeries([ addTestUserToClassroom, makeTestCourseNotFree, addTestUserToPrepaid, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res) -> expect(res.statusCode).toBe(200) cb() ], makeTestIterator(@), done) makeTestCourseNotFree = (test, cb) -> test.course.set('free', false) test.course.save cb addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToPrepaid = (test, cb) -> test.prepaid.set('redeemers', [{userID: test.user.get('_id')}]) test.prepaid.save cb describe 'DELETE /db/course_instance/:id/members', -> beforeEach (done) -> clearModels([CourseInstance, Course, User, Classroom, Prepaid], done) beforeEach (done) -> loginJoe (@joe) => done() beforeEach init.course({free: true}) beforeEach init.classroom() beforeEach init.courseInstance() beforeEach init.user() beforeEach init.prepaid() it 'removes a member to the given CourseInstance', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() ], makeTestIterator(@), done) it 'removes the CourseInstance from the User.courseInstances', (done) -> async.eachSeries([ addTestUserToClassroom, addTestUserToCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(1) cb() removeTestUserFromCourseInstance, (test, cb) -> User.findById(test.user.id).exec (err, user) -> expect(_.size(user.get('courseInstances'))).toBe(0) cb() ], makeTestIterator(@), done) addTestUserToClassroom = (test, cb) -> test.classroom.set('members', [test.user.get('_id')]) test.classroom.save cb addTestUserToCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.post {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(1) expect(body.members[0]).toBe(test.user.id) cb() removeTestUserFromCourseInstance = (test, cb) -> url = getURL("/db/course_instance/#{test.courseInstance.id}/members") request.del {uri: url, json: {userID: test.user.id}}, (err, res, body) -> expect(res.statusCode).toBe(200) expect(body.members.length).toBe(0) cb() makeTestIterator = (testObject) -> (func, callback) -> func(testObject, callback)
[ { "context": "ileoverview Tests for no-lonely-if rule.\n# @author Brandon Mills\n###\n'use strict'\n\n#------------------------------", "end": 73, "score": 0.9986366033554077, "start": 60, "tag": "NAME", "value": "Brandon Mills" } ]
src/tests/rules/no-lonely-if.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-lonely-if rule. # @author Brandon Mills ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-lonely-if' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' errors = [ message: 'Unexpected if as the only statement in an else block.' type: 'IfStatement' ] ruleTester.run 'no-lonely-if', rule, # Examples of code that should not trigger the rule valid: [ ''' if a ; else if b ; ''' ''' if a ; else if b ; b ''' 'if a then b else if c then d' 'x = if a then b else if c then d' # postfix if shouldn't trigger ''' if a b else c if d ''' ] # Examples of code that should trigger the rule invalid: [ { code: ''' if a ; else if b ; ''' # output: ''' # if a # ; # else if b # ; # ''' errors } { code: ''' if a foo() else if b bar() ''' # output: ''' # if a # foo() # else if b # bar() # ''' errors } { code: ''' if a foo() else ### comment ### if b bar() ''' # output: ''' # if a # foo() # else ### comment ### if b # bar() # ''' errors } { code: ''' if a foo() else ### otherwise, do the other thing ### if b bar() ''' # output: null errors } { code: ''' if a foo() else if ### this comment is ok ### b bar() ''' # output: ''' # if a # foo() # else if ### this comment is ok ### b # bar() # ''' errors } { code: ''' if a foo() else if b bar() ### this comment will prevent this test case from being autofixed. ### ''' # output: null errors } { code: ''' if foo ; else if bar then baz() ''' # output: ''' # if foo # ; # else if bar then baz() # ''' errors } { # Not fixed; removing the braces would cause a SyntaxError. code: ''' if foo ; else if bar baz() qux() ''' # output: null errors } { code: ''' if a foo() else if b bar() else if c baz() else qux() ''' # output: # 'if (a) {\n' + # ' foo();\n' + # '} else if (b) {\n' + # ' bar();\n' + # ' } else if (c) {\n' + # ' baz();\n' + # ' } else {\n' + # ' qux();\n' + # ' }' errors } ]
84410
###* # @fileoverview Tests for no-lonely-if rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-lonely-if' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' errors = [ message: 'Unexpected if as the only statement in an else block.' type: 'IfStatement' ] ruleTester.run 'no-lonely-if', rule, # Examples of code that should not trigger the rule valid: [ ''' if a ; else if b ; ''' ''' if a ; else if b ; b ''' 'if a then b else if c then d' 'x = if a then b else if c then d' # postfix if shouldn't trigger ''' if a b else c if d ''' ] # Examples of code that should trigger the rule invalid: [ { code: ''' if a ; else if b ; ''' # output: ''' # if a # ; # else if b # ; # ''' errors } { code: ''' if a foo() else if b bar() ''' # output: ''' # if a # foo() # else if b # bar() # ''' errors } { code: ''' if a foo() else ### comment ### if b bar() ''' # output: ''' # if a # foo() # else ### comment ### if b # bar() # ''' errors } { code: ''' if a foo() else ### otherwise, do the other thing ### if b bar() ''' # output: null errors } { code: ''' if a foo() else if ### this comment is ok ### b bar() ''' # output: ''' # if a # foo() # else if ### this comment is ok ### b # bar() # ''' errors } { code: ''' if a foo() else if b bar() ### this comment will prevent this test case from being autofixed. ### ''' # output: null errors } { code: ''' if foo ; else if bar then baz() ''' # output: ''' # if foo # ; # else if bar then baz() # ''' errors } { # Not fixed; removing the braces would cause a SyntaxError. code: ''' if foo ; else if bar baz() qux() ''' # output: null errors } { code: ''' if a foo() else if b bar() else if c baz() else qux() ''' # output: # 'if (a) {\n' + # ' foo();\n' + # '} else if (b) {\n' + # ' bar();\n' + # ' } else if (c) {\n' + # ' baz();\n' + # ' } else {\n' + # ' qux();\n' + # ' }' errors } ]
true
###* # @fileoverview Tests for no-lonely-if rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-lonely-if' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' errors = [ message: 'Unexpected if as the only statement in an else block.' type: 'IfStatement' ] ruleTester.run 'no-lonely-if', rule, # Examples of code that should not trigger the rule valid: [ ''' if a ; else if b ; ''' ''' if a ; else if b ; b ''' 'if a then b else if c then d' 'x = if a then b else if c then d' # postfix if shouldn't trigger ''' if a b else c if d ''' ] # Examples of code that should trigger the rule invalid: [ { code: ''' if a ; else if b ; ''' # output: ''' # if a # ; # else if b # ; # ''' errors } { code: ''' if a foo() else if b bar() ''' # output: ''' # if a # foo() # else if b # bar() # ''' errors } { code: ''' if a foo() else ### comment ### if b bar() ''' # output: ''' # if a # foo() # else ### comment ### if b # bar() # ''' errors } { code: ''' if a foo() else ### otherwise, do the other thing ### if b bar() ''' # output: null errors } { code: ''' if a foo() else if ### this comment is ok ### b bar() ''' # output: ''' # if a # foo() # else if ### this comment is ok ### b # bar() # ''' errors } { code: ''' if a foo() else if b bar() ### this comment will prevent this test case from being autofixed. ### ''' # output: null errors } { code: ''' if foo ; else if bar then baz() ''' # output: ''' # if foo # ; # else if bar then baz() # ''' errors } { # Not fixed; removing the braces would cause a SyntaxError. code: ''' if foo ; else if bar baz() qux() ''' # output: null errors } { code: ''' if a foo() else if b bar() else if c baz() else qux() ''' # output: # 'if (a) {\n' + # ' foo();\n' + # '} else if (b) {\n' + # ' bar();\n' + # ' } else if (c) {\n' + # ' baz();\n' + # ' } else {\n' + # ' qux();\n' + # ' }' errors } ]
[ { "context": "r: second\n theField: rest\n\ncontenders: [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"", "end": 167, "score": 0.9998190999031067, "start": 153, "tag": "NAME", "value": "Michael Phelps" }, { "context": "Field: rest\n\ncontend...
documentation/coffee/splats.coffee
khaled/coffee-script
1
gold: silver: theField: "unknown" awardMedals: (first, second, rest...) -> gold: first silver: second theField: rest contenders: [ "Michael Phelps" "Liu Xiang" "Yao Ming" "Allyson Felix" "Shawn Johnson" "Roman Sebrle" "Guo Jingjing" "Tyson Gay" "Asafa Powell" "Usain Bolt" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + theField
193588
gold: silver: theField: "unknown" awardMedals: (first, second, rest...) -> gold: first silver: second theField: rest contenders: [ "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + theField
true
gold: silver: theField: "unknown" awardMedals: (first, second, rest...) -> gold: first silver: second theField: rest contenders: [ "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" ] awardMedals contenders... alert "Gold: " + gold alert "Silver: " + silver alert "The Field: " + theField
[ { "context": "@KimaAttachments = new Mongo.Collection 'kimaattachments'\n\n\n# { \"_", "end": 16, "score": 0.9435830116271973, "start": 1, "tag": "USERNAME", "value": "KimaAttachments" }, { "context": "dcd7dea84ce.jpg\", \"type\" : \"image/jpeg\", \"key\" : \"AdurnCp4wQPbEMuJp_144049...
config/collections/files/kimaattachments.coffee
sawima/kimashare
0
@KimaAttachments = new Mongo.Collection 'kimaattachments' # { "_id" : "yC7Mw5Yjofj8Mq32b", "name" : "photo-1438216983993-cdcd7dea84ce.jpg", "type" : "image/jpeg", "key" : "AdurnCp4wQPbEMuJp_1440495327132_photo-1438216983993-cdcd7dea84ce.jpg", "size" : 8451333, "path" : "/Products/AdurnCp4wQPbEMuJp_1440495327132_photo-1438216983993-cdcd7dea84ce.jpg", "folderpath" : "/Products", "createdAt" : ISODate("2015-08-25T09:35:27.133Z"), "metadata" : { "owner" : "FWhAoKCerXv32bn6H" } }
75092
@KimaAttachments = new Mongo.Collection 'kimaattachments' # { "_id" : "yC7Mw5Yjofj8Mq32b", "name" : "photo-1438216983993-cdcd7dea84ce.jpg", "type" : "image/jpeg", "key" : "<KEY>", "size" : 8451333, "path" : "/Products/AdurnCp4wQPbEMuJp_1440495327132_photo-1438216983993-cdcd7dea84ce.jpg", "folderpath" : "/Products", "createdAt" : ISODate("2015-08-25T09:35:27.133Z"), "metadata" : { "owner" : "FWhAoKCerXv32bn6H" } }
true
@KimaAttachments = new Mongo.Collection 'kimaattachments' # { "_id" : "yC7Mw5Yjofj8Mq32b", "name" : "photo-1438216983993-cdcd7dea84ce.jpg", "type" : "image/jpeg", "key" : "PI:KEY:<KEY>END_PI", "size" : 8451333, "path" : "/Products/AdurnCp4wQPbEMuJp_1440495327132_photo-1438216983993-cdcd7dea84ce.jpg", "folderpath" : "/Products", "createdAt" : ISODate("2015-08-25T09:35:27.133Z"), "metadata" : { "owner" : "FWhAoKCerXv32bn6H" } }
[ { "context": "elper.defaultGateway.customer.create {firstName: 'Bob', lastName: lastName}, (err, response) ->\n ", "end": 281, "score": 0.999756932258606, "start": 278, "tag": "NAME", "value": "Bob" }, { "context": "elper.defaultGateway.customer.create {firstName: 'Ryan', lastN...
spec/integration/braintree/customer_search_spec.coffee
StreamCo/braintree_node
0
require("../../spec_helper") {Config} = require('../../../lib/braintree/config') describe "CustomerSearch", -> describe "search", -> lastName = null before (done) -> lastName = specHelper.randomId() specHelper.defaultGateway.customer.create {firstName: 'Bob', lastName: lastName}, (err, response) -> specHelper.defaultGateway.customer.create {firstName: 'Ryan', lastName: lastName}, (err, response) -> done() it "can return no results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.email().is(specHelper.randomId() + "@example.com")), (err, response) -> assert.isNull(err) assert.equal(response.length(), 0) done() it "can return a single result", (done) -> search = (search) -> search.firstName().is("Bob") search.lastName().is(lastName) specHelper.defaultGateway.customer.search search, (err, response) -> response.first (err, customer) -> assert.equal(customer.firstName, 'Bob') assert.equal(customer.lastName, lastName) done() it "allows stream style interation of results", (done) -> search = specHelper.defaultGateway.customer.search (search) -> search.lastName().is(lastName) customers = [] search.on 'data', (customer) -> customers.push customer search.on 'end', -> assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() search.resume() it "can return multiple results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.lastName().is(lastName)), (err, response) -> customers = [] response.each (err, customer) -> customers.push customer if customers.length == 2 assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() it "handles complex searches", (done) -> id = specHelper.randomId() email = "#{specHelper.randomId()}@example.com" firstName = "John_#{specHelper.randomId()}" lastName = "Smith_#{specHelper.randomId()}" cardToken = "card_#{specHelper.randomId()}" customerParams = company: "Braintree" email: email fax: "(123)456-7890" firstName: firstName id: id lastName: lastName phone: "(456)123-7890" website: "http://www.example.com/" creditCard: number: "5105105105105100" expirationDate: "05/2012" cardholderName: "#{firstName} #{lastName}" token: cardToken billingAddress: firstName: firstName lastName: lastName streetAddress: "123 Fake St" extendedAddress: "Suite 403" locality: "Chicago" region: "IL" postalCode: "60607" countryName: "United States of America" specHelper.defaultGateway.customer.create customerParams, (err, response) -> textCriteria = addressCountryName: "United States of America" addressExtendedAddress: "Suite 403" addressFirstName: firstName addressLastName: lastName addressLocality: "Chicago" addressPostalCode: "60607" addressStreetAddress: "123 Fake St" cardholderName: "#{firstName} #{lastName}" company: "Braintree" email: email fax: "(123)456-7890" firstName: firstName id: id lastName: lastName paymentMethodToken: cardToken phone: "(456)123-7890" website: "http://www.example.com/" equalityCriteria = creditCardExpirationDate: "05/2012" partialCriteria = creditCardNumber: startsWith: "5105" endsWith: "100" multipleValueCriteria = ids: customerParams.id today = new Date() yesterday = new Date(); yesterday.setDate(today.getDate() - 1) tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1) rangeCriteria = createdAt: min: yesterday max: tomorrow search = (search) -> for criteria, value of textCriteria search[criteria]().is(value) for criteria, value of equalityCriteria search[criteria]().is(value) for criteria, partial of partialCriteria for operator, value of partial search[criteria]()[operator](value) for criteria, value of multipleValueCriteria search[criteria]().is(value) for criteria, range of rangeCriteria for operator, value of range search[criteria]()[operator](value) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.id, customerParams.id) assert.isNull(err) done() it "searches on customer's paypal account by email", (done) -> customerId = "CUSTOMER_#{specHelper.randomId()}" firstName = "John_#{specHelper.randomId()}" lastName = "Smith_#{specHelper.randomId()}" paymentMethodToken = "PAYPAL_ACCOUNT_#{specHelper.randomId()}" customerParams = id: customerId firstName: firstName lastName: lastName specHelper.defaultGateway.customer.create customerParams, (err, response) -> myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig)) specHelper.defaultGateway.clientToken.generate({}, (err, result) -> clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken)) authorizationFingerprint = clientToken.authorizationFingerprint params = authorizationFingerprint: authorizationFingerprint paypalAccount: consentCode: 'PAYPAL_CONSENT_CODE' token: paymentMethodToken myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) -> nonce = JSON.parse(body).paypalAccounts[0].nonce paypalAccountParams = customerId: customerId paymentMethodNonce: nonce specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) -> search = (search) -> search.paypalAccountEmail().is(response.paymentMethod.email) search.id().is(customerId) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.paypalAccounts[0].token, paymentMethodToken) assert.isNull(err) done() ) )
171012
require("../../spec_helper") {Config} = require('../../../lib/braintree/config') describe "CustomerSearch", -> describe "search", -> lastName = null before (done) -> lastName = specHelper.randomId() specHelper.defaultGateway.customer.create {firstName: '<NAME>', lastName: lastName}, (err, response) -> specHelper.defaultGateway.customer.create {firstName: '<NAME>', lastName: lastName}, (err, response) -> done() it "can return no results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.email().is(specHelper.randomId() + "@example.com")), (err, response) -> assert.isNull(err) assert.equal(response.length(), 0) done() it "can return a single result", (done) -> search = (search) -> search.firstName().is("<NAME>") search.lastName().is(lastName) specHelper.defaultGateway.customer.search search, (err, response) -> response.first (err, customer) -> assert.equal(customer.firstName, '<NAME>') assert.equal(customer.lastName, lastName) done() it "allows stream style interation of results", (done) -> search = specHelper.defaultGateway.customer.search (search) -> search.lastName().is(lastName) customers = [] search.on 'data', (customer) -> customers.push customer search.on 'end', -> assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() search.resume() it "can return multiple results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.lastName().is(lastName)), (err, response) -> customers = [] response.each (err, customer) -> customers.push customer if customers.length == 2 assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() it "handles complex searches", (done) -> id = specHelper.randomId() email = "#{specHelper.randomId()}<EMAIL>" firstName = "<NAME>_#{specHelper.randomId()}" lastName = "<NAME>_#{specHelper.randomId()}" cardToken = "<KEY>_#{specHelper.randomId()}" customerParams = company: "Braintree" email: email fax: "(123)456-7890" firstName: <NAME> id: id lastName: <NAME> phone: "(456)123-7890" website: "http://www.example.com/" creditCard: number: "5105105105105100" expirationDate: "05/2012" cardholderName: <NAME>} #{<NAME>}" token: cardToken billingAddress: firstName: <NAME> lastName: <NAME> streetAddress: "123 Fake St" extendedAddress: "Suite 403" locality: "Chicago" region: "IL" postalCode: "60607" countryName: "United States of America" specHelper.defaultGateway.customer.create customerParams, (err, response) -> textCriteria = addressCountryName: "United States of America" addressExtendedAddress: "Suite 403" addressFirstName: <NAME> addressLastName: <NAME> addressLocality: "Chicago" addressPostalCode: "60607" addressStreetAddress: "123 Fake St" cardholderName:<NAME> "#{<NAME>} #{<NAME>}" company: "Braintree" email: email fax: "(123)456-7890" firstName: <NAME> id: id lastName: <NAME> paymentMethodToken: cardToken phone: "(456)123-7890" website: "http://www.example.com/" equalityCriteria = creditCardExpirationDate: "05/2012" partialCriteria = creditCardNumber: startsWith: "5105" endsWith: "100" multipleValueCriteria = ids: customerParams.id today = new Date() yesterday = new Date(); yesterday.setDate(today.getDate() - 1) tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1) rangeCriteria = createdAt: min: yesterday max: tomorrow search = (search) -> for criteria, value of textCriteria search[criteria]().is(value) for criteria, value of equalityCriteria search[criteria]().is(value) for criteria, partial of partialCriteria for operator, value of partial search[criteria]()[operator](value) for criteria, value of multipleValueCriteria search[criteria]().is(value) for criteria, range of rangeCriteria for operator, value of range search[criteria]()[operator](value) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.id, customerParams.id) assert.isNull(err) done() it "searches on customer's paypal account by email", (done) -> customerId = "CUSTOMER_#{specHelper.randomId()}" firstName = "<NAME>_#{specHelper.randomId()}" lastName = "<NAME>_#{specHelper.randomId()}" paymentMethodToken = "PAYPAL_ACCOUNT_#{specHelper.randomId()}" customerParams = id: customerId firstName: firstName lastName: lastName specHelper.defaultGateway.customer.create customerParams, (err, response) -> myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig)) specHelper.defaultGateway.clientToken.generate({}, (err, result) -> clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken)) authorizationFingerprint = clientToken.authorizationFingerprint params = authorizationFingerprint: authorizationFingerprint paypalAccount: consentCode: 'PAYPAL_CONSENT_CODE' token: paymentMethodToken myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) -> nonce = JSON.parse(body).paypalAccounts[0].nonce paypalAccountParams = customerId: customerId paymentMethodNonce: nonce specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) -> search = (search) -> search.paypalAccountEmail().is(response.paymentMethod.email) search.id().is(customerId) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.paypalAccounts[0].token, paymentMethodToken) assert.isNull(err) done() ) )
true
require("../../spec_helper") {Config} = require('../../../lib/braintree/config') describe "CustomerSearch", -> describe "search", -> lastName = null before (done) -> lastName = specHelper.randomId() specHelper.defaultGateway.customer.create {firstName: 'PI:NAME:<NAME>END_PI', lastName: lastName}, (err, response) -> specHelper.defaultGateway.customer.create {firstName: 'PI:NAME:<NAME>END_PI', lastName: lastName}, (err, response) -> done() it "can return no results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.email().is(specHelper.randomId() + "@example.com")), (err, response) -> assert.isNull(err) assert.equal(response.length(), 0) done() it "can return a single result", (done) -> search = (search) -> search.firstName().is("PI:NAME:<NAME>END_PI") search.lastName().is(lastName) specHelper.defaultGateway.customer.search search, (err, response) -> response.first (err, customer) -> assert.equal(customer.firstName, 'PI:NAME:<NAME>END_PI') assert.equal(customer.lastName, lastName) done() it "allows stream style interation of results", (done) -> search = specHelper.defaultGateway.customer.search (search) -> search.lastName().is(lastName) customers = [] search.on 'data', (customer) -> customers.push customer search.on 'end', -> assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() search.resume() it "can return multiple results", (done) -> specHelper.defaultGateway.customer.search ((search) -> search.lastName().is(lastName)), (err, response) -> customers = [] response.each (err, customer) -> customers.push customer if customers.length == 2 assert.equal(customers.length, 2) assert.equal(customers[0].lastName, lastName) assert.equal(customers[1].lastName, lastName) done() it "handles complex searches", (done) -> id = specHelper.randomId() email = "#{specHelper.randomId()}PI:EMAIL:<EMAIL>END_PI" firstName = "PI:NAME:<NAME>END_PI_#{specHelper.randomId()}" lastName = "PI:NAME:<NAME>END_PI_#{specHelper.randomId()}" cardToken = "PI:KEY:<KEY>END_PI_#{specHelper.randomId()}" customerParams = company: "Braintree" email: email fax: "(123)456-7890" firstName: PI:NAME:<NAME>END_PI id: id lastName: PI:NAME:<NAME>END_PI phone: "(456)123-7890" website: "http://www.example.com/" creditCard: number: "5105105105105100" expirationDate: "05/2012" cardholderName: PI:NAME:<NAME>END_PI} #{PI:NAME:<NAME>END_PI}" token: cardToken billingAddress: firstName: PI:NAME:<NAME>END_PI lastName: PI:NAME:<NAME>END_PI streetAddress: "123 Fake St" extendedAddress: "Suite 403" locality: "Chicago" region: "IL" postalCode: "60607" countryName: "United States of America" specHelper.defaultGateway.customer.create customerParams, (err, response) -> textCriteria = addressCountryName: "United States of America" addressExtendedAddress: "Suite 403" addressFirstName: PI:NAME:<NAME>END_PI addressLastName: PI:NAME:<NAME>END_PI addressLocality: "Chicago" addressPostalCode: "60607" addressStreetAddress: "123 Fake St" cardholderName:PI:NAME:<NAME>END_PI "#{PI:NAME:<NAME>END_PI} #{PI:NAME:<NAME>END_PI}" company: "Braintree" email: email fax: "(123)456-7890" firstName: PI:NAME:<NAME>END_PI id: id lastName: PI:NAME:<NAME>END_PI paymentMethodToken: cardToken phone: "(456)123-7890" website: "http://www.example.com/" equalityCriteria = creditCardExpirationDate: "05/2012" partialCriteria = creditCardNumber: startsWith: "5105" endsWith: "100" multipleValueCriteria = ids: customerParams.id today = new Date() yesterday = new Date(); yesterday.setDate(today.getDate() - 1) tomorrow = new Date(); tomorrow.setDate(today.getDate() + 1) rangeCriteria = createdAt: min: yesterday max: tomorrow search = (search) -> for criteria, value of textCriteria search[criteria]().is(value) for criteria, value of equalityCriteria search[criteria]().is(value) for criteria, partial of partialCriteria for operator, value of partial search[criteria]()[operator](value) for criteria, value of multipleValueCriteria search[criteria]().is(value) for criteria, range of rangeCriteria for operator, value of range search[criteria]()[operator](value) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.id, customerParams.id) assert.isNull(err) done() it "searches on customer's paypal account by email", (done) -> customerId = "CUSTOMER_#{specHelper.randomId()}" firstName = "PI:NAME:<NAME>END_PI_#{specHelper.randomId()}" lastName = "PI:NAME:<NAME>END_PI_#{specHelper.randomId()}" paymentMethodToken = "PAYPAL_ACCOUNT_#{specHelper.randomId()}" customerParams = id: customerId firstName: firstName lastName: lastName specHelper.defaultGateway.customer.create customerParams, (err, response) -> myHttp = new specHelper.clientApiHttp(new Config(specHelper.defaultConfig)) specHelper.defaultGateway.clientToken.generate({}, (err, result) -> clientToken = JSON.parse(specHelper.decodeClientToken(result.clientToken)) authorizationFingerprint = clientToken.authorizationFingerprint params = authorizationFingerprint: authorizationFingerprint paypalAccount: consentCode: 'PAYPAL_CONSENT_CODE' token: paymentMethodToken myHttp.post("/client_api/v1/payment_methods/paypal_accounts.json", params, (statusCode, body) -> nonce = JSON.parse(body).paypalAccounts[0].nonce paypalAccountParams = customerId: customerId paymentMethodNonce: nonce specHelper.defaultGateway.paymentMethod.create paypalAccountParams, (err, response) -> search = (search) -> search.paypalAccountEmail().is(response.paymentMethod.email) search.id().is(customerId) specHelper.defaultGateway.customer.search search, (err, response) -> assert.isTrue(response.success) assert.equal(response.length(), 1) response.first (err, customer) -> assert.isObject(customer) assert.equal(customer.paypalAccounts[0].token, paymentMethodToken) assert.isNull(err) done() ) )
[ { "context": "moryDataSource(@records)\n @let 'records', -> ['Rose Tyler', 'Martha Jones', 'Amy Pond', 'Rory Pond', 'unkno", "end": 910, "score": 0.9997937083244324, "start": 900, "tag": "NAME", "value": "Rose Tyler" }, { "context": "(@records)\n @let 'records', -> ['Rose Tyler...
spec/javascripts/data_source_builder_spec.js.coffee
beeflamian/shuttle
327
# Copyright 2014 Square Inc. # # 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. #= require data_source_builder #= require memory_data_source describe 'DataSourceBuilder', -> @let 'dataSource', -> @builder.build() @let 'builder', -> new DataSourceBuilder() describe 'with a base', -> @let 'baseDataSource', -> new MemoryDataSource(@records) @let 'records', -> ['Rose Tyler', 'Martha Jones', 'Amy Pond', 'Rory Pond', 'unknown'] beforeEach -> @builder.base(@baseDataSource) describe 'with no modifiers', -> it 'simply returns the base', -> expect(@dataSource).toBe(@baseDataSource) describe 'with filtering', -> beforeEach -> @builder.filter(yes) it 'has filtering', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) expectPromise(@dataSource.fetch(3)).toResolveWith(['Amy Pond', 'Rory Pond']) describe 'and with caching', -> beforeEach -> @builder.cache(yes) it 'has caching', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) spyOn(@baseDataSource, 'fetch').andCallThrough() expectPromise(@dataSource.fetch(1)).toResolveWith(['Amy Pond']) expectPromise(@dataSource.fetch(3)).toResolveWith(['Rory Pond']) @dataSource.rewind(1) expectPromise(@dataSource.fetch(4)).toResolveWith(['Rory Pond']) expect(@baseDataSource.fetch.callCount).toEqual(4)
218727
# Copyright 2014 Square Inc. # # 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. #= require data_source_builder #= require memory_data_source describe 'DataSourceBuilder', -> @let 'dataSource', -> @builder.build() @let 'builder', -> new DataSourceBuilder() describe 'with a base', -> @let 'baseDataSource', -> new MemoryDataSource(@records) @let 'records', -> ['<NAME>', '<NAME>', '<NAME>my Pond', 'Rory Pond', 'unknown'] beforeEach -> @builder.base(@baseDataSource) describe 'with no modifiers', -> it 'simply returns the base', -> expect(@dataSource).toBe(@baseDataSource) describe 'with filtering', -> beforeEach -> @builder.filter(yes) it 'has filtering', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) expectPromise(@dataSource.fetch(3)).toResolveWith(['<NAME>my Pond', 'Rory Pond']) describe 'and with caching', -> beforeEach -> @builder.cache(yes) it 'has caching', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) spyOn(@baseDataSource, 'fetch').andCallThrough() expectPromise(@dataSource.fetch(1)).toResolveWith(['<NAME>my Pond']) expectPromise(@dataSource.fetch(3)).toResolveWith(['<NAME>ory Pond']) @dataSource.rewind(1) expectPromise(@dataSource.fetch(4)).toResolveWith(['Rory Pond']) expect(@baseDataSource.fetch.callCount).toEqual(4)
true
# Copyright 2014 Square Inc. # # 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. #= require data_source_builder #= require memory_data_source describe 'DataSourceBuilder', -> @let 'dataSource', -> @builder.build() @let 'builder', -> new DataSourceBuilder() describe 'with a base', -> @let 'baseDataSource', -> new MemoryDataSource(@records) @let 'records', -> ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PImy Pond', 'Rory Pond', 'unknown'] beforeEach -> @builder.base(@baseDataSource) describe 'with no modifiers', -> it 'simply returns the base', -> expect(@dataSource).toBe(@baseDataSource) describe 'with filtering', -> beforeEach -> @builder.filter(yes) it 'has filtering', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) expectPromise(@dataSource.fetch(3)).toResolveWith(['PI:NAME:<NAME>END_PImy Pond', 'Rory Pond']) describe 'and with caching', -> beforeEach -> @builder.cache(yes) it 'has caching', -> @dataSource.applyFilter 'ponds', (name) -> (/\sPond$/.test(name)) spyOn(@baseDataSource, 'fetch').andCallThrough() expectPromise(@dataSource.fetch(1)).toResolveWith(['PI:NAME:<NAME>END_PImy Pond']) expectPromise(@dataSource.fetch(3)).toResolveWith(['PI:NAME:<NAME>END_PIory Pond']) @dataSource.rewind(1) expectPromise(@dataSource.fetch(4)).toResolveWith(['Rory Pond']) expect(@baseDataSource.fetch.callCount).toEqual(4)
[ { "context": " 'Test'\n Authors.insert postId: id, fullname: 'Max Nowack'\n Authors.insert postId: id, fullname: 'John D", "end": 507, "score": 0.9998874664306641, "start": 497, "tag": "NAME", "value": "Max Nowack" }, { "context": "Nowack'\n Authors.insert postId: id, fullna...
tests/server-transform.coffee
maximalmeteor/server-transform
44
Meteor.startup -> Posts = new Mongo.Collection 'posts' Comments = new Mongo.Collection 'comments' Authors = new Mongo.Collection 'authors' if Meteor.isServer ServerTransform.enableLogging() Comments.allow insert: -> true update: -> true remove: -> true Comments.deny insert: -> false update: -> false remove: -> false Posts.remove {} Comments.remove {} id = Posts.insert name: 'Test' Authors.insert postId: id, fullname: 'Max Nowack' Authors.insert postId: id, fullname: 'John Doe' Posts.serverTransform (doc) -> doc.commentsCount = Comments.find({postId: doc._id}, reactive: true).count() return doc Meteor.publishTransformed 'posts_1', -> Comments.remove {} Comments.insert postId: id, text: 'Hello' Posts.find() Meteor.publishTransformed 'posts_2', -> Posts.find().serverTransform (doc) -> doc.test_2 = true return doc Meteor.publishTransformed 'posts_3', -> Posts.find().serverTransform test_3: true Meteor.publishTransformed 'posts_4', -> Posts.find().serverTransform authors: (doc) -> Authors.find {postId: doc._id}, reactive: true Tinytest.add 'ServerTransform - single property', (test) -> Posts.serverTransform authorName: (doc) -> return 'max' post = Posts.findOne() post = ServerTransform.applyTransformations Posts._serverTransformations, post test.equal post.authorName, 'max' if Meteor.isClient Tinytest.addAsync 'ServerTransform - simple', (test, next) -> Meteor.subscribe 'posts_1', -> test.isTrue Posts.find().count() > 0 post = Posts.findOne() Comments.insert postId: post._id, text: 'Hello' Posts.find(_id: post._id).observe changed: (doc) -> test.isTrue doc.commentsCount > 1 next() # Meteor.setTimeout -> # test.isTrue Posts.findOne(post._id).commentsCount > 1 # next() # , 2000 Tinytest.addAsync 'ServerTransform - local transform', (test, next) -> Meteor.subscribe 'posts_2', -> post = Posts.findOne() test.isTrue post.test_2 next() Tinytest.addAsync 'ServerTransform - local transform with object definition', (test, next) -> Meteor.subscribe 'posts_3', -> post = Posts.findOne() test.isTrue post.test_3 next() Tinytest.addAsync 'ServerTransform - sub cursor publication', (test, next) -> Meteor.subscribe 'posts_4', -> post = Posts.findOne() cursor = Authors.find postId: post._id test.equal cursor.count(), 2 next()
203210
Meteor.startup -> Posts = new Mongo.Collection 'posts' Comments = new Mongo.Collection 'comments' Authors = new Mongo.Collection 'authors' if Meteor.isServer ServerTransform.enableLogging() Comments.allow insert: -> true update: -> true remove: -> true Comments.deny insert: -> false update: -> false remove: -> false Posts.remove {} Comments.remove {} id = Posts.insert name: 'Test' Authors.insert postId: id, fullname: '<NAME>' Authors.insert postId: id, fullname: '<NAME>' Posts.serverTransform (doc) -> doc.commentsCount = Comments.find({postId: doc._id}, reactive: true).count() return doc Meteor.publishTransformed 'posts_1', -> Comments.remove {} Comments.insert postId: id, text: 'Hello' Posts.find() Meteor.publishTransformed 'posts_2', -> Posts.find().serverTransform (doc) -> doc.test_2 = true return doc Meteor.publishTransformed 'posts_3', -> Posts.find().serverTransform test_3: true Meteor.publishTransformed 'posts_4', -> Posts.find().serverTransform authors: (doc) -> Authors.find {postId: doc._id}, reactive: true Tinytest.add 'ServerTransform - single property', (test) -> Posts.serverTransform authorName: (doc) -> return 'max' post = Posts.findOne() post = ServerTransform.applyTransformations Posts._serverTransformations, post test.equal post.authorName, 'max' if Meteor.isClient Tinytest.addAsync 'ServerTransform - simple', (test, next) -> Meteor.subscribe 'posts_1', -> test.isTrue Posts.find().count() > 0 post = Posts.findOne() Comments.insert postId: post._id, text: 'Hello' Posts.find(_id: post._id).observe changed: (doc) -> test.isTrue doc.commentsCount > 1 next() # Meteor.setTimeout -> # test.isTrue Posts.findOne(post._id).commentsCount > 1 # next() # , 2000 Tinytest.addAsync 'ServerTransform - local transform', (test, next) -> Meteor.subscribe 'posts_2', -> post = Posts.findOne() test.isTrue post.test_2 next() Tinytest.addAsync 'ServerTransform - local transform with object definition', (test, next) -> Meteor.subscribe 'posts_3', -> post = Posts.findOne() test.isTrue post.test_3 next() Tinytest.addAsync 'ServerTransform - sub cursor publication', (test, next) -> Meteor.subscribe 'posts_4', -> post = Posts.findOne() cursor = Authors.find postId: post._id test.equal cursor.count(), 2 next()
true
Meteor.startup -> Posts = new Mongo.Collection 'posts' Comments = new Mongo.Collection 'comments' Authors = new Mongo.Collection 'authors' if Meteor.isServer ServerTransform.enableLogging() Comments.allow insert: -> true update: -> true remove: -> true Comments.deny insert: -> false update: -> false remove: -> false Posts.remove {} Comments.remove {} id = Posts.insert name: 'Test' Authors.insert postId: id, fullname: 'PI:NAME:<NAME>END_PI' Authors.insert postId: id, fullname: 'PI:NAME:<NAME>END_PI' Posts.serverTransform (doc) -> doc.commentsCount = Comments.find({postId: doc._id}, reactive: true).count() return doc Meteor.publishTransformed 'posts_1', -> Comments.remove {} Comments.insert postId: id, text: 'Hello' Posts.find() Meteor.publishTransformed 'posts_2', -> Posts.find().serverTransform (doc) -> doc.test_2 = true return doc Meteor.publishTransformed 'posts_3', -> Posts.find().serverTransform test_3: true Meteor.publishTransformed 'posts_4', -> Posts.find().serverTransform authors: (doc) -> Authors.find {postId: doc._id}, reactive: true Tinytest.add 'ServerTransform - single property', (test) -> Posts.serverTransform authorName: (doc) -> return 'max' post = Posts.findOne() post = ServerTransform.applyTransformations Posts._serverTransformations, post test.equal post.authorName, 'max' if Meteor.isClient Tinytest.addAsync 'ServerTransform - simple', (test, next) -> Meteor.subscribe 'posts_1', -> test.isTrue Posts.find().count() > 0 post = Posts.findOne() Comments.insert postId: post._id, text: 'Hello' Posts.find(_id: post._id).observe changed: (doc) -> test.isTrue doc.commentsCount > 1 next() # Meteor.setTimeout -> # test.isTrue Posts.findOne(post._id).commentsCount > 1 # next() # , 2000 Tinytest.addAsync 'ServerTransform - local transform', (test, next) -> Meteor.subscribe 'posts_2', -> post = Posts.findOne() test.isTrue post.test_2 next() Tinytest.addAsync 'ServerTransform - local transform with object definition', (test, next) -> Meteor.subscribe 'posts_3', -> post = Posts.findOne() test.isTrue post.test_3 next() Tinytest.addAsync 'ServerTransform - sub cursor publication', (test, next) -> Meteor.subscribe 'posts_4', -> post = Posts.findOne() cursor = Authors.find postId: post._id test.equal cursor.count(), 2 next()
[ { "context": "otypal ones.\nclass Cat\n constructor: -> @name = 'Whiskers'\n breed: 'tabby'\n hair: 'cream'\n\nwhiskers = ne", "end": 3028, "score": 0.99942946434021, "start": 3020, "tag": "NAME", "value": "Whiskers" } ]
QProjectManager/node_modules/jade/support/coffee-script/test/test_comprehensions.coffee
rkoyama1623/Quantum
35
# Basic array comprehensions. nums = n * n for n in [1, 2, 3] when n % 2 isnt 0 results = n * 2 for n in nums ok results.join(',') is '2,18' # Basic object comprehensions. obj = {one: 1, two: 2, three: 3} names = prop + '!' for prop of obj odds = prop + '!' for prop, value of obj when value % 2 isnt 0 ok names.join(' ') is "one! two! three!" ok odds.join(' ') is "one! three!" # Basic range comprehensions. nums = i * 3 for i in [1..3] negs = x for x in [-20..-5*2] negs = negs[0..2] result = nums.concat(negs).join(', ') ok result is '3, 6, 9, -20, -19, -18' ok i is 3 ok x is -10 # With range comprehensions, you can loop in steps. results = x for x in [0...15] by 5 ok results.join(' ') is '0 5 10' results = x for x in [0..100] by 10 ok results.join(' ') is '0 10 20 30 40 50 60 70 80 90 100' # And can loop downwards, with a negative step. results = x for x in [5..1] ok results.join(' ') is '5 4 3 2 1' ok results.join(' ') is [(10-5)..(-2+3)].join(' ') results = x for x in [10..1] ok results.join(' ') is [10..1].join(' ') results = x for x in [10...0] by -2 ok results.join(' ') is [10, 8, 6, 4, 2].join(' ') # Multiline array comprehension with filter. evens = for num in [1, 2, 3, 4, 5, 6] when num % 2 is 0 num *= -1 num -= 2 num * -1 ok evens.join(', ') is '4, 6, 8' # The in operator still works, standalone. ok 2 of evens # Ensure that the closure wrapper preserves local variables. obj = {} for method in ['one', 'two', 'three'] obj[method] = -> "I'm " + method ok obj.one() is "I'm one" ok obj.two() is "I'm two" ok obj.three() is "I'm three" i = 0 for i in [1..3] -> 'func' break if false ok i is 3 # Ensure that local variables are closed over for range comprehensions. funcs = for i in [1..3] -> -i ok (func() for func in funcs).join(' ') is '-1 -2 -3' ok i is 3 # Ensure that closing over local variables doesn't break scoping laws. for i in [0] count = 0 i = 50 -> ok count is 0 ok i is 50 # Even when referenced in the filter. list = ['one', 'two', 'three'] methods = for num, i in list when num isnt 'two' and i isnt 1 -> num + ' ' + i ok methods.length is 2 ok methods[0]() is 'one 0' ok methods[1]() is 'three 2' # Naked ranges are expanded into arrays. array = [0..10] ok(num % 2 is 0 for num in array by 2) # Nested comprehensions. multiLiner = for x in [3..5] for y in [3..5] [x, y] singleLiner = [x, y] for y in [3..5] for x in [3..5] ok multiLiner.length is singleLiner.length ok 5 is multiLiner[2][2][1] ok 5 is singleLiner[2][2][1] # Comprehensions within parentheses. result = null store = (obj) -> result = obj store (x * 2 for x in [3, 2, 1]) ok result.join(' ') is '6 4 2' # Closure-wrapped comprehensions that refer to the "arguments" object. expr = -> result = item * item for item in arguments ok expr(2, 4, 8).join(' ') is '4 16 64' # Fast object comprehensions over all properties, including prototypal ones. class Cat constructor: -> @name = 'Whiskers' breed: 'tabby' hair: 'cream' whiskers = new Cat own = value for key, value of whiskers all = value for all key, value of whiskers ok own.join(' ') is 'Whiskers' ok all.sort().join(' ') is 'Whiskers cream tabby' # Optimized range comprehensions. exxes = 'x' for [0...10] ok exxes.join(' ') is 'x x x x x x x x x x' # Comprehensions safely redeclare parameters if they're not present in closest # scope. rule = (x) -> x learn = -> rule for rule in [1, 2, 3] ok learn().join(' ') is '1 2 3' ok rule(101) is 101
49415
# Basic array comprehensions. nums = n * n for n in [1, 2, 3] when n % 2 isnt 0 results = n * 2 for n in nums ok results.join(',') is '2,18' # Basic object comprehensions. obj = {one: 1, two: 2, three: 3} names = prop + '!' for prop of obj odds = prop + '!' for prop, value of obj when value % 2 isnt 0 ok names.join(' ') is "one! two! three!" ok odds.join(' ') is "one! three!" # Basic range comprehensions. nums = i * 3 for i in [1..3] negs = x for x in [-20..-5*2] negs = negs[0..2] result = nums.concat(negs).join(', ') ok result is '3, 6, 9, -20, -19, -18' ok i is 3 ok x is -10 # With range comprehensions, you can loop in steps. results = x for x in [0...15] by 5 ok results.join(' ') is '0 5 10' results = x for x in [0..100] by 10 ok results.join(' ') is '0 10 20 30 40 50 60 70 80 90 100' # And can loop downwards, with a negative step. results = x for x in [5..1] ok results.join(' ') is '5 4 3 2 1' ok results.join(' ') is [(10-5)..(-2+3)].join(' ') results = x for x in [10..1] ok results.join(' ') is [10..1].join(' ') results = x for x in [10...0] by -2 ok results.join(' ') is [10, 8, 6, 4, 2].join(' ') # Multiline array comprehension with filter. evens = for num in [1, 2, 3, 4, 5, 6] when num % 2 is 0 num *= -1 num -= 2 num * -1 ok evens.join(', ') is '4, 6, 8' # The in operator still works, standalone. ok 2 of evens # Ensure that the closure wrapper preserves local variables. obj = {} for method in ['one', 'two', 'three'] obj[method] = -> "I'm " + method ok obj.one() is "I'm one" ok obj.two() is "I'm two" ok obj.three() is "I'm three" i = 0 for i in [1..3] -> 'func' break if false ok i is 3 # Ensure that local variables are closed over for range comprehensions. funcs = for i in [1..3] -> -i ok (func() for func in funcs).join(' ') is '-1 -2 -3' ok i is 3 # Ensure that closing over local variables doesn't break scoping laws. for i in [0] count = 0 i = 50 -> ok count is 0 ok i is 50 # Even when referenced in the filter. list = ['one', 'two', 'three'] methods = for num, i in list when num isnt 'two' and i isnt 1 -> num + ' ' + i ok methods.length is 2 ok methods[0]() is 'one 0' ok methods[1]() is 'three 2' # Naked ranges are expanded into arrays. array = [0..10] ok(num % 2 is 0 for num in array by 2) # Nested comprehensions. multiLiner = for x in [3..5] for y in [3..5] [x, y] singleLiner = [x, y] for y in [3..5] for x in [3..5] ok multiLiner.length is singleLiner.length ok 5 is multiLiner[2][2][1] ok 5 is singleLiner[2][2][1] # Comprehensions within parentheses. result = null store = (obj) -> result = obj store (x * 2 for x in [3, 2, 1]) ok result.join(' ') is '6 4 2' # Closure-wrapped comprehensions that refer to the "arguments" object. expr = -> result = item * item for item in arguments ok expr(2, 4, 8).join(' ') is '4 16 64' # Fast object comprehensions over all properties, including prototypal ones. class Cat constructor: -> @name = '<NAME>' breed: 'tabby' hair: 'cream' whiskers = new Cat own = value for key, value of whiskers all = value for all key, value of whiskers ok own.join(' ') is 'Whiskers' ok all.sort().join(' ') is 'Whiskers cream tabby' # Optimized range comprehensions. exxes = 'x' for [0...10] ok exxes.join(' ') is 'x x x x x x x x x x' # Comprehensions safely redeclare parameters if they're not present in closest # scope. rule = (x) -> x learn = -> rule for rule in [1, 2, 3] ok learn().join(' ') is '1 2 3' ok rule(101) is 101
true
# Basic array comprehensions. nums = n * n for n in [1, 2, 3] when n % 2 isnt 0 results = n * 2 for n in nums ok results.join(',') is '2,18' # Basic object comprehensions. obj = {one: 1, two: 2, three: 3} names = prop + '!' for prop of obj odds = prop + '!' for prop, value of obj when value % 2 isnt 0 ok names.join(' ') is "one! two! three!" ok odds.join(' ') is "one! three!" # Basic range comprehensions. nums = i * 3 for i in [1..3] negs = x for x in [-20..-5*2] negs = negs[0..2] result = nums.concat(negs).join(', ') ok result is '3, 6, 9, -20, -19, -18' ok i is 3 ok x is -10 # With range comprehensions, you can loop in steps. results = x for x in [0...15] by 5 ok results.join(' ') is '0 5 10' results = x for x in [0..100] by 10 ok results.join(' ') is '0 10 20 30 40 50 60 70 80 90 100' # And can loop downwards, with a negative step. results = x for x in [5..1] ok results.join(' ') is '5 4 3 2 1' ok results.join(' ') is [(10-5)..(-2+3)].join(' ') results = x for x in [10..1] ok results.join(' ') is [10..1].join(' ') results = x for x in [10...0] by -2 ok results.join(' ') is [10, 8, 6, 4, 2].join(' ') # Multiline array comprehension with filter. evens = for num in [1, 2, 3, 4, 5, 6] when num % 2 is 0 num *= -1 num -= 2 num * -1 ok evens.join(', ') is '4, 6, 8' # The in operator still works, standalone. ok 2 of evens # Ensure that the closure wrapper preserves local variables. obj = {} for method in ['one', 'two', 'three'] obj[method] = -> "I'm " + method ok obj.one() is "I'm one" ok obj.two() is "I'm two" ok obj.three() is "I'm three" i = 0 for i in [1..3] -> 'func' break if false ok i is 3 # Ensure that local variables are closed over for range comprehensions. funcs = for i in [1..3] -> -i ok (func() for func in funcs).join(' ') is '-1 -2 -3' ok i is 3 # Ensure that closing over local variables doesn't break scoping laws. for i in [0] count = 0 i = 50 -> ok count is 0 ok i is 50 # Even when referenced in the filter. list = ['one', 'two', 'three'] methods = for num, i in list when num isnt 'two' and i isnt 1 -> num + ' ' + i ok methods.length is 2 ok methods[0]() is 'one 0' ok methods[1]() is 'three 2' # Naked ranges are expanded into arrays. array = [0..10] ok(num % 2 is 0 for num in array by 2) # Nested comprehensions. multiLiner = for x in [3..5] for y in [3..5] [x, y] singleLiner = [x, y] for y in [3..5] for x in [3..5] ok multiLiner.length is singleLiner.length ok 5 is multiLiner[2][2][1] ok 5 is singleLiner[2][2][1] # Comprehensions within parentheses. result = null store = (obj) -> result = obj store (x * 2 for x in [3, 2, 1]) ok result.join(' ') is '6 4 2' # Closure-wrapped comprehensions that refer to the "arguments" object. expr = -> result = item * item for item in arguments ok expr(2, 4, 8).join(' ') is '4 16 64' # Fast object comprehensions over all properties, including prototypal ones. class Cat constructor: -> @name = 'PI:NAME:<NAME>END_PI' breed: 'tabby' hair: 'cream' whiskers = new Cat own = value for key, value of whiskers all = value for all key, value of whiskers ok own.join(' ') is 'Whiskers' ok all.sort().join(' ') is 'Whiskers cream tabby' # Optimized range comprehensions. exxes = 'x' for [0...10] ok exxes.join(' ') is 'x x x x x x x x x x' # Comprehensions safely redeclare parameters if they're not present in closest # scope. rule = (x) -> x learn = -> rule for rule in [1, 2, 3] ok learn().join(' ') is '1 2 3' ok rule(101) is 101
[ { "context": "ter: index\n options: \n clientId: \"53af466e96ab7635384b71fa\"\n _tenantId: \"53af466e96ab7635384b71fb\"\n", "end": 710, "score": 0.9777336120605469, "start": 686, "tag": "KEY", "value": "53af466e96ab7635384b71fa" }, { "context": "\"53af466e96a...
test/support/load-server.coffee
codedoctor/hapi-auth-bearer-mw
1
_ = require 'underscore' Hapi = require "hapi" mongoose = require 'mongoose' databaseCleaner = require './database-cleaner' index = require '../../lib/index' hapiUserStoreMultiTenant = require 'hapi-user-store-multi-tenant' hapiOauthStoreMultiTenant = require 'hapi-oauth-store-multi-tenant' loggingEnabled = false testUrl = 'mongodb://localhost/looksnearme-test' module.exports = loadServer = (cb) -> server = new Hapi.Server() server.connection port: 5675 host: "localhost" pluginConf = [ register: hapiUserStoreMultiTenant , register: hapiOauthStoreMultiTenant , register: index options: clientId: "53af466e96ab7635384b71fa" _tenantId: "53af466e96ab7635384b71fb" ] server.register pluginConf, (err) -> return cb err if err server.auth.strategy 'default', 'hapi-auth-bearer-mw', {} server.auth.default 'default' server.route path: "/test" method: "POST" handler: (request, reply) -> reply request.auth?.credentials mongoose.disconnect() mongoose.connect testUrl, (err) -> return cb err if err databaseCleaner loggingEnabled, (err) -> return cb err if err cb err,server
115858
_ = require 'underscore' Hapi = require "hapi" mongoose = require 'mongoose' databaseCleaner = require './database-cleaner' index = require '../../lib/index' hapiUserStoreMultiTenant = require 'hapi-user-store-multi-tenant' hapiOauthStoreMultiTenant = require 'hapi-oauth-store-multi-tenant' loggingEnabled = false testUrl = 'mongodb://localhost/looksnearme-test' module.exports = loadServer = (cb) -> server = new Hapi.Server() server.connection port: 5675 host: "localhost" pluginConf = [ register: hapiUserStoreMultiTenant , register: hapiOauthStoreMultiTenant , register: index options: clientId: "<KEY>" _tenantId: "5<KEY>" ] server.register pluginConf, (err) -> return cb err if err server.auth.strategy 'default', 'hapi-auth-bearer-mw', {} server.auth.default 'default' server.route path: "/test" method: "POST" handler: (request, reply) -> reply request.auth?.credentials mongoose.disconnect() mongoose.connect testUrl, (err) -> return cb err if err databaseCleaner loggingEnabled, (err) -> return cb err if err cb err,server
true
_ = require 'underscore' Hapi = require "hapi" mongoose = require 'mongoose' databaseCleaner = require './database-cleaner' index = require '../../lib/index' hapiUserStoreMultiTenant = require 'hapi-user-store-multi-tenant' hapiOauthStoreMultiTenant = require 'hapi-oauth-store-multi-tenant' loggingEnabled = false testUrl = 'mongodb://localhost/looksnearme-test' module.exports = loadServer = (cb) -> server = new Hapi.Server() server.connection port: 5675 host: "localhost" pluginConf = [ register: hapiUserStoreMultiTenant , register: hapiOauthStoreMultiTenant , register: index options: clientId: "PI:KEY:<KEY>END_PI" _tenantId: "5PI:KEY:<KEY>END_PI" ] server.register pluginConf, (err) -> return cb err if err server.auth.strategy 'default', 'hapi-auth-bearer-mw', {} server.auth.default 'default' server.route path: "/test" method: "POST" handler: (request, reply) -> reply request.auth?.credentials mongoose.disconnect() mongoose.connect testUrl, (err) -> return cb err if err databaseCleaner loggingEnabled, (err) -> return cb err if err cb err,server
[ { "context": "nstanceName', 'serviceName', ssh: users: {user1: 'passw1', user2: 'passw2'}\n assertBasicProperties co", "end": 2408, "score": 0.9957825541496277, "start": 2402, "tag": "PASSWORD", "value": "passw1" }, { "context": "rviceName', ssh: users: {user1: 'passw1', user2: ...
imports/server/ssh-container.tests.coffee
ICTU/docker-dashboard
33
{ assert, expect } = require 'meteor/practicalmeteor:chai' SshContainer = require './ssh-container' assertBasicProperties = (config) -> expect(config, 'Configuration object').to.be.a('object') assert.equal config.image, 'ictu/docker-ssh' assert.equal config.container_name, 'projectName-instanceName-serviceName-ssh' assert.equal config.environment.CONTAINER, 'projectName-instanceName-serviceName' assert.equal config.labels['bigboat.instance.name'], 'instanceName' assert.equal config.labels['bigboat.service.name'], 'serviceName' assert.equal config.labels['bigboat.service.type'], 'ssh' assert.equal config.labels['bigboat.container.map_docker'], 'true' assert.equal config.restart, 'unless-stopped' describe 'SshContainer', -> describe 'buildComposeConfig', -> it 'should not return any configuration when enable_ssh or ssh is not present', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', {} assert.equal config, undefined it 'should return default configuration when `enable_ssh` is true (backwards compatibility)', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should return default configuration when `ssh` is true', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should allow to customize the shell', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: shell: '/bin/sh' assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, '/bin/sh' it 'should allow to set authentication credentials', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: users: {user1: 'passw1', user2: 'passw2'} assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'multiUser' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' assert.equal config.environment.AUTH_TUPLES, 'user1:passw1;user2:passw2' it 'should give presidence to `ssh` when both `enable_ssh` and `ssh` are defined',-> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: {shell: 'someshell'}, enable_ssh: true assertBasicProperties config assert.equal config.environment.CONTAINER_SHELL, 'someshell'
33821
{ assert, expect } = require 'meteor/practicalmeteor:chai' SshContainer = require './ssh-container' assertBasicProperties = (config) -> expect(config, 'Configuration object').to.be.a('object') assert.equal config.image, 'ictu/docker-ssh' assert.equal config.container_name, 'projectName-instanceName-serviceName-ssh' assert.equal config.environment.CONTAINER, 'projectName-instanceName-serviceName' assert.equal config.labels['bigboat.instance.name'], 'instanceName' assert.equal config.labels['bigboat.service.name'], 'serviceName' assert.equal config.labels['bigboat.service.type'], 'ssh' assert.equal config.labels['bigboat.container.map_docker'], 'true' assert.equal config.restart, 'unless-stopped' describe 'SshContainer', -> describe 'buildComposeConfig', -> it 'should not return any configuration when enable_ssh or ssh is not present', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', {} assert.equal config, undefined it 'should return default configuration when `enable_ssh` is true (backwards compatibility)', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should return default configuration when `ssh` is true', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should allow to customize the shell', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: shell: '/bin/sh' assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, '/bin/sh' it 'should allow to set authentication credentials', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: users: {user1: '<PASSWORD>', user2: '<PASSWORD>'} assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'multiUser' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' assert.equal config.environment.AUTH_TUPLES, 'user1:passw1;user2:passw2' it 'should give presidence to `ssh` when both `enable_ssh` and `ssh` are defined',-> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: {shell: 'someshell'}, enable_ssh: true assertBasicProperties config assert.equal config.environment.CONTAINER_SHELL, 'someshell'
true
{ assert, expect } = require 'meteor/practicalmeteor:chai' SshContainer = require './ssh-container' assertBasicProperties = (config) -> expect(config, 'Configuration object').to.be.a('object') assert.equal config.image, 'ictu/docker-ssh' assert.equal config.container_name, 'projectName-instanceName-serviceName-ssh' assert.equal config.environment.CONTAINER, 'projectName-instanceName-serviceName' assert.equal config.labels['bigboat.instance.name'], 'instanceName' assert.equal config.labels['bigboat.service.name'], 'serviceName' assert.equal config.labels['bigboat.service.type'], 'ssh' assert.equal config.labels['bigboat.container.map_docker'], 'true' assert.equal config.restart, 'unless-stopped' describe 'SshContainer', -> describe 'buildComposeConfig', -> it 'should not return any configuration when enable_ssh or ssh is not present', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', {} assert.equal config, undefined it 'should return default configuration when `enable_ssh` is true (backwards compatibility)', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should return default configuration when `ssh` is true', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', enable_ssh: true assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' it 'should allow to customize the shell', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: shell: '/bin/sh' assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'noAuth' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, '/bin/sh' it 'should allow to set authentication credentials', -> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: users: {user1: 'PI:PASSWORD:<PASSWORD>END_PI', user2: 'PI:PASSWORD:<PASSWORD>END_PI'} assertBasicProperties config assert.equal config.environment.AUTH_MECHANISM, 'multiUser' assert.equal config.environment.HTTP_ENABLED, 'false' assert.equal config.environment.CONTAINER_SHELL, 'bash' assert.equal config.environment.AUTH_TUPLES, 'user1:passw1;user2:passw2' it 'should give presidence to `ssh` when both `enable_ssh` and `ssh` are defined',-> config = SshContainer.buildComposeConfig 'projectName', 'instanceName', 'serviceName', ssh: {shell: 'someshell'}, enable_ssh: true assertBasicProperties config assert.equal config.environment.CONTAINER_SHELL, 'someshell'
[ { "context": "map to a dictionary-like string', ->\n hash = {'Jonathan': 24, 'Bash': 23, 'Matt': 26}\n\n it 'should not", "end": 5519, "score": 0.9990134239196777, "start": 5511, "tag": "NAME", "value": "Jonathan" }, { "context": "ing', ->\n hash = {'Jonathan': 24, 'Bash': 2...
coffee/test/test_humanize.spec.coffee
kevinsawicki/humanize
2
describe 'Millions as word', -> it 'should pass', -> expect(Humanize).toBeDefined() expect(Humanize.intword(123456789, 6)).toEqual('123.45M') describe 'Ordinal value of numbers Test Suite', -> describe 'Ordinal value for numbers ending in zero', -> it 'should return 0 if the number is 0 (cos 0th doesnt read very well)', -> expect(Humanize.ordinal(0)).toEqual(0) it 'should return the number with suffix th', -> expect(Humanize.ordinal(10)).toEqual('10th') describe 'Ordinal value for numbers ending in one', -> it 'should end in st for numbers not ending in 11', -> expect(Humanize.ordinal(1)).toEqual('1st') expect(Humanize.ordinal(11)).toNotEqual('11st') expect(Humanize.ordinal(21)).toEqual('21st') it 'should be 11th for numbers ending in 11', -> expect(Humanize.ordinal(11)).toEqual('11th') expect(Humanize.ordinal(111)).toEqual('111th') describe 'Ordinal value for numbers ending in two', -> it 'should end in nd for numbers not ending in 12', -> expect(Humanize.ordinal(2)).toEqual('2nd') expect(Humanize.ordinal(12)).toNotEqual('12nd') expect(Humanize.ordinal(22)).toEqual('22nd') it 'should be 12th for numbers ending in 12', -> expect(Humanize.ordinal(12)).toEqual('12th') expect(Humanize.ordinal(112)).toEqual('112th') describe 'Ordinal value for numbers ending in three', -> it 'should end in rd for numbers not ending in 13', -> expect(Humanize.ordinal(3)).toEqual('3rd') expect(Humanize.ordinal(13)).toNotEqual('13rd') expect(Humanize.ordinal(23)).toEqual('23rd') it 'should be 13th for numbers ending in 13', -> expect(Humanize.ordinal(13)).toEqual('13th') expect(Humanize.ordinal(113)).toEqual('113th') describe 'Ordinal value for numbers ending in four', -> it 'should end in th for numbers', -> expect(Humanize.ordinal(4)).toEqual('4th') expect(Humanize.ordinal(14)).toEqual('14th') expect(Humanize.ordinal(24)).toEqual('24th') describe 'Pluralize tests', -> it 'should append an s as the default', -> expect(Humanize.pluralize(1,'cupcake')).toEqual('cupcake') expect(Humanize.pluralize(2,'cupcake')).toEqual('cupcakes') it 'should return provided value for special cases', -> expect(Humanize.pluralize(1,'person','people')).toEqual('person') expect(Humanize.pluralize(2,'person','people')).toEqual('people') expect(Humanize.pluralize(1,'child','children')).toEqual('child') expect(Humanize.pluralize(2,'child','children')).toEqual('children') describe 'Filesize tests for nerds', -> it 'should append bytes if it is less than 1024 bytes', -> expect(Humanize.filesize(512)).toEqual('512 bytes') it 'should return a file in KB if it is more than 1024 bytes', -> expect(Humanize.filesize(1080)).toEqual('1 KB') it 'should return a file in MB if it is more than a 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024)).toEqual('2.22 MB') it 'should return a file in GB if it is more than a 1024 * 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024*1024)).toEqual('2.22 GB') describe 'Truncating objects to shorter versions', -> objs = str: 'abcdefghijklmnopqrstuvwxyz' num: 1234567890 arr: [1, 2, 3, 4, 5] it 'should truncate a long string with ellipsis', -> expect(Humanize.truncate(objs.str, 14)).toEqual('abcdefghijk...') expect(Humanize.truncate(objs.str, 14, '...kidding')).toEqual('abcd...kidding') it 'should truncate a number to an upper bound', -> expect(Humanize.truncatenumber(objs.num, 500)).toEqual('500+') it 'should not trucate things that are too short', -> expect(Humanize.truncate(objs.str, objs.str.length + 1)).toEqual(objs.str) expect(Humanize.truncatenumber(objs.num, objs.num + 1)).toEqual("#{objs.num}") describe 'Converting a list to a readable, oxford commafied string', -> items = ['apple', 'orange', 'banana', 'pear', 'pineapple'] it 'should return an empty string when given an empty list', -> expect(Humanize.oxford(items.slice(0, 0))).toEqual('') it 'should return a string version of a list that has only one value', -> expect(Humanize.oxford(items.slice(0, 1))).toEqual('apple') it 'should return items separated by "and" when given a list of two values', -> expect(Humanize.oxford(items.slice(0, 2))).toEqual('apple and orange') it 'should convert a list to an oxford commafied string', -> expect(Humanize.oxford(items.slice(0))).toEqual('apple, orange, banana, pear, and pineapple') it 'should truncate a large list of items with proper pluralization', -> expect(Humanize.oxford(items.slice(0), 3)).toEqual('apple, orange, banana, and 2 others') expect(Humanize.oxford(items.slice(0), 4)).toEqual('apple, orange, banana, pear, and 1 other') it 'should accept custom trucation strings', -> limitStr = ", and some other fruits" expect(Humanize.oxford(items.slice(0), 3, limitStr)).toEqual('apple, orange, banana' + limitStr) expect(Humanize.oxford(items.slice(0, 3), 3, limitStr)).toEqual('apple, orange, and banana') describe 'Converting a hashmap to a dictionary-like string', -> hash = {'Jonathan': 24, 'Bash': 23, 'Matt': 26} it 'should not accept non-objects', -> expect(Humanize.dictionary('String')).toEqual('') expect(Humanize.dictionary((arg) -> 'Function')).toEqual('') expect(Humanize.dictionary([1, 2, 3])).toEqual('') it 'should convert a hash to a key-value string', -> expect(Humanize.dictionary(hash)).toEqual('Jonathan is 24, Bash is 23, Matt is 26') describe 'Converting pace arguments into strings', -> it 'should convert two pace arguments to a string', -> second = 1000 week = 6.048e8 decade = 3.156e11 expect(Humanize.pace(4, week)).toEqual('Approximately 4 times per week') expect(Humanize.pace(1.5, second, "heartbeat")).toEqual('Approximately 2 heartbeats per second') expect(Humanize.pace(1, decade, "life crisis")).toEqual('Less than 1 life crisis per week') describe 'Converting line breaks', -> it 'should convert /\n to a <br/> tag', -> expect(Humanize.nl2br('\n')).toEqual('<br/>') it 'should convert a <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br>')).toEqual('\r\n') it 'should convert a <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br/>')).toEqual('\r\n') it 'should convert a malformed <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br >')).toEqual('\r\n') it 'should convert a malformed <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br />')).toEqual('\r\n') describe 'Capitalizing words', -> it 'should convert "ship it" to "Ship it"', -> expect(Humanize.capitalize('ship it')).toEqual('Ship it') it 'should convert "ship it" to "Ship It"', -> expect(Humanize.titlecase('ship it', true)).toEqual('Ship It')
30242
describe 'Millions as word', -> it 'should pass', -> expect(Humanize).toBeDefined() expect(Humanize.intword(123456789, 6)).toEqual('123.45M') describe 'Ordinal value of numbers Test Suite', -> describe 'Ordinal value for numbers ending in zero', -> it 'should return 0 if the number is 0 (cos 0th doesnt read very well)', -> expect(Humanize.ordinal(0)).toEqual(0) it 'should return the number with suffix th', -> expect(Humanize.ordinal(10)).toEqual('10th') describe 'Ordinal value for numbers ending in one', -> it 'should end in st for numbers not ending in 11', -> expect(Humanize.ordinal(1)).toEqual('1st') expect(Humanize.ordinal(11)).toNotEqual('11st') expect(Humanize.ordinal(21)).toEqual('21st') it 'should be 11th for numbers ending in 11', -> expect(Humanize.ordinal(11)).toEqual('11th') expect(Humanize.ordinal(111)).toEqual('111th') describe 'Ordinal value for numbers ending in two', -> it 'should end in nd for numbers not ending in 12', -> expect(Humanize.ordinal(2)).toEqual('2nd') expect(Humanize.ordinal(12)).toNotEqual('12nd') expect(Humanize.ordinal(22)).toEqual('22nd') it 'should be 12th for numbers ending in 12', -> expect(Humanize.ordinal(12)).toEqual('12th') expect(Humanize.ordinal(112)).toEqual('112th') describe 'Ordinal value for numbers ending in three', -> it 'should end in rd for numbers not ending in 13', -> expect(Humanize.ordinal(3)).toEqual('3rd') expect(Humanize.ordinal(13)).toNotEqual('13rd') expect(Humanize.ordinal(23)).toEqual('23rd') it 'should be 13th for numbers ending in 13', -> expect(Humanize.ordinal(13)).toEqual('13th') expect(Humanize.ordinal(113)).toEqual('113th') describe 'Ordinal value for numbers ending in four', -> it 'should end in th for numbers', -> expect(Humanize.ordinal(4)).toEqual('4th') expect(Humanize.ordinal(14)).toEqual('14th') expect(Humanize.ordinal(24)).toEqual('24th') describe 'Pluralize tests', -> it 'should append an s as the default', -> expect(Humanize.pluralize(1,'cupcake')).toEqual('cupcake') expect(Humanize.pluralize(2,'cupcake')).toEqual('cupcakes') it 'should return provided value for special cases', -> expect(Humanize.pluralize(1,'person','people')).toEqual('person') expect(Humanize.pluralize(2,'person','people')).toEqual('people') expect(Humanize.pluralize(1,'child','children')).toEqual('child') expect(Humanize.pluralize(2,'child','children')).toEqual('children') describe 'Filesize tests for nerds', -> it 'should append bytes if it is less than 1024 bytes', -> expect(Humanize.filesize(512)).toEqual('512 bytes') it 'should return a file in KB if it is more than 1024 bytes', -> expect(Humanize.filesize(1080)).toEqual('1 KB') it 'should return a file in MB if it is more than a 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024)).toEqual('2.22 MB') it 'should return a file in GB if it is more than a 1024 * 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024*1024)).toEqual('2.22 GB') describe 'Truncating objects to shorter versions', -> objs = str: 'abcdefghijklmnopqrstuvwxyz' num: 1234567890 arr: [1, 2, 3, 4, 5] it 'should truncate a long string with ellipsis', -> expect(Humanize.truncate(objs.str, 14)).toEqual('abcdefghijk...') expect(Humanize.truncate(objs.str, 14, '...kidding')).toEqual('abcd...kidding') it 'should truncate a number to an upper bound', -> expect(Humanize.truncatenumber(objs.num, 500)).toEqual('500+') it 'should not trucate things that are too short', -> expect(Humanize.truncate(objs.str, objs.str.length + 1)).toEqual(objs.str) expect(Humanize.truncatenumber(objs.num, objs.num + 1)).toEqual("#{objs.num}") describe 'Converting a list to a readable, oxford commafied string', -> items = ['apple', 'orange', 'banana', 'pear', 'pineapple'] it 'should return an empty string when given an empty list', -> expect(Humanize.oxford(items.slice(0, 0))).toEqual('') it 'should return a string version of a list that has only one value', -> expect(Humanize.oxford(items.slice(0, 1))).toEqual('apple') it 'should return items separated by "and" when given a list of two values', -> expect(Humanize.oxford(items.slice(0, 2))).toEqual('apple and orange') it 'should convert a list to an oxford commafied string', -> expect(Humanize.oxford(items.slice(0))).toEqual('apple, orange, banana, pear, and pineapple') it 'should truncate a large list of items with proper pluralization', -> expect(Humanize.oxford(items.slice(0), 3)).toEqual('apple, orange, banana, and 2 others') expect(Humanize.oxford(items.slice(0), 4)).toEqual('apple, orange, banana, pear, and 1 other') it 'should accept custom trucation strings', -> limitStr = ", and some other fruits" expect(Humanize.oxford(items.slice(0), 3, limitStr)).toEqual('apple, orange, banana' + limitStr) expect(Humanize.oxford(items.slice(0, 3), 3, limitStr)).toEqual('apple, orange, and banana') describe 'Converting a hashmap to a dictionary-like string', -> hash = {'<NAME>': 24, 'Bash': 23, '<NAME>': 26} it 'should not accept non-objects', -> expect(Humanize.dictionary('String')).toEqual('') expect(Humanize.dictionary((arg) -> 'Function')).toEqual('') expect(Humanize.dictionary([1, 2, 3])).toEqual('') it 'should convert a hash to a key-value string', -> expect(Humanize.dictionary(hash)).toEqual('<NAME> is 24, Bash is 23, <NAME> is 26') describe 'Converting pace arguments into strings', -> it 'should convert two pace arguments to a string', -> second = 1000 week = 6.048e8 decade = 3.156e11 expect(Humanize.pace(4, week)).toEqual('Approximately 4 times per week') expect(Humanize.pace(1.5, second, "heartbeat")).toEqual('Approximately 2 heartbeats per second') expect(Humanize.pace(1, decade, "life crisis")).toEqual('Less than 1 life crisis per week') describe 'Converting line breaks', -> it 'should convert /\n to a <br/> tag', -> expect(Humanize.nl2br('\n')).toEqual('<br/>') it 'should convert a <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br>')).toEqual('\r\n') it 'should convert a <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br/>')).toEqual('\r\n') it 'should convert a malformed <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br >')).toEqual('\r\n') it 'should convert a malformed <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br />')).toEqual('\r\n') describe 'Capitalizing words', -> it 'should convert "ship it" to "Ship it"', -> expect(Humanize.capitalize('ship it')).toEqual('Ship it') it 'should convert "ship it" to "Ship It"', -> expect(Humanize.titlecase('ship it', true)).toEqual('Ship It')
true
describe 'Millions as word', -> it 'should pass', -> expect(Humanize).toBeDefined() expect(Humanize.intword(123456789, 6)).toEqual('123.45M') describe 'Ordinal value of numbers Test Suite', -> describe 'Ordinal value for numbers ending in zero', -> it 'should return 0 if the number is 0 (cos 0th doesnt read very well)', -> expect(Humanize.ordinal(0)).toEqual(0) it 'should return the number with suffix th', -> expect(Humanize.ordinal(10)).toEqual('10th') describe 'Ordinal value for numbers ending in one', -> it 'should end in st for numbers not ending in 11', -> expect(Humanize.ordinal(1)).toEqual('1st') expect(Humanize.ordinal(11)).toNotEqual('11st') expect(Humanize.ordinal(21)).toEqual('21st') it 'should be 11th for numbers ending in 11', -> expect(Humanize.ordinal(11)).toEqual('11th') expect(Humanize.ordinal(111)).toEqual('111th') describe 'Ordinal value for numbers ending in two', -> it 'should end in nd for numbers not ending in 12', -> expect(Humanize.ordinal(2)).toEqual('2nd') expect(Humanize.ordinal(12)).toNotEqual('12nd') expect(Humanize.ordinal(22)).toEqual('22nd') it 'should be 12th for numbers ending in 12', -> expect(Humanize.ordinal(12)).toEqual('12th') expect(Humanize.ordinal(112)).toEqual('112th') describe 'Ordinal value for numbers ending in three', -> it 'should end in rd for numbers not ending in 13', -> expect(Humanize.ordinal(3)).toEqual('3rd') expect(Humanize.ordinal(13)).toNotEqual('13rd') expect(Humanize.ordinal(23)).toEqual('23rd') it 'should be 13th for numbers ending in 13', -> expect(Humanize.ordinal(13)).toEqual('13th') expect(Humanize.ordinal(113)).toEqual('113th') describe 'Ordinal value for numbers ending in four', -> it 'should end in th for numbers', -> expect(Humanize.ordinal(4)).toEqual('4th') expect(Humanize.ordinal(14)).toEqual('14th') expect(Humanize.ordinal(24)).toEqual('24th') describe 'Pluralize tests', -> it 'should append an s as the default', -> expect(Humanize.pluralize(1,'cupcake')).toEqual('cupcake') expect(Humanize.pluralize(2,'cupcake')).toEqual('cupcakes') it 'should return provided value for special cases', -> expect(Humanize.pluralize(1,'person','people')).toEqual('person') expect(Humanize.pluralize(2,'person','people')).toEqual('people') expect(Humanize.pluralize(1,'child','children')).toEqual('child') expect(Humanize.pluralize(2,'child','children')).toEqual('children') describe 'Filesize tests for nerds', -> it 'should append bytes if it is less than 1024 bytes', -> expect(Humanize.filesize(512)).toEqual('512 bytes') it 'should return a file in KB if it is more than 1024 bytes', -> expect(Humanize.filesize(1080)).toEqual('1 KB') it 'should return a file in MB if it is more than a 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024)).toEqual('2.22 MB') it 'should return a file in GB if it is more than a 1024 * 1024 * 1024 bytes', -> expect(Humanize.filesize(2.22*1024*1024*1024)).toEqual('2.22 GB') describe 'Truncating objects to shorter versions', -> objs = str: 'abcdefghijklmnopqrstuvwxyz' num: 1234567890 arr: [1, 2, 3, 4, 5] it 'should truncate a long string with ellipsis', -> expect(Humanize.truncate(objs.str, 14)).toEqual('abcdefghijk...') expect(Humanize.truncate(objs.str, 14, '...kidding')).toEqual('abcd...kidding') it 'should truncate a number to an upper bound', -> expect(Humanize.truncatenumber(objs.num, 500)).toEqual('500+') it 'should not trucate things that are too short', -> expect(Humanize.truncate(objs.str, objs.str.length + 1)).toEqual(objs.str) expect(Humanize.truncatenumber(objs.num, objs.num + 1)).toEqual("#{objs.num}") describe 'Converting a list to a readable, oxford commafied string', -> items = ['apple', 'orange', 'banana', 'pear', 'pineapple'] it 'should return an empty string when given an empty list', -> expect(Humanize.oxford(items.slice(0, 0))).toEqual('') it 'should return a string version of a list that has only one value', -> expect(Humanize.oxford(items.slice(0, 1))).toEqual('apple') it 'should return items separated by "and" when given a list of two values', -> expect(Humanize.oxford(items.slice(0, 2))).toEqual('apple and orange') it 'should convert a list to an oxford commafied string', -> expect(Humanize.oxford(items.slice(0))).toEqual('apple, orange, banana, pear, and pineapple') it 'should truncate a large list of items with proper pluralization', -> expect(Humanize.oxford(items.slice(0), 3)).toEqual('apple, orange, banana, and 2 others') expect(Humanize.oxford(items.slice(0), 4)).toEqual('apple, orange, banana, pear, and 1 other') it 'should accept custom trucation strings', -> limitStr = ", and some other fruits" expect(Humanize.oxford(items.slice(0), 3, limitStr)).toEqual('apple, orange, banana' + limitStr) expect(Humanize.oxford(items.slice(0, 3), 3, limitStr)).toEqual('apple, orange, and banana') describe 'Converting a hashmap to a dictionary-like string', -> hash = {'PI:NAME:<NAME>END_PI': 24, 'Bash': 23, 'PI:NAME:<NAME>END_PI': 26} it 'should not accept non-objects', -> expect(Humanize.dictionary('String')).toEqual('') expect(Humanize.dictionary((arg) -> 'Function')).toEqual('') expect(Humanize.dictionary([1, 2, 3])).toEqual('') it 'should convert a hash to a key-value string', -> expect(Humanize.dictionary(hash)).toEqual('PI:NAME:<NAME>END_PI is 24, Bash is 23, PI:NAME:<NAME>END_PI is 26') describe 'Converting pace arguments into strings', -> it 'should convert two pace arguments to a string', -> second = 1000 week = 6.048e8 decade = 3.156e11 expect(Humanize.pace(4, week)).toEqual('Approximately 4 times per week') expect(Humanize.pace(1.5, second, "heartbeat")).toEqual('Approximately 2 heartbeats per second') expect(Humanize.pace(1, decade, "life crisis")).toEqual('Less than 1 life crisis per week') describe 'Converting line breaks', -> it 'should convert /\n to a <br/> tag', -> expect(Humanize.nl2br('\n')).toEqual('<br/>') it 'should convert a <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br>')).toEqual('\r\n') it 'should convert a <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br/>')).toEqual('\r\n') it 'should convert a malformed <br> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br >')).toEqual('\r\n') it 'should convert a malformed <br/> tag to /\r/\n (new line)', -> expect(Humanize.br2nl('<br />')).toEqual('\r\n') describe 'Capitalizing words', -> it 'should convert "ship it" to "Ship it"', -> expect(Humanize.capitalize('ship it')).toEqual('Ship it') it 'should convert "ship it" to "Ship It"', -> expect(Humanize.titlecase('ship it', true)).toEqual('Ship It')
[ { "context": "\n# Commands:\n# hubot \n# hubot \n#\n# Author:\n# Sambhav Thakur <sambhavkumar228@gmail.com>\n\nutils = require './u", "end": 164, "score": 0.9998932480812073, "start": 150, "tag": "NAME", "value": "Sambhav Thakur" }, { "context": "hubot \n# hubot \n#\n# Author...
scripts/1_general.coffee
sambhav228/AAE-Chat-bot
3
# Description: # Handle Help Options # also: internet speed checks and critical system status # # Commands: # hubot # hubot # # Author: # Sambhav Thakur <sambhavkumar228@gmail.com> utils = require './utils' module.exports = (robot) -> robot.respond /(get|show|create|generate)+[ ]+(my|the|all)*[ ]*(reports|sfdc reports|report|sfdc report)/i, (msg) -> msg.send "K, let me get that for you." UrlExt="/schedule/automations/deploy" #UrlExt="/authentication" jsondata = { "taskRelativePath":"My Tasks\\Notepad Test.atmx", "botRunners": [ { "client":"WIN-3AUGDSPKS6K", "user":"runner" } ] } #postdata = JSON.parse(strdata) utils.apicall(UrlExt,jsondata,msg,robot, callback = (msg,jsonbody) -> jsonresp = JSON.parse(jsonbody) output = jsonresp['message'] StrMsg = "Done:\n" StrMsg = StrMsg + "\t *#{output}*" msg.send StrMsg )
110396
# Description: # Handle Help Options # also: internet speed checks and critical system status # # Commands: # hubot # hubot # # Author: # <NAME> <<EMAIL>> utils = require './utils' module.exports = (robot) -> robot.respond /(get|show|create|generate)+[ ]+(my|the|all)*[ ]*(reports|sfdc reports|report|sfdc report)/i, (msg) -> msg.send "K, let me get that for you." UrlExt="/schedule/automations/deploy" #UrlExt="/authentication" jsondata = { "taskRelativePath":"My Tasks\\Notepad Test.atmx", "botRunners": [ { "client":"WIN-3AUGDSPKS6K", "user":"runner" } ] } #postdata = JSON.parse(strdata) utils.apicall(UrlExt,jsondata,msg,robot, callback = (msg,jsonbody) -> jsonresp = JSON.parse(jsonbody) output = jsonresp['message'] StrMsg = "Done:\n" StrMsg = StrMsg + "\t *#{output}*" msg.send StrMsg )
true
# Description: # Handle Help Options # also: internet speed checks and critical system status # # Commands: # hubot # hubot # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> utils = require './utils' module.exports = (robot) -> robot.respond /(get|show|create|generate)+[ ]+(my|the|all)*[ ]*(reports|sfdc reports|report|sfdc report)/i, (msg) -> msg.send "K, let me get that for you." UrlExt="/schedule/automations/deploy" #UrlExt="/authentication" jsondata = { "taskRelativePath":"My Tasks\\Notepad Test.atmx", "botRunners": [ { "client":"WIN-3AUGDSPKS6K", "user":"runner" } ] } #postdata = JSON.parse(strdata) utils.apicall(UrlExt,jsondata,msg,robot, callback = (msg,jsonbody) -> jsonresp = JSON.parse(jsonbody) output = jsonresp['message'] StrMsg = "Done:\n" StrMsg = StrMsg + "\t *#{output}*" msg.send StrMsg )
[ { "context": " onCheck = => @onCheck index\n img key: index, className: 'captcha-icon', src: imageUrl, onClic", "end": 1969, "score": 0.5469022393226624, "start": 1964, "tag": "KEY", "value": "index" } ]
talk-account/client/app/captcha-icons.coffee
ikingye/talk-os
3,084
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' {div, button, form, img, input, span, a} = React.DOM module.exports = React.createClass displayName: 'captcha-icons' propTypes: onSelect: React.PropTypes.func.isRequired lang: React.PropTypes.string.isRequired isDone: React.PropTypes.bool.isRequired getInitialState: -> info: null isForbidden: false error: null componentDidMount: -> @loadSetupInfo() loadSetupInfo: -> ajax.captchaSetup data: num: 5 lang: @props.lang success: (resp) => @setState info: resp error: (err) => # error = JSON.parse err.response onRefresh: -> @setState info: null, error: null @props.onSelect null @loadSetupInfo() onCheck: (index) -> ajax.captchaValid data: uid: @state.info.uid value: @state.info.values[index] error: (err) => if err.status is 429 @setState isForbidden: true @setState error: err.response success: (resp) => if resp.valid @props.onSelect @state.info.uid else @setState error: locales.get('invalidedCaptchaTryAgain', @props.lang) @loadSetupInfo() renderChooser: -> guideText = locales.get('pleaseSelectX', @props.lang) .replace '%s', @state.info.imageName div className: 'captcha-icons is-default', div className: 'as-head', span className: 'text-guide', guideText span className: 'icon icon-refresh', onClick: @onRefresh Space height: 10 div className: 'as-body', @state.info.values.map (imageId, index) => imageUrl = ajax.captchaImage @state.info.uid, @props.lang, index onCheck = => @onCheck index img key: index, className: 'captcha-icon', src: imageUrl, onClick: onCheck if @state.error? div className: 'as-response', Space height: 10 span className: 'hint-error', @state.error renderLoading: -> div className: 'captcha-icons is-loading', locales.get('loading', @props.lang) renderDone: -> div className: 'captcha-icons is-successful', span className: 'icon icon-circle-check' Space width: 5 span className: 'text-guide', locales.get('captchaSucceed', @props.lang) renderForbidden: -> div className: 'captcha-icon is-forbidden', span className: 'hint-error', locales.get('captchaTooManyTime', @props.lang) render: -> if @props.isDone @renderDone() else if @state.isForbidden @renderForbidden() else if @state.info? @renderChooser() else @renderLoading()
122931
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' {div, button, form, img, input, span, a} = React.DOM module.exports = React.createClass displayName: 'captcha-icons' propTypes: onSelect: React.PropTypes.func.isRequired lang: React.PropTypes.string.isRequired isDone: React.PropTypes.bool.isRequired getInitialState: -> info: null isForbidden: false error: null componentDidMount: -> @loadSetupInfo() loadSetupInfo: -> ajax.captchaSetup data: num: 5 lang: @props.lang success: (resp) => @setState info: resp error: (err) => # error = JSON.parse err.response onRefresh: -> @setState info: null, error: null @props.onSelect null @loadSetupInfo() onCheck: (index) -> ajax.captchaValid data: uid: @state.info.uid value: @state.info.values[index] error: (err) => if err.status is 429 @setState isForbidden: true @setState error: err.response success: (resp) => if resp.valid @props.onSelect @state.info.uid else @setState error: locales.get('invalidedCaptchaTryAgain', @props.lang) @loadSetupInfo() renderChooser: -> guideText = locales.get('pleaseSelectX', @props.lang) .replace '%s', @state.info.imageName div className: 'captcha-icons is-default', div className: 'as-head', span className: 'text-guide', guideText span className: 'icon icon-refresh', onClick: @onRefresh Space height: 10 div className: 'as-body', @state.info.values.map (imageId, index) => imageUrl = ajax.captchaImage @state.info.uid, @props.lang, index onCheck = => @onCheck index img key: <KEY>, className: 'captcha-icon', src: imageUrl, onClick: onCheck if @state.error? div className: 'as-response', Space height: 10 span className: 'hint-error', @state.error renderLoading: -> div className: 'captcha-icons is-loading', locales.get('loading', @props.lang) renderDone: -> div className: 'captcha-icons is-successful', span className: 'icon icon-circle-check' Space width: 5 span className: 'text-guide', locales.get('captchaSucceed', @props.lang) renderForbidden: -> div className: 'captcha-icon is-forbidden', span className: 'hint-error', locales.get('captchaTooManyTime', @props.lang) render: -> if @props.isDone @renderDone() else if @state.isForbidden @renderForbidden() else if @state.info? @renderChooser() else @renderLoading()
true
React = require 'react' Immutable = require 'immutable' ajax = require '../ajax' detect = require '../util/detect' locales = require '../locales' controllers = require '../controllers' Space = React.createFactory require 'react-lite-space' {div, button, form, img, input, span, a} = React.DOM module.exports = React.createClass displayName: 'captcha-icons' propTypes: onSelect: React.PropTypes.func.isRequired lang: React.PropTypes.string.isRequired isDone: React.PropTypes.bool.isRequired getInitialState: -> info: null isForbidden: false error: null componentDidMount: -> @loadSetupInfo() loadSetupInfo: -> ajax.captchaSetup data: num: 5 lang: @props.lang success: (resp) => @setState info: resp error: (err) => # error = JSON.parse err.response onRefresh: -> @setState info: null, error: null @props.onSelect null @loadSetupInfo() onCheck: (index) -> ajax.captchaValid data: uid: @state.info.uid value: @state.info.values[index] error: (err) => if err.status is 429 @setState isForbidden: true @setState error: err.response success: (resp) => if resp.valid @props.onSelect @state.info.uid else @setState error: locales.get('invalidedCaptchaTryAgain', @props.lang) @loadSetupInfo() renderChooser: -> guideText = locales.get('pleaseSelectX', @props.lang) .replace '%s', @state.info.imageName div className: 'captcha-icons is-default', div className: 'as-head', span className: 'text-guide', guideText span className: 'icon icon-refresh', onClick: @onRefresh Space height: 10 div className: 'as-body', @state.info.values.map (imageId, index) => imageUrl = ajax.captchaImage @state.info.uid, @props.lang, index onCheck = => @onCheck index img key: PI:KEY:<KEY>END_PI, className: 'captcha-icon', src: imageUrl, onClick: onCheck if @state.error? div className: 'as-response', Space height: 10 span className: 'hint-error', @state.error renderLoading: -> div className: 'captcha-icons is-loading', locales.get('loading', @props.lang) renderDone: -> div className: 'captcha-icons is-successful', span className: 'icon icon-circle-check' Space width: 5 span className: 'text-guide', locales.get('captchaSucceed', @props.lang) renderForbidden: -> div className: 'captcha-icon is-forbidden', span className: 'hint-error', locales.get('captchaTooManyTime', @props.lang) render: -> if @props.isDone @renderDone() else if @state.isForbidden @renderForbidden() else if @state.info? @renderChooser() else @renderLoading()
[ { "context": "s req.query -> Mongoose model find options\n@author Alex Suslov <suslov@me.com>\n@copyright MIT\n###\n\nQuery =\n wor", "end": 174, "score": 0.9997479915618896, "start": 163, "tag": "NAME", "value": "Alex Suslov" }, { "context": " Mongoose model find options\n@author A...
coffee/old.coffee
alexsuslov/wcQuery
1
'use strict' mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId ### Express req.query -> Mongoose model find options @author Alex Suslov <suslov@me.com> @copyright MIT ### Query = words: limit:(self)-> self.options.limit = parseInt self.query.limit skip:(self)-> self.options.skip = parseInt self.query.skip order:(self)-> query = self.query options = self.options options.sort ?= {} if query.order[0] is '-' options.sort[self_str(query.order)] = -1 else options.sort[query.order] = 1 delete query.order self commands: '~':(self)-> query:false ### main @param query[String] string from EXPRESS req @return Object conditions: mongo filter object options: mongo find options ### main:(@query)-> @options = {} @conditions = {} for name in ['or','and'] @logical(name) @order().limit().opt() { conditions: @conditions options: @options } # @ ### @param value[String] 'name=test' @return Object {name:'test'} ### expression:(value)-> data = value.split '=' ret = {} ret[data[0]] = @parse data[1] ret #create logical function # @param name[String] function name ['or','and'] # @return Object logical:(name)-> if @query[name] Arr = @query[name].split ',' if Arr.length @conditions['$' + name] = (for value in Arr @expression value) delete @query[name] @ parseVal:(val)-> return parseFloat val if @type is 'Number' return !!val if @type is 'Boolean' return new ObjectId val if @type is 'ObjectID' return new Date val if @type is 'Date' val ### Clean regexp simbols @param str[String] string to clean @return [String] cleaning string ### escapeRegExp: (str)-> str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") ### Parse ~, !, .... @param str[String] '!name' @return Object condition value ### parse:(str)-> tr = @_str str # mod return $mod: tr.split '|' if str[0] is '%' # in return $in: tr.split '|' if str[0] is '@' # nin return $nin: tr.split '|' if str[0] is '#' # gt return $gt: @parseVal tr if str[0] is '>' # gte return $gte: @parseVal tr if str[0] is ']' # lt return $lt: @parseVal tr if str[0] is '<' # lte return $lte: @parseVal tr if str[0] is '[' # not eq return $ne: @parseVal tr if str[0] is '!' # Exists return "$exists": true if str is '+' return "$exists": false if str is '-' # ~regex return $regex:@escapeRegExp( tr), $options:'i' if str[0] is '~' # # text # return $text:$search:tr if str[0] is '$' # ObjectId return new ObjectId(tr) if str[0] is '_' @parseVal str ### Cut first char from string @param str[String] '!test' @return String 'test' ### _str:(str)-> str.substr( 1 , str.length) ### Create options from query ### opt:-> if @query for name of @query @query[name] = decodeURI @query[name] # detect type @type = @detectType name @conditions[name] = @parse @query[name] if @query[name] @ detectType: (name)-> if @model and @model.schema.path(name) # Date Boolean Array if @model.schema.path(name).instance is 'undefined' if model.schema.path(name).options?.type if model.schema.path(name).options.type.name is Date return 'Date' if model.schema.path(name).options.type.name is Boolean return 'Boolean' if model.schema.path(name).options.type.name is Array return 'Array' # Number String ObjectID return @model.schema.path(name).instance if @model 'String' ### Create sort from query ### order:-> if @query.order @options.sort ?= {} if @query.order[0] is '-' @options.sort[@_str(@query.order)] = -1 else @options.sort[@query.order] = 1 delete @query.order @ ### Create limit from query ### limit:-> # limit if @query.limit @options.limit = parseInt @query.limit delete @query.limit else @options.limit = 25 # skip if @query.skip @options.skip = parseInt @query.skip delete @query.skip else @options.skip = 0 @ module.exports = (query)-> Query.main query module.exports.Query = Query
158555
'use strict' mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId ### Express req.query -> Mongoose model find options @author <NAME> <<EMAIL>> @copyright MIT ### Query = words: limit:(self)-> self.options.limit = parseInt self.query.limit skip:(self)-> self.options.skip = parseInt self.query.skip order:(self)-> query = self.query options = self.options options.sort ?= {} if query.order[0] is '-' options.sort[self_str(query.order)] = -1 else options.sort[query.order] = 1 delete query.order self commands: '~':(self)-> query:false ### main @param query[String] string from EXPRESS req @return Object conditions: mongo filter object options: mongo find options ### main:(@query)-> @options = {} @conditions = {} for name in ['or','and'] @logical(name) @order().limit().opt() { conditions: @conditions options: @options } # @ ### @param value[String] 'name=test' @return Object {name:'test'} ### expression:(value)-> data = value.split '=' ret = {} ret[data[0]] = @parse data[1] ret #create logical function # @param name[String] function name ['or','and'] # @return Object logical:(name)-> if @query[name] Arr = @query[name].split ',' if Arr.length @conditions['$' + name] = (for value in Arr @expression value) delete @query[name] @ parseVal:(val)-> return parseFloat val if @type is 'Number' return !!val if @type is 'Boolean' return new ObjectId val if @type is 'ObjectID' return new Date val if @type is 'Date' val ### Clean regexp simbols @param str[String] string to clean @return [String] cleaning string ### escapeRegExp: (str)-> str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") ### Parse ~, !, .... @param str[String] '!name' @return Object condition value ### parse:(str)-> tr = @_str str # mod return $mod: tr.split '|' if str[0] is '%' # in return $in: tr.split '|' if str[0] is '@' # nin return $nin: tr.split '|' if str[0] is '#' # gt return $gt: @parseVal tr if str[0] is '>' # gte return $gte: @parseVal tr if str[0] is ']' # lt return $lt: @parseVal tr if str[0] is '<' # lte return $lte: @parseVal tr if str[0] is '[' # not eq return $ne: @parseVal tr if str[0] is '!' # Exists return "$exists": true if str is '+' return "$exists": false if str is '-' # ~regex return $regex:@escapeRegExp( tr), $options:'i' if str[0] is '~' # # text # return $text:$search:tr if str[0] is '$' # ObjectId return new ObjectId(tr) if str[0] is '_' @parseVal str ### Cut first char from string @param str[String] '!test' @return String 'test' ### _str:(str)-> str.substr( 1 , str.length) ### Create options from query ### opt:-> if @query for name of @query @query[name] = decodeURI @query[name] # detect type @type = @detectType name @conditions[name] = @parse @query[name] if @query[name] @ detectType: (name)-> if @model and @model.schema.path(name) # Date Boolean Array if @model.schema.path(name).instance is 'undefined' if model.schema.path(name).options?.type if model.schema.path(name).options.type.name is Date return 'Date' if model.schema.path(name).options.type.name is Boolean return 'Boolean' if model.schema.path(name).options.type.name is Array return 'Array' # Number String ObjectID return @model.schema.path(name).instance if @model 'String' ### Create sort from query ### order:-> if @query.order @options.sort ?= {} if @query.order[0] is '-' @options.sort[@_str(@query.order)] = -1 else @options.sort[@query.order] = 1 delete @query.order @ ### Create limit from query ### limit:-> # limit if @query.limit @options.limit = parseInt @query.limit delete @query.limit else @options.limit = 25 # skip if @query.skip @options.skip = parseInt @query.skip delete @query.skip else @options.skip = 0 @ module.exports = (query)-> Query.main query module.exports.Query = Query
true
'use strict' mongoose = require('mongoose') Schema = mongoose.Schema ObjectId = Schema.Types.ObjectId ### Express req.query -> Mongoose model find options @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @copyright MIT ### Query = words: limit:(self)-> self.options.limit = parseInt self.query.limit skip:(self)-> self.options.skip = parseInt self.query.skip order:(self)-> query = self.query options = self.options options.sort ?= {} if query.order[0] is '-' options.sort[self_str(query.order)] = -1 else options.sort[query.order] = 1 delete query.order self commands: '~':(self)-> query:false ### main @param query[String] string from EXPRESS req @return Object conditions: mongo filter object options: mongo find options ### main:(@query)-> @options = {} @conditions = {} for name in ['or','and'] @logical(name) @order().limit().opt() { conditions: @conditions options: @options } # @ ### @param value[String] 'name=test' @return Object {name:'test'} ### expression:(value)-> data = value.split '=' ret = {} ret[data[0]] = @parse data[1] ret #create logical function # @param name[String] function name ['or','and'] # @return Object logical:(name)-> if @query[name] Arr = @query[name].split ',' if Arr.length @conditions['$' + name] = (for value in Arr @expression value) delete @query[name] @ parseVal:(val)-> return parseFloat val if @type is 'Number' return !!val if @type is 'Boolean' return new ObjectId val if @type is 'ObjectID' return new Date val if @type is 'Date' val ### Clean regexp simbols @param str[String] string to clean @return [String] cleaning string ### escapeRegExp: (str)-> str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") ### Parse ~, !, .... @param str[String] '!name' @return Object condition value ### parse:(str)-> tr = @_str str # mod return $mod: tr.split '|' if str[0] is '%' # in return $in: tr.split '|' if str[0] is '@' # nin return $nin: tr.split '|' if str[0] is '#' # gt return $gt: @parseVal tr if str[0] is '>' # gte return $gte: @parseVal tr if str[0] is ']' # lt return $lt: @parseVal tr if str[0] is '<' # lte return $lte: @parseVal tr if str[0] is '[' # not eq return $ne: @parseVal tr if str[0] is '!' # Exists return "$exists": true if str is '+' return "$exists": false if str is '-' # ~regex return $regex:@escapeRegExp( tr), $options:'i' if str[0] is '~' # # text # return $text:$search:tr if str[0] is '$' # ObjectId return new ObjectId(tr) if str[0] is '_' @parseVal str ### Cut first char from string @param str[String] '!test' @return String 'test' ### _str:(str)-> str.substr( 1 , str.length) ### Create options from query ### opt:-> if @query for name of @query @query[name] = decodeURI @query[name] # detect type @type = @detectType name @conditions[name] = @parse @query[name] if @query[name] @ detectType: (name)-> if @model and @model.schema.path(name) # Date Boolean Array if @model.schema.path(name).instance is 'undefined' if model.schema.path(name).options?.type if model.schema.path(name).options.type.name is Date return 'Date' if model.schema.path(name).options.type.name is Boolean return 'Boolean' if model.schema.path(name).options.type.name is Array return 'Array' # Number String ObjectID return @model.schema.path(name).instance if @model 'String' ### Create sort from query ### order:-> if @query.order @options.sort ?= {} if @query.order[0] is '-' @options.sort[@_str(@query.order)] = -1 else @options.sort[@query.order] = 1 delete @query.order @ ### Create limit from query ### limit:-> # limit if @query.limit @options.limit = parseInt @query.limit delete @query.limit else @options.limit = 25 # skip if @query.skip @options.skip = parseInt @query.skip delete @query.skip else @options.skip = 0 @ module.exports = (query)-> Query.main query module.exports.Query = Query
[ { "context": "ote, Monty Python and the Holy Grail]\n ____\n Dennis: Come and see the violence inherent in the system", "end": 4802, "score": 0.7334281802177429, "start": 4796, "tag": "NAME", "value": "Dennis" }, { "context": " the system. Help! Help! I'm being repressed!\n\n ...
src/asciidoc.coffee
gaybro8777/hubot-asciidoc
0
# Description: # A way to discover the Asciidoc(tor) markup. # # Commands: # hubot asciidoc comment # hubot asciidoc comment block # hubot asciidoc delimited blocks # hubot asciidoc example block # hubot asciidoc listing block # hubot asciidoc source block # hubot asciidoc literal block # hubot asciidoc passthrough block # hubot asciidoc quote block # hubot asciidoc open block # hubot asciidoc table block # hubot asciidoc image block # hubot asciidoc keyboard # hubot asciidoc menu selection # hubot asciidoc ui buttons # hubot asciidoc inline image # hubot asciidoc inline icon # hubot asciidoc link macro # hubot asciidoc mailto link # hubot asciidoc stem # hubot asciidoc stem asciimath # hubot asciidoc stem latex # hubot asciidoc footnote # hubot asciidoc footnote reference # hubot asciidoc document title # hubot asciidoc section 0 # hubot asciidoc section 1 # hubot asciidoc section 2 # hubot asciidoc section 3 # hubot asciidoc section 4 # hubot asciidoc section 5 # hubot asciidoc attribute entry # hubot asciidoc author # hubot asciidoc revision information # hubot asciidoc revision subscript # hubot asciidoc revision superscript # hubot asciidoc revision callout # hubot asciidoc revision checklist # hubot asciidoc revision man page # # Snippets # snippets = 'comment': title: "Single comment" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` // A single-line comment. ``` """ 'comment block': title: "Comment block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` //// A multi-line comment. Notice it's a delimited block. //// ``` """ 'delimited blocks': title: "Delimited blocks" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#delimited-blocks" description: """ *Delimiter line* ``` **** Valid sidebar block **** ``` """ 'example block': title: "Example block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#example" description: """ ``` .The title of the example ==== The content of the example ==== ``` A sample: ``` .Sample document ==== Here's a sample AsciiDoc document: [listing] .... = Title of Document Doc Writer :toc: This guide provides... .... The document header is useful, but not required. ==== ``` """ 'listing block': title: "Listing block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" prefix: '--' description: """ *Listing block* ``` [listing] This is an example of a paragraph styled with `listing`. Notice that the monospace markup is preserved in the output. ``` *Delimited listing block* ``` ---- This is an example of a _listing block_. The content inside is rendered as <pre> text. ---- ``` """ 'source block': title: "Source block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" description: """ ``` [source,ruby] ---- require 'sinatra' get '/hi' do "Hello World!" end ---- ``` """ 'literal block': title: "Literal block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#literal-text-and-blocks" description: """ ``` .... Lazarus: Where is the *defensive operations manual*? Computer: Calculating ... Can not locate object that you are not authorized to know exists. Would you like to ask another question? Lazarus: Did the werewolves tell you to say that? Computer: Calculating ... .... ``` Notice in the output that the bold text formatting is not rendered nor are the three, consecutive periods replaced by the ellipsis Unicode character. """ 'passthrough block': title: "Passthrough block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#pass-bl" description: """ A block passthrough is delimited by four plus signs `++++`. ``` ++++ <video poster="images/movie-reel.png"> <source src="videos/writing-zen.webm" type="video/webm"> </video> ++++ ``` If you want substitutions to be performed on the content in a delimited passthrough block, you can add them using the subs attribute. ``` [subs="attributes"] ++++ {name} image:tiger.png[] ++++ ``` """ 'quote block': title: "Quote block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#quote" description: """ ``` [quote, Monty Python and the Holy Grail] ____ Dennis: Come and see the violence inherent in the system. Help! Help! I'm being repressed! King Arthur: Bloody peasant! Dennis: Oh, what a giveaway! Did you hear that? Did you hear that, eh? That's what I'm on about! Did you see him repressing me? You saw him, Didn't you? ____ ``` """ 'open block': title: "Open block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#open-blocks" description: """ ``` -- An open block can be an anonymous container, or it can masquerade as any other block. -- ``` """ 'table block': title: "Table block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#tables" description: """ ``` |=== |Cell in column 1, row 1 |Cell in column 2, row 1 |Cell in column 3, row 1 |Cell in column 1, row 2 |Cell in column 2, row 2 |Cell in column 3, row 2 |=== ``` """ 'image block': title: "Block image" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#images" description: """ ``` image::sunset.jpg[Sunset] ``` """ # Inline Macros # 'keyboard': title: "Keyboard shortcut" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#keyboard-shortcuts' description: "kbd:[Ctrl+T]" 'menu selection': title: "Menu selection" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#menu-selections' description: "menu:File[Save]" 'ui buttons': title: "UI button" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#ui-buttons' description: "btn:[OK]" 'inline image': title: "Inline image" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#images' description: "image:logo.png[Logo]" 'inline icon': title: "Inline icon" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#inline-icons' description: "icon:tags[]" 'link macro': title: "Explicit link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "link:external.html#livereload[LiveReload]" 'mailto link': title: "E-mail link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "mailto:doc@example.com[Doc Writer] $0" 'stem': title: "STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "stem:[sqrt(4) = 2]" 'stem asciimath': title: "AsciiMath STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "asciimath:[expressoin]" 'stem latexmath': title: "LaTeX STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "latexmath:[expression]" 'footnote': title: "Footnote" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnote:[The footnote content]" 'footnote reference': title: "Footnote reference" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnoteref:[disclaimer,Opinions are my own.]" # Sections # 'document title': title: "Document title (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#document-title" description: """ ``` = Title ``` """ 'section 0': title: "Level 0 section / part (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` = Section 0 ``` """ 'section 1': title: "Level 1 section / chapter (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` == Section 1 ``` """ 'section 2': title: "Level 2 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` === Section 2 ``` """ 'section 3': title: "Level 3 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ==== Section 3 ``` """ 'section 4': title: "Level 4 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ===== Section 4 ``` """ 'section 5': title: "Level 5 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ====== Section 5 ``` """ # Others # 'attribute entry': title: "Define or update a document attribute" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#setting-attributes-on-a-document" description: """ ``` :name: value ``` """ 'author': title: "Author and email line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#author-and-email" description: """ The author of a document is listed on the line beneath the document’s title. An optional email address or URL can follow an author’s name inside angle brackets. ``` = The Dangerous and Thrilling Documentation Chronicles Kismet Rainbow Chameleon <kismet@asciidoctor.org> ``` """ 'revision information': title: "Document revision line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#revision-number-date-and-remark" description: """ The revision information is listed on the third line of the header, beneath the author information line. ``` v1.0, October 2, 2013: First incarnation ``` """ 'subscript': title: "subscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One tilde `~` on either side of a word or phrase makes it subscript. ``` H~2~O ``` """ 'superscript': title: "superscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One caret `^` on either side of a word or phrase makes it superscript. ``` E=mc^2^ ``` """ 'callout': title: "Callout number" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#callouts" description: """ Callout numbers (aka callouts `<number>`) provide a means to add annotations to lines in a verbatim block. Here’s a basic example of a verbatim block that uses callouts: ``` [source,ruby] ---- require 'sinatra' <1> ---- <1> Library import ``` """ 'checklist': title: "Unchecked checklist item" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#checklist" description: """ List items can be marked complete using checklists. ``` - [*] checked - [x] also checked - [ ] not checked - normal list item ``` """ # Templates # 'man page': title: "Man page template" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#man-pages" # See also http://docopt.org/ for how to describe commmand line options. description: """ ``` = eva(1) Andrew Stanton v1.0.0 :manmanual: EVE :mansource: EVE :man-linkstyle: blue R <> == NAME eve - analyzes an image to determine if it's a picture of a life form == SYNOPSIS *eve* ['OPTION']... 'FILE'... == OPTIONS *-o, --out-file*=_OUT_FILE_:: Write result to file _OUT_FILE_. *-c, --capture*:: Capture specimen if it's a picture of a life form. == EXIT STATUS *0*:: Success. Image is a picture of a life form. *1*:: Failure. Image is not a picture of a life form. == RESOURCES *Project web site:* http://eve.example.org == COPYING Copyright \(C) 2008 {author}. Free use of this software is granted under the terms of the MIT License. ``` """ sendAttachments = (msg, attachments) -> # The case of Gitter if msg.robot.adapter.constructor.name == "HubotGitter2Adapter" attachments.forEach (attachment) -> msg.send """ [#{attachment.title}](#{attachment.title_link}) #{attachment.text} """ else # By default go slack msg.robot.adapter.customMessage channel: msg.envelope.room username: msg.robot.name attachments: attachments generateAttachment = (snippet) -> attachment= title: snippet.title title_link: snippet.descriptionMoreURL pretext: snippet.pretext fallback: snippet.fallback text: """ #{snippet.description} """ mrkdwn_in: ["text"] attachment module.exports = (robot) -> robot.respond /asciidoc (.*)/i, (msg) -> query = msg.match[1] snippet = snippets[query.toLowerCase()] if snippet? attachments = [generateAttachment(snippet)] else attachment= title: "The query ​*#{query}*​ was not found" title_link: "https://github.com/anthonny/tweetiments/issues/new" fallback: "The query ​*#{query}*​ was not found" text: """ *#{msg.robot.name}* could not find a match for ​*#{query}*. *#{msg.robot.name}* is just a robot and he may need human help to add the entry. 1. Open an issue at https://github.com/anthonny/hubot-asciidoc/issues. 2. Call it *Add <query>* to *hubot-asciidoc* 3. Bonus points: create a pull request and add it yourself. See https://github.com/anthonny/hubot-asciidoc/README.adoc for help. *#{msg.robot.name}* thanks you :beers:. """ mrkdwn_in: ["text"] attachments = [attachment] sendAttachments msg, attachments
155511
# Description: # A way to discover the Asciidoc(tor) markup. # # Commands: # hubot asciidoc comment # hubot asciidoc comment block # hubot asciidoc delimited blocks # hubot asciidoc example block # hubot asciidoc listing block # hubot asciidoc source block # hubot asciidoc literal block # hubot asciidoc passthrough block # hubot asciidoc quote block # hubot asciidoc open block # hubot asciidoc table block # hubot asciidoc image block # hubot asciidoc keyboard # hubot asciidoc menu selection # hubot asciidoc ui buttons # hubot asciidoc inline image # hubot asciidoc inline icon # hubot asciidoc link macro # hubot asciidoc mailto link # hubot asciidoc stem # hubot asciidoc stem asciimath # hubot asciidoc stem latex # hubot asciidoc footnote # hubot asciidoc footnote reference # hubot asciidoc document title # hubot asciidoc section 0 # hubot asciidoc section 1 # hubot asciidoc section 2 # hubot asciidoc section 3 # hubot asciidoc section 4 # hubot asciidoc section 5 # hubot asciidoc attribute entry # hubot asciidoc author # hubot asciidoc revision information # hubot asciidoc revision subscript # hubot asciidoc revision superscript # hubot asciidoc revision callout # hubot asciidoc revision checklist # hubot asciidoc revision man page # # Snippets # snippets = 'comment': title: "Single comment" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` // A single-line comment. ``` """ 'comment block': title: "Comment block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` //// A multi-line comment. Notice it's a delimited block. //// ``` """ 'delimited blocks': title: "Delimited blocks" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#delimited-blocks" description: """ *Delimiter line* ``` **** Valid sidebar block **** ``` """ 'example block': title: "Example block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#example" description: """ ``` .The title of the example ==== The content of the example ==== ``` A sample: ``` .Sample document ==== Here's a sample AsciiDoc document: [listing] .... = Title of Document Doc Writer :toc: This guide provides... .... The document header is useful, but not required. ==== ``` """ 'listing block': title: "Listing block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" prefix: '--' description: """ *Listing block* ``` [listing] This is an example of a paragraph styled with `listing`. Notice that the monospace markup is preserved in the output. ``` *Delimited listing block* ``` ---- This is an example of a _listing block_. The content inside is rendered as <pre> text. ---- ``` """ 'source block': title: "Source block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" description: """ ``` [source,ruby] ---- require 'sinatra' get '/hi' do "Hello World!" end ---- ``` """ 'literal block': title: "Literal block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#literal-text-and-blocks" description: """ ``` .... Lazarus: Where is the *defensive operations manual*? Computer: Calculating ... Can not locate object that you are not authorized to know exists. Would you like to ask another question? Lazarus: Did the werewolves tell you to say that? Computer: Calculating ... .... ``` Notice in the output that the bold text formatting is not rendered nor are the three, consecutive periods replaced by the ellipsis Unicode character. """ 'passthrough block': title: "Passthrough block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#pass-bl" description: """ A block passthrough is delimited by four plus signs `++++`. ``` ++++ <video poster="images/movie-reel.png"> <source src="videos/writing-zen.webm" type="video/webm"> </video> ++++ ``` If you want substitutions to be performed on the content in a delimited passthrough block, you can add them using the subs attribute. ``` [subs="attributes"] ++++ {name} image:tiger.png[] ++++ ``` """ 'quote block': title: "Quote block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#quote" description: """ ``` [quote, Monty Python and the Holy Grail] ____ <NAME>: Come and see the violence inherent in the system. Help! Help! I'm being repressed! <NAME>: Bloody peasant! <NAME>: Oh, what a giveaway! Did you hear that? Did you hear that, eh? That's what I'm on about! Did you see him repressing me? You saw him, Didn't you? ____ ``` """ 'open block': title: "Open block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#open-blocks" description: """ ``` -- An open block can be an anonymous container, or it can masquerade as any other block. -- ``` """ 'table block': title: "Table block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#tables" description: """ ``` |=== |Cell in column 1, row 1 |Cell in column 2, row 1 |Cell in column 3, row 1 |Cell in column 1, row 2 |Cell in column 2, row 2 |Cell in column 3, row 2 |=== ``` """ 'image block': title: "Block image" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#images" description: """ ``` image::sunset.jpg[Sunset] ``` """ # Inline Macros # 'keyboard': title: "Keyboard shortcut" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#keyboard-shortcuts' description: "kbd:[Ctrl+T]" 'menu selection': title: "Menu selection" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#menu-selections' description: "menu:File[Save]" 'ui buttons': title: "UI button" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#ui-buttons' description: "btn:[OK]" 'inline image': title: "Inline image" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#images' description: "image:logo.png[Logo]" 'inline icon': title: "Inline icon" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#inline-icons' description: "icon:tags[]" 'link macro': title: "Explicit link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "link:external.html#livereload[LiveReload]" 'mailto link': title: "E-mail link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "mailto:<EMAIL>[Doc Writer] $0" 'stem': title: "STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "stem:[sqrt(4) = 2]" 'stem asciimath': title: "AsciiMath STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "asciimath:[expressoin]" 'stem latexmath': title: "LaTeX STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "latexmath:[expression]" 'footnote': title: "Footnote" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnote:[The footnote content]" 'footnote reference': title: "Footnote reference" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnoteref:[disclaimer,Opinions are my own.]" # Sections # 'document title': title: "Document title (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#document-title" description: """ ``` = Title ``` """ 'section 0': title: "Level 0 section / part (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` = Section 0 ``` """ 'section 1': title: "Level 1 section / chapter (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` == Section 1 ``` """ 'section 2': title: "Level 2 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` === Section 2 ``` """ 'section 3': title: "Level 3 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ==== Section 3 ``` """ 'section 4': title: "Level 4 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ===== Section 4 ``` """ 'section 5': title: "Level 5 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ====== Section 5 ``` """ # Others # 'attribute entry': title: "Define or update a document attribute" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#setting-attributes-on-a-document" description: """ ``` :name: value ``` """ 'author': title: "Author and email line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#author-and-email" description: """ The author of a document is listed on the line beneath the document’s title. An optional email address or URL can follow an author’s name inside angle brackets. ``` = The Dangerous and Thrilling Documentation Chronicles <NAME> <<EMAIL>> ``` """ 'revision information': title: "Document revision line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#revision-number-date-and-remark" description: """ The revision information is listed on the third line of the header, beneath the author information line. ``` v1.0, October 2, 2013: First incarnation ``` """ 'subscript': title: "subscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One tilde `~` on either side of a word or phrase makes it subscript. ``` H~2~O ``` """ 'superscript': title: "superscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One caret `^` on either side of a word or phrase makes it superscript. ``` E=mc^2^ ``` """ 'callout': title: "Callout number" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#callouts" description: """ Callout numbers (aka callouts `<number>`) provide a means to add annotations to lines in a verbatim block. Here’s a basic example of a verbatim block that uses callouts: ``` [source,ruby] ---- require 'sinatra' <1> ---- <1> Library import ``` """ 'checklist': title: "Unchecked checklist item" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#checklist" description: """ List items can be marked complete using checklists. ``` - [*] checked - [x] also checked - [ ] not checked - normal list item ``` """ # Templates # 'man page': title: "Man page template" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#man-pages" # See also http://docopt.org/ for how to describe commmand line options. description: """ ``` = eva(1) <NAME> v1.0.0 :manmanual: EVE :mansource: EVE :man-linkstyle: blue R <> == NAME eve - analyzes an image to determine if it's a picture of a life form == SYNOPSIS *eve* ['OPTION']... 'FILE'... == OPTIONS *-o, --out-file*=_OUT_FILE_:: Write result to file _OUT_FILE_. *-c, --capture*:: Capture specimen if it's a picture of a life form. == EXIT STATUS *0*:: Success. Image is a picture of a life form. *1*:: Failure. Image is not a picture of a life form. == RESOURCES *Project web site:* http://eve.example.org == COPYING Copyright \(C) 2008 {author}. Free use of this software is granted under the terms of the MIT License. ``` """ sendAttachments = (msg, attachments) -> # The case of Gitter if msg.robot.adapter.constructor.name == "HubotGitter2Adapter" attachments.forEach (attachment) -> msg.send """ [#{attachment.title}](#{attachment.title_link}) #{attachment.text} """ else # By default go slack msg.robot.adapter.customMessage channel: msg.envelope.room username: msg.robot.name attachments: attachments generateAttachment = (snippet) -> attachment= title: snippet.title title_link: snippet.descriptionMoreURL pretext: snippet.pretext fallback: snippet.fallback text: """ #{snippet.description} """ mrkdwn_in: ["text"] attachment module.exports = (robot) -> robot.respond /asciidoc (.*)/i, (msg) -> query = msg.match[1] snippet = snippets[query.toLowerCase()] if snippet? attachments = [generateAttachment(snippet)] else attachment= title: "The query ​*#{query}*​ was not found" title_link: "https://github.com/anthonny/tweetiments/issues/new" fallback: "The query ​*#{query}*​ was not found" text: """ *#{msg.robot.name}* could not find a match for ​*#{query}*. *#{msg.robot.name}* is just a robot and he may need human help to add the entry. 1. Open an issue at https://github.com/anthonny/hubot-asciidoc/issues. 2. Call it *Add <query>* to *hubot-asciidoc* 3. Bonus points: create a pull request and add it yourself. See https://github.com/anthonny/hubot-asciidoc/README.adoc for help. *#{msg.robot.name}* thanks you :beers:. """ mrkdwn_in: ["text"] attachments = [attachment] sendAttachments msg, attachments
true
# Description: # A way to discover the Asciidoc(tor) markup. # # Commands: # hubot asciidoc comment # hubot asciidoc comment block # hubot asciidoc delimited blocks # hubot asciidoc example block # hubot asciidoc listing block # hubot asciidoc source block # hubot asciidoc literal block # hubot asciidoc passthrough block # hubot asciidoc quote block # hubot asciidoc open block # hubot asciidoc table block # hubot asciidoc image block # hubot asciidoc keyboard # hubot asciidoc menu selection # hubot asciidoc ui buttons # hubot asciidoc inline image # hubot asciidoc inline icon # hubot asciidoc link macro # hubot asciidoc mailto link # hubot asciidoc stem # hubot asciidoc stem asciimath # hubot asciidoc stem latex # hubot asciidoc footnote # hubot asciidoc footnote reference # hubot asciidoc document title # hubot asciidoc section 0 # hubot asciidoc section 1 # hubot asciidoc section 2 # hubot asciidoc section 3 # hubot asciidoc section 4 # hubot asciidoc section 5 # hubot asciidoc attribute entry # hubot asciidoc author # hubot asciidoc revision information # hubot asciidoc revision subscript # hubot asciidoc revision superscript # hubot asciidoc revision callout # hubot asciidoc revision checklist # hubot asciidoc revision man page # # Snippets # snippets = 'comment': title: "Single comment" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` // A single-line comment. ``` """ 'comment block': title: "Comment block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#comments" description: """ ``` //// A multi-line comment. Notice it's a delimited block. //// ``` """ 'delimited blocks': title: "Delimited blocks" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#delimited-blocks" description: """ *Delimiter line* ``` **** Valid sidebar block **** ``` """ 'example block': title: "Example block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#example" description: """ ``` .The title of the example ==== The content of the example ==== ``` A sample: ``` .Sample document ==== Here's a sample AsciiDoc document: [listing] .... = Title of Document Doc Writer :toc: This guide provides... .... The document header is useful, but not required. ==== ``` """ 'listing block': title: "Listing block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" prefix: '--' description: """ *Listing block* ``` [listing] This is an example of a paragraph styled with `listing`. Notice that the monospace markup is preserved in the output. ``` *Delimited listing block* ``` ---- This is an example of a _listing block_. The content inside is rendered as <pre> text. ---- ``` """ 'source block': title: "Source block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#listing-blocks" description: """ ``` [source,ruby] ---- require 'sinatra' get '/hi' do "Hello World!" end ---- ``` """ 'literal block': title: "Literal block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#literal-text-and-blocks" description: """ ``` .... Lazarus: Where is the *defensive operations manual*? Computer: Calculating ... Can not locate object that you are not authorized to know exists. Would you like to ask another question? Lazarus: Did the werewolves tell you to say that? Computer: Calculating ... .... ``` Notice in the output that the bold text formatting is not rendered nor are the three, consecutive periods replaced by the ellipsis Unicode character. """ 'passthrough block': title: "Passthrough block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#pass-bl" description: """ A block passthrough is delimited by four plus signs `++++`. ``` ++++ <video poster="images/movie-reel.png"> <source src="videos/writing-zen.webm" type="video/webm"> </video> ++++ ``` If you want substitutions to be performed on the content in a delimited passthrough block, you can add them using the subs attribute. ``` [subs="attributes"] ++++ {name} image:tiger.png[] ++++ ``` """ 'quote block': title: "Quote block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#quote" description: """ ``` [quote, Monty Python and the Holy Grail] ____ PI:NAME:<NAME>END_PI: Come and see the violence inherent in the system. Help! Help! I'm being repressed! PI:NAME:<NAME>END_PI: Bloody peasant! PI:NAME:<NAME>END_PI: Oh, what a giveaway! Did you hear that? Did you hear that, eh? That's what I'm on about! Did you see him repressing me? You saw him, Didn't you? ____ ``` """ 'open block': title: "Open block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#open-blocks" description: """ ``` -- An open block can be an anonymous container, or it can masquerade as any other block. -- ``` """ 'table block': title: "Table block" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#tables" description: """ ``` |=== |Cell in column 1, row 1 |Cell in column 2, row 1 |Cell in column 3, row 1 |Cell in column 1, row 2 |Cell in column 2, row 2 |Cell in column 3, row 2 |=== ``` """ 'image block': title: "Block image" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#images" description: """ ``` image::sunset.jpg[Sunset] ``` """ # Inline Macros # 'keyboard': title: "Keyboard shortcut" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#keyboard-shortcuts' description: "kbd:[Ctrl+T]" 'menu selection': title: "Menu selection" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#menu-selections' description: "menu:File[Save]" 'ui buttons': title: "UI button" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#ui-buttons' description: "btn:[OK]" 'inline image': title: "Inline image" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#images' description: "image:logo.png[Logo]" 'inline icon': title: "Inline icon" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#inline-icons' description: "icon:tags[]" 'link macro': title: "Explicit link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "link:external.html#livereload[LiveReload]" 'mailto link': title: "E-mail link" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#url' description: "mailto:PI:EMAIL:<EMAIL>END_PI[Doc Writer] $0" 'stem': title: "STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "stem:[sqrt(4) = 2]" 'stem asciimath': title: "AsciiMath STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "asciimath:[expressoin]" 'stem latexmath': title: "LaTeX STEM expression" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#activating-stem-support' description: "latexmath:[expression]" 'footnote': title: "Footnote" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnote:[The footnote content]" 'footnote reference': title: "Footnote reference" descriptionMoreURL: 'http://asciidoctor.org/docs/user-manual/#user-footnotes' description: "footnoteref:[disclaimer,Opinions are my own.]" # Sections # 'document title': title: "Document title (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#document-title" description: """ ``` = Title ``` """ 'section 0': title: "Level 0 section / part (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` = Section 0 ``` """ 'section 1': title: "Level 1 section / chapter (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` == Section 1 ``` """ 'section 2': title: "Level 2 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` === Section 2 ``` """ 'section 3': title: "Level 3 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ==== Section 3 ``` """ 'section 4': title: "Level 4 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ===== Section 4 ``` """ 'section 5': title: "Level 5 section (single-line syntax)" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#sections" description: """ ``` ====== Section 5 ``` """ # Others # 'attribute entry': title: "Define or update a document attribute" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#setting-attributes-on-a-document" description: """ ``` :name: value ``` """ 'author': title: "Author and email line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#author-and-email" description: """ The author of a document is listed on the line beneath the document’s title. An optional email address or URL can follow an author’s name inside angle brackets. ``` = The Dangerous and Thrilling Documentation Chronicles PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ``` """ 'revision information': title: "Document revision line" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#revision-number-date-and-remark" description: """ The revision information is listed on the third line of the header, beneath the author information line. ``` v1.0, October 2, 2013: First incarnation ``` """ 'subscript': title: "subscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One tilde `~` on either side of a word or phrase makes it subscript. ``` H~2~O ``` """ 'superscript': title: "superscript" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#subscript-and-superscript" description: """ One caret `^` on either side of a word or phrase makes it superscript. ``` E=mc^2^ ``` """ 'callout': title: "Callout number" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#callouts" description: """ Callout numbers (aka callouts `<number>`) provide a means to add annotations to lines in a verbatim block. Here’s a basic example of a verbatim block that uses callouts: ``` [source,ruby] ---- require 'sinatra' <1> ---- <1> Library import ``` """ 'checklist': title: "Unchecked checklist item" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#checklist" description: """ List items can be marked complete using checklists. ``` - [*] checked - [x] also checked - [ ] not checked - normal list item ``` """ # Templates # 'man page': title: "Man page template" descriptionMoreURL: "http://asciidoctor.org/docs/user-manual/#man-pages" # See also http://docopt.org/ for how to describe commmand line options. description: """ ``` = eva(1) PI:NAME:<NAME>END_PI v1.0.0 :manmanual: EVE :mansource: EVE :man-linkstyle: blue R <> == NAME eve - analyzes an image to determine if it's a picture of a life form == SYNOPSIS *eve* ['OPTION']... 'FILE'... == OPTIONS *-o, --out-file*=_OUT_FILE_:: Write result to file _OUT_FILE_. *-c, --capture*:: Capture specimen if it's a picture of a life form. == EXIT STATUS *0*:: Success. Image is a picture of a life form. *1*:: Failure. Image is not a picture of a life form. == RESOURCES *Project web site:* http://eve.example.org == COPYING Copyright \(C) 2008 {author}. Free use of this software is granted under the terms of the MIT License. ``` """ sendAttachments = (msg, attachments) -> # The case of Gitter if msg.robot.adapter.constructor.name == "HubotGitter2Adapter" attachments.forEach (attachment) -> msg.send """ [#{attachment.title}](#{attachment.title_link}) #{attachment.text} """ else # By default go slack msg.robot.adapter.customMessage channel: msg.envelope.room username: msg.robot.name attachments: attachments generateAttachment = (snippet) -> attachment= title: snippet.title title_link: snippet.descriptionMoreURL pretext: snippet.pretext fallback: snippet.fallback text: """ #{snippet.description} """ mrkdwn_in: ["text"] attachment module.exports = (robot) -> robot.respond /asciidoc (.*)/i, (msg) -> query = msg.match[1] snippet = snippets[query.toLowerCase()] if snippet? attachments = [generateAttachment(snippet)] else attachment= title: "The query ​*#{query}*​ was not found" title_link: "https://github.com/anthonny/tweetiments/issues/new" fallback: "The query ​*#{query}*​ was not found" text: """ *#{msg.robot.name}* could not find a match for ​*#{query}*. *#{msg.robot.name}* is just a robot and he may need human help to add the entry. 1. Open an issue at https://github.com/anthonny/hubot-asciidoc/issues. 2. Call it *Add <query>* to *hubot-asciidoc* 3. Bonus points: create a pull request and add it yourself. See https://github.com/anthonny/hubot-asciidoc/README.adoc for help. *#{msg.robot.name}* thanks you :beers:. """ mrkdwn_in: ["text"] attachments = [attachment] sendAttachments msg, attachments
[ { "context": "store.remove done\n\n beforeEach ->\n @redisKey = uuid.v1()\n @jobManager = new JobManager\n client: ", "end": 650, "score": 0.9944137930870056, "start": 643, "tag": "KEY", "value": "uuid.v1" } ]
test/enqueue-jobs-for-webhooks-broadcast-received-spec.coffee
octoblu/meshblu-core-task-enqueue-jobs-for-webhooks-broadcast-received
0
redis = require 'fakeredis' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' mongojs = require 'mongojs' RedisNS = require '@octoblu/redis-ns' uuid = require 'uuid' {beforeEach, context, describe, it} = global {expect} = require 'chai' EnqueueJobsForWebhooksBroadcastReceived = require '../' describe 'EnqueueJobsForWebhooksBroadcastReceived', -> beforeEach (done) -> @datastore = new Datastore database: mongojs('meshblu-core-task-enqueue-jobs-for-webhooks-broadcast-received') collection: 'devices' @datastore.remove done beforeEach -> @redisKey = uuid.v1() @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 beforeEach -> client = new RedisNS 'ns', redis.createClient(@redisKey) @sut = new EnqueueJobsForWebhooksBroadcastReceived { datastore: @datastore jobManager: new JobManager {client: client, timeoutSeconds: 1} uuidAliasResolver: {resolve: (uuid, callback) -> callback(null, uuid)} } describe '->do', -> context 'with a device with no webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'with a device with one webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' meshblu: forwarders: broadcast: received: [{ type: 'webhook' url: 'https://google.com' method: 'POST' }] }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] forwardedRoutes: [] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).to.containSubset { metadata: jobType: 'DeliverWebhook' auth: uuid: 'subscriber' fromUuid: 'subscriber' toUuid: 'subscriber' messageType: 'broadcast.received' route: [{type: "broadcast.received", from: "subscriber", to: "subscriber"}] forwardedRoutes: [] options: type: 'webhook' url: 'https://google.com' method: 'POST' rawData: '{}' } done() context 'when given a valid job where the last hop from does not match the to', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'emitter', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should not enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).not.to.exist done()
92516
redis = require 'fakeredis' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' mongojs = require 'mongojs' RedisNS = require '@octoblu/redis-ns' uuid = require 'uuid' {beforeEach, context, describe, it} = global {expect} = require 'chai' EnqueueJobsForWebhooksBroadcastReceived = require '../' describe 'EnqueueJobsForWebhooksBroadcastReceived', -> beforeEach (done) -> @datastore = new Datastore database: mongojs('meshblu-core-task-enqueue-jobs-for-webhooks-broadcast-received') collection: 'devices' @datastore.remove done beforeEach -> @redisKey = <KEY>() @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 beforeEach -> client = new RedisNS 'ns', redis.createClient(@redisKey) @sut = new EnqueueJobsForWebhooksBroadcastReceived { datastore: @datastore jobManager: new JobManager {client: client, timeoutSeconds: 1} uuidAliasResolver: {resolve: (uuid, callback) -> callback(null, uuid)} } describe '->do', -> context 'with a device with no webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'with a device with one webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' meshblu: forwarders: broadcast: received: [{ type: 'webhook' url: 'https://google.com' method: 'POST' }] }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] forwardedRoutes: [] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).to.containSubset { metadata: jobType: 'DeliverWebhook' auth: uuid: 'subscriber' fromUuid: 'subscriber' toUuid: 'subscriber' messageType: 'broadcast.received' route: [{type: "broadcast.received", from: "subscriber", to: "subscriber"}] forwardedRoutes: [] options: type: 'webhook' url: 'https://google.com' method: 'POST' rawData: '{}' } done() context 'when given a valid job where the last hop from does not match the to', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'emitter', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should not enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).not.to.exist done()
true
redis = require 'fakeredis' Datastore = require 'meshblu-core-datastore' JobManager = require 'meshblu-core-job-manager' mongojs = require 'mongojs' RedisNS = require '@octoblu/redis-ns' uuid = require 'uuid' {beforeEach, context, describe, it} = global {expect} = require 'chai' EnqueueJobsForWebhooksBroadcastReceived = require '../' describe 'EnqueueJobsForWebhooksBroadcastReceived', -> beforeEach (done) -> @datastore = new Datastore database: mongojs('meshblu-core-task-enqueue-jobs-for-webhooks-broadcast-received') collection: 'devices' @datastore.remove done beforeEach -> @redisKey = PI:KEY:<KEY>END_PI() @jobManager = new JobManager client: new RedisNS 'ns', redis.createClient(@redisKey) timeoutSeconds: 1 beforeEach -> client = new RedisNS 'ns', redis.createClient(@redisKey) @sut = new EnqueueJobsForWebhooksBroadcastReceived { datastore: @datastore jobManager: new JobManager {client: client, timeoutSeconds: 1} uuidAliasResolver: {resolve: (uuid, callback) -> callback(null, uuid)} } describe '->do', -> context 'with a device with no webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse context 'with a device with one webhooks', -> beforeEach (done) -> @datastore.insert { uuid: 'subscriber' meshblu: forwarders: broadcast: received: [{ type: 'webhook' url: 'https://google.com' method: 'POST' }] }, done context 'when given a valid job', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'subscriber', to: 'subscriber'}] forwardedRoutes: [] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).to.containSubset { metadata: jobType: 'DeliverWebhook' auth: uuid: 'subscriber' fromUuid: 'subscriber' toUuid: 'subscriber' messageType: 'broadcast.received' route: [{type: "broadcast.received", from: "subscriber", to: "subscriber"}] forwardedRoutes: [] options: type: 'webhook' url: 'https://google.com' method: 'POST' rawData: '{}' } done() context 'when given a valid job where the last hop from does not match the to', -> beforeEach (done) -> request = metadata: auth: {uuid: 'subscriber'} route: [{type: 'broadcast.received', from: 'emitter', to: 'subscriber'}] responseId: 'its-electric' rawData: '{}' @sut.do request, (error, @response) => done error it 'should return a 204', -> expectedResponse = metadata: responseId: 'its-electric' code: 204 status: 'No Content' expect(@response).to.deep.equal expectedResponse it 'should not enqueue a job to deliver the webhook', (done) -> @jobManager.getRequest ['request'], (error, request) => return done error if error? expect(request).not.to.exist done()
[ { "context": "[0]\n\n\n\nfor t in test_data\n key = 'testing auto-format #'+(i++)\n add_test key, t\n\n# vows\n# .describ", "end": 1556, "score": 0.5380566716194153, "start": 1548, "tag": "KEY", "value": "format #" } ]
dw.js/test/auto-format-test.coffee
webvariants/datawrapper
1
root._ = require 'underscore' root.Globalize = require 'globalize' vows = require 'vows' assert = require 'assert' dw = require '../dw-2.0.js' test_data = [] test_data.push ['5.4', 5.4, 4.2, 4, 3.6, 3.4] test_data.push ['33k', 33030, 27540] test_data.push ['33,030', 33030, 33100] test_data.push ['5', 5, 7, 9, 10, 13] test_data.push ['50', 50, 70, 90, 100, 130] test_data.push ['500', 500, 700, 900, 1000, 1300] test_data.push ['5k', 5000, 7000, 9000, 10000, 13000] test_data.push ['50k', 50000, 70000, 90000, 100000, 130000] test_data.push ['0.5M', 500000, 700000, 900000, 1000000, 1300000] test_data.push ['510k', 510000, 540000, 900000, 1000000, 1300000] test_data.push ['1', 1, 2, 3, 4, 5] test_data.push ['0.1', 0.1, 0.2, 0.3, 0.4, 0.5] test_data.push ['0.01', 0.01, 0.02, 0.03, 0.04, 0.05] test_data.push ['1 × 10<sup>-3</sup>', 0.001, 0.002, 0.003, 0.004, 0.005] test_data.push ['1 × 10<sup>-4</sup>', 0.00011, 0.0002, 0.0003, 0.0004, 0.0005] test_data.push ['11 × 10<sup>-5</sup>', 0.00011, 0.00013, 0.0003, 0.0004, 0.0005] i = 0 batch = {} add_test = (key, t) -> batch[key] = 'topic': () -> chart = dw.chart({}) chart.locale 'en-US' ds = dw.dataset [dw.column('numbers', t.slice(1))] chart.dataset ds chart 'check format': (chart) -> ds = chart.dataset() col = ds.column(0) fmt = chart.columnFormatter(ds.column(0)) assert.equal fmt(col.val(0), true), t[0] for t in test_data key = 'testing auto-format #'+(i++) add_test key, t # vows # .describe('Testing number column auto-formatting') # .addBatch(batch) # .export module
203959
root._ = require 'underscore' root.Globalize = require 'globalize' vows = require 'vows' assert = require 'assert' dw = require '../dw-2.0.js' test_data = [] test_data.push ['5.4', 5.4, 4.2, 4, 3.6, 3.4] test_data.push ['33k', 33030, 27540] test_data.push ['33,030', 33030, 33100] test_data.push ['5', 5, 7, 9, 10, 13] test_data.push ['50', 50, 70, 90, 100, 130] test_data.push ['500', 500, 700, 900, 1000, 1300] test_data.push ['5k', 5000, 7000, 9000, 10000, 13000] test_data.push ['50k', 50000, 70000, 90000, 100000, 130000] test_data.push ['0.5M', 500000, 700000, 900000, 1000000, 1300000] test_data.push ['510k', 510000, 540000, 900000, 1000000, 1300000] test_data.push ['1', 1, 2, 3, 4, 5] test_data.push ['0.1', 0.1, 0.2, 0.3, 0.4, 0.5] test_data.push ['0.01', 0.01, 0.02, 0.03, 0.04, 0.05] test_data.push ['1 × 10<sup>-3</sup>', 0.001, 0.002, 0.003, 0.004, 0.005] test_data.push ['1 × 10<sup>-4</sup>', 0.00011, 0.0002, 0.0003, 0.0004, 0.0005] test_data.push ['11 × 10<sup>-5</sup>', 0.00011, 0.00013, 0.0003, 0.0004, 0.0005] i = 0 batch = {} add_test = (key, t) -> batch[key] = 'topic': () -> chart = dw.chart({}) chart.locale 'en-US' ds = dw.dataset [dw.column('numbers', t.slice(1))] chart.dataset ds chart 'check format': (chart) -> ds = chart.dataset() col = ds.column(0) fmt = chart.columnFormatter(ds.column(0)) assert.equal fmt(col.val(0), true), t[0] for t in test_data key = 'testing auto-<KEY>'+(i++) add_test key, t # vows # .describe('Testing number column auto-formatting') # .addBatch(batch) # .export module
true
root._ = require 'underscore' root.Globalize = require 'globalize' vows = require 'vows' assert = require 'assert' dw = require '../dw-2.0.js' test_data = [] test_data.push ['5.4', 5.4, 4.2, 4, 3.6, 3.4] test_data.push ['33k', 33030, 27540] test_data.push ['33,030', 33030, 33100] test_data.push ['5', 5, 7, 9, 10, 13] test_data.push ['50', 50, 70, 90, 100, 130] test_data.push ['500', 500, 700, 900, 1000, 1300] test_data.push ['5k', 5000, 7000, 9000, 10000, 13000] test_data.push ['50k', 50000, 70000, 90000, 100000, 130000] test_data.push ['0.5M', 500000, 700000, 900000, 1000000, 1300000] test_data.push ['510k', 510000, 540000, 900000, 1000000, 1300000] test_data.push ['1', 1, 2, 3, 4, 5] test_data.push ['0.1', 0.1, 0.2, 0.3, 0.4, 0.5] test_data.push ['0.01', 0.01, 0.02, 0.03, 0.04, 0.05] test_data.push ['1 × 10<sup>-3</sup>', 0.001, 0.002, 0.003, 0.004, 0.005] test_data.push ['1 × 10<sup>-4</sup>', 0.00011, 0.0002, 0.0003, 0.0004, 0.0005] test_data.push ['11 × 10<sup>-5</sup>', 0.00011, 0.00013, 0.0003, 0.0004, 0.0005] i = 0 batch = {} add_test = (key, t) -> batch[key] = 'topic': () -> chart = dw.chart({}) chart.locale 'en-US' ds = dw.dataset [dw.column('numbers', t.slice(1))] chart.dataset ds chart 'check format': (chart) -> ds = chart.dataset() col = ds.column(0) fmt = chart.columnFormatter(ds.column(0)) assert.equal fmt(col.val(0), true), t[0] for t in test_data key = 'testing auto-PI:KEY:<KEY>END_PI'+(i++) add_test key, t # vows # .describe('Testing number column auto-formatting') # .addBatch(batch) # .export module
[ { "context": "on'\n gOptions =\n dirname: '.'\n users:\n zhuangbiaowei:\n name: \"BiaoWei Zhuang\"\n email: [\n", "end": 914, "score": 0.9918866157531738, "start": 901, "tag": "USERNAME", "value": "zhuangbiaowei" }, { "context": ".'\n users:\n zhuang...
test/get-contributors-test.coffee
snowyu/get-contributors.js
1
fs = require 'fs' cson = require 'cson' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' mockery = require 'mockery' _ = require 'lodash' should = chai.should() expect = chai.expect assert = chai.assert chai.use(sinonChai) setImmediate = setImmediate || process.nextTick mockery.registerMock 'git-commiters', (options, callback)-> options = options || {} if fakeError? callback(fakeError) else callback(null, fakeResults) return mockery.enable warnOnUnregistered: false fakeResults = [] fakeError = null getContributors = require '../src/' readFile = (aFile)-> fs.readFileSync(aFile, encoding:'utf8') describe 'get-contributors', -> fakeMergeUser = readFile __dirname+'/fixture/merge-user.cson' gOptions = dirname: '.' users: zhuangbiaowei: name: "BiaoWei Zhuang" email: [ "zhuangbiaowei@gmail.com" "zhuangbiaowei@huawei.com" ] riceball: name: "Riceball LEE" email: "snowyu.lee@gmail.com" fields: [ 'name' ] before -> after -> mockery.deregisterMock('git-commiters') mockery.disable() beforeEach -> fakeResults = cson.parseCSONString fakeMergeUser it 'should calc percentage', (done)-> options = _.extend {}, gOptions, fields: ['name', 'percent', 'commits', 'insertions', 'deletions'] weight: commit:0.6, deletion:0.2 getContributors options .then (users)-> users.should.be.deep.equal [ { name: 'BiaoWei Zhuang' insertions: 63 commits: 57 deletions: 4 percent: '63.2' } { name: 'Riceball LEE' insertions: 37 commits: 33 deletions: 1 percent: '36.8' } ] users .nodeify(done) it 'should merge user and sort by percentage', (done)-> gOptions.fields = ['name'] getContributors gOptions .then (users)-> users.should.be.deep.equal [ {name: 'BiaoWei Zhuang'} {name: 'Riceball LEE'} ] users .nodeify(done)
93067
fs = require 'fs' cson = require 'cson' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' mockery = require 'mockery' _ = require 'lodash' should = chai.should() expect = chai.expect assert = chai.assert chai.use(sinonChai) setImmediate = setImmediate || process.nextTick mockery.registerMock 'git-commiters', (options, callback)-> options = options || {} if fakeError? callback(fakeError) else callback(null, fakeResults) return mockery.enable warnOnUnregistered: false fakeResults = [] fakeError = null getContributors = require '../src/' readFile = (aFile)-> fs.readFileSync(aFile, encoding:'utf8') describe 'get-contributors', -> fakeMergeUser = readFile __dirname+'/fixture/merge-user.cson' gOptions = dirname: '.' users: zhuangbiaowei: name: "<NAME>" email: [ "<EMAIL>" "<EMAIL>" ] riceball: name: "<NAME>" email: "<EMAIL>" fields: [ 'name' ] before -> after -> mockery.deregisterMock('git-commiters') mockery.disable() beforeEach -> fakeResults = cson.parseCSONString fakeMergeUser it 'should calc percentage', (done)-> options = _.extend {}, gOptions, fields: ['name', 'percent', 'commits', 'insertions', 'deletions'] weight: commit:0.6, deletion:0.2 getContributors options .then (users)-> users.should.be.deep.equal [ { name: '<NAME>' insertions: 63 commits: 57 deletions: 4 percent: '63.2' } { name: '<NAME>' insertions: 37 commits: 33 deletions: 1 percent: '36.8' } ] users .nodeify(done) it 'should merge user and sort by percentage', (done)-> gOptions.fields = ['name'] getContributors gOptions .then (users)-> users.should.be.deep.equal [ {name: '<NAME>'} {name: '<NAME>'} ] users .nodeify(done)
true
fs = require 'fs' cson = require 'cson' chai = require 'chai' sinon = require 'sinon' sinonChai = require 'sinon-chai' mockery = require 'mockery' _ = require 'lodash' should = chai.should() expect = chai.expect assert = chai.assert chai.use(sinonChai) setImmediate = setImmediate || process.nextTick mockery.registerMock 'git-commiters', (options, callback)-> options = options || {} if fakeError? callback(fakeError) else callback(null, fakeResults) return mockery.enable warnOnUnregistered: false fakeResults = [] fakeError = null getContributors = require '../src/' readFile = (aFile)-> fs.readFileSync(aFile, encoding:'utf8') describe 'get-contributors', -> fakeMergeUser = readFile __dirname+'/fixture/merge-user.cson' gOptions = dirname: '.' users: zhuangbiaowei: name: "PI:NAME:<NAME>END_PI" email: [ "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" ] riceball: name: "PI:NAME:<NAME>END_PI" email: "PI:EMAIL:<EMAIL>END_PI" fields: [ 'name' ] before -> after -> mockery.deregisterMock('git-commiters') mockery.disable() beforeEach -> fakeResults = cson.parseCSONString fakeMergeUser it 'should calc percentage', (done)-> options = _.extend {}, gOptions, fields: ['name', 'percent', 'commits', 'insertions', 'deletions'] weight: commit:0.6, deletion:0.2 getContributors options .then (users)-> users.should.be.deep.equal [ { name: 'PI:NAME:<NAME>END_PI' insertions: 63 commits: 57 deletions: 4 percent: '63.2' } { name: 'PI:NAME:<NAME>END_PI' insertions: 37 commits: 33 deletions: 1 percent: '36.8' } ] users .nodeify(done) it 'should merge user and sort by percentage', (done)-> gOptions.fields = ['name'] getContributors gOptions .then (users)-> users.should.be.deep.equal [ {name: 'PI:NAME:<NAME>END_PI'} {name: 'PI:NAME:<NAME>END_PI'} ] users .nodeify(done)
[ { "context": "anyName ?= 'GitHub, Inc'\n submitUrl ?= 'http://54.249.141.255:1127/post'\n autoSubmit ?= true\n ignoreSyste", "end": 329, "score": 0.9708980917930603, "start": 315, "tag": "IP_ADDRESS", "value": "54.249.141.255" } ]
atom/common/api/lib/crash-reporter.coffee
gstack/fresh-shell
2
{spawn} = require 'child_process' binding = process.atomBinding 'crash_reporter' class CrashReporter start: (options={}) -> {productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options productName ?= 'Atom-Shell' companyName ?= 'GitHub, Inc' submitUrl ?= 'http://54.249.141.255:1127/post' autoSubmit ?= true ignoreSystemCrashHandler ?= false extra ?= {} extra._productName ?= productName extra._companyName ?= companyName extra._version ?= if process.type is 'browser' require('app').getVersion() else require('remote').require('app').getVersion() start = -> binding.start productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra if process.platform is 'win32' args = [ "--reporter-url=#{submitUrl}" "--application-name=#{productName}" "--v=1" ] env = ATOM_SHELL_INTERNAL_CRASH_SERVICE: 1 spawn process.execPath, args, {env, detached: true} start() else start() module.exports = new CrashReporter
47469
{spawn} = require 'child_process' binding = process.atomBinding 'crash_reporter' class CrashReporter start: (options={}) -> {productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options productName ?= 'Atom-Shell' companyName ?= 'GitHub, Inc' submitUrl ?= 'http://172.16.31.10:1127/post' autoSubmit ?= true ignoreSystemCrashHandler ?= false extra ?= {} extra._productName ?= productName extra._companyName ?= companyName extra._version ?= if process.type is 'browser' require('app').getVersion() else require('remote').require('app').getVersion() start = -> binding.start productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra if process.platform is 'win32' args = [ "--reporter-url=#{submitUrl}" "--application-name=#{productName}" "--v=1" ] env = ATOM_SHELL_INTERNAL_CRASH_SERVICE: 1 spawn process.execPath, args, {env, detached: true} start() else start() module.exports = new CrashReporter
true
{spawn} = require 'child_process' binding = process.atomBinding 'crash_reporter' class CrashReporter start: (options={}) -> {productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra} = options productName ?= 'Atom-Shell' companyName ?= 'GitHub, Inc' submitUrl ?= 'http://PI:IP_ADDRESS:172.16.31.10END_PI:1127/post' autoSubmit ?= true ignoreSystemCrashHandler ?= false extra ?= {} extra._productName ?= productName extra._companyName ?= companyName extra._version ?= if process.type is 'browser' require('app').getVersion() else require('remote').require('app').getVersion() start = -> binding.start productName, companyName, submitUrl, autoSubmit, ignoreSystemCrashHandler, extra if process.platform is 'win32' args = [ "--reporter-url=#{submitUrl}" "--application-name=#{productName}" "--v=1" ] env = ATOM_SHELL_INTERNAL_CRASH_SERVICE: 1 spawn process.execPath, args, {env, detached: true} start() else start() module.exports = new CrashReporter
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9929454922676086, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-symlink-dir-junction-relative.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. # Test creating and resolving relative junction or symbolic link # Prepare. # Test fs.symlink() # Test fs.symlinkSync() verifyLink = (linkPath) -> stats = fs.lstatSync(linkPath) assert.ok stats.isSymbolicLink() data1 = fs.readFileSync(linkPath + "/x.txt", "ascii") data2 = fs.readFileSync(linkTarget + "/x.txt", "ascii") assert.strictEqual data1, data2 # Clean up. fs.unlinkSync linkPath completed++ return common = require("../common") assert = require("assert") path = require("path") fs = require("fs") completed = 0 expected_tests = 2 linkPath1 = path.join(common.tmpDir, "junction1") linkPath2 = path.join(common.tmpDir, "junction2") linkTarget = path.join(common.fixturesDir) linkData = "../fixtures" try fs.mkdirSync common.tmpDir try fs.unlinkSync linkPath1 try fs.unlinkSync linkPath2 fs.symlink linkData, linkPath1, "junction", (err) -> throw err if err verifyLink linkPath1 return fs.symlinkSync linkData, linkPath2, "junction" verifyLink linkPath2 process.on "exit", -> assert.equal completed, expected_tests return
138130
# 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. # Test creating and resolving relative junction or symbolic link # Prepare. # Test fs.symlink() # Test fs.symlinkSync() verifyLink = (linkPath) -> stats = fs.lstatSync(linkPath) assert.ok stats.isSymbolicLink() data1 = fs.readFileSync(linkPath + "/x.txt", "ascii") data2 = fs.readFileSync(linkTarget + "/x.txt", "ascii") assert.strictEqual data1, data2 # Clean up. fs.unlinkSync linkPath completed++ return common = require("../common") assert = require("assert") path = require("path") fs = require("fs") completed = 0 expected_tests = 2 linkPath1 = path.join(common.tmpDir, "junction1") linkPath2 = path.join(common.tmpDir, "junction2") linkTarget = path.join(common.fixturesDir) linkData = "../fixtures" try fs.mkdirSync common.tmpDir try fs.unlinkSync linkPath1 try fs.unlinkSync linkPath2 fs.symlink linkData, linkPath1, "junction", (err) -> throw err if err verifyLink linkPath1 return fs.symlinkSync linkData, linkPath2, "junction" verifyLink linkPath2 process.on "exit", -> assert.equal completed, expected_tests 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. # Test creating and resolving relative junction or symbolic link # Prepare. # Test fs.symlink() # Test fs.symlinkSync() verifyLink = (linkPath) -> stats = fs.lstatSync(linkPath) assert.ok stats.isSymbolicLink() data1 = fs.readFileSync(linkPath + "/x.txt", "ascii") data2 = fs.readFileSync(linkTarget + "/x.txt", "ascii") assert.strictEqual data1, data2 # Clean up. fs.unlinkSync linkPath completed++ return common = require("../common") assert = require("assert") path = require("path") fs = require("fs") completed = 0 expected_tests = 2 linkPath1 = path.join(common.tmpDir, "junction1") linkPath2 = path.join(common.tmpDir, "junction2") linkTarget = path.join(common.fixturesDir) linkData = "../fixtures" try fs.mkdirSync common.tmpDir try fs.unlinkSync linkPath1 try fs.unlinkSync linkPath2 fs.symlink linkData, linkPath1, "junction", (err) -> throw err if err verifyLink linkPath1 return fs.symlinkSync linkData, linkPath2, "junction" verifyLink linkPath2 process.on "exit", -> assert.equal completed, expected_tests return
[ { "context": "#\n# String class extensions\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\next String.prototype,\n #\n # Checks if the str", "end": 68, "score": 0.9998761415481567, "start": 51, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/lang/src/string.coffee
lovely-io/lovely.io-stl
2
# # String class extensions # # Copyright (C) 2011 Nikolay Nemshilov # ext String.prototype, # # Checks if the string is an empty string # # @return {Boolean} check result # empty: -> `this == ''` # # Checks if the string contains only white-spaces # # @return {Boolean} check result # blank: -> `this == false` # # Removes trailing whitespaces # # @return {String} trimmed version # trim: String.prototype.trim || -> str = @replace(/^\s\s*/, ''); i = str.length while ((/\s/).test(str.charAt(i-=1))) ; str.slice(0, i + 1) # # Returns a copy of the string with all the tags removed # # @return {String} without tags # stripTags: -> @replace /<\/?[^>]+>/ig, '' # # Converts underscored or dasherized string to a camelized one # # @returns {String} camelized version # camelize: -> @replace /(\-|_)+(.)?/g, (match, dash, chr)-> if chr then chr.toUpperCase() else '' # # Converts a camelized or dasherized string into an underscored one # # @return {String} underscored version # underscored: -> @replace(/(^|[a-z\d])([A-Z]+)/g, '$1_$2').replace(/\-/g, '_').toLowerCase() # # Converts the string into a dashed string # # @return {String} dasherized version # dasherize: -> @underscored().replace(/_/g, '-') # # Returns a capitalised version of the string # # @return {String} captialised version # capitalize: -> @charAt(0).toUpperCase() + @substring(1).toLowerCase() # # Checks if the string contains the given substring # # @param {String} a substring # @return {Boolean} check result # includes: (string) -> @indexOf(string) isnt -1 # # Checks if this string ends with the given substring # # @param {String} a sbustring # @return {Boolean} check result # endsWith: (substring)-> (@length - @lastIndexOf(substring)) is substring.length # # Checks if the string starts with the given substring # # @param {String} a substring # @return {Boolean} check result # startsWith: (substring)-> @indexOf(substring) is 0 # # Converts the string into an itenteger value # # @param {Integer} convertion base, default 10 # @return {Integer|NaN} result # toInt: (base)-> parseInt(this, if base is undefined then 10 else base) # # Converts the string into a float value # # @return {Float|NaN} result # toFloat: -> parseFloat(this)
119871
# # String class extensions # # Copyright (C) 2011 <NAME> # ext String.prototype, # # Checks if the string is an empty string # # @return {Boolean} check result # empty: -> `this == ''` # # Checks if the string contains only white-spaces # # @return {Boolean} check result # blank: -> `this == false` # # Removes trailing whitespaces # # @return {String} trimmed version # trim: String.prototype.trim || -> str = @replace(/^\s\s*/, ''); i = str.length while ((/\s/).test(str.charAt(i-=1))) ; str.slice(0, i + 1) # # Returns a copy of the string with all the tags removed # # @return {String} without tags # stripTags: -> @replace /<\/?[^>]+>/ig, '' # # Converts underscored or dasherized string to a camelized one # # @returns {String} camelized version # camelize: -> @replace /(\-|_)+(.)?/g, (match, dash, chr)-> if chr then chr.toUpperCase() else '' # # Converts a camelized or dasherized string into an underscored one # # @return {String} underscored version # underscored: -> @replace(/(^|[a-z\d])([A-Z]+)/g, '$1_$2').replace(/\-/g, '_').toLowerCase() # # Converts the string into a dashed string # # @return {String} dasherized version # dasherize: -> @underscored().replace(/_/g, '-') # # Returns a capitalised version of the string # # @return {String} captialised version # capitalize: -> @charAt(0).toUpperCase() + @substring(1).toLowerCase() # # Checks if the string contains the given substring # # @param {String} a substring # @return {Boolean} check result # includes: (string) -> @indexOf(string) isnt -1 # # Checks if this string ends with the given substring # # @param {String} a sbustring # @return {Boolean} check result # endsWith: (substring)-> (@length - @lastIndexOf(substring)) is substring.length # # Checks if the string starts with the given substring # # @param {String} a substring # @return {Boolean} check result # startsWith: (substring)-> @indexOf(substring) is 0 # # Converts the string into an itenteger value # # @param {Integer} convertion base, default 10 # @return {Integer|NaN} result # toInt: (base)-> parseInt(this, if base is undefined then 10 else base) # # Converts the string into a float value # # @return {Float|NaN} result # toFloat: -> parseFloat(this)
true
# # String class extensions # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # ext String.prototype, # # Checks if the string is an empty string # # @return {Boolean} check result # empty: -> `this == ''` # # Checks if the string contains only white-spaces # # @return {Boolean} check result # blank: -> `this == false` # # Removes trailing whitespaces # # @return {String} trimmed version # trim: String.prototype.trim || -> str = @replace(/^\s\s*/, ''); i = str.length while ((/\s/).test(str.charAt(i-=1))) ; str.slice(0, i + 1) # # Returns a copy of the string with all the tags removed # # @return {String} without tags # stripTags: -> @replace /<\/?[^>]+>/ig, '' # # Converts underscored or dasherized string to a camelized one # # @returns {String} camelized version # camelize: -> @replace /(\-|_)+(.)?/g, (match, dash, chr)-> if chr then chr.toUpperCase() else '' # # Converts a camelized or dasherized string into an underscored one # # @return {String} underscored version # underscored: -> @replace(/(^|[a-z\d])([A-Z]+)/g, '$1_$2').replace(/\-/g, '_').toLowerCase() # # Converts the string into a dashed string # # @return {String} dasherized version # dasherize: -> @underscored().replace(/_/g, '-') # # Returns a capitalised version of the string # # @return {String} captialised version # capitalize: -> @charAt(0).toUpperCase() + @substring(1).toLowerCase() # # Checks if the string contains the given substring # # @param {String} a substring # @return {Boolean} check result # includes: (string) -> @indexOf(string) isnt -1 # # Checks if this string ends with the given substring # # @param {String} a sbustring # @return {Boolean} check result # endsWith: (substring)-> (@length - @lastIndexOf(substring)) is substring.length # # Checks if the string starts with the given substring # # @param {String} a substring # @return {Boolean} check result # startsWith: (substring)-> @indexOf(substring) is 0 # # Converts the string into an itenteger value # # @param {Integer} convertion base, default 10 # @return {Integer|NaN} result # toInt: (base)-> parseInt(this, if base is undefined then 10 else base) # # Converts the string into a float value # # @return {Float|NaN} result # toFloat: -> parseFloat(this)
[ { "context": "ication\n# HUBOT_WUNDERLIST_SMTP_AUTH_PASSWORD - password for authentication\n#\n# Commands:\n# hubot wunderlist", "end": 602, "score": 0.7983406782150269, "start": 590, "tag": "PASSWORD", "value": "password for" }, { "context": " all todos are added to the Inbox.\...
src/scripts/wunderlist.coffee
neilprosser/hubot-scripts
1
# Description: # wunderlist allows you to add todos to your wunderlist directly from hubot # # Dependencies: # "mailer": "0.6.7" # # Configuration: # HUBOT_WUNDERLIST_SMTP_HOST - your smtp host e.g. smtp.gmail.com # HUBOT_WUNDERLIST_SMTP_PORT - the port to connect to # HUBOT_WUNDERLIST_SMTP_USESSL - wether you want to connect via SSL # HUBOT_WUNDERLIST_SMTP_SENDDOMAIN - the domain from which to send # HUBOT_WUNDERLIST_SMTP_USEAUTH - BOOL: authentication required # HUBOT_WUNDERLIST_SMTP_AUTH_NAME - username for authentication # HUBOT_WUNDERLIST_SMTP_AUTH_PASSWORD - password for authentication # # Commands: # hubot wunderlist all the users - display all users which have registered # hubot wunderlist add me with <email> - add <email> as wunderlist login # hubot wunderlist my login - display your wunderlist email # hubot wunderlist forget me - remove the wunderlist login # hubot wunderlist me <a todo> - adds the todo to your wunderlist Inbox # # Notes: # Currently all todos are added to the Inbox. # # Author: # mrtazz mail = require 'mailer' module.exports = (robot) -> robot.respond /wunderlist all the users/i, (msg) -> theReply = "Here is who I know:\n" for own key, user of robot.brain.data.users if(user.wunderlistmail) theReply += user.name + " is " + user.wunderlistmail + "\n" msg.send theReply robot.respond /wunderlist add me with ([\w\d-_.]+@[\w\d-_.]+)/i, (msg) -> wunderlistmail = msg.match[1] msg.message.user.wunderlistmail = wunderlistmail msg.send "Ok, you are " + wunderlistmail + " on Wunderlist" robot.respond /wunderlist my login/i, (msg) -> user = msg.message.user if user.wunderlistmail msg.reply "You are known as " + user.wunderlistmail + " on Wunderlist" else text = "I don't know who you are. You should probably identify yourself" text += "with your Wunderlist login" msg.reply text robot.respond /wunderlist forget me/i, (msg) -> user = msg.message.user user.wunderlistmail = null msg.reply("Ok, I have no idea who you are anymore.") robot.respond /wunderlist me (.*)/i, (msg) -> todo = msg.match[1] wunderlistmail = msg.message.user.wunderlistmail # change list here subject = "Inbox" # option settings options = { host : process.env.HUBOT_WUNDERLIST_SMTP_HOST , port : process.env.HUBOT_WUNDERLIST_SMTP_PORT or 25 , ssl : process.env.HUBOT_WUNDERLIST_SMTP_USESSL or true , domain : process.env.HUBOT_WUNDERLIST_SMTP_SENDDOMAIN or 'localhost', authentication : process.env.HUBOT_WUNDERLIST_SMTP_USEAUTH or false , username : process.env.HUBOT_WUNDERLIST_SMTP_AUTH_NAME , password : process.env.HUBOT_WUNDERLIST_SMTP_AUTH_PASSWORD } if (options.host) options.authentication = if options.authentication is true then 'login' else 'none' options.to = 'me@wunderlist.com' options.from = wunderlistmail options.subject = subject options.body = todo mail.send options, (err, result) -> console.log(err) if (err) msg.reply "I'm sorry, I couldn't add your todo." else msg.reply "Your todo was added."
38932
# Description: # wunderlist allows you to add todos to your wunderlist directly from hubot # # Dependencies: # "mailer": "0.6.7" # # Configuration: # HUBOT_WUNDERLIST_SMTP_HOST - your smtp host e.g. smtp.gmail.com # HUBOT_WUNDERLIST_SMTP_PORT - the port to connect to # HUBOT_WUNDERLIST_SMTP_USESSL - wether you want to connect via SSL # HUBOT_WUNDERLIST_SMTP_SENDDOMAIN - the domain from which to send # HUBOT_WUNDERLIST_SMTP_USEAUTH - BOOL: authentication required # HUBOT_WUNDERLIST_SMTP_AUTH_NAME - username for authentication # HUBOT_WUNDERLIST_SMTP_AUTH_PASSWORD - <PASSWORD> authentication # # Commands: # hubot wunderlist all the users - display all users which have registered # hubot wunderlist add me with <email> - add <email> as wunderlist login # hubot wunderlist my login - display your wunderlist email # hubot wunderlist forget me - remove the wunderlist login # hubot wunderlist me <a todo> - adds the todo to your wunderlist Inbox # # Notes: # Currently all todos are added to the Inbox. # # Author: # mrtazz mail = require 'mailer' module.exports = (robot) -> robot.respond /wunderlist all the users/i, (msg) -> theReply = "Here is who I know:\n" for own key, user of robot.brain.data.users if(user.wunderlistmail) theReply += user.name + " is " + user.wunderlistmail + "\n" msg.send theReply robot.respond /wunderlist add me with ([\w\d-_.]+@[\w\d-_.]+)/i, (msg) -> wunderlistmail = msg.match[1] msg.message.user.wunderlistmail = wunderlistmail msg.send "Ok, you are " + wunderlistmail + " on Wunderlist" robot.respond /wunderlist my login/i, (msg) -> user = msg.message.user if user.wunderlistmail msg.reply "You are known as " + user.wunderlistmail + " on Wunderlist" else text = "I don't know who you are. You should probably identify yourself" text += "with your Wunderlist login" msg.reply text robot.respond /wunderlist forget me/i, (msg) -> user = msg.message.user user.wunderlistmail = null msg.reply("Ok, I have no idea who you are anymore.") robot.respond /wunderlist me (.*)/i, (msg) -> todo = msg.match[1] wunderlistmail = msg.message.user.wunderlistmail # change list here subject = "Inbox" # option settings options = { host : process.env.HUBOT_WUNDERLIST_SMTP_HOST , port : process.env.HUBOT_WUNDERLIST_SMTP_PORT or 25 , ssl : process.env.HUBOT_WUNDERLIST_SMTP_USESSL or true , domain : process.env.HUBOT_WUNDERLIST_SMTP_SENDDOMAIN or 'localhost', authentication : process.env.HUBOT_WUNDERLIST_SMTP_USEAUTH or false , username : process.env.HUBOT_WUNDERLIST_SMTP_AUTH_NAME , password : <PASSWORD>.<PASSWORD> } if (options.host) options.authentication = if options.authentication is true then 'login' else 'none' options.to = '<EMAIL>' options.from = wunderlistmail options.subject = subject options.body = todo mail.send options, (err, result) -> console.log(err) if (err) msg.reply "I'm sorry, I couldn't add your todo." else msg.reply "Your todo was added."
true
# Description: # wunderlist allows you to add todos to your wunderlist directly from hubot # # Dependencies: # "mailer": "0.6.7" # # Configuration: # HUBOT_WUNDERLIST_SMTP_HOST - your smtp host e.g. smtp.gmail.com # HUBOT_WUNDERLIST_SMTP_PORT - the port to connect to # HUBOT_WUNDERLIST_SMTP_USESSL - wether you want to connect via SSL # HUBOT_WUNDERLIST_SMTP_SENDDOMAIN - the domain from which to send # HUBOT_WUNDERLIST_SMTP_USEAUTH - BOOL: authentication required # HUBOT_WUNDERLIST_SMTP_AUTH_NAME - username for authentication # HUBOT_WUNDERLIST_SMTP_AUTH_PASSWORD - PI:PASSWORD:<PASSWORD>END_PI authentication # # Commands: # hubot wunderlist all the users - display all users which have registered # hubot wunderlist add me with <email> - add <email> as wunderlist login # hubot wunderlist my login - display your wunderlist email # hubot wunderlist forget me - remove the wunderlist login # hubot wunderlist me <a todo> - adds the todo to your wunderlist Inbox # # Notes: # Currently all todos are added to the Inbox. # # Author: # mrtazz mail = require 'mailer' module.exports = (robot) -> robot.respond /wunderlist all the users/i, (msg) -> theReply = "Here is who I know:\n" for own key, user of robot.brain.data.users if(user.wunderlistmail) theReply += user.name + " is " + user.wunderlistmail + "\n" msg.send theReply robot.respond /wunderlist add me with ([\w\d-_.]+@[\w\d-_.]+)/i, (msg) -> wunderlistmail = msg.match[1] msg.message.user.wunderlistmail = wunderlistmail msg.send "Ok, you are " + wunderlistmail + " on Wunderlist" robot.respond /wunderlist my login/i, (msg) -> user = msg.message.user if user.wunderlistmail msg.reply "You are known as " + user.wunderlistmail + " on Wunderlist" else text = "I don't know who you are. You should probably identify yourself" text += "with your Wunderlist login" msg.reply text robot.respond /wunderlist forget me/i, (msg) -> user = msg.message.user user.wunderlistmail = null msg.reply("Ok, I have no idea who you are anymore.") robot.respond /wunderlist me (.*)/i, (msg) -> todo = msg.match[1] wunderlistmail = msg.message.user.wunderlistmail # change list here subject = "Inbox" # option settings options = { host : process.env.HUBOT_WUNDERLIST_SMTP_HOST , port : process.env.HUBOT_WUNDERLIST_SMTP_PORT or 25 , ssl : process.env.HUBOT_WUNDERLIST_SMTP_USESSL or true , domain : process.env.HUBOT_WUNDERLIST_SMTP_SENDDOMAIN or 'localhost', authentication : process.env.HUBOT_WUNDERLIST_SMTP_USEAUTH or false , username : process.env.HUBOT_WUNDERLIST_SMTP_AUTH_NAME , password : PI:PASSWORD:<PASSWORD>END_PI.PI:PASSWORD:<PASSWORD>END_PI } if (options.host) options.authentication = if options.authentication is true then 'login' else 'none' options.to = 'PI:EMAIL:<EMAIL>END_PI' options.from = wunderlistmail options.subject = subject options.body = todo mail.send options, (err, result) -> console.log(err) if (err) msg.reply "I'm sorry, I couldn't add your todo." else msg.reply "Your todo was added."
[ { "context": "peString = \"Hobby Servo\"\n when 0x40 # TODO(Matt Zhao): Implement when these are implemented\n ", "end": 1913, "score": 0.9994476437568665, "start": 1904, "tag": "NAME", "value": "Matt Zhao" }, { "context": "ring = \"Grizzly Bear v3\"\n when 0x8...
app/scripts/robot/read_descriptor.coffee
sutkarsh/daemon
0
angular.module('daemon.read_descriptor', []) .service('read_descriptor', [ -> buffer = requireNode("buffer") readString = (buf, startIndex) -> length = buf.readUInt8(startIndex) description = buf.slice(startIndex + 1, length + startIndex + 1) [ description.toString("utf8") length + startIndex + 1 ] readChannelDescriptor = (buf, startIndex) -> index = startIndex + 1 numChannels = buf.readUInt8(startIndex) descriptors = [numChannels] i = 0 while i < numChannels channelDescriptor = readString(buf, index + 1) type = buf.readUInt8(channelDescriptor[1]) typeData = typeChannel(buf, type, channelDescriptor[1] + 1) descriptors.push [ channelDescriptor[0] typeData[0] ] index = typeData[1] i++ descriptors typeChannel = (buf, typeBinary, startIndex) -> FLAGS_LENGTH = 1 SAMPLE_RATE_LENGTH = 2 BIT_PER_SAMPLE_LENGTH = 1 INTERNAL_TIMER_TICK_FREQ_LENGTH = 4 INTERNAL_CYCLE_TIME_TICK_LENGTH = 4 MODE = 1 SPEED = 4 numTotal = startIndex typeString = "" switch typeBinary when 0x00 numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Digital In/Out" when 0x01 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Input" when 0x02 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Output" when 0x03 num = numTotal + BIT_PER_SAMPLE_LENGTH + INTERNAL_TIMER_TICK_FREQ_LENGTH + INTERNAL_CYCLE_TIME_TICK_LENGTH numTotal = calibrationType(buf, num) typeString = "Hobby Servo" when 0x40 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic I2C" when 0x41 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic SPI" when 0x42 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic UART" when 0x80 numTotal += MODE + SPEED typeString = "Grizzly Bear v3" when 0x81 # TODO(Matt Zhao): change when battery buzzer additional info block changed num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Battery Buzzer" when 0x82 # TODO(Matt Zhao): change when team flag additional info block changed numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Team Flag" when 0xfe # numTotal += MODE; # TODO(Matt Zhao): Uncomment previous line if firmware is fixed typeString = "Actuator Mode" when 0xff #no calibration data present typeString = "debugger" [ typeString numTotal ] calibrationType = (buf, startIndex) -> type = buf.readUInt8(startIndex) numTotal = startIndex + 1 FLOAT_LENGTH = 4 COUNT_ENTRIES_LENGTH = 4 switch type when 0x00 numTotal += 0 when 0x01 numTotal += 2 * FLOAT_LENGTH when 0x02 numTotal += 3 * FLOAT_LENGTH when 0x03 numTotal += 3 * FLOAT_LENGTH when 0x04 countEntries = buf.readUInt32LE(numTotal) numTotal += COUNT_ENTRIES_LENGTH + countEntries * 2 * FLOAT_LENGTH numTotal return readChannelDescriptor ])
17721
angular.module('daemon.read_descriptor', []) .service('read_descriptor', [ -> buffer = requireNode("buffer") readString = (buf, startIndex) -> length = buf.readUInt8(startIndex) description = buf.slice(startIndex + 1, length + startIndex + 1) [ description.toString("utf8") length + startIndex + 1 ] readChannelDescriptor = (buf, startIndex) -> index = startIndex + 1 numChannels = buf.readUInt8(startIndex) descriptors = [numChannels] i = 0 while i < numChannels channelDescriptor = readString(buf, index + 1) type = buf.readUInt8(channelDescriptor[1]) typeData = typeChannel(buf, type, channelDescriptor[1] + 1) descriptors.push [ channelDescriptor[0] typeData[0] ] index = typeData[1] i++ descriptors typeChannel = (buf, typeBinary, startIndex) -> FLAGS_LENGTH = 1 SAMPLE_RATE_LENGTH = 2 BIT_PER_SAMPLE_LENGTH = 1 INTERNAL_TIMER_TICK_FREQ_LENGTH = 4 INTERNAL_CYCLE_TIME_TICK_LENGTH = 4 MODE = 1 SPEED = 4 numTotal = startIndex typeString = "" switch typeBinary when 0x00 numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Digital In/Out" when 0x01 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Input" when 0x02 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Output" when 0x03 num = numTotal + BIT_PER_SAMPLE_LENGTH + INTERNAL_TIMER_TICK_FREQ_LENGTH + INTERNAL_CYCLE_TIME_TICK_LENGTH numTotal = calibrationType(buf, num) typeString = "Hobby Servo" when 0x40 # TODO(<NAME>): Implement when these are implemented typeString = "Generic I2C" when 0x41 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic SPI" when 0x42 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic UART" when 0x80 numTotal += MODE + SPEED typeString = "Grizzly Bear v3" when 0x81 # TODO(<NAME> Zhao): change when battery buzzer additional info block changed num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Battery Buzzer" when 0x82 # TODO(<NAME>): change when team flag additional info block changed numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Team Flag" when 0xfe # numTotal += MODE; # TODO(<NAME>): Uncomment previous line if firmware is fixed typeString = "Actuator Mode" when 0xff #no calibration data present typeString = "debugger" [ typeString numTotal ] calibrationType = (buf, startIndex) -> type = buf.readUInt8(startIndex) numTotal = startIndex + 1 FLOAT_LENGTH = 4 COUNT_ENTRIES_LENGTH = 4 switch type when 0x00 numTotal += 0 when 0x01 numTotal += 2 * FLOAT_LENGTH when 0x02 numTotal += 3 * FLOAT_LENGTH when 0x03 numTotal += 3 * FLOAT_LENGTH when 0x04 countEntries = buf.readUInt32LE(numTotal) numTotal += COUNT_ENTRIES_LENGTH + countEntries * 2 * FLOAT_LENGTH numTotal return readChannelDescriptor ])
true
angular.module('daemon.read_descriptor', []) .service('read_descriptor', [ -> buffer = requireNode("buffer") readString = (buf, startIndex) -> length = buf.readUInt8(startIndex) description = buf.slice(startIndex + 1, length + startIndex + 1) [ description.toString("utf8") length + startIndex + 1 ] readChannelDescriptor = (buf, startIndex) -> index = startIndex + 1 numChannels = buf.readUInt8(startIndex) descriptors = [numChannels] i = 0 while i < numChannels channelDescriptor = readString(buf, index + 1) type = buf.readUInt8(channelDescriptor[1]) typeData = typeChannel(buf, type, channelDescriptor[1] + 1) descriptors.push [ channelDescriptor[0] typeData[0] ] index = typeData[1] i++ descriptors typeChannel = (buf, typeBinary, startIndex) -> FLAGS_LENGTH = 1 SAMPLE_RATE_LENGTH = 2 BIT_PER_SAMPLE_LENGTH = 1 INTERNAL_TIMER_TICK_FREQ_LENGTH = 4 INTERNAL_CYCLE_TIME_TICK_LENGTH = 4 MODE = 1 SPEED = 4 numTotal = startIndex typeString = "" switch typeBinary when 0x00 numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Digital In/Out" when 0x01 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Input" when 0x02 num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Analog Output" when 0x03 num = numTotal + BIT_PER_SAMPLE_LENGTH + INTERNAL_TIMER_TICK_FREQ_LENGTH + INTERNAL_CYCLE_TIME_TICK_LENGTH numTotal = calibrationType(buf, num) typeString = "Hobby Servo" when 0x40 # TODO(PI:NAME:<NAME>END_PI): Implement when these are implemented typeString = "Generic I2C" when 0x41 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic SPI" when 0x42 # TODO(Matt Zhao): Implement when these are implemented typeString = "Generic UART" when 0x80 numTotal += MODE + SPEED typeString = "Grizzly Bear v3" when 0x81 # TODO(PI:NAME:<NAME>END_PI Zhao): change when battery buzzer additional info block changed num = numTotal + SAMPLE_RATE_LENGTH + BIT_PER_SAMPLE_LENGTH numTotal = calibrationType(buf, num) typeString = "Battery Buzzer" when 0x82 # TODO(PI:NAME:<NAME>END_PI): change when team flag additional info block changed numTotal += FLAGS_LENGTH + SAMPLE_RATE_LENGTH typeString = "Team Flag" when 0xfe # numTotal += MODE; # TODO(PI:NAME:<NAME>END_PI): Uncomment previous line if firmware is fixed typeString = "Actuator Mode" when 0xff #no calibration data present typeString = "debugger" [ typeString numTotal ] calibrationType = (buf, startIndex) -> type = buf.readUInt8(startIndex) numTotal = startIndex + 1 FLOAT_LENGTH = 4 COUNT_ENTRIES_LENGTH = 4 switch type when 0x00 numTotal += 0 when 0x01 numTotal += 2 * FLOAT_LENGTH when 0x02 numTotal += 3 * FLOAT_LENGTH when 0x03 numTotal += 3 * FLOAT_LENGTH when 0x04 countEntries = buf.readUInt32LE(numTotal) numTotal += COUNT_ENTRIES_LENGTH + countEntries * 2 * FLOAT_LENGTH numTotal return readChannelDescriptor ])
[ { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright (C) 2014 Jesús Espino ", "end": 38, "score": 0.9998898506164551, "start": 25, "tag": "NAME", "value": "Andrey Antukh" }, { "context": "###\n# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>\n# Copyright...
public/taiga-front/app/coffee/modules/resources/userstories.coffee
mabotech/maboss
0
### # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be> # Copyright (C) 2014 Jesús Espino Garcia <jespinog@gmail.com> # Copyright (C) 2014 David Barragán Merino <bameda@dbarragan.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/userstories.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage) -> service = {} hashSuffix = "userstories-queryparams" service.get = (projectId, usId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("userstories", usId, params) service.listUnassigned = (projectId, filters) -> params = {"project": projectId, "milestone": "null"} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.listAll = (projectId, filters) -> params = {"project": projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.bulkCreate = (projectId, status, bulk) -> data = { project_id: projectId status_id: status bulk_stories: bulk } url = $urls.resolve("bulk-create-us") return $http.post(url, data) service.bulkUpdateBacklogOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-backlog-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateSprintOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-sprint-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateKanbanOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-kanban-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeShowTags = (projectId, showTags) -> hash = generateHash([projectId, 'showTags']) $storage.set(hash, showTags) service.getShowTags = (projectId) -> hash = generateHash([projectId, 'showTags']) return $storage.get(hash) or null return (instance) -> instance.userstories = service module = angular.module("taigaResources") module.factory("$tgUserstoriesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", resourceProvider])
9350
### # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # Copyright (C) 2014 <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/userstories.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage) -> service = {} hashSuffix = "userstories-queryparams" service.get = (projectId, usId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("userstories", usId, params) service.listUnassigned = (projectId, filters) -> params = {"project": projectId, "milestone": "null"} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.listAll = (projectId, filters) -> params = {"project": projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.bulkCreate = (projectId, status, bulk) -> data = { project_id: projectId status_id: status bulk_stories: bulk } url = $urls.resolve("bulk-create-us") return $http.post(url, data) service.bulkUpdateBacklogOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-backlog-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateSprintOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-sprint-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateKanbanOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-kanban-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeShowTags = (projectId, showTags) -> hash = generateHash([projectId, 'showTags']) $storage.set(hash, showTags) service.getShowTags = (projectId) -> hash = generateHash([projectId, 'showTags']) return $storage.get(hash) or null return (instance) -> instance.userstories = service module = angular.module("taigaResources") module.factory("$tgUserstoriesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", resourceProvider])
true
### # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Copyright (C) 2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # File: modules/resources/userstories.coffee ### taiga = @.taiga generateHash = taiga.generateHash resourceProvider = ($repo, $http, $urls, $storage) -> service = {} hashSuffix = "userstories-queryparams" service.get = (projectId, usId) -> params = service.getQueryParams(projectId) params.project = projectId return $repo.queryOne("userstories", usId, params) service.listUnassigned = (projectId, filters) -> params = {"project": projectId, "milestone": "null"} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.listAll = (projectId, filters) -> params = {"project": projectId} params = _.extend({}, params, filters or {}) service.storeQueryParams(projectId, params) return $repo.queryMany("userstories", params) service.bulkCreate = (projectId, status, bulk) -> data = { project_id: projectId status_id: status bulk_stories: bulk } url = $urls.resolve("bulk-create-us") return $http.post(url, data) service.bulkUpdateBacklogOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-backlog-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateSprintOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-sprint-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.bulkUpdateKanbanOrder = (projectId, data) -> url = $urls.resolve("bulk-update-us-kanban-order") params = {project_id: projectId, bulk_stories: data} return $http.post(url, params) service.listValues = (projectId, type) -> params = {"project": projectId} service.storeQueryParams(projectId, params) return $repo.queryMany(type, params) service.storeQueryParams = (projectId, params) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) $storage.set(hash, params) service.getQueryParams = (projectId) -> ns = "#{projectId}:#{hashSuffix}" hash = generateHash([projectId, ns]) return $storage.get(hash) or {} service.storeShowTags = (projectId, showTags) -> hash = generateHash([projectId, 'showTags']) $storage.set(hash, showTags) service.getShowTags = (projectId) -> hash = generateHash([projectId, 'showTags']) return $storage.get(hash) or null return (instance) -> instance.userstories = service module = angular.module("taigaResources") module.factory("$tgUserstoriesResourcesProvider", ["$tgRepo", "$tgHttp", "$tgUrls", "$tgStorage", resourceProvider])
[ { "context": ": the Shell.\"\n\n user = @userForId('1', {name: \"Shell\"})\n\n process.stdin.resume()\n process.stdin.", "end": 322, "score": 0.9930880665779114, "start": 317, "tag": "USERNAME", "value": "Shell" }, { "context": "Timeout =>\n user = @userForId('1', {na...
src/hubot/shell.coffee
harperreed/hubot
1
Robot = require 'robot' class Shell extends Robot send: (user, strings...) -> strings.forEach (str) -> console.log str reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length == 0 @receive new Robot.Message user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "Zach Holman"}) , 3000 exports.Shell = Shell
94626
Robot = require 'robot' class Shell extends Robot send: (user, strings...) -> strings.forEach (str) -> console.log str reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length == 0 @receive new Robot.Message user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "<NAME>"}) , 3000 exports.Shell = Shell
true
Robot = require 'robot' class Shell extends Robot send: (user, strings...) -> strings.forEach (str) -> console.log str reply: (user, strings...) -> strings.forEach (str) => @send user, "#{user.name}: #{str}" run: -> console.log "Hubot: the Shell." user = @userForId('1', {name: "Shell"}) process.stdin.resume() process.stdin.on 'data', (txt) => txt.toString().split("\n").forEach (line) => return if line.length == 0 @receive new Robot.Message user, line setTimeout => user = @userForId('1', {name: "Shell"}) atmos = @userForId('2', {name: "atmos"}) holman = @userForId('3', {name: "PI:NAME:<NAME>END_PI"}) , 3000 exports.Shell = Shell
[ { "context": "cd'\n\n customerMock: ->\n firstName = uniqueId 'Heinz'\n lastName = uniqueId 'Mayer'\n\n customerNum", "end": 2896, "score": 0.999392569065094, "start": 2891, "tag": "NAME", "value": "Heinz" }, { "context": "tName = uniqueId 'Heinz'\n lastName = uniqueId '...
src/spec/helper.coffee
celeste-horgan/sphere-order-export
3
_ = require 'underscore' uniqueId = (prefix) -> _.uniqueId "#{prefix}#{new Date().getTime()}_" module.exports = orderPaymentInfo: (container, orderId) -> container: container key: orderId value: paymentMethod: 'Cash' paymentID: '7' shippingMethodMock: (zone, taxCategory) -> name: uniqueId 'S' zoneRates: [ { zone: typeId: 'zone' id: zone.id shippingRates: [ { price: {currencyCode: 'EUR', centAmount: 99}} ] } ] isDefault: false taxCategory: typeId: 'tax-category' id: taxCategory.id zoneMock: -> name: uniqueId 'Z' taxCategoryMock: -> name: uniqueId 'TC' rates: [ { name: '5%' amount: 0.05 includedInPrice: false country: 'DE' id: 'jvzkDxzl' } ] productTypeMock: -> name: uniqueId 'PT' description: 'bla' typeMock: -> key: uniqueId 'order-custom-fields' name: en: 'Custom order fields' resourceTypeIds: [ 'order' ], fieldDefinitions: [{ name: 'field1', label: en: 'Custom field' required: false, type: name: 'Boolean' inputHint: 'SingleLine' },{ name: 'field2', label: en: 'Second custom field' required: false, type: name: 'String' inputHint: 'SingleLine' }] productMock: (productType) -> productType: typeId: 'product-type' id: productType.id name: en: uniqueId 'P' slug: en: uniqueId 'p' masterVariant: sku: uniqueId 'sku' orderMock: (shippingMethod, product, taxCategory, customer, type) -> id: uniqueId 'o' orderState: 'Open' paymentState: 'Pending' shipmentState: 'Pending' customerId: customer.id customerEmail: customer.email lineItems: [ { productId: product.id name: de: 'foo' variant: id: 1 taxRate: name: 'myTax' amount: 0.10 includedInPrice: false country: 'DE' quantity: 1 price: value: centAmount: 999 currencyCode: 'EUR' } ] totalPrice: currencyCode: 'EUR' centAmount: 999 returnInfo: [] shippingInfo: shippingMethodName: 'UPS' price: currencyCode: 'EUR' centAmount: 99 shippingRate: price: currencyCode: 'EUR' centAmount: 99 taxRate: _.first taxCategory.rates taxCategory: typeId: 'tax-category' id: taxCategory.id shippingMethod: typeId: 'shipping-method' id: shippingMethod.id custom: type: typeId: 'type' id: type.id fields: field1: true field2: 'abcd' customerMock: -> firstName = uniqueId 'Heinz' lastName = uniqueId 'Mayer' customerNumber: uniqueId 'c' email: "#{firstName}.#{lastName}@commercetools.de" firstName: firstName lastName: lastName password: uniqueId 'password' externalId: uniqueId 'external'
158755
_ = require 'underscore' uniqueId = (prefix) -> _.uniqueId "#{prefix}#{new Date().getTime()}_" module.exports = orderPaymentInfo: (container, orderId) -> container: container key: orderId value: paymentMethod: 'Cash' paymentID: '7' shippingMethodMock: (zone, taxCategory) -> name: uniqueId 'S' zoneRates: [ { zone: typeId: 'zone' id: zone.id shippingRates: [ { price: {currencyCode: 'EUR', centAmount: 99}} ] } ] isDefault: false taxCategory: typeId: 'tax-category' id: taxCategory.id zoneMock: -> name: uniqueId 'Z' taxCategoryMock: -> name: uniqueId 'TC' rates: [ { name: '5%' amount: 0.05 includedInPrice: false country: 'DE' id: 'jvzkDxzl' } ] productTypeMock: -> name: uniqueId 'PT' description: 'bla' typeMock: -> key: uniqueId 'order-custom-fields' name: en: 'Custom order fields' resourceTypeIds: [ 'order' ], fieldDefinitions: [{ name: 'field1', label: en: 'Custom field' required: false, type: name: 'Boolean' inputHint: 'SingleLine' },{ name: 'field2', label: en: 'Second custom field' required: false, type: name: 'String' inputHint: 'SingleLine' }] productMock: (productType) -> productType: typeId: 'product-type' id: productType.id name: en: uniqueId 'P' slug: en: uniqueId 'p' masterVariant: sku: uniqueId 'sku' orderMock: (shippingMethod, product, taxCategory, customer, type) -> id: uniqueId 'o' orderState: 'Open' paymentState: 'Pending' shipmentState: 'Pending' customerId: customer.id customerEmail: customer.email lineItems: [ { productId: product.id name: de: 'foo' variant: id: 1 taxRate: name: 'myTax' amount: 0.10 includedInPrice: false country: 'DE' quantity: 1 price: value: centAmount: 999 currencyCode: 'EUR' } ] totalPrice: currencyCode: 'EUR' centAmount: 999 returnInfo: [] shippingInfo: shippingMethodName: 'UPS' price: currencyCode: 'EUR' centAmount: 99 shippingRate: price: currencyCode: 'EUR' centAmount: 99 taxRate: _.first taxCategory.rates taxCategory: typeId: 'tax-category' id: taxCategory.id shippingMethod: typeId: 'shipping-method' id: shippingMethod.id custom: type: typeId: 'type' id: type.id fields: field1: true field2: 'abcd' customerMock: -> firstName = uniqueId '<NAME>' lastName = uniqueId '<NAME>' customerNumber: uniqueId 'c' email: <EMAIL>" firstName: firstName lastName: lastName password: uniqueId '<PASSWORD>' externalId: uniqueId 'external'
true
_ = require 'underscore' uniqueId = (prefix) -> _.uniqueId "#{prefix}#{new Date().getTime()}_" module.exports = orderPaymentInfo: (container, orderId) -> container: container key: orderId value: paymentMethod: 'Cash' paymentID: '7' shippingMethodMock: (zone, taxCategory) -> name: uniqueId 'S' zoneRates: [ { zone: typeId: 'zone' id: zone.id shippingRates: [ { price: {currencyCode: 'EUR', centAmount: 99}} ] } ] isDefault: false taxCategory: typeId: 'tax-category' id: taxCategory.id zoneMock: -> name: uniqueId 'Z' taxCategoryMock: -> name: uniqueId 'TC' rates: [ { name: '5%' amount: 0.05 includedInPrice: false country: 'DE' id: 'jvzkDxzl' } ] productTypeMock: -> name: uniqueId 'PT' description: 'bla' typeMock: -> key: uniqueId 'order-custom-fields' name: en: 'Custom order fields' resourceTypeIds: [ 'order' ], fieldDefinitions: [{ name: 'field1', label: en: 'Custom field' required: false, type: name: 'Boolean' inputHint: 'SingleLine' },{ name: 'field2', label: en: 'Second custom field' required: false, type: name: 'String' inputHint: 'SingleLine' }] productMock: (productType) -> productType: typeId: 'product-type' id: productType.id name: en: uniqueId 'P' slug: en: uniqueId 'p' masterVariant: sku: uniqueId 'sku' orderMock: (shippingMethod, product, taxCategory, customer, type) -> id: uniqueId 'o' orderState: 'Open' paymentState: 'Pending' shipmentState: 'Pending' customerId: customer.id customerEmail: customer.email lineItems: [ { productId: product.id name: de: 'foo' variant: id: 1 taxRate: name: 'myTax' amount: 0.10 includedInPrice: false country: 'DE' quantity: 1 price: value: centAmount: 999 currencyCode: 'EUR' } ] totalPrice: currencyCode: 'EUR' centAmount: 999 returnInfo: [] shippingInfo: shippingMethodName: 'UPS' price: currencyCode: 'EUR' centAmount: 99 shippingRate: price: currencyCode: 'EUR' centAmount: 99 taxRate: _.first taxCategory.rates taxCategory: typeId: 'tax-category' id: taxCategory.id shippingMethod: typeId: 'shipping-method' id: shippingMethod.id custom: type: typeId: 'type' id: type.id fields: field1: true field2: 'abcd' customerMock: -> firstName = uniqueId 'PI:NAME:<NAME>END_PI' lastName = uniqueId 'PI:NAME:<NAME>END_PI' customerNumber: uniqueId 'c' email: PI:EMAIL:<EMAIL>END_PI" firstName: firstName lastName: lastName password: uniqueId 'PI:PASSWORD:<PASSWORD>END_PI' externalId: uniqueId 'external'
[ { "context": "が入室したぞ!\n inlog:(room,player)->\n name=\"#{player.name}\"\n pr=\"\"\n unless room.blind in [\"co", "end": 1613, "score": 0.9083701968193054, "start": 1602, "tag": "USERNAME", "value": "player.name" }, { "context": "alid:player.realid\n ...
server/rpc/game/game.coffee
Yukimir/jinrou
0
#,type シェアするやつ Shared= game:require '../../../client/code/shared/game.coffee' prize:require '../../../client/code/shared/prize.coffee' cron=require 'cron' # 浅いコピー copyObject=(obj)-> result=Object.create Object.getPrototypeOf obj for key in Object.keys(obj) result[key]=obj[key] result # ゲームオブジェクトを読み込む loadGame = (roomid, ss, callback)-> if games[roomid]? callback null, games[roomid] else M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else games[roomid] = Game.unserialize doc,ss callback null, games[roomid] #内部用 module.exports= newGame: (room,ss)-> game=new Game ss,room games[room.id]=game M.games.insert game.serialize() # 游戏オブジェクトを読み込んで使用可能にする ### loadDB:(roomid,ss,cb)-> if games[roomid] # 既に読み込んでいる cb games[roomid] return M.games.find({finished:false}).each (err,doc)-> return unless doc? if err? console.log err throw err games[doc.id]=Game.unserialize doc,ss ### # 参加中のプレイヤー人数(Endless黑暗火锅用) endlessPlayersNumber:(roomid)-> game=games[roomid] if game? # 拒绝复活はカウントしない return game.players.filter((x)->!x.dead || !x.norevive).length else return Number.NaN # プレイヤーが入室したぞ! inlog:(room,player)-> name="#{player.name}" pr="" unless room.blind in ["complete","yes"] # 匿名模式のときは称号OFF player.nowprize?.forEach? (x)-> if x.type=="prize" prname=Server.prize.prizeName x.value if prname? pr+=prname else # 接続 pr+=x.value if room.blind in ["complete","yes"] && room.theme #如果房间使用了主题,匿名房间也可以有称号 theme = Server.game.themes[room.theme] if theme != null pr = theme.skins[player.userid].prize if pr name="#{Server.prize.prizeQuote pr}#{name}" if room.mode=="waiting" # 开始前(ふつう) log= comment:"#{name} 加入了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log # プレイヤーを追加 newpl=Player.factory "Waiting" newpl.setProfile { id:player.userid realid:player.realid name:player.name } newpl.setTarget null games[room.id].players.push newpl games[room.id].participants.push newpl else if room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅" # Endless黑暗火锅に途中参加 if games[room.id] game=games[room.id] log= comment:"#{name} 加入了游戏。" mode:"inlog" to:player.userid splashlog room.id,game,log # プレイヤーを追加(まだ参加しない系のひと) newpl=Player.factory "Watching" newpl.setProfile { id:player.userid realid:player.realid name:player.name } newpl.setTarget null # 头像追加 game.iconcollection[newpl.id]=player.icon # playersには追加しない(翌朝追加) games[room.id].participants.push newpl outlog:(room,player)-> log= comment:"#{player.name} 离开了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid kicklog:(room,player)-> log= comment:"#{player.name} 被踢出了游戏。" userid:-1 name:null mode:"system" console.log "game"+room.id+"存在" unless games[room.id]? # 检索数据库game是否不存在? M.games.findOne {id:room.id}, (err,doc)=> if err? console.log err throw err unless doc? M.rooms.remove {id:room.id} console.log "由于game不存在,room"+room.id+"被移除" return games[roomid]=game=Game.unserialize doc,ss ne() return if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid helperlog:(ss,room,player,topl)-> loadGame room.id, ss, (err,game)-> log=null if topl? log= comment:"#{player.name} 成为了 #{topl.name} 的帮手。" userid:-1 name:null mode:"system" else log= comment:"#{player.name} 放弃做帮手了。" userid:-1 name:null mode:"system" if game? splashlog room.id,game, log deletedlog:(ss,room)-> loadGame room.id, ss, (err,game)-> if game? log= comment:"这个房间已经废弃。" userid:-1 name:null mode:"system" splashlog room.id,game, log # 状況に応じたチャンネルを割り当てる playerchannel:(ss,roomid,session)-> loadGame roomid, ss, (err,game)-> unless game? return player=game.getPlayerReal session.userId unless player? session.channel.subscribe "room#{roomid}_audience" # session.channel.subscribe "room#{roomid}_notwerewolf" # session.channel.subscribe "room#{roomid}_notcouple" return if player.isJobType "GameMaster" session.channel.subscribe "room#{roomid}_gamemaster" return ### if player.dead session.channel.subscribe "room#{roomid}_heaven" if game.rule.heavenview!="view" || !player.dead if player.isWerewolf() session.channel.subscribe "room#{roomid}_werewolf" else session.channel.subscribe "room#{roomid}_notwerewolf" if game.rule.heavenview!="view" || !player.dead if player.isJobType "Couple" session.channel.subscribe "room#{roomid}_couple" else session.channel.subscribe "room#{roomid}_notcouple" if player.isJobType "Fox" session.channel.subscribe "room#{roomid}_fox" ### Server= game: game:module.exports rooms:require './rooms.coffee' themes:require './themes.coffee' prize:require '../../prize.coffee' oauth:require '../../oauth.coffee' class Game constructor:(@ss,room)-> # @ss: ss if room? @id=room.id # GMがいる場合 @gm= if room.gm then room.owner.userid else null @players=[] # 母猪たち @participants=[] # 参加者全て(@playersと同じ内容含む) @rule=null @finished=false #终了したかどうか @day=0 #何日目か(0=準備中) @night=false # false:昼 true:夜 @winner=null # 勝ったチーム名 @quantum_patterns=[] # 全部の場合を列挙({(id):{jobtype:"Jobname",dead:Boolean},...}) # DBには現れない @timerid=null @voting=false # 投票猶予時間 @timer_start=null # 残り時間のカウント開始時間(秒) @timer_remain=null # 残り時間全体(秒) @timer_mode=null # タイマーの名前 @revote_num=0 # 再投票を行った回数 @last_time=Date.now() # 最後に動きがあった時間 @werewolf_target=[] # LowBの襲い先 @werewolf_target_remain=0 #襲撃先をあと何人设定できるか @werewolf_flag=[] # LowB襲撃に関するフラグ @slientexpires=0 # 静かにしてろ!(この时间まで) @heavenview=false # 灵界表示がどうなっているか @gamelogs=[] @iconcollection={} #(id):(url) # 决定配置(DBに入らないかも・・・) @joblist=null # 游戏スタートに必要な情報 @startoptions=null @startplayers=null @startsupporters=null # 希望役职制のときに开始前に职业选择するフェーズ @rolerequestingphase=false @rolerequesttable={} # 一览{(id):(jobtype)} # 投票箱を用意しておく @votingbox=new VotingBox this # New Year Messageのためだけの変数 @currentyear = null ### さまざまな出来事 id: 動作した人 gamelogs=[ {id:(id),type:(type/null),target:(id,null),event:(String),flag:(String),day:(Number)}, {...}, ### # JSON用object化(DB保存用) serialize:-> { id:@id #logs:@logs rule:@rule players:@players.map (x)->x.serialize() # 差分 additionalParticipants: @participants?.filter((x)=>@players.indexOf(x)<0).map (x)->x.serialize() finished:@finished day:@day night:@night winner:@winner jobscount:@jobscount gamelogs:@gamelogs gm:@gm iconcollection:@iconcollection werewolf_flag:@werewolf_flag werewolf_target:@werewolf_target werewolf_target_remain:@werewolf_target_remain #quantum_patterns:@quantum_patterns } #DB用をもとにコンストラクト @unserialize:(obj,ss)-> game=new Game ss game.id=obj.id game.gm=obj.gm #game.logs=obj.logs game.rule=obj.rule game.players=obj.players.map (x)->Player.unserialize x # 追加する if obj.additionalParticipants game.participants=game.players.concat obj.additionalParticipants.map (x)->Player.unserialize x else game.participants=game.players.concat [] game.finished=obj.finished game.day=obj.day game.night=obj.night game.winner=obj.winner game.jobscount=obj.jobscount game.gamelogs=obj.gamelogs ? {} game.gm=obj.gm game.iconcollection=obj.iconcollection ? {} game.werewolf_flag=if Array.isArray obj.werewolf_flag # 配列ではなく文字列/nullだった時代のあれ obj.werewolf_flag else if obj.werewolf_flag? [obj.werewolf_flag] else [] game.werewolf_target=obj.werewolf_target ? [] game.werewolf_target_remain=obj.werewolf_target_remain ? 0 # 开始前なら準備中を用意してあげないと! if game.day==0 Server.game.rooms.oneRoomS game.id,(room)-> if room.error? return game.players=[] for plobj in room.players newpl=Player.factory "Waiting" newpl.setProfile { id:plobj.userid realid:plobj.realid name:plobj.name } newpl.setTarget null game.players.push newpl game.participants=game.players.concat [] game.quantum_patterns=obj.quantum_patterns ? [] unless game.finished if game.rule game.timer() if game.day>0 if !game.night # 昼の場合投票箱をつくる game.votingbox.setCandidates game.players.filter (x)->!x.dead game # 公開情報 publicinfo:(obj)-> #obj:选项 { rule:@rule finished:@finished players:@players.map (x)=> r=x.publicinfo() r.icon= @iconcollection[x.id] ? null if obj?.openjob r.jobname=x.getJobname() #r.option=x.optionString() r.option="" r.originalJobname=x.originalJobname r.winner=x.winner if obj?.gm || not (@rule?.blind=="complete" || (@rule?.blind=="yes" && !@finished)) # 公開してもよい r.realid=x.realid r day:@day night:@night jobscount:@jobscount } # IDからプレイヤー getPlayer:(id)-> @players.filter((x)->x.id==id)[0] getPlayerReal:(realid)-> #@players.filter((x)->x.realid==realid)[0] || if @gm && @gm==realid then new GameMaster realid,realid,"游戏管理员" @participants.filter((x)->x.realid==realid)[0] # DBにセーブ save:-> M.games.update {id:@id},{ $set: @serialize() $setOnInsert: { logs: [] } } # gamelogsに追加 addGamelog:(obj)-> @gamelogs ?= [] @gamelogs.push { id:obj.id ? null type:obj.type ? null target:obj.target ? null event:obj.event ? null flag:obj.flag ? null day:@day # 何気なく日付も追加 } setrule:(rule)->@rule=rule #成功:null #players: 参加者 supporters: 其他 setplayers:(res)-> options=@startoptions players=@startplayers supporters=@startsupporters jnumber=0 joblist=@joblist players=players.concat [] #模仿者 plsl=players.length #実際の参加人数(身代わり含む) if @rule.scapegoat=="on" plsl++ # 必要な职业の jallnum = plsl if @rule.chemical == "on" jallnum *= 2 @players=[] @iconcollection={} for job,num of joblist unless isNaN num jnumber+=parseInt num if parseInt(num)<0 res "玩家人数无效(#{job}:#{num})。多次重试可能解决这个错误。" return if jnumber!=jallnum # 数が合わない res "玩家人数无效 (#{jnumber}/#{jallnum}/#{players.length})。多次重试可能解决这个错误。" return # 名字と数を出したやつ @jobscount={} unless options.yaminabe_hidejobs # 公開モード for job,num of joblist continue unless num>0 testpl=new jobs[job] @jobscount[job]= name:testpl.jobname number:num # 盗賊の処理 thief_jobs=[] if joblist.Thief>0 # 小偷一人につき2回抜く for i in [0...(joblist.Thief*2)] # 1つ抜く keys=[] # 数に比例した职业一览を作る for job,num of joblist unless job in Shared.game.nonhumans for j in [0...num] keys.push job keys=shuffle keys until keys.length==0 || joblist[keys[0]]>0 # 抜けない keys.splice 0,1 # これは抜ける if keys.length==0 # もう無い res "小偷处理失败" return thief_jobs.push keys[0] joblist[keys[0]]-- # 代わりに母猪1つ入れる joblist.Human ?= 0 joblist.Human++ # 1人に対していくつ职业を選出するか jobperpl = 1 if @rule.chemical == "on" jobperpl = 2 # まず替身君を決めてあげる if @rule.scapegoat=="on" # LowB、妖狐にはならない nogoat=[] #身代わりがならない职业 if @rule.safety!="free" nogoat=nogoat.concat Shared.game.nonhumans #人外は除く if @rule.safety=="full" # 危ない nogoat=nogoat.concat ["QueenSpectator","Spy2","Poisoner","Cat","BloodyMary","Noble"] jobss=[] for job in Object.keys jobs continue if !joblist[job] || (job in nogoat) j=0 while j<joblist[job] jobss.push job j++ # 獲得した职业 gotjs = [] i=0 # 無限ループ防止 while ++i<100 && gotjs.length < jobperpl r=Math.floor Math.random()*jobss.length continue unless joblist[jobss[r]]>0 # 职业はjobss[r] gotjs.push jobss[r] joblist[jobss[r]]-- j++ if gotjs.length < jobperpl # 決まっていない res "角色分配失败" return # 替身君のプロフィール profile = { id:"替身君" realid:"替身君" name:"替身君" } if @rule.chemical == "on" # 炼成LowBなので合体职业にする pl1 = Player.factory gotjs[0] pl1.setProfile profile pl1.scapegoat = true pl2 = Player.factory gotjs[1] pl2.setProfile profile pl2.scapegoat = true # ケミカル合体 newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.scapegoat = true newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつーに newpl=Player.factory gotjs[0] #替身君 newpl.setProfile profile newpl.scapegoat = true @players.push newpl if @rule.rolerequest=="on" && @rule.chemical != "on" # 希望职业制ありの場合はまず希望を優先してあげる # (炼成LowBのときは面倒なのでパス) for job,num of joblist while num>0 # 候補を集める conpls=players.filter (x)=> @rolerequesttable[x.userid]==job if conpls.length==0 # もうない break # 候補がいたので決めてあげる r=Math.floor Math.random()*conpls.length pl=conpls[r] players=players.filter (x)->x!=pl newpl=Player.factory job newpl.setProfile { id:pl.userid realid:pl.realid name:pl.name } @players.push newpl if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true num-- # 残った分は戻す joblist[job]=num # 各プレイヤーの獲得职业の一覧 gotjs = [] for i in [0...(players.length)] gotjs.push [] # LowB系と妖狐系を全て数える(やや適当) all_wolves = 0 all_foxes = 0 for job,num of joblist unless isNaN num if job in Shared.game.categories.Werewolf all_wolves += num if job in Shared.game.categories.Fox all_foxes += num for job,num of joblist i=0 while i++<num r=Math.floor Math.random()*players.length if @rule.chemical == "on" && gotjs[r].length == 1 # 炼成LowBの場合調整が入る if all_wolves == 1 # LowBが1人のときはLowBを消さない if (gotjs[r][0] in Shared.game.categories.Werewolf && job in Shared.game.categories.Fox) || (gotjs[r][0] in Shared.game.categories.Fox && job in Shared.game.categories.Werewolf) # LowB×妖狐はまずい continue gotjs[r].push job if gotjs[r].length >= jobperpl # 必要な职业を獲得した pl=players[r] profile = { id:pl.userid realid:pl.realid name:pl.name } if @rule.chemical == "on" # 炼成LowB pl1 = Player.factory gotjs[r][0] pl1.setProfile profile pl2 = Player.factory gotjs[r][1] pl2.setProfile profile newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつうのLowB newpl=Player.factory gotjs[r][0] newpl.setProfile profile @players.push newpl players.splice r,1 gotjs.splice r,1 if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true if joblist.Thief>0 # 小偷がいる場合 thieves=@players.filter (x)->x.isJobType "Thief" for pl in thieves pl.setFlag JSON.stringify thief_jobs.splice 0,2 # サブ系 if options.decider # 决定者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Decider # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if options.authority # 权力者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Authority # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if @rule.wolfminion # 狼的仆从がいる場合、子分决定者を作る wolves=@players.filter((x)->x.isWerewolf()) if wolves.length>0 r=Math.floor Math.random()*wolves.length pl=wolves[r] sub=Player.factory "MinionSelector" # 子分决定者 pl.transProfile sub newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl pl.transform @,newpl,true if @rule.drunk # 酒鬼がいる場合 nonvillagers= @players.filter (x)->!x.isJobType "Human" if nonvillagers.length>0 r=Math.floor Math.random()*nonvillagers.length pl=nonvillagers[r] newpl=Player.factory null,pl,null,Drunk # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true # プレイヤーシャッフル @players=shuffle @players @participants=@players.concat [] # 模仿者 # ここでプレイヤー以外の処理をする for pl in supporters if pl.mode=="gm" # 游戏管理员だ gm=Player.factory "GameMaster" gm.setProfile { id:pl.userid realid:pl.realid name:pl.name } @participants.push gm else if result=pl.mode?.match /^helper_(.+)$/ # 帮手だ ppl=@players.filter((x)->x.id==result[1])[0] unless ppl? res "#{pl.name} 的帮助对象已不存在。" return helper=Player.factory "Helper" helper.setProfile { id:pl.realid realid:pl.realid name:pl.name } helper.setFlag ppl.id # ヘルプ先 @participants.push helper #@participants.push new GameMaster pl.userid,pl.realid,pl.name # 量子LowBの場合はここで可能性リストを作る if @rule.jobrule=="特殊规则.量子LowB" # パターンを初期化(最初は全パターン) quats=[] # のとみquantum_patterns pattern_no=0 # とばす # 职业を列挙した配列をつくる jobname_list=[] for job of jobs i=@rule.quantum_joblist[job] if i>0 jobname_list.push { type:job, number:i } # LowB用 i=1 while @rule.quantum_joblist["Werewolf#{i}"]>0 jobname_list.push { type:"Werewolf#{i}" number:@rule.quantum_joblist["Werewolf#{i}"] } i++ # プレイヤーIDを列挙した配列もつくる playerid_list=@players.map (pl)->pl.id # 0,1,...,(n-1)の中からkコ選んだ組み合わせを返す関数 combi=(n,k)-> `var i;` if k<=0 return [[]] if n<=k #n<kのときはないけど・・・ return [[0...n]] # 0からn-1まで resulty=[] for i in [0..(n-k)] # 0 <= i <= n-k for x in combi n-i-1,k-1 resulty.push [i].concat x.map (y)->y+i+1 resulty # 職をひとつ処理 makeonejob=(joblist,plids)-> cont=joblist[0] unless cont? return [[]] # 決めて抜く coms=combi plids.length,cont.number # その番号のを resulty2=[] for pat in coms #pat: 1つのパターン bas=[] pll=plids.concat [] i=0 for num in pat bas.push { id:pll[num-i] job:cont.type } pll.splice num-i,1 # 抜く i+=1 resulty2=resulty2.concat makeonejob(joblist.slice(1),pll).map (arr)-> bas.concat arr resulty2 jobsobj=makeonejob jobname_list,playerid_list # パターンを作る for arr in jobsobj obj={} for o in arr result=o.job.match /^Werewolf(\d+)$/ if result obj[o.id]={ jobtype:"Werewolf" rank:+result[1] # 狼の序列 dead:false } else obj[o.id]={ jobtype:o.job dead:false } quats.push obj # できた @quantum_patterns=quats if @rule.quantumwerewolf_table=="anonymous" # 概率表は数字で表示するので番号をつけてあげる for pl,i in shuffle @players.concat [] pl.setFlag JSON.stringify { number:i+1 } res null #======== 游戏進行の処理 #次のターンに進む nextturn:-> clearTimeout @timerid if @day<=0 # はじまる前 @day=1 @night=true # ゲーム開始時の年を記録 @currentyear = (new Date).getFullYear() else if @night==true @day++ @night=false else @night=true if @night==false && @currentyear+1 == (new Date).getFullYear() # 新年メッセージ @currentyear++ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"现在是 #{@currentyear} 年了。" splashlog @id,this,log else # 普通メッセージ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"第#{@day}天的#{if @night then '夜晚' else '白天'}到来了。" splashlog @id,this,log #死体処理 @bury(if @night then "night" else "day") if @rule.jobrule=="特殊规则.量子LowB" # 量子LowB # 全员の確率を出してあげるよーーーーー # 確率テーブルを probability_table={} numberref_table={} dead_flg=true while dead_flg dead_flg=false for x in @players if x.dead continue dead=0 for obj in @quantum_patterns if obj[x.id].dead==true dead++ if dead==@quantum_patterns.length # 死んだ!!!!!!!!!!!!!!!!! x.die this,"werewolf" dead_flg=true for x in @players count= Human:0 Diviner:0 Werewolf:0 dead:0 for obj in @quantum_patterns count[obj[x.id].jobtype]++ if obj[x.id].dead==true count.dead++ sum=count.Human+count.Diviner+count.Werewolf pflag=JSON.parse x.flag if sum==0 # 世界が崩壊した x.setFlag JSON.stringify { number:pflag?.number Human:0 Diviner:0 Werewolf:0 dead:0 } # ログ用 probability_table[x.id]={ name:x.name Human:0 Werewolf:0 } if @rule.quantumwerewolf_dead=="on" #死亡確率も probability_table[x.id].dead=0 if @rule.quantumwerewolf_diviner=="on" # 占卜师の確率も probability_table[x.id].Diviner=0 else x.setFlag JSON.stringify { number:pflag?.number Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum dead:count.dead/sum } # ログ用 if @rule.quantumwerewolf_diviner=="on" probability_table[x.id]={ name:x.name Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum } else probability_table[x.id]={ name:x.name Human:(count.Human+count.Diviner)/sum Werewolf:count.Werewolf/sum } if @rule.quantumwerewolf_dead!="no" || count.dead==sum # 死亡率も probability_table[x.id].dead=count.dead/sum if @rule.quantumwerewolf_table=="anonymous" # 番号を表示 numberref_table[pflag.number]=x probability_table[x.id].name="玩家 #{pflag.number}" if @rule.quantumwerewolf_table=="anonymous" # ソートしなおしてあげて痕跡を消す probability_table=((probability_table,numberref_table)-> result={} i=1 x=null while x=numberref_table[i] result["_$_player#{i}"]=probability_table[x.id] i++ result )(probability_table,numberref_table) # ログを出す log= mode:"probability_table" probability_table:probability_table splashlog @id,this,log # もう一回死体処理 @bury(if @night then "night" else "day") return if @judge() @voting=false if @night # job数据を作る # LowBの襲い先 @werewolf_target=[] unless @day==1 && @rule.scapegoat!="off" @werewolf_target_remain=1 else if @rule.scapegoat=="on" # 誰が襲ったかはランダム onewolf=@players.filter (x)->x.isWerewolf() if onewolf.length>0 r=Math.floor Math.random()*onewolf.length @werewolf_target.push { from:onewolf[r].id to:"替身君" # みがわり } @werewolf_target_remain=0 else # 誰も襲わない @werewolf_target_remain=0 werewolf_flag_result=[] for fl in @werewolf_flag if fl=="Diseased" # 病人フラグが立っている(今日は襲撃できない @werewolf_target_remain=0 log= mode:"wolfskill" comment:"LowB们染病了。今天无法出击。" splashlog @id,this,log else if fl=="WolfCub" # 狼之子フラグが立っている(2回襲撃できる) @werewolf_target_remain=2 log= mode:"wolfskill" comment:"为狼之子复仇吧,今天可以袭击两个人。" splashlog @id,this,log else werewolf_flag_result.push fl @werewolf_flag=werewolf_flag_result # Fireworks should be lit at just before sunset. x = @players.filter((pl)->pl.isJobType("Pyrotechnist") && pl.accessByJobType("Pyrotechnist")?.flag == "using") if x.length # 全员花火の虜にしてしまう for pl in @players newpl=Player.factory null,pl,null,WatchingFireworks pl.transProfile newpl newpl.cmplFlag=x[0].id                     pl.transform this,newpl,true                 # Pyrotechnist should break the blockade of Threatened.sunset                 for pyr in x                     pyr.accessByJobType("Pyrotechnist").sunset this alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunset this else player.deadsunset this else # 誤爆防止 @werewolf_target_remain=0 # 処理 if @rule.deathnote # 死亡笔记採用 alives=@players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] sub=Player.factory "Light" # 副を作る pl.transProfile sub sub.sunset this newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl @players.forEach (x,i)=> # 入れ替え if x.id==newpl.id @players[i]=newpl else x # Endless黑暗火锅用途中参加処理 if @rule.jobrule=="特殊规则.Endless黑暗火锅" exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] jobnames=Object.keys(jobs).filter (name)->!(name in exceptions) pcs=@participants.concat [] join_count=0 for player in pcs if player.isJobType "Watching" # 参加待機のひとだ if !@players.some((p)->p.id==player.id) # 本参加ではないのでOK # 职业をランダムに决定 newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob player.transProfile newpl player.transferData newpl # 观战者を除去 @participants=@participants.filter (x)->x!=player # プレイヤーとして追加 @players.push newpl @participants.push newpl # ログをだす log= mode:"system" comment:"#{newpl.name} 加入了游戏。" splashlog @id,@,log join_count++ # たまに転生 deads=shuffle @players.filter (x)->x.dead && !x.norevive # 転生確率 # 1人の転生確率をpとすると死者n人に対して転生人数の期待値はpn人。 # 1ターンに2人しぬとしてp(n+2)=2とおくとp=2/(n+2) 。 # 少し減らして人数を減少に持って行く p = 2/(deads.length+3) # 死者全员に対して転生判定 for pl in deads if Math.random()<p # でも参加者がいたら蘇生のかわりに if join_count>0 && Math.random()>p join_count-- continue newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob pl.transProfile newpl pl.transferData newpl # 蘇生 newpl.setDead false pl.transform @,newpl,true log= mode:"system" comment:"#{pl.name} 转生了。" splashlog @id,@,log @ss.publish.user newpl.id,"refresh",{id:@id} # 投票リセット処理 @votingbox.init() @votingbox.setCandidates @players.filter (x)->!x.dead alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunrise this else player.deadsunrise this for pl in @players if !pl.dead pl.votestart this @revote_num=0 # 重新投票の回数は0にリセット #死体処理 @bury "other" return if @judge() @splashjobinfo() if @night @checkjobs() else # 昼は15秒规则があるかも if @rule.silentrule>0 @silentexpires=Date.now()+@rule.silentrule*1000 # これまでは黙っていよう! @save() @timer() #全员に状況更新 pls:状況更新したい人を指定する場合の配列 splashjobinfo:(pls)-> unless pls? # プレイヤー以外にも @ss.publish.channel "room#{@id}_audience","getjob",makejobinfo this,null # GMにも if @gm? @ss.publish.channel "room#{@id}_gamemaster","getjob",makejobinfo this,@getPlayerReal @gm pls=@participants pls.forEach (x)=> @ss.publish.user x.realid,"getjob",makejobinfo this,x #全员寝たかチェック 寝たなら処理してtrue #timeoutがtrueならば时间切れなので时间でも待たない checkjobs:(timeout)-> if @day==0 # 开始前(希望役职制) if timeout || @players.every((x)=>@rolerequesttable[x.id]?) # 全员できたぞ @setplayers (result)=> unless result? @rolerequestingphase=false @nextturn() @ss.publish.channel "room#{@id}","refresh",{id:@id} true else false else if @players.every( (x)=>x.dead || x.sleeping(@)) if @voting || timeout || !@rule.night || @rule.waitingnight!="wait" #夜に时间がある場合は待ってあげる @midnight() @nextturn() true else false else false #夜の能力を処理する midnight:-> alives=[] deads=[] pids=[] mids=[] for player in @players pids.push player.id # gather all midnightSort mids = mids.concat player.gatherMidnightSort() if player.dead deads.push player.id else alives.push player.id # unique mids.sort (a, b)=> return a - b midsu=[mids[0]] for mid in mids if midsu[midsu.length-1] != mid then midsu.push mid # 処理順はmidnightSortでソート pids = shuffle pids for mid in midsu for pid in pids player=@getPlayer pid pmids = player.gatherMidnightSort() if player.id in alives if mid in pmids player.midnight this,mid else if mid in pmids player.deadnight this,mid # 狼の処理 for target in @werewolf_target t=@getPlayer target.to continue unless t? # 噛まれた t.addGamelog this,"bitten" if @rule.noticebitten=="notice" || t.isJobType "Devil" log= mode:"skill" to:t.id comment:"#{t.name} 被LowB袭击了。" splashlog @id,this,log if !t.dead # 死んだ t.die this,"werewolf",target.from # 逃亡者を探す runners=@players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==target.to runners.forEach (x)=> x.die this,"werewolf2",target.from # その家に逃げていたら逃亡者も死ぬ if !t.dead # 死んでない flg_flg=false # なにかのフラグ for fl in @werewolf_flag res = fl.match /^ToughWolf_(.+)$/ if res? # 硬汉LowBがすごい tw = @getPlayer res[1] t=@getPlayer target.to if t? t.setDead true,"werewolf2" t.dying this,"werewolf2",tw.id flg_flg=true if tw? unless tw.dead tw.die this,"werewolf2" tw.addGamelog this,"toughwolfKilled",t.type,t.id break unless flg_flg # 一途は発動しなかった for fl in @werewolf_flag res = fl.match /^GreedyWolf_(.+)$/ if res? # 欲張り狼がやられた! gw = @getPlayer res[1] if gw? gw.die this,"werewolf2" gw.addGamelog this,"greedyKilled",t.type,t.id # 以降は襲撃できない flg_flg=true break if flg_flg # 欲張りのあれで襲撃终了 break @werewolf_flag=@werewolf_flag.filter (fl)-> # こいつらは1夜限り return !(/^(?:GreedyWolf|ToughWolf)_/.test fl) # 死んだ人を処理する type: タイミング # type: "day": 夜が明けたタイミング "night": 处刑後 "other":其他(ターン変わり時の能力で死んだやつなど) bury:(type)-> deads=[] loop deads=@players.filter (x)->x.dead && x.found deadsl=deads.length alives=@players.filter (x)->!x.dead alives.forEach (x)=> x.beforebury this,type deads=@players.filter (x)->x.dead && x.found if deadsl>=deads.length # もう新しく死んだ人はいない break # 灵界で职业表示してよいかどうか更新 switch @rule.heavenview when "view" @heavenview=true when "norevive" @heavenview=!@players.some((x)->x.isReviver()) else @heavenview=false deads=shuffle deads # 順番バラバラ deads.forEach (x)=> situation=switch x.found #死因 when "werewolf","werewolf2","poison","hinamizawa","vampire","vampire2","witch","dog","trap","bomb","marycurse","psycho","crafty" "不成样子的尸体被发现了" when "curse" # 呪殺 if @rule.deadfox=="obvious" "被咒杀了" else "不成样子的尸体被发现了" when "punish" "被处刑了" when "spygone" "离开了村子" when "deathnote" "的尸体被发现了" when "foxsuicide" "追随着妖狐自尽了" when "friendsuicide" "追随着恋人自尽了" when "infirm" "衰老而死了" when "gmpunish" "被GM处死了" when "gone-day" "因为没有及时投票猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" when "gone-night" "因为没有及时使用夜间技能猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" else "死了" log= mode:"system" comment:"#{x.name} #{situation}" splashlog @id,this,log situation=switch x.found #死因 when "werewolf","werewolf2" "LowB的袭击" when "poison" "毒药" when "hinamizawa" "雏见泽症候群发作" when "vampire","vampire2" "吸血鬼的袭击" when "witch" "魔女的毒药" when "dog" "犬的袭击" when "trap" "陷阱" when "bomb" "炸弹" when "marycurse" "玛丽的诅咒" when "psycho" "变态杀人狂" when "curse" "咒杀" when "punish" "处刑" when "spygone" "失踪" when "deathnote" "心梗" when "foxsuicide" "追随妖狐自尽" when "friendsuicide" "追随恋人自尽" when "infirm" "老死" when "gmpunish" "被GM处死" when "gone-day" "昼间猝死" when "crafty" "假死" when "gone-night" "夜间猝死" else "未知原因" log= mode:"system" to:-1 comment:"#{x.name} 的死因是 #{situation}" splashlog @id,this,log ### if x.found=="punish" # 处刑→灵能 @players.forEach (y)=> if y.isJobType "Psychic" # 灵能 y.results.push x ### @addGamelog { # 死んだときと死因を記録 id:x.id type:x.type event:"found" flag:x.found } x.setDead x.dead,"" #発見されました @ss.publish.user x.realid,"refresh",{id:@id} if @rule.will=="die" && x.will # 死んだら遗言発表 log= mode:"will" name:x.name comment:x.will splashlog @id,this,log # 死者应该立刻从投票候选人中去除 @votingbox.candidates = @votingbox.candidates.filter (x)->!x.dead deads.length # 投票終わりチェック # 返り値意味ないんじゃないの? execute:-> return false unless @votingbox.isVoteAllFinished() [mode,player,tos,table]=@votingbox.check() if mode=="novote" # 誰も投票していない・・・ @revote_num=Infinity @judge() return false # 投票结果 log= mode:"voteresult" voteresult:table tos:tos splashlog @id,this,log if mode=="runoff" # 重新投票になった @dorevote "runoff" return false else if mode=="revote" # 重新投票になった @dorevote "revote" return false else if mode=="punish" # 投票 # 结果が出た 死んだ! # だれが投票したか調べる follower=table.filter((obj)-> obj.voteto==player.id).map (obj)->obj.id player.die this,"punish",follower if player.dead && @rule.GMpsychic=="on" # GM灵能 log= mode:"system" comment:"根据灵能的结论,被处刑的 #{player.name} 是 #{player.getPsychicResult()}。" splashlog @id,this,log @votingbox.remains-- if @votingbox.remains>0 # もっと殺したい!!!!!!!!! @bury "other" return false if @judge() log= mode:"system" comment:"今天还有#{@votingbox.remains}人将被处刑。请继续投票。" splashlog @id,this,log # 再び投票する処理(下と同じ… なんとかならないか?) @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() return false @nextturn() return true # 重新投票 dorevote:(mode)-> # mode: "runoff" - 决胜投票による重新投票 "revote" - 同数による重新投票 "gone" - 突然死による重新投票 if mode!="runoff" @revote_num++ if @revote_num>=4 # 4回重新投票 @judge() return remains=4-@revote_num if mode=="runoff" log= mode:"system" comment:"决胜投票。" else log= mode:"system" comment:"重新投票。" if isFinite remains log.comment += "如果在接下来的#{remains}轮投票中无法达成一致,本场游戏将以平局处理。" splashlog @id,this,log @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() # 勝敗决定 judge:-> aliveps=@players.filter (x)->!x.dead # 生きている人を集める # 数える alives=aliveps.length humans=aliveps.map((x)->x.humanCount()).reduce(((a,b)->a+b), 0) wolves=aliveps.map((x)->x.werewolfCount()).reduce(((a,b)->a+b), 0) vampires=aliveps.map((x)->x.vampireCount()).reduce(((a,b)->a+b), 0) team=null friends_count=null # 量子LowBのときは特殊ルーチン if @rule.jobrule=="特殊规则.量子LowB" assured_wolf= alive:0 dead:0 total_wolf=0 obj=@quantum_patterns[0] if obj? for key,value of obj if value.jobtype=="Werewolf" total_wolf++ for x in @players unless x.flag # まだだった・・・ break flag=JSON.parse x.flag if flag.Werewolf==1 # うわあああ絶対LowBだ!!!!!!!!!! if flag.dead==1 assured_wolf.dead++ else if flag.dead==0 assured_wolf.alive++ if alives<=assured_wolf.alive*2 # あーーーーーーー team="Werewolf" else if assured_wolf.dead==total_wolf # 全滅した team="Human" else # もうひとつもないんだ・・・ log= mode:"system" comment:"世界崩坏,概率无法定义。" splashlog @id,this,log team="Draw" else if alives==0 # 全滅 team="Draw" else if wolves==0 && vampires==0 # 母猪胜利 team="Human" else if humans<=wolves && vampires==0 # LowB胜利 team="Werewolf" else if humans<=vampires && wolves==0 # 吸血鬼胜利 team="Vampire" if team=="Werewolf" && wolves==1 # 一匹狼判定 lw=aliveps.filter((x)->x.isWerewolf())[0] if lw?.isJobType "LoneWolf" team="LoneWolf" if team? # 妖狐判定 if @players.some((x)->!x.dead && x.isFox()) team="Fox" # 恋人判定 if @players.some((x)->x.isFriend()) # 终了時に恋人生存 friends=@players.filter (x)->x.isFriend() && !x.dead gid=0 friends_count=0 friends_table={} for pl in friends unless friends_table[pl.id]? pt=pl.getPartner() unless friends_table[pt]? friends_count++ gid++ friends_table[pl.id]=gid friends_table[pt]=gid else # 合併 friends_table[pl.id]=friends_table[pt] else unless friends_table[pt]? friends_table[pt]=friends_table[pl.id] else if friends_table[pt]!=friends_table[pl.id] # 食い違っている c=Math.min friends_table[pt],friends_table[pl.id] d=Math.max friends_table[pt],friends_table[pl.id] for key,value of friends_table if value==d friends_table[key]=c # グループが合併した friends_count-- if friends_count==1 # 1組しかいない if @rule.friendsjudge=="alive" team="Friend" else if friends.length==alives team="Friend" else if friends_count>1 if alives==friends.length team="Friend" else # 恋人バトル team=null # カルト判定 if alives>0 && aliveps.every((x)->x.isCult() || x.isJobType("CultLeader") && x.getTeam()=="Cult" ) # 全員信者 team="Cult" # 悪魔くん判定 isDevilWinner = (pl)-> # 悪魔くんが勝利したか判定する return false unless pl? return false unless pl.isJobType "Devil" if pl.isComplex() return isDevilWinner(pl.sub) || (pl.getTeam() == "Devil" && isDevilWinner(pl.main)) else return pl.flag == "winner" if @players.some(isDevilWinner) team="Devil" if @revote_num>=4 && !team? # 重新投票多すぎ team="Draw" # 平局 if team? # 勝敗决定 @finished=true @last_time=Date.now() @winner=team if team!="Draw" @players.forEach (x)=> iswin=x.isWinner this,team if @rule.losemode # 败北村(負けたら勝ち) if iswin==true iswin=false else if iswin==false iswin=true # ただし突然死したら負け if @gamelogs.some((log)-> log.id==x.id && log.event=="found" && log.flag in ["gone-day","gone-night"] ) iswin=false x.setWinner iswin #胜利か # ユーザー情報 if x.winner M.users.update {userid:x.realid},{$push: {win:@id}} else M.users.update {userid:x.realid},{$push: {lose:@id}} log= mode:"nextturn" finished:true resultstring=null#结果 teamstring=null #阵营 [resultstring,teamstring]=switch team when "Human" if alives>0 && aliveps.every((x)->x.isJobType "Neet") ["村子变成了NEET的乐园。","母猪胜利"] else ["村子里的LowB已经被赶尽杀绝。","母猪胜利"] when "Werewolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","LowB胜利"] when "Fox" ["村子成了妖狐的玩物。","妖狐胜利"] when "Devil" ["村子成了恶魔的玩物。","恶魔胜利"] when "Friend" if friends_count>1 # みんなで胜利(珍しい) ["村子被恋人们支配了。","恋人胜利"] else friends=@players.filter (x)->x.isFriend() if friends.length==2 && friends.some((x)->x.isJobType "Noble") && friends.some((x)->x.isJobType "Slave") ["在主仆两人跨越世俗禁忌的爱情面前,所有阻碍都无法与之匹敌。","恋人胜利"] else ["在#{@players.filter((x)->x.isFriend() && !x.dead).length}人爱的力量面前,所有阻碍都无法与之匹敌。","恋人胜利"] when "Cult" ["村子被教会支配了。","邪教胜利"] when "Vampire" ["吸血鬼饮尽了最后一个村民的鲜血,向着下一个住满了猎物的村庄前进了…","吸血鬼胜利"] when "LoneWolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","一匹狼胜利"] when "Draw" ["平局。",""] # 替身君单独胜利 winpl = @players.filter (x)->x.winner if(winpl.length==1 && winpl[0].realid=="替身君") resultstring="村子成了替身君的玩物。" log.comment="#{if teamstring then "【#{teamstring}】" else ""}#{resultstring}" splashlog @id,this,log # 房间を终了状态にする M.rooms.update {id:@id},{$set:{mode:"end"}} @ss.publish.channel "room#{@id}","refresh",{id:@id} @save() @prize_check() clearTimeout @timerid # 向房间成员通报猝死统计 norevivers=@gamelogs.filter((x)->x.event=="found" && x.flag in ["gone-day","gone-night"]).map((x)->x.id) if norevivers.length message = id:@id userlist:[] time:parseInt(60/@players.length) for x in norevivers pl = @getPlayer x message.userlist.push {"userid":pl.realid,"name":pl.name} @ss.publish.channel "room#{@id}",'punishalert',message # DBからとってきて告知ツイート M.rooms.findOne {id:@id},(err,doc)-> return unless doc? tweet doc.id,"「#{doc.name}」的结果: #{log.comment} #月下LowB" return true else return false timer:-> return if @finished func=null time=null mode=null # なんのカウントか timeout= => # 残り时间を知らせるぞ! @timer_start=parseInt Date.now()/1000 @timer_remain=time @timer_mode=mode @ss.publish.channel "room#{@id}","time",{time:time, mode:mode} if time>30 @timerid=setTimeout timeout,30000 time-=30 else if time>0 @timerid=setTimeout timeout,time*1000 time=0 else # 时间切れ func() if @rolerequestingphase # 希望役职制 time=60 mode="希望选择" func= => # 強制开始 @checkjobs true else if @night && !@voting # 夜 time=@rule.night mode="夜" return unless time func= => # ね な い こ だ れ だ unless @checkjobs true if @rule.remain # 犹豫时间があるよ @voting=true @timer() else @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else return else if @night # 夜の犹豫 time=@rule.remain mode="犹豫" func= => # ね な い こ だ れ だ @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else if !@voting # 昼 time=@rule.day mode="昼" return unless time func= => unless @execute() if @rule.remain # 犹豫があるよ @voting=true log= mode:"system" comment:"白天的讨论时间到此结束。请投票决定要处死的人。" splashlog @id,this,log @timer() else # 突然死 revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return else # 犹豫时间も過ぎたよ! time=@rule.remain mode="犹豫" func= => unless @execute() revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return timeout() # プレイヤーごとに 見せてもよいログをリストにする makelogs:(logs,player)-> result = [] for x in logs ls = makelogsFor this, player, x result.push ls... return result prize_check:-> Server.prize.checkPrize @,(obj)=> # obj: {(userid):[prize]} # 賞を算出した pls=@players.filter (x)->x.realid!="替身君" # 各々に対して処理 query={userid:{$in:pls.map (x)->x.realid}} M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # いままでの賞の一览 # 差分をとる newprize=obj[doc.userid].filter (x)->!(x in oldprize) if newprize.length>0 M.users.update {userid:doc.userid},{$set:{prize:obj[doc.userid]}} pl=@getPlayerReal doc.userid pnames=newprize.map (plzid)-> Server.prize.prizeQuote Server.prize.prizeName plzid log= mode:"system" comment:"#{pl.name} 获得了称号 #{pnames.join ''}。" splashlog @id,this,log ### M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # 賞の一览 # 賞を算出しなおしてもらう Server.prize.checkPrize doc.userid,(prize)=> prize=prize.concat doc.ownprize if doc.ownprize? # 新規に獲得した賞を探す newprizes= prize.filter (x)->!(x in oldprize) if newprizes.length>0 M.users.update {userid:doc.userid},{$set:{prize:prize}} pl=@getPlayerReal doc.userid newprizes.forEach (x)=> log= mode:"system" comment:"#{pl.name}は#{Server.prize.prizeQuote Server.prize.prizeName x}を獲得しました。" splashlog @id,this,log @addGamelog { id: pl.id type:pl.type event:"getprize" flag:x target:null } ### ### logs:[{ mode:"day"(昼) / "system"(システムメッセージ) / "werewolf"(狼) / "heaven"(天国) / "prepare"(开始前/终了後) / "skill"(能力ログ) / "nextturn"(游戏進行) / "audience"(观战者のひとりごと) / "monologue"(夜のひとりごと) / "voteresult" (投票结果) / "couple"(共有者) / "fox"(妖狐) / "will"(遗言) comment: String userid:Userid name?:String to:Userid / null (あると、その人だけ) (nextturnの場合) day:Number night:Boolean finished?:Boolean (voteresultの場合) voteresult:[] tos:Object },...] rule:{ number: Number # プレイヤー数 scapegoat : "on"(身代わり君が死ぬ) "off"(参加者が死ぬ) "no"(誰も死なない) } ### # 投票箱 class VotingBox constructor:(@game)-> @init() init:-> # 投票箱を空にする @remains=1 # 残り处刑人数 @runoffmode=false # 重新投票中か @candidates=[] @start() start:-> @votes=[] #{player:Player, to:Player} setCandidates:(@candidates)-> # 候補者をセットする[Player] isVoteFinished:(player)->@votes.some (x)->x.player.id==player.id vote:(player,voteto)-> # power: 票数 pl=@game.getPlayer voteto unless pl? return "这个玩家不存在" if pl.dead return "这个人已经死了" me=@game.getPlayer player.id unless me? return "你没有加入游戏" if @isVoteFinished player return "你已经投过票了" if pl.id==player.id && @game.rule.votemyself!="ok" return "不能向自己投票" @votes.push { player:@game.getPlayer player.id to:pl power:1 priority:0 } log= mode:"voteto" to:player.id comment:"#{player.name} 向 #{pl.name} 投票了" splashlog @game.id,@game,log null # その人の投票オブジェクトを得る getHisVote:(player)-> @votes.filter((x)->x.player.id==player.id)[0] # 票のパワーを变更する votePower:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.power=value else v.power+=value # 優先度つける votePriority:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.priority=value else v.priority+=value # 处刑人数を増やす addPunishedNumber:(num)-> @remains+=num isVoteAllFinished:-> alives=@game.players.filter (x)->!x.dead alives.every (x)=> x.voted @game,@ compareGots:(a,b)-> # aとbをsort用に(gots) # aのほうが小さい: -1 < # bのほうが小さい: 1 > if a.votes>b.votes return 1 else if a.votes<b.votes return -1 else if a.priority>b.priority return 1 else if a.priority<b.priority return -1 else return 0 check:-> # return [mode,result,tos,table] # 投票が終わったのでアレする # 投票表を作る tos={} table=[] gots={} #for obj in @votes alives = @game.players.filter (x)->!x.dead for pl in alives obj=@getHisVote pl o=pl.publicinfo() if obj? gots[obj.to.id] ?= { votes:0 priority:-Infinity } go=gots[obj.to.id] go.votes+=obj.power if go.priority<obj.priority go.priority=obj.priority tos[obj.to.id]=go.votes o.voteto=obj.to.id # 投票先情報を付け加える table.push o for pl in alives vote = gots[pl.id] if vote? vote = pl.modifyMyVote @game, vote gots[pl.id] = vote tos[pl.id] = vote.votes # 獲得票数が少ない順に並べる cands=Object.keys(gots).sort (a,b)=> @compareGots gots[a],gots[b] # 獲得票数多い一览 back=null tops=[] for id in cands by -1 if !back? || @compareGots(gots[back],gots[id])==0 tops.push id back=id else break if tops.length==0 # 誰も投票していない return ["novote",null,tos,table] if tops.length>1 # 決まらない! 重新投票になった if @game.rule.runoff!="no" && !@runoffmode @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] else return ["revote",null,tos,table] if @game.rule.runoff=="yes" && !@runoffmode # 候補は1人だけど决胜投票をしないといけない if tops.length<=1 # 候補がたりない back=null flag=false tops=[] for id in cands by -1 ok=false if !back? ok=true else if @compareGots(gots[back],gots[id])==0 ok=true else if flag==false # 决胜投票なので1回だけOK! flag=true ok=true else break if ok tops.push id back=id if tops.length>1 @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] # 结果を教える return ["punish",@game.getPlayer(tops[0]),tos,table] class Player constructor:-> # realid:本当のid id:仮のidかもしれない name:名字 icon:头像URL @dead=false @found=null # 死体の発見状況 @winner=null # 勝敗 @scapegoat=false # 替身君かどうか @flag=null # 职业ごとの自由なフラグ @will=null # 遗言 # もと的职业 @originalType=@type @originalJobname=@getJobname() # 拒绝复活 @norevive=false @factory:(type,main=null,sub=null,cmpl=null)-> p=null if cmpl? # 複合 mainとsubを使用 #cmpl: 複合の親として使用するオブジェクト myComplex=Object.create main #Complexから sample=new cmpl # 手動でComplexを継承したい Object.keys(sample).forEach (x)-> delete sample[x] # own propertyは全部消す for name of sample # sampleのown Propertyは一つもない myComplex[name]=sample[name] # 混合职业 p=Object.create myComplex p.main=main p.sub=sub p.cmplFlag=null else if !jobs[type]? p=new Player else p=new jobs[type] p serialize:-> r= type:@type id:@id realid:@realid name:@name dead:@dead scapegoat:@scapegoat will:@will flag:@flag winner:@winner originalType:@originalType originalJobname:@originalJobname norevive:@norevive if @isComplex() r.type="Complex" r.Complex_main=@main.serialize() r.Complex_sub=@sub?.serialize() r.Complex_type=@cmplType r.Complex_flag=@cmplFlag r @unserialize:(obj)-> unless obj? return null p=if obj.type=="Complex" # 複合 cmplobj=complexes[obj.Complex_type ? "Complex"] Player.factory null, Player.unserialize(obj.Complex_main), Player.unserialize(obj.Complex_sub),cmplobj else # 普通 Player.factory obj.type p.setProfile obj #id,realid,name... p.dead=obj.dead p.scapegoat=obj.scapegoat p.will=obj.will p.flag=obj.flag p.winner=obj.winner p.originalType=obj.originalType p.originalJobname=obj.originalJobname p.norevive=!!obj.norevive # backward compatibility if p.isComplex() p.cmplFlag=obj.Complex_flag p # 汎用関数: Complexを再構築する(chain:Complexの列(上から)) @reconstruct:(chain,base)-> for cmpl,i in chain by -1 newpl=Player.factory null,base,cmpl.sub,complexes[cmpl.cmplType] ### for ok in Object.keys cmpl # 自己のプロパティのみ unless ok=="main" || ok=="sub" newpl[ok]=cmpl[ok] ### newpl.cmplFlag=cmpl.cmplFlag base=newpl base publicinfo:-> # 見せてもいい情報 { id:@id name:@name dead:@dead norevive:@norevive } # プロパティセット系(Complex対応) setDead:(@dead,@found)-> setWinner:(@winner)-> setTarget:(@target)-> setFlag:(@flag)-> setWill:(@will)-> setOriginalType:(@originalType)-> setOriginalJobname:(@originalJobname)-> setNorevive:(@norevive)-> # ログが見えるかどうか(通常の游戏中、個人宛は除外) isListener:(game,log)-> if log.mode in ["day","system","nextturn","prepare","monologue","heavenmonologue","skill","will","voteto","gm","gmreply","helperwhisper","probability_table","userinfo"] # 全員に見える true else if log.mode in ["heaven","gmheaven"] # 死んでたら見える @dead else if log.mode=="voteresult" game.rule.voteresult!="hide" # 隠すかどうか else false # midnightの実行順(小さいほうが先) midnightSort: 100 # 本人に見える职业名 getJobDisp:->@jobname # 本人に見える职业タイプ getTypeDisp:->@type # 职业名を得る getJobname:->@jobname # 母猪かどうか isHuman:->!@isWerewolf() # LowBかどうか isWerewolf:->false # 洋子かどうか isFox:->false # 妖狐の仲間としてみえるか isFoxVisible:->false # 恋人かどうか isFriend:->false # Complexかどうか isComplex:->false # 教会信者かどうか isCult:->false # 吸血鬼かどうか isVampire:->false # 酒鬼かどうか isDrunk:->false # 蘇生可能性を秘めているか isReviver:->false # Am I Dead? isDead:->{dead:@dead,found:@found} # get my team getTeam:-> @team # 終了時の人間カウント humanCount:-> if !@isFox() && @isHuman() 1 else 0 werewolfCount:-> if !@isFox() && @isWerewolf() 1 else 0 vampireCount:-> if !@isFox() && @isVampire() 1 else 0 # jobtypeが合っているかどうか(夜) isJobType:(type)->type==@type #An access to @flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" if @isJobType(type) return this null gatherMidnightSort:-> return [@midnightSort] # complexのJobTypeを調べる isCmplType:(type)->false # 投票先决定 dovote:(game,target)-> # 戻り値にも意味があるよ! err=game.votingbox.vote this,target,1 if err? return err @voteafter game,target return null voteafter:(game,target)-> # 昼のはじまり(死体処理よりも前) sunrise:(game)-> deadsunrise:(game)-> # 昼の投票準備 votestart:(game)-> #@voteto=null return if @dead if @scapegoat # 替身君は投票 alives=game.players.filter (x)=>!x.dead && x!=this r=Math.floor Math.random()*alives.length # 投票先 return unless alives[r]? #@voteto=alives[r].id @dovote game,alives[r].id # 夜のはじまり(死体処理よりも前) sunset:(game)-> deadsunset:(game)-> # 夜にもう寝たか sleeping:(game)->true # 夜に仕事を追えたか(基本sleepingと一致) jobdone:(game)->@sleeping game # 死んだ後でも仕事があるとfalse deadJobdone:(game)->true # 昼に投票を終えたか voted:(game,votingbox)->game.votingbox.isVoteFinished this # 夜の仕事 job:(game,playerid,query)-> @setTarget playerid null # 夜の仕事を行う midnight:(game,midnightSort)-> # 夜死んでいたときにmidnightの代わりに呼ばれる deadnight:(game,midnightSort)-> # 対象 job_target:1 # ビットフラグ # 対象用の値 @JOB_T_ALIVE:1 # 生きた人が対象 @JOB_T_DEAD :2 # 死んだ人が対象 #LowBに食われて死ぬかどうか willDieWerewolf:true #占いの结果 fortuneResult:"母猪" getFortuneResult:->@fortuneResult #霊能の結果 psychicResult:"母猪" getPsychicResult:->@psychicResult #チーム Human/Werewolf team: "Human" #胜利かどうか team:胜利阵营名 isWinner:(game,team)-> team==@team # 自己の阵营かどうか # 殺されたとき(found:死因。fromは場合によりplayerid。punishの場合は[playerid])) die:(game,found,from)-> return if @dead if found=="werewolf" && !@willDieWerewolf # 襲撃耐性あり return pl=game.getPlayer @id pl.setDead true,found pl.dying game,found,from # 死んだとき dying:(game,found)-> # 行きかえる revive:(game)-> # logging: ログを表示するか if @norevive # 蘇生しない return @setDead false,null p=@getParent game unless p?.sub==this # サブのときはいいや・・・ log= mode:"system" comment:"#{@name} 复活了。" splashlog game.id,game,log @addGamelog game,"revive",null,null game.ss.publish.user @id,"refresh",{id:game.id} # 埋葬するまえに全员呼ばれる(foundが見られる状況で) beforebury: (game,type)-> # 占われたとき(结果は別にとられる player:占い元) divined:(game,player)-> # ちょっかいを出されたとき(jobのとき) touched:(game,from)-> # 选择肢を返す makeJobSelection:(game)-> if game.night # 夜の能力 jt=@job_target if jt>0 # 参加者を选择する result=[] for pl in game.players if (pl.dead && (jt&Player.JOB_T_DEAD))||(!pl.dead && (jt&Player.JOB_T_ALIVE)) result.push { name:pl.name value:pl.id } else result=[] else # 昼の投票 result=[] if game?.votingbox for pl in game.votingbox.candidates result.push { name:pl.name value:pl.id } result checkJobValidity:(game,query)-> sl=@makeJobSelection game return sl.length==0 || sl.some((x)->x.value==query.target) # 职业情報を載せる makejobinfo:(game,obj,jobdisp)-> # 開くべきフォームを配列で(生きている場合) obj.open ?=[] if !@jobdone(game) && (game.night || @chooseJobDay(game)) obj.open.push @type # 职业解説のアレ obj.desc ?= [] type = @getTypeDisp() if type? obj.desc.push { name:jobdisp ? @getJobDisp() type:type } obj.job_target=@getjob_target() # 选择肢を教える {name:"名字",value:"値"} obj.job_selection ?= [] obj.job_selection=obj.job_selection.concat @makeJobSelection game # 重複を取り除くのはクライアント側にやってもらおうかな… # 女王观战者が見える if @team=="Human" obj.queens=game.players.filter((x)->x.isJobType "QueenSpectator").map (x)-> x.publicinfo() else # セットなどによる漏洩を防止 delete obj.queens # 昼でも対象选择を行えるか chooseJobDay:(game)->false # 仕事先情報を教える getjob_target:->@job_target # 昼の发言の选择肢 getSpeakChoiceDay:(game)-> ["day","monologue"] # 夜の发言の选择肢を得る getSpeakChoice:(game)-> ["monologue"] # 自分宛の投票を書き換えられる modifyMyVote:(game, vote)-> vote # Complexから抜ける uncomplex:(game,flag=false)-> #flag: 自己がComplexで自己が消滅するならfalse 自己がmainまたはsubで親のComplexを消すならtrue(その際subは消滅) befpl=game.getPlayer @id # objがPlayerであること calleeは呼び出し元のオブジェクト chainは継承連鎖 # index: game.playersの番号 chk=(obj,index,callee,chain)-> return unless obj? chc=chain.concat obj if obj.isComplex() if flag # mainまたはsubである if obj.main==callee || obj.sub==callee # 自己は消える game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc else # 自己がComplexである if obj==callee game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc game.players.forEach (x,i)=> if x.id==@id chk x,i,this,[] # participantsも for pl,j in game.participants if pl.id==@id game.participants[j]=game.players[i] break aftpl=game.getPlayer @id #前と後で比較 if befpl.getJobname()!=aftpl.getJobname() aftpl.setOriginalJobname "#{befpl.originalJobname}→#{aftpl.getJobname()}" # 自己自身を変える transform:(game,newpl,override,initial=false)-> # override: trueなら全部変える falseならメイン职业のみ変える @addGamelog game,"transform",newpl.type # 职业変化ログ if override || !@isComplex() # 全部取っ払ってnewplになる newpl.setOriginalType @originalType if @getJobname()!=newpl.getJobname() unless initial # ふつうの変化 newpl.setOriginalJobname "#{@originalJobname}→#{newpl.getJobname()}" else # 最初の変化(ログに残さない) newpl.setOriginalJobname newpl.getJobname() pa=@getParent game unless pa? # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=newpl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=newpl else # 親がいた if pa.main==this # 親書き換え newparent=Player.factory null,newpl,pa.sub,complexes[pa.cmplType] newparent.cmplFlag=pa.cmplFlag newpl.transProfile newparent pa.transform game,newparent,override # たのしい再帰 else # サブだった pa.sub=newpl else # 中心のみ変える pa=game.getPlayer @id orig_originalJobname=pa.originalJobname chain=[pa] while pa.main.isComplex() pa=pa.main chain.push pa # pa.mainはComplexではない toppl=Player.reconstruct chain,newpl toppl.setOriginalJobname "#{orig_originalJobname}→#{toppl.getJobname()}" # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=toppl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=toppl getParent:(game)-> chk=(parent,name)=> if parent[name]?.isComplex?() if parent[name].main==this || parent[name].sub==this return parent[name] else return chk(parent[name],"main") || chk(parent[name],"sub") else return null for pl,i in game.players c=chk game.players,i return c if c? return null # 親なんていない # 自己のイベントを記述 addGamelog:(game,event,flag,target,type=@type)-> game.addGamelog { id:@id type:type target:target event:event flag:flag } # 個人情報的なことをセット setProfile:(obj={})-> @id=obj.id @realid=obj.realid @name=obj.name # 個人情報的なことを移動 transProfile:(newpl)-> newpl.setProfile this # フラグ類を新しいPlayerオブジェクトへ移動 transferData:(newpl)-> return unless newpl? newpl.scapegoat=@scapegoat newpl.setDead @dead,@found class Human extends Player type:"Human" jobname:"母猪" class Werewolf extends Player type:"Werewolf" jobname:"LowB" sunset:(game)-> @setTarget null unless game.day==1 && game.rule.scapegoat!="off" if @scapegoat && @isAttacker() && game.players.filter((x)->!x.dead && x.isWerewolf() && x.isAttacker()).length==1 # 自己しかLowBがいない hus=game.players.filter (x)->!x.dead && !x.isWerewolf() while hus.length>0 && game.werewolf_target_remain>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } hus.splice r,1 if game.werewolf_target_remain>0 # 襲撃したい人全员襲撃したけどまだ襲撃できるときは重複襲撃 hus=game.players.filter (x)->!x.dead && !x.isWerewolf() # safety counter i = 100 while hus.length>0 && game.werewolf_target_remain>0 && i > 0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } i-- sleeping:(game)->game.werewolf_target_remain<=0 || !game.night job:(game,playerid)-> tp = game.getPlayer playerid if game.werewolf_target_remain<=0 return "已经决定了袭击对象" if game.rule.wolfattack!="ok" && tp?.isWerewolf() # LowBはLowBに攻撃できない return "LowB之间不能相互袭击" game.werewolf_target.push { from:@id to:playerid } game.werewolf_target_remain-- tp.touched game,@id log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚袭击 #{tp.name}。" if @isJobType "SolitudeWolf" # 孤独的狼なら自己だけ… log.to=@id splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null isHuman:->false isWerewolf:->true # おおかみ専用メソッド:襲撃できるか isAttacker:->!@dead isListener:(game,log)-> if log.mode in ["werewolf","wolfskill"] true else super isJobType:(type)-> # 便宜的 if type=="_Werewolf" return true super willDieWerewolf:false fortuneResult:"LowB" psychicResult:"LowB" team: "Werewolf" makejobinfo:(game,result)-> super if game.night && game.werewolf_target_remain>0 # まだ襲える result.open.push "_Werewolf" # LowBは仲間が分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() # 间谍2も分かる result.spy2s=game.players.filter((x)->x.isJobType "Spy2").map (x)-> x.publicinfo() getSpeakChoice:(game)-> ["werewolf"].concat super class Diviner extends Player type:"Diviner" jobname:"占卜师" midnightSort: 100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid)-> super pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> unless game.rule.divineresult=="immediate" @dodivine game @divineeffect game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @target if p? p.divined game,this #占い実行 dodivine:(game)-> p=game.getPlayer @target if p? @results.push { player: p.publicinfo() result: "#{@name} 占卜了 #{p.name} 的身份,他是 #{p.getFortuneResult()}。" } @addGamelog game,"divine",p.type,@target # 占った showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Psychic extends Player type:"Psychic" jobname:"灵能者" constructor:-> super @setFlag "" # ここにメッセージを入れよう sunset:(game)-> super if game.rule.psychicresult=="sunset" @showpsychicresult game sunrise:(game)-> super unless game.rule.psychicresult=="sunset" @showpsychicresult game showpsychicresult:(game)-> return unless @flag? @flag.split("\n").forEach (x)=> return unless x log= mode:"skill" to:@id comment:x splashlog game.id,game,log @setFlag "" # 处刑で死んだ人を調べる beforebury:(game,type)-> @setFlag if @flag? then @flag else "" game.players.filter((x)->x.dead && x.found=="punish").forEach (x)=> @setFlag @flag+"根据 #{@name} 的灵能结论,被处刑的 #{x.name} 是 #{x.getPsychicResult()}。\n" class Madman extends Player type:"Madman" jobname:"狂人" team:"Werewolf" makejobinfo:(game,result)-> super delete result.queens class Guard extends Player type:"Guard" jobname:"猎人" midnightSort: 80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} # 失敗した @setTarget "" job:(game,playerid)-> if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" else @setTarget playerid pl=game.getPlayer(playerid) log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true newpl.touched game,@id null class Couple extends Player type:"Couple" jobname:"共有者" makejobinfo:(game,result)-> super # 共有者は仲間が分かる result.peers=game.players.filter((x)->x.isJobType "Couple").map (x)-> x.publicinfo() isListener:(game,log)-> if log.mode=="couple" true else super getSpeakChoice:(game)-> ["couple"].concat super class Fox extends Player type:"Fox" jobname:"妖狐" team:"Fox" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true makejobinfo:(game,result)-> super # 妖狐は仲間が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() divined:(game,player)-> super # 妖狐呪殺 @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した isListener:(game,log)-> if log.mode=="fox" true else super getSpeakChoice:(game)-> ["fox"].concat super class Poisoner extends Player type:"Poisoner" jobname:"埋毒者" dying:(game,found,from)-> super # 埋毒者の逆襲 canbedead = game.players.filter (x)->!x.dead # 生きている人たち if found=="werewolf" # 噛まれた場合は狼のみ if game.rule.poisonwolf == "selector" # 襲撃者を道連れにする canbedead = canbedead.filter (x)->x.id==from else canbedead=canbedead.filter (x)->x.isWerewolf() else if found=="vampire" canbedead=canbedead.filter (x)->x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"poison" @addGamelog game,"poisonkill",null,pl.id class BigWolf extends Werewolf type:"BigWolf" jobname:"大LowB" fortuneResult:"母猪" psychicResult:"大LowB" class TinyFox extends Diviner type:"TinyFox" jobname:"小狐" fortuneResult:"母猪" psychicResult:"小狐" team:"Fox" midnightSort:100 isHuman:->false isFox:->true makejobinfo:(game,result)-> super # 子狐は妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() dodivine:(game)-> p=game.getPlayer @target if p? success= Math.random()<0.5 # 成功したかどうか re=if success then "是 #{p.getFortuneResult()}" else "是一个看不透的可疑人物" @results.push { player: p.publicinfo() result: "根据 #{@name} 的占卜结果,#{p.name} #{re},大概。" } @addGamelog game,"foxdivine",success,p.id showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Bat extends Player type:"Bat" jobname:"蝙蝠" team:"" isWinner:(game,team)-> !@dead # 生きて入ればとにかく胜利 class Noble extends Player type:"Noble" jobname:"贵族" die:(game,found)-> if found=="werewolf" return if @dead # 奴隶たち slaves = game.players.filter (x)->!x.dead && x.isJobType "Slave" unless slaves.length super # 自己が死ぬ else # 奴隶が代わりに死ぬ slaves.forEach (x)-> x.die game,"werewolf2" x.addGamelog game,"slavevictim" @addGamelog game,"nobleavoid" else super class Slave extends Player type:"Slave" jobname:"奴隶" isWinner:(game,team)-> nobles=game.players.filter (x)->!x.dead && x.isJobType "Noble" if team==@team && nobles.length==0 true # 母猪阵营の勝ちで贵族は死んだ else false makejobinfo:(game,result)-> super # 奴隶は贵族が分かる result.nobles=game.players.filter((x)->x.isJobType "Noble").map (x)-> x.publicinfo() class Magician extends Player type:"Magician" jobname:"魔术师" midnightSort:100 isReviver:->!@dead sunset:(game)-> @setTarget (if game.day<3 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> if game.day<3 # まだ発動できない return "现在还不能发动技能" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null sleeping:(game)->game.day<3 || @target? midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=if pl.scapegoat then 0.6 else 0.3 unless Math.random()<r # 失敗 @addGamelog game,"raise",false,pl.id return # 蘇生 目を覚まさせる @addGamelog game,"raise",true,pl.id pl.revive game job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Spy extends Player type:"Spy" jobname:"间谍" team:"Werewolf" midnightSort:100 sleeping:->true # 能力使わなくてもいい jobdone:->@flag in ["spygone","day1"] # 能力を使ったか sunrise:(game)-> if game.day<=1 @setFlag "day1" # まだ去れない else @setFlag null job:(game,playerid)-> return "已经发动了技能" if @flag=="spygone" @setFlag "spygone" log= mode:"skill" to:@id comment:"#{@name} 决定要离开村子。" splashlog game.id,game,log null midnight:(game,midnightSort)-> if !@dead && @flag=="spygone" # 村を去る @setFlag "spygone" @die game,"spygone" job_target:0 isWinner:(game,team)-> team==@team && @dead && @flag=="spygone" # LowBが勝った上で自己は任務完了の必要あり makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class WolfDiviner extends Werewolf type:"WolfDiviner" jobname:"LowB占卜师" midnightSort:100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> @setTarget null @setFlag null # 占い対象 @result=null # 占卜结果 super sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && @flag? job:(game,playerid,query)-> if query.jobtype!="WolfDiviner" # LowBの仕事 return super # 占い if @flag? return "已经决定占卜对象" pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" @setFlag playerid unless pl.getTeam()=="Werewolf" && pl.isHuman() # 狂人は変化するので pl.touched game,@id log= mode:"skill" to:@id comment:"LowB占卜师 #{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> super @divineeffect game unless game.rule.divineresult=="immediate" @dodivine game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @flag if p? p.divined game,this if p.isJobType "Diviner" # 逆呪殺 @die game,"curse" showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log dodivine:(game)-> p=game.getPlayer @flag if p? @results.push { player: p.publicinfo() result: "LowB占卜师 #{@name} 占卜了 #{p.name} 的身份,他是 #{p.jobname}。" } @addGamelog game,"wolfdivine",null,@flag # 占った if p.getTeam()=="Werewolf" && p.isHuman() # 狂人変化 #避免狂人成为某些职业,"GameMaster"保留 jobnames=Object.keys jobs jobnames=jobnames.filter((x)->!(x in ["MinionSelector","Thief","Helper","QuantumPlayer","Waiting","Watching"])) newjob = jobnames[Math.floor(Math.random() * jobnames.length)] plobj=p.serialize() plobj.type=newjob newpl=Player.unserialize plobj # 新生狂人 newpl.setFlag null p.transferData newpl p.transform game,newpl,false p=game.getPlayer @flag p.sunset game log= mode:"skill" to:p.id comment:"#{p.name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.splashjobinfo [game.getPlayer newpl.id] makejobinfo:(game,result)-> super if game.night if @flag? # もう占いは終わった result.open = result.open?.filter (x)=>x!="WolfDiviner" class Fugitive extends Player type:"Fugitive" jobname:"逃亡者" midnightSort:100 sunset:(game)-> @setTarget null if game.day<=1 #&& game.rule.scapegoat!="off" # 一日目は逃げない @setTarget "" else if @scapegoat # 身代わり君の自動占い als=game.players.filter (x)=>!x.dead && x.id!=@id if als.length==0 @setTarget "" return r=Math.floor Math.random()*als.length if @job game,als[r].id,{} @setTarget "" sleeping:->@target? job:(game,playerid)-> # 逃亡先 pl=game.getPlayer playerid if pl?.dead return "不能逃到死者的家里去" if playerid==@id return "不能逃到自己的家里去" @setTarget playerid pl?.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 逃亡到 #{pl.name} 的家里去了。" splashlog game.id,game,log @addGamelog game,"runto",null,pl.id null die:(game,found)-> # 狼の襲撃・吸血鬼の襲撃・魔女の毒薬は回避 if found in ["werewolf","vampire","witch"] if @target!="" return else super else super midnight:(game,midnightSort)-> # LowBの家に逃げていたら即死 pl=game.getPlayer @target return unless pl? if !pl.dead && pl.isWerewolf() && pl.getTeam() in ["Werewolf","LoneWolf"] @die game,"werewolf2" else if !pl.dead && pl.isVampire() && pl.getTeam()=="Vampire" @die game,"vampire2" isWinner:(game,team)-> team==@team && !@dead # 母猪胜利で生存 class Merchant extends Player type:"Merchant" jobname:"商人" constructor:-> super @setFlag null # 発送済みかどうか sleeping:->true jobdone:(game)->game.day<=1 || @flag? job:(game,playerid,query)-> if @flag? return "商品已经送出" # 即時発送 unless query.Merchant_kit in ["Diviner","Psychic","Guard"] return "要送出的商品无效" kit_names= "Diviner":"占卜套装" "Psychic":"灵能套装" "Guard":"守护套装" pl=game.getPlayer playerid unless pl? return "发送无效" if pl.dead return "发送对象已经死亡" if pl.id==@id return "不能发送给自己" pl.touched game,@id # 複合させる sub=Player.factory query.Merchant_kit # 副を作る pl.transProfile sub sub.sunset game newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 寄出了 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log # 入れ替え先は気づいてもらう log= mode:"skill" to:newpl.id comment:"#{newpl.name} 收到了礼物 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} @setFlag query.Merchant_kit # 発送済み @addGamelog game,"sendkit",@flag,newpl.id null class QueenSpectator extends Player type:"QueenSpectator" jobname:"女王观战者" dying:(game,found)-> super # 感染 humans = game.players.filter (x)->!x.dead && x.isHuman() # 生きている人たち humans.forEach (x)-> x.die game,"hinamizawa" class MadWolf extends Werewolf type:"MadWolf" jobname:"狂LowB" team:"Human" sleeping:->true class Neet extends Player type:"Neet" jobname:"NEET" team:"" sleeping:->true voted:(game,votingbox)->true isWinner:->true class Liar extends Player type:"Liar" jobname:"骗子" midnightSort:100 job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も constructor:-> super @results=[] sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid,query)-> # 占い if @target? return "已经决定占卜对象" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log null sunrise:(game)-> super return if !@results? || @results.length==0 log= mode:"skill" to:@id comment:"虽然不是很自信,根据骗子占卜的结果 #{@results[@results.length-1].player.name} 大概是 #{@results[@results.length-1].result},大概。" splashlog game.id,game,log midnight:(game,midnightSort)-> p=game.getPlayer @target if p? @addGamelog game,"liardivine",null,p.id @results.push { player: p.publicinfo() result: if Math.random()<0.3 # 成功 p.getFortuneResult() else # 逆 fr = p.getFortuneResult() switch fr when "母猪" "LowB" when "LowB" "母猪" else fr } isWinner:(game,team)->team==@team && !@dead # 母猪胜利で生存 class Spy2 extends Player type:"Spy2" jobname:"间谍Ⅱ" team:"Werewolf" makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() dying:(game,found)-> super @publishdocument game publishdocument:(game)-> str=game.players.map (x)-> "#{x.name}:#{x.jobname}" .join " \n" log= mode:"system" comment:"发现了 #{@name} 的调查报告书。" splashlog game.id,game,log log2= mode:"will" comment:str splashlog game.id,game,log2 isWinner:(game,team)-> team==@team && !@dead class Copier extends Player type:"Copier" jobname:"模仿者" team:"" isHuman:->false sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} job:(game,playerid,query)-> # 模仿者先 if @target? return "已经模仿了其他人" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 模仿了 #{pl.name} 的能力。" splashlog game.id,game,log p=game.getPlayer playerid newpl=Player.factory p.type @transProfile newpl @transferData newpl @transform game,newpl,false pl=game.getPlayer @id pl.sunset game # 初期化してあげる #game.ss.publish.user newpl.id,"refresh",{id:game.id} game.splashjobinfo [game.getPlayer @id] null isWinner:(game,team)->false # 模仿者しないと負け class Light extends Player type:"Light" jobname:"死亡笔记" midnightSort:100 sleeping:->true jobdone:(game)->@target? || game.day==1 sunset:(game)-> @setTarget null job:(game,playerid,query)-> # 模仿者先 if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 在死亡笔记上写下了 #{pl.name} 的名字。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"deathnote" # 誰かに移る処理 @uncomplex game,true # 自己からは抜ける class Fanatic extends Madman type:"Fanatic" jobname:"狂信者" makejobinfo:(game,result)-> super # 狂信者はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() class Immoral extends Player type:"Immoral" jobname:"背德者" team:"Fox" beforebury:(game,type)-> # 狐が全員死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" makejobinfo:(game,result)-> super # 妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() class Devil extends Player type:"Devil" jobname:"恶魔" team:"Devil" psychicResult:"LowB" die:(game,found)-> return if @dead if found=="werewolf" # 死なないぞ! unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="punish" # 处刑されたぞ! if @flag=="bitten" # 噛まれたあと处刑された @setFlag "winner" else super else super isWinner:(game,team)->team==@team && @flag=="winner" class ToughGuy extends Player type:"ToughGuy" jobname:"硬汉" die:(game,found)-> if found=="werewolf" # 狼の襲撃に耐える @setFlag "bitten" else super sunrise:(game)-> super if @flag=="bitten" @setFlag "dying" # 死にそう! sunset:(game)-> super if @flag=="dying" # 噛まれた次の夜 @setFlag null @setDead true,"werewolf" class Cupid extends Player type:"Cupid" jobname:"丘比特" team:"Friend" constructor:-> super @setFlag null # 恋人1 @setTarget null # 恋人2 sunset:(game)-> if game.day>=2 && @flag? # 2日目以降はもう遅い @setFlag "" @setTarget "" else @setFlag null @setTarget null if @scapegoat # 身代わり君の自動占い alives=game.players.filter (x)->!x.dead i=0 while i++<2 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@flag? && @target? job:(game,playerid,query)-> if @flag? && @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" unless @flag? @setFlag playerid log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 定为恋人中的一人。" splashlog game.id,game,log return null if @flag==playerid return "请选择另一个恋人" @setTarget playerid # 恋人二人が决定した plpls=[game.getPlayer(@flag), game.getPlayer(@target)] for pl,i in plpls # 2人ぶん処理 pl.touched game,@id newpl=Player.factory null,pl,null,Friend # 恋人だ! newpl.cmplFlag=plpls[1-i].id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 射出了爱之箭。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{newpl.name} 成为了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [game.getPlayer(@flag), game.getPlayer(@target)] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 跟踪狂 class Stalker extends Player type:"Stalker" jobname:"跟踪狂" team:"" sunset:(game)-> super if !@flag # ストーキング先を決めていない @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setTarget "" sleeping:->@flag? job:(game,playerid,query)-> if @target? || @flag? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 跟踪了 #{pl.name}(#{pl.jobname})。" splashlog game.id,game,log @setFlag playerid # ストーキング対象プレイヤー null isWinner:(game,team)-> @isWinnerStalk game,team,[] # 跟踪狂連鎖対応版 isWinnerStalk:(game,team,ids)-> if @id in ids # ループしてるので負け return false pl=game.getPlayer @flag return false unless pl? if team==pl.getTeam() return true if pl.isJobType "Stalker" # 跟踪狂を追跡 return pl.isWinnerStalk game,team,ids.concat @id else return pl.isWinner game,team makejobinfo:(game,result)-> super p=game.getPlayer @flag if p? result.stalking=p.publicinfo() # 被诅咒者 class Cursed extends Player type:"Cursed" jobname:"被诅咒者" die:(game,found)-> return if @dead if found=="werewolf" # 噛まれた場合LowB侧になる unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="vampire" # 吸血鬼にもなる!!! unless @flag # まだ噛まれていない @setFlag "vampire" else super sunset:(game)-> if @flag in ["bitten","vampire"] # この夜から変化する log=null newpl=null if @flag=="bitten" log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了LowB。" newpl=Player.factory "Werewolf" else log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了吸血鬼。" newpl=Player.factory "Vampire" @transProfile newpl @transferData newpl @transform game,newpl,false newpl.sunset game splashlog game.id,game,log if @flag=="bitten" # LowB侧に知らせる #game.ss.publish.channel "room#{game.id}_werewolf","refresh",{id:game.id} game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() else # 吸血鬼に知らせる game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isVampire() # 自己も知らせる #game.ss.publish.user newpl.realid,"refresh",{id:game.id} game.splashjobinfo [this] class ApprenticeSeer extends Player type:"ApprenticeSeer" jobname:"见习占卜师" beforebury:(game,type)-> # 占卜师が誰か死んでいたら占卜师に進化 if game.players.some((x)->x.dead && x.isJobType("Diviner")) || game.players.every((x)->!x.isJobType("Diviner")) newpl=Player.factory "Diviner" @transProfile newpl @transferData newpl log= mode:"skill" to:@id comment:"#{@name} 从 #{@jobname} 变成了 #{newpl.jobname}。" splashlog game.id,game,log @transform game,newpl,false # 更新 game.ss.publish.user newpl.realid,"refresh",{id:game.id} class Diseased extends Player type:"Diseased" jobname:"病人" dying:(game,found)-> super if found=="werewolf" # 噛まれた場合次の日LowB襲撃できない! game.werewolf_flag.push "Diseased" # 病人フラグを立てる class Spellcaster extends Player type:"Spellcaster" jobname:"咒言师" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 初日は発動できません @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" arr=[] try arr=JSON.parse @flag catch error arr=[] unless arr instanceof Array arr=[] if playerid in arr # 既に呪いをかけたことがある return "这个对象已经被咒言诅咒过了。" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 夺去了 #{pl.name} 的声音。" splashlog game.id,game,log arr.push playerid @setFlag JSON.stringify arr null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 的声音被夺去了。今天白天无法发言。" splashlog game.id,game,log # 複合させる newpl=Player.factory null,t,null,Muted # 黙る人 t.transProfile newpl t.transform game,newpl,true class Lycan extends Player type:"Lycan" jobname:"狼凭" fortuneResult:"LowB" class Priest extends Player type:"Priest" jobname:"圣职者" midnightSort:70 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid,query)-> if @flag? return "已经使用了能力" if @target? return "已经选择了对象" pl=game.getPlayer playerid unless pl? return "这个对象不存在" if playerid==@id return "不能将自己选为对象" pl.touched game,@id @setTarget playerid @setFlag "done" # すでに能力を発動している log= mode:"skill" to:@id comment:"#{@name} 以神圣的力量守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,HolyProtected # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元 pl.transform game,newpl,true null class Prince extends Player type:"Prince" jobname:"王子" die:(game,found)-> if found=="punish" && !@flag? # 处刑された @setFlag "used" # 能力使用済 log= mode:"system" comment:"#{@name} 是 #{@jobname}。本次处刑被取消了。" splashlog game.id,game,log @addGamelog game,"princeCO" else super # Paranormal Investigator class PI extends Diviner type:"PI" jobname:"超常现象研究者" sleeping:->true jobdone:->@flag? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 调查了 #{pl.name} 和他的左右邻居。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game @setFlag "done" # 能力一回限り null #占い実行 dodivine:(game)-> pls=[] game.players.forEach (x,i)=> if x.id==@target pls.push x # 前 if i==0 pls.push game.players[game.players.length-1] else pls.push game.players[i-1] # 後 if i>=game.players.length-1 pls.push game.players[0] else pls.push game.players[i+1] if pls.length>0 rs=pls.map((x)->x?.getFortuneResult()).filter((x)->x!="母猪") # 母猪以外 # 重複をとりのぞく nrs=[] rs.forEach (x,i)-> if rs.indexOf(x,i+1)<0 nrs.push x tpl=game.getPlayer @target resultstring=if nrs.length>0 @addGamelog game,"PIdivine",true,tpl.id "发现了 #{nrs.join ","} 活动的迹象" else @addGamelog game,"PIdivine",false,tpl.id "发现全员都是母猪" @results.push { player:game.getPlayer(@target).publicinfo() result:"#{@name} 调查了 #{tpl.name} 和他的左右邻居,#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Sorcerer extends Diviner type:"Sorcerer" jobname:"妖术师" team:"Werewolf" sleeping:->@target? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 用妖术调查了 #{pl.name}。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null #占い実行 dodivine:(game)-> pl=game.getPlayer @target if pl? resultstring=if pl.isJobType "Diviner" "是占卜师" else "不是占卜师" @results.push { player: game.getPlayer(@target).publicinfo() result: "#{@name} 用妖术调查了 #{pl.name},他#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Doppleganger extends Player type:"Doppleganger" jobname:"二重身" sleeping:->true jobdone:->@flag? team:"" # 最初はチームに属さない! job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能将自己选为对象" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 成为了 #{game.getPlayer(playerid).name} 的二重身。" splashlog game.id,game,log @setFlag playerid # 二重身先 null beforebury:(game,type)-> founds=game.players.filter (x)->x.dead && x.found # 対象が死んだら移る if founds.some((x)=>x.id==@flag) p=game.getPlayer @flag # その人 newplmain=Player.factory p.type @transProfile newplmain @transferData newplmain me=game.getPlayer @id # まだ二重身できる sub=Player.factory "Doppleganger" @transProfile sub newpl=Player.factory null, newplmain,sub,Complex # 合体 @transProfile newpl pa=@getParent game # 親を得る unless pa? # 親はいない @transform game,newpl,false else # 親がいる if pa.sub==this # subなら親ごと置換 pa.transform game,newpl,false else # mainなら自己だけ置換 @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"dopplemove",newpl.type,newpl.id game.ss.publish.user newpl.realid,"refresh",{id:game.id} class CultLeader extends Player type:"CultLeader" jobname:"邪教主" team:"Cult" midnightSort:100 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 发展 #{pl.name} 成为信者。" splashlog game.id,game,log @addGamelog game,"brainwash",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 成为了教会的信者。" # 信者 splashlog game.id,game,log newpl=Player.factory null, t,null,CultMember # 合体 t.transProfile newpl t.transform game,newpl,true makejobinfo:(game,result)-> super # 信者は分かる result.cultmembers=game.players.filter((x)->x.isCult()).map (x)-> x.publicinfo() class Vampire extends Player type:"Vampire" jobname:"吸血鬼" team:"Vampire" willDieWerewolf:false fortuneResult:"吸血鬼" midnightSort:100 sleeping:(game)->@target? || game.day==1 isHuman:->false isVampire:->true sunset:(game)-> @setTarget null if game.day>1 && @scapegoat r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid,query)-> # 襲う先 if @target? return "已经选择了对象" if game.day==1 return "今天不能袭击" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"vampire",@id # 逃亡者を探す runners=game.players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==t.id runners.forEach (x)=> x.die game,"vampire2",@id # その家に逃げていたら逃亡者も死ぬ makejobinfo:(game,result)-> super # 吸血鬼が分かる result.vampires=game.players.filter((x)->x.isVampire()).map (x)-> x.publicinfo() class LoneWolf extends Werewolf type:"LoneWolf" jobname:"一匹狼" team:"LoneWolf" isWinner:(game,team)->team==@team && !@dead class Cat extends Poisoner type:"Cat" jobname:"猫又" midnightSort:100 isReviver:->true sunset:(game)-> @setTarget (if game.day<2 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null jobdone:->@target? sleeping:->true midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=Math.random() # 0<=r<1 unless r<=0.25 # 失敗 @addGamelog game,"catraise",false,pl.id return if r<=0.05 # 5%の確率で誤爆 deads=game.players.filter (x)->x.dead if deads.length==0 # 誰もいないじゃん @addGamelog game,"catraise",false,pl.id return pl=deads[Math.floor(Math.random()*deads.length)] @addGamelog game,"catraise",pl.id,@target else @addGamelog game,"catraise",true,@target # 蘇生 目を覚まさせる pl.revive game deadnight:(game,midnightSort)-> @setTarget @id @midnight game, midnightSort job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Witch extends Player type:"Witch" jobname:"魔女" midnightSort:100 isReviver:->!@dead job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も sleeping:->true jobdone:->@target? || (@flag in [3,5,6]) # @flag:ビットフラグ 1:殺害1使用済 2:殺害2使用済 4:蘇生使用済 8:今晩蘇生使用 16:今晩殺人使用 constructor:-> super @setFlag 0 # 発送済みかどうか sunset:(game)-> @setTarget null unless @flag @setFlag 0 else # jobだけ実行してmidnightがなかったときの処理 if @flag & 8 @setFlag @flag^8 if @flag & 16 @setFlag @flag^16 job:(game,playerid,query)-> # query.Witch_drug pl=game.getPlayer playerid unless pl? return "魔药使用无效" if pl.id==@id return "不能对自己使用魔药" if query.Witch_drug=="kill" # 毒薬 if game.day==1 return "今天不能使用毒药" if (@flag&3)==3 # 蘇生薬は使い切った return "已经不能使用毒药了" else if (@flag&4) && (@flag&3) # すでに薬は2つ使っている return "已经不能使用毒药了" if pl.dead return "使用目标已经死亡" # 薬を使用 pl.touched game,@id @flag |= 16 # 今晩殺害使用 if (@flag&1)==0 @flag |= 1 # 1つ目 else @flag |= 2 # 2つ目 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了毒药。" splashlog game.id,game,log else # 蘇生薬 if (@flag&3)==3 || (@flag&4) return "已经不能使用复活药了" if !pl.dead return "使用对象活着" # 薬を使用 pl.touched game,@id @flag |= 12 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了复活药。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? if @flag & 8 # 蘇生 @setFlag @flag^8 # 蘇生 目を覚まさせる @addGamelog game,"witchraise",null,pl.id pl.revive game else if @flag & 16 # 殺害 @setFlag @flag^16 @addGamelog game,"witchkill",null,pl.id pl.die game,"witch" class Oldman extends Player type:"Oldman" jobname:"老人" midnight:(game,midnightSort)-> # 夜の終わり wolves=game.players.filter (x)->x.isWerewolf() && !x.dead if wolves.length*2<=game.day # 寿命 @die game,"infirm" class Tanner extends Player type:"Tanner" jobname:"皮革匠" team:"" die:(game,found)-> if found in ["gone-day","gone-night"] # 突然死はダメ @setFlag "gone" super isWinner:(game,team)->@dead && @flag!="gone" class OccultMania extends Player type:"OccultMania" jobname:"怪诞狂热者" midnightSort:100 sleeping:(game)->@target? || game.day<2 sunset:(game)-> @setTarget (if game.day>=2 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在不能使用能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 指定了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> p=game.getPlayer @target return unless p? # 変化先决定 type="Human" if p.isJobType "Diviner" type="Diviner" else if p.isWerewolf() type="Werewolf" newpl=Player.factory type @transProfile newpl @transferData newpl newpl.sunset game # 初期化してあげる @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.realid,"refresh",{id:game.id} null # 狼之子 class WolfCub extends Werewolf type:"WolfCub" jobname:"狼之子" dying:(game,found)-> super game.werewolf_flag.push "WolfCub" # 低语狂人 class WhisperingMad extends Fanatic type:"WhisperingMad" jobname:"低语狂人" getSpeakChoice:(game)-> ["werewolf"].concat super isListener:(game,log)-> if log.mode=="werewolf" true else super class Lover extends Player type:"Lover" jobname:"求爱者" team:"Friend" constructor:-> super @setTarget null # 相手 sunset:(game)-> unless @flag? if @scapegoat # 替身君は求愛しない @setFlag true @setTarget "" else @setTarget null sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能射出爱之箭" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的对象" pl.touched game,@id @setTarget playerid @setFlag true # 恋人二人が决定した plpls=[this,pl] for x,i in plpls newpl=Player.factory null,x,null,Friend # 恋人だ! x.transProfile newpl x.transform game,newpl,true # 入れ替え newpl.cmplFlag=plpls[1-i].id log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 求爱了。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{pl.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [this, pl] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 仆从选择者 class MinionSelector extends Player type:"MinionSelector" jobname:"仆从选择者" team:"Werewolf" sleeping:(game)->@target? || game.day>1 # 初日のみ sunset:(game)-> @setTarget (if game.day==1 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day!=1 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" # 複合させる newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"wolfskill" comment:"#{@name} 指定 #{pl.name}(#{pl.jobname})成为了狼的仆从。" splashlog game.id,game,log log= mode:"skill" to:pl.id comment:"#{pl.name} 变成了狼的仆从。" splashlog game.id,game,log null # 小偷 class Thief extends Player type:"Thief" jobname:"小偷" team:"" sleeping:(game)->@target? || game.day>1 sunset:(game)-> @setTarget (if game.day==1 then null else "") # @flag:JSON的职业候補配列 if !target? arr=JSON.parse(@flag ? '["Human"]') jobnames=arr.map (x)-> testpl=new jobs[x] testpl.getJobDisp() log= mode:"skill" to:@id comment:"#{@name} 可以选择的职业有 #{jobnames.join(",")}。" splashlog game.id,game,log if @scapegoat # 身代わり君 r=Math.floor Math.random()*arr.length @job game,arr[r] job:(game,target)-> @setTarget target unless jobs[target]? return "不能变成那个职业" newpl=Player.factory target @transProfile newpl @transferData newpl newpl.sunset game @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} null makeJobSelection:(game)-> if game.night # 职业から选择 arr=JSON.parse(@flag ? '["Human"]') arr.map (x)-> testpl=new jobs[x] { name:testpl.getJobDisp() value:x } else super class Dog extends Player type:"Dog" jobname:"犬" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 sunset:(game)-> super @setTarget null # 1日目:飼い主选择 选择後:かみ殺す人选择 if !@flag? # 飼い主を決めていない if @scapegoat alives=game.players.filter (x)=>!x.dead && x.id!=@id if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setFlag "" @setTarget "" else # 飼い主を护卫する pl=game.getPlayer @flag if pl? if pl.dead # もう死んでるじゃん @setTarget "" # 洗濯済み else newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true sleeping:->@flag? jobdone:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" unless @flag? pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能成为自己的饲主。" pl.touched game,@id # 飼い主を选择した log= mode:"skill" to:@id comment:"#{@name} 选择 #{pl.name} 成为了自己的饲主。" splashlog game.id,game,log @setFlag playerid # 飼い主 @setTarget "" # 襲撃対象はなし else # 襲う pl=game.getPlayer @flag @setTarget @flag log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night if @flag? # 飼い主いる pl=game.getPlayer @flag if pl? if !pl.read result.open.push "Dog1" result.dogOwner=pl.publicinfo() else result.open.push "Dog2" makeJobSelection:(game)-> # 噛むときは対象选择なし if game.night && @flag? [] else super class Dictator extends Player type:"Dictator" jobname:"独裁者" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能发的能力" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid # 处刑する人 log= mode:"system" comment:"独裁者 #{@name} 宣布将要处刑 #{pl.name}。" splashlog game.id,game,log @setFlag true # 使用済 # その場で殺す!!! pl.die game,"punish",[@id] # 天黑了 log= mode:"system" comment:"独裁者 #{@name} 宣布,现在天黑了。" splashlog game.id,game,log # 強制的に次のターンへ game.nextturn() null class SeersMama extends Player type:"SeersMama" jobname:"占卜师的妈妈" sleeping:->true sunset:(game)-> unless @flag # まだ能力を実行していない # 占卜师を探す divs = game.players.filter (pl)->pl.isJobType "Diviner" divsstr=if divs.length>0 "#{divs.map((x)->x.name).join ','} 是占卜师" else "没有占卜师" log= mode:"skill" to:@id comment:"#{@name} 是占卜师的妈妈。#{divsstr}。" splashlog game.id,game,log @setFlag true #使用済 class Trapper extends Player type:"Trapper" jobname:"陷阱师" midnightSort:81 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目は护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> unless playerid==@id && game.rule.guardmyself!="ok" if playerid==@flag # 前も护卫した return "不能连续两天守护一个人" @setTarget playerid @setFlag playerid pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 的陷阱守护了 #{pl.name}。" splashlog game.id,game,log null else "不能守护自己" midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,TrapGuarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class WolfBoy extends Madman type:"WolfBoy" jobname:"狼少年" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 伪装成了LowB。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Lycanized pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class Hoodlum extends Player type:"Hoodlum" jobname:"无赖" team:"" constructor:-> super @setFlag "[]" # 殺したい対象IDを入れておく @setTarget null sunset:(game)-> unless @target? # 2人選んでもらう @setTarget null if @scapegoat # 身代わり alives=game.players.filter (x)=>!x.dead && x!=this i=0 while i++<2 && alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" plids=JSON.parse(@flag||"[]") if pl.id in plids # 既にいる return "#{pl.name} 已经被选为对象" plids.push pl.id @setFlag JSON.stringify plids log= mode:"skill" to:@id comment:"#{@name} 憎恨 #{pl.name}。" splashlog game.id,game,log if plids.length>=2 @setTarget "" else # 2人目を選んでほしい @setTarget null null isWinner:(game,team)-> if @dead # 死んでたらだめ return false pls=JSON.parse(@flag).map (id)->game.getPlayer id return pls.every (pl)->pl?.dead==true class QuantumPlayer extends Player type:"QuantumPlayer" jobname:"量子人类" midnightSort:100 getJobname:-> flag=JSON.parse(@flag||"{}") jobname=null if flag.Human==1 jobname="母猪" else if flag.Diviner==1 jobname="占卜师" else if flag.Werewolf==1 jobname="LowB" numstr="" if flag.number? numstr="##{flag.number}" ret=if jobname? "量子人类#{numstr}(#{jobname})" else "量子人类#{numstr}" if @originalJobname != ret # 収束したぞ! @setOriginalJobname ret return ret sleeping:-> tarobj=JSON.parse(@target || "{}") tarobj.Diviner? && tarobj.Werewolf? # 両方指定してあるか sunset:(game)-> # @flagに{Human:(確率),Diviner:(確率),Werewolf:(確率),dead:(確率)}的なのが入っているぞ! obj=JSON.parse(@flag || "{}") tarobj= Diviner:null Werewolf:null if obj.Diviner==0 tarobj.Diviner="" # なし if obj.Werewolf==0 || (game.rule.quantumwerewolf_firstattack!="on" && game.day==1) tarobj.Werewolf="" @setTarget JSON.stringify tarobj if @scapegoat # 身代わり君の自動占い unless tarobj.Diviner? r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{ jobtype:"_Quantum_Diviner" } unless tarobj.Werewolf? nonme =game.players.filter (pl)=> pl!=this r=Math.floor Math.random()*nonme.length @job game,nonme[r].id,{ jobtype:"_Quantum_Werewolf" } isJobType:(type)-> # 便宜的 if type=="_Quantum_Diviner" || type=="_Quantum_Werewolf" return true super job:(game,playerid,query)-> tarobj=JSON.parse(@target||"{}") pl=game.getPlayer playerid unless pl? return "这个对象不存在" if query.jobtype=="_Quantum_Diviner" && !tarobj.Diviner? tarobj.Diviner=playerid log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log else if query.jobtype=="_Quantum_Werewolf" && !tarobj.Werewolf? if @id==playerid return "不能袭击自己。" tarobj.Werewolf=playerid log= mode:"skill" to:@id comment:"#{@name} 决定要袭击 #{pl.name}。" splashlog game.id,game,log else return "对象选择无效" @setTarget JSON.stringify tarobj null midnight:(game,midnightSort)-> # ここで処理 tarobj=JSON.parse(@target||"{}") if tarobj.Diviner pl=game.getPlayer tarobj.Diviner if pl? # 一旦自己が占卜师のやつ以外排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].jobtype=="Diviner" && obj[@id].dead==false # 1つ選んで占卜结果を决定 if pats.length>0 index=Math.floor Math.random()*pats.length j=pats[index][tarobj.Diviner].jobtype if j == "Werewolf" log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 LowB。" splashlog game.id,game,log # LowBのやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype == "Werewolf" else true else log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 母猪。" splashlog game.id,game,log # 母猪のやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype!="Werewolf" else true else # 占えない log= mode:"skill" to:@id comment:"#{@name} 已经不可能是占卜师,不能进行占卜。" splashlog game.id,game,log if tarobj.Werewolf pl=game.getPlayer tarobj.Werewolf if pl? game.quantum_patterns=game.quantum_patterns.filter (obj)=> # 何番が筆頭かを求める min=Infinity for key,value of obj if value.jobtype=="Werewolf" && value.dead==false && value.rank<min min=value.rank if obj[@id].jobtype=="Werewolf" && obj[@id].rank==min && obj[@id].dead==false # 自己が筆頭LowB if obj[pl.id].jobtype == "Werewolf"# || obj[pl.id].dead==true # 襲えない false else # さらに対応するやつを死亡させる obj[pl.id].dead=true true else true isWinner:(game,team)-> flag=JSON.parse @flag unless flag? return false if flag.Werewolf==1 && team=="Werewolf" # LowBがかったぞ!!!!! true else if flag.Werewolf==0 && team=="Human" # 人类がかったぞ!!!!! true else # よくわからないぞ! false makejobinfo:(game,result)-> super tarobj=JSON.parse(@target||"{}") unless tarobj.Diviner? result.open.push "_Quantum_Diviner" unless tarobj.Werewolf? result.open.push "_Quantum_Werewolf" if game.rule.quantumwerewolf_table=="anonymous" # 番号がある flag=JSON.parse @flag result.quantumwerewolf_number=flag.number die:(game,found)-> super # 可能性を排除する pats=[] if found=="punish" # 处刑されたときは既に死んでいた可能性を排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].dead==false else pats=game.quantum_patterns if pats.length # 1つ選んで职业を决定 index=Math.floor Math.random()*pats.length tjt=pats[index][@id].jobtype trk=pats[index][@id].rank if trk? pats=pats.filter (obj)=> obj[@id].jobtype==tjt && obj[@id].rank==trk else pats=pats.filter (obj)=> obj[@id].jobtype==tjt # ワタシハシンダ pats.forEach (obj)=> obj[@id].dead=true game.quantum_patterns=pats class RedHood extends Player type:"RedHood" jobname:"小红帽" sleeping:->true isReviver:->!@dead || @flag? dying:(game,found,from)-> super if found=="werewolf" # 狼に襲われた # 誰に襲われたか覚えておく @setFlag from else @setFlag null deadsunset:(game)-> if @flag w=game.getPlayer @flag if w?.dead # 殺した狼が死んだ!復活する @revive game deadsunrise:(game)-> # 同じ @deadsunset game class Counselor extends Player type:"Counselor" jobname:"策士" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目はカウンセリングできない @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 尝试了策反 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead tteam = t.getTeam() if t.isWerewolf() && tteam in ["Werewolf","LoneWolf"] # LowBとかヴァンパイアを襲ったら殺される @die game,"werewolf2" @addGamelog game,"counselKilled",t.type,@target return if t.isVampire() && tteam=="Vampire" @die game,"vampire2" @addGamelog game,"counselKilled",t.type,@target return if tteam!="Human" log= mode:"skill" to:t.id comment:"#{t.name} 被策反了。" splashlog game.id,game,log @addGamelog game,"counselSuccess",t.type,@target # 複合させる newpl=Player.factory null,t,null,Counseled # カウンセリングされた t.transProfile newpl t.transform game,newpl,true else @addGamelog game,"counselFailure",t.type,@target # 巫女 class Miko extends Player type:"Miko" jobname:"巫女" midnightSort:71 sleeping:->true jobdone:->!!@flag job:(game,playerid,query)-> if @flag return "已经使用了能力" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 用神圣的力量守护了自己。" splashlog game.id,game,log @setFlag "using" null midnight:(game,midnightSort)-> # 複合させる if @flag=="using" pl = game.getPlayer @id newpl=Player.factory null,pl,null,MikoProtected # 守られた人 pl.transProfile newpl pl.transform game,newpl,true @setFlag "done" null makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class GreedyWolf extends Werewolf type:"GreedyWolf" jobname:"贪婪的狼" sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && (@flag || game.day==1) job:(game,playerid,query)-> if query.jobtype!="GreedyWolf" # LowBの仕事 return super if @flag return "已经使用了能力" @setFlag true if game.werewolf_target_remain+game.werewolf_target.length ==0 return "今晚不能袭击" log= mode:"wolfskill" comment:"为了满足 #{@name} 的贪欲。LowB们今晚可以多袭击一个人。" splashlog game.id,game,log game.werewolf_target_remain++ game.werewolf_flag.push "GreedyWolf_#{@id}" game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() null makejobinfo:(game,result)-> super if game.night if @sleeping game # 襲撃は必要ない result.open = result.open?.filter (x)=>x!="_Werewolf" if !@flag && game.day>=2 result.open?.push "GreedyWolf" makeJobSelection:(game)-> if game.night && @sleeping(game) && !@jobdone(game) # 欲張る选择肢のみある return [] else return super checkJobValidity:(game,query)-> if query.jobtype=="GreedyWolf" # なしでOK! return true return super class FascinatingWolf extends Werewolf type:"FascinatingWolf" jobname:"魅惑的女狼" sleeping:(game)->super && @flag? sunset:(game)-> super if @scapegoat && !@flag? # 誘惑する hus=game.players.filter (x)->!x.dead && !x.isWerewolf() if hus.length>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{jobtype:"FascinatingWolf"} else @setFlag "" job:(game,playerid,query)-> if query.jobtype!="FascinatingWolf" # LowBの仕事 return super if @flag return "已经使用了能力" pl=game.getPlayer playerid unless pl? return "对象玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 魅惑了 #{pl.name}。" @setFlag playerid splashlog game.id,game,log null dying:(game,found)-> # 死んだぞーーーーーーーーーーーーーー super # LWなら変えない if game.players.filter((x)->x.isWerewolf() && !x.dead).length==0 return pl=game.getPlayer @flag unless pl? # あれれーーー return if pl.dead # 既に死んでいた return unless pl.isHuman() && pl.getTeam()!="Werewolf" # 誘惑できない return newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:pl.id comment:"#{pl.name} 被狼魅惑了。" splashlog game.id,game,log makejobinfo:(game,result)-> super if game.night if @flag # もう誘惑は必要ない result.open = result.open?.filter (x)=>x!="FascinatingWolf" class SolitudeWolf extends Werewolf type:"SolitudeWolf" jobname:"孤独的狼" sleeping:(game)-> !@flag || super isListener:(game,log)-> if (log.mode in ["werewolf","wolfskill"]) && (log.to != @id) # 狼の声は听不到(自己のスキルは除く) false else super job:(game,playerid,query)-> if !@flag return "现在还不能袭击" super isAttacker:->!@dead && @flag sunset:(game)-> wolves=game.players.filter (x)->x.isWerewolf() attackers=wolves.filter (x)->!x.dead && x.isAttacker() if !@flag && attackers.length==0 # 襲えるやつ誰もいない @setFlag true log= mode:"skill" to:@id comment:"#{@name} 现在可以袭击他人了。" splashlog game.id,game,log else if @flag && attackers.length>1 # 複数いるのでやめる @setFlag false log= mode:"skill" to:@id comment:"其他的LowB还活着。#{@name} 现在不能袭击他人。" splashlog game.id,game,log super getSpeakChoice:(game)-> res=super return res.filter (x)->x!="werewolf" makejobinfo:(game,result)-> super delete result.wolves delete result.spy2s class ToughWolf extends Werewolf type:"ToughWolf" jobname:"硬汉LowB" job:(game,playerid,query)-> if query.jobtype!="ToughWolf" # LowBの仕事 return super if @flag return "已经使用了能力" res=super if res? return res @setFlag true game.werewolf_flag.push "ToughWolf_#{@id}" tp=game.getPlayer playerid unless tp? return "这个对象不存在" log= mode:"wolfskill" comment:"#{@name} 抱着舍身的觉悟袭击了 #{tp.name}。" splashlog game.id,game,log null class ThreateningWolf extends Werewolf type:"ThreateningWolf" jobname:"威吓的狼" jobdone:(game)-> if game.night super else @flag? chooseJobDay:(game)->true sunrise:(game)-> super @setTarget null job:(game,playerid,query)-> if query.jobtype!="ThreateningWolf" # LowBの仕事 return super if @flag return "已经使用了能力" if game.night return "夜晚不能使用能力" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid @setFlag true log= mode:"skill" to:@id comment:"#{@name} 威吓了 #{pl.name}。" splashlog game.id,game,log null sunset:(game)-> t=game.getPlayer @target return unless t? return if t.dead # 威嚇して能力無しにする @addGamelog game,"threaten",t.type,@target # 複合させる log= mode:"skill" to:t.id comment:"#{t.name} 受到了威吓。今晚的能力无法发动。" splashlog game.id,game,log newpl=Player.factory null,t,null,Threatened # カウンセリングされた t.transProfile newpl t.transform game,newpl,true super makejobinfo:(game,result)-> super if game.night # 夜は威嚇しない result.open = result.open?.filter (x)=>x!="ThreateningWolf" class HolyMarked extends Human type:"HolyMarked" jobname:"圣痕者" class WanderingGuard extends Player type:"WanderingGuard" jobname:"游荡猎人" midnightSort:80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else fl=JSON.parse(@flag ? "[]") alives=game.players.filter (x)->!x.dead if alives.every((pl)=>(pl.id in fl) || (game.rule.guardmyself!="ok" && pl.id==@id)) # もう护卫対象がいない @setTarget "" else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> fl=JSON.parse(@flag ? "[]") if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" fl=JSON.parse(@flag ? "[]") if playerid in fl return "这个人已经不能守护了" @setTarget playerid # OK! pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null beforebury:(game,type)-> if type=="day" # 昼になったとき if game.players.filter((x)->x.dead && x.found).length==0 # 誰も死ななかった!护卫できない pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 不能护卫 #{pl.name}。" splashlog game.id,game,log fl=JSON.parse(@flag ? "[]") fl.push pl.id @setFlag JSON.stringify fl makeJobSelection:(game)-> if game.night fl=JSON.parse(@flag ? "[]") a=super return a.filter (obj)->!(obj.value in fl) else return super class ObstructiveMad extends Madman type:"ObstructiveMad" jobname:"碍事的狂人" midnightSort:90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 妨碍了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineObstructed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true null class TroubleMaker extends Player type:"TroubleMaker" jobname:"闹事者" midnightSort:100 sleeping:->true jobdone:->!!@flag makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super job:(game,playerid)-> return "已经使用了能力" if @flag @setFlag "using" log= mode:"skill" to:@id comment:"#{@name} 在村子里引发了混乱。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # ここが無効化されたら発動しないように if @flag=="using" @setFlag "using2" null sunrise:(game)-> if @flag=="using2" game.votingbox.addPunishedNumber 1 # トラブルがおきた log= mode:"system" comment:"闹事者在村子里引发了混乱。今日将会处刑 #{game.votingbox.remains} 个人。" splashlog game.id,game,log @setFlag "done" else if @flag=="using" # 不発だった @setFlag "done" deadsunrise:(game)->@sunrise game class FrankensteinsMonster extends Player type:"FrankensteinsMonster" jobname:"弗兰肯斯坦的怪物" die:(game,found)-> super if found=="punish" # 处刑で死んだらもうひとり处刑できる game.votingbox.addPunishedNumber 1 beforebury:(game)-> # 新しく死んだひとたちで母猪阵营ひとたち # 不吸收弗兰肯斯坦的怪物 founds=game.players.filter (x)->x.dead && x.found && x.getTeam()=="Human" && !x.isJobType("FrankensteinsMonster") # 吸収する thispl=this for pl in founds log= mode:"skill" to:@id comment:"#{@name} 从 #{pl.name} 的尸体里吸收了 #{pl.getJobname()} 的能力。" splashlog game.id,game,log # 同じ能力を subpl = Player.factory pl.type thispl.transProfile subpl newpl=Player.factory null, thispl,subpl,Complex # 合成する thispl.transProfile newpl # 置き換える thispl.transform game,newpl,true thispl=newpl thispl.addGamelog game,"frankeneat",pl.type,pl.id if founds.length>0 game.splashjobinfo [thispl] class BloodyMary extends Player type:"BloodyMary" jobname:"血腥玛丽" isReviver:->true getJobname:->if @flag then @jobname else "玛丽" getJobDisp:->@getJobname() getTypeDisp:->if @flag then @type else "Mary" sleeping:->true deadJobdone:(game)-> if @target? true else if @flag=="punish" !(game.players.some (x)->!x.dead && x.getTeam()=="Human") else if @flag=="werewolf" if game.players.filter((x)->!x.dead && x.isWerewolf()).length>1 !(game.players.some (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"]) else # 狼が残り1匹だと何もない true else true dying:(game,found,from)-> if found in ["punish","werewolf"] # 能力が… orig_jobname=@getJobname() @setFlag found if orig_jobname != @getJobname() # 変わった! @setOriginalJobname @originalJobname.replace("血腥玛丽","玛丽").replace("玛丽","血腥玛丽") super sunset:(game)-> @setTarget null deadsunset:(game)-> @sunset game job:(game,playerid)-> unless @flag in ["punish","werewolf"] return "不能使用能力" pl=game.getPlayer playerid unless pl? return "对象不存在" log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log @setTarget playerid null # 呪い殺す!!!!!!!!! deadnight:(game,midnightSort)-> pl=game.getPlayer @target unless pl? return pl.die game,"marycurse",@id # 蘇生できない revive:-> isWinner:(game,team)-> if @flag=="punish" team in ["Werewolf","LoneWolf"] else team==@team makeJobSelection:(game)-> if game.night pls=[] if @flag=="punish" # 母猪を…… pls=game.players.filter (x)->!x.dead && x.getTeam()=="Human" else if @flag=="werewolf" # LowBを…… pls=game.players.filter (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"] return (for pl in pls { name:pl.name value:pl.id } ) else super makejobinfo:(game,obj)-> super if @flag && !("BloodyMary" in obj.open) obj.open.push "BloodyMary" class King extends Player type:"King" jobname:"国王" voteafter:(game,target)-> super game.votingbox.votePower this,1 class PsychoKiller extends Madman type:"PsychoKiller" jobname:"变态杀人狂" midnightSort:110 constructor:-> super @flag="[]" touched:(game,from)-> # 殺すリストに追加する fl=try JSON.parse @flag || "[]" catch e [] fl.push from @setFlag JSON.stringify fl sunset:(game)-> @setFlag "[]" midnight:(game,midnightSort)-> fl=try JSON.parse @flag || "[]" catch e [] for id in fl pl=game.getPlayer id if pl? && !pl.dead pl.die game,"psycho",@id @setFlag "[]" deadnight:(game,midnightSort)-> @midnight game, midnightSort class SantaClaus extends Player type:"SantaClaus" jobname:"圣诞老人" midnightSort:100 sleeping:->@target? constructor:-> super @setFlag "[]" isWinner:(game,team)->@flag=="gone" || super sunset:(game)-> # まだ届けられる人がいるかチェック fl=JSON.parse(@flag ? "[]") if game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) @setTarget null if @scapegoat cons=game.players.filter((x)=>!x.dead && x.id!=@id && !(x.id in fl)) if cons.length>0 r=Math.floor Math.random()*cons.length @job game,cons[r].id,{} else @setTarget "" else @setTarget "" sunrise:(game)-> # 全员に配ったかチェック fl=JSON.parse(@flag ? "[]") unless game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) # 村を去る @setFlag "gone" @die game,"spygone" job:(game,playerid)-> if @flag=="gone" return "已经离开了村子" fl=JSON.parse(@flag ? "[]") if playerid == @id return "不能把礼物送给自己" if playerid in fl return "这个人已经不能继续接受礼物了" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 赠送了礼物。" splashlog game.id,game,log fl.push playerid @setFlag JSON.stringify fl null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return if @flag=="gone" # プレゼントを送る r=Math.random() settype="" setname="" if r<0.05 # 毒だった log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了剧毒的礼物。" splashlog game.id,game,log pl.die game,"poison",@id @addGamelog game,"sendpresent","poison",pl.id return else if r<0.1 settype="HolyMarked" setname="圣痕者套装" else if r<0.15 settype="Oldman" setname="玉手箱" else if r<0.225 settype="Priest" setname="圣职者套装" else if r<0.3 settype="Miko" setname="Cosplay套装(巫女)" else if r<0.55 settype="Diviner" setname="占卜套装" else if r<0.8 settype="Guard" setname="守护套装" else settype="Psychic" setname="灵能套装" # 複合させる log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了礼物 #{setname}。" splashlog game.id,game,log # 複合させる sub=Player.factory settype # 副を作る pl.transProfile sub newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true @addGamelog game,"sendpresent",settype,pl.id #怪盗 class Phantom extends Player type:"Phantom" jobname:"怪盗" sleeping:->@target? sunset:(game)-> if @flag==true # もう交換済みだ @setTarget "" else @setTarget null if @scapegoat rs=@makeJobSelection game if rs.length>0 r=Math.floor Math.random()*rs.length @job game,rs[r].value,{ jobtype:@type } makeJobSelection:(game)-> if game.night res=[{ name:"放弃盗取" value:"" }] sup=super for obj in sup pl=game.getPlayer obj.value unless pl?.scapegoat res.push obj return res else super job:(game,playerid)-> @setTarget playerid if playerid=="" # 交換しない log= mode:"skill" to:@id comment:"#{@name} 没有盗取职业。" splashlog game.id,game,log return pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 盗取了 #{pl.name} 的职业。#{pl.name} 是 #{pl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"phantom",pl.type,playerid null sunrise:(game)-> @setFlag true pl=game.getPlayer @target unless pl? return savedobj={} pl.makejobinfo game,savedobj flagobj={} # jobinfo表示のみ抜粋 for value in Shared.game.jobinfos if savedobj[value.name]? flagobj[value.name]=savedobj[value.name] # 自己はそ的职业に変化する newpl=Player.factory pl.type @transProfile newpl @transferData newpl @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 盗まれた側は怪盗予備軍のフラグを立てる newpl2=Player.factory null,pl,null,PhantomStolen newpl2.cmplFlag=flagobj pl.transProfile newpl2 pl.transform game,newpl2,true class BadLady extends Player type:"BadLady" jobname:"恶女" team:"Friend" sleeping:->@flag?.set sunset:(game)-> unless @flag?.set # まだ恋人未设定 if @scapegoat @flag={ set:true } job:(game,playerid,query)-> fl=@flag ? {} if fl.set return "已经决定了对象" if playerid==@id return "请选择自己以外的对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id unless fl.main? # 本命を決める fl.main=playerid log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为自己的本命对象。" splashlog game.id,game,log @setFlag fl @addGamelog game,"badlady_main",pl.type,playerid return null unless fl.keep? # キープ相手を決める fl.keep=playerid fl.set=true @setFlag fl log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为玩弄的对象。" splashlog game.id,game,log # 2人を恋人、1人をキープに plm=game.getPlayer fl.main for pll in [plm,pl] if pll? log= mode:"skill" to:pll.id comment:"#{pll.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 自己恋人 newpl=Player.factory null,this,null,Friend # 恋人だ! newpl.cmplFlag=fl.main @transProfile newpl @transform game,newpl,true # 入れ替え # 相手恋人 newpl=Player.factory null,plm,null,Friend # 恋人だ! newpl.cmplFlag=@id plm.transProfile newpl plm.transform game,newpl,true # 入れ替え # キープ newpl=Player.factory null,pl,null,KeepedLover # 恋人か? newpl.cmplFlag=@id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え game.splashjobinfo [@id,plm.id,pl.id].map (id)->game.getPlayer id @addGamelog game,"badlady_keep",pl.type,playerid null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night # 夜の选择肢 fl=@flag ? {} unless fl.set unless fl.main # 本命を決める result.open.push "BadLady1" else if !fl.keep # 手玉に取る result.open.push "BadLady2" # 看板娘 class DrawGirl extends Player type:"DrawGirl" jobname:"看板娘" sleeping:->true dying:(game,found)-> if found=="werewolf" # 狼に噛まれた @setFlag "bitten" else @setFlag "" super deadsunrise:(game)-> # 夜明けで死亡していた場合 if @flag=="bitten" # 噛まれて死亡した場合 game.votingbox.addPunishedNumber 1 log= mode:"system" comment:"#{@name} 是看板娘。今日将有 #{game.votingbox.remains} 人被处刑。" splashlog game.id,game,log @setFlag "" @addGamelog game,"drawgirlpower",null,null # 慎重的狼 class CautiousWolf extends Werewolf type:"CautiousWolf" jobname:"慎重的狼" makeJobSelection:(game)-> if game.night r=super return r.concat { name:"不袭击" value:"" } else return super job:(game,playerid)-> if playerid!="" super return # 不袭击場合 game.werewolf_target.push { from:@id to:"" } game.werewolf_target_remain-- log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚不发动袭击。" splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null # 烟火师 class Pyrotechnist extends Player type:"Pyrotechnist" jobname:"烟火师" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能使用此能力" log= mode:"skill" to:@id comment:"#{@name} 准备释放烟火了。" splashlog game.id,game,log # 使用済 @setFlag "using" null sunset:(game)-> if @flag=="using" log= mode:"system" comment:"美丽的烟火被打上了天空。今晚不能使用能力。" splashlog game.id,game,log @setFlag "done" deadsunset:(game)-> @sunset game checkJobValidity:(game,query)-> if query.jobtype=="Pyrotechnist" # 対象选择は不要 return true return super # 面包店 class Baker extends Player type:"Baker" jobname:"面包店" sleeping:->true sunrise:(game)-> # 最初の1人が面包店ログを管理 bakers=game.players.filter (x)->x.isJobType "Baker" firstBakery=bakers[0] if firstBakery?.id==@id # わ た し だ if bakers.some((x)->!x.dead) # 生存面包店がいる if @flag=="done" @setFlag null log= mode:"system" comment:"面包店烤好了美味的面包。" splashlog game.id,game,log else if @flag!="done" # 全员死亡していてまたログを出していない log= mode:"system" comment:"今天开始没有美味的面包吃了。" splashlog game.id,game,log @setFlag "done" deadsunrise:(game)-> @sunrise game class Bomber extends Madman type:"Bomber" jobname:"炸弹魔" midnightSort:81 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效。" pl.touched game,@id @setTarget playerid @setFlag true # 爆弾を仕掛ける log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 送出了炸弹。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,BombTrapped pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true @addGamelog game,"bomber_set",pl.type,@target null class Blasphemy extends Player type:"Blasphemy" jobname:"亵渎者" team:"Fox" midnightSort:100 sleeping:(game)->@target? || @flag constructor:-> super @setFlag null sunset:(game)-> if @flag @setTarget "" else @setTarget null if @scapegoat # 替身君 alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" beforebury:(game,type)-> if @flag # まだ狐を作ってないときは耐える # 狐が全员死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" job:(game,playerid)-> if @flag || @target? return "已经不能发动能力了" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 亵渎了 #{pl.name}。" splashlog game.id,game,log @addGamelog game,"blasphemy",pl.type,playerid return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # まずい対象だと自己が冒涜される if pl.type in ["Fugitive","QueenSpectator","Liar","Spy2","LoneWolf"] pl=this return if pl.dead @setFlag true # 狐凭をつける newpl=Player.factory null,pl,null,FoxMinion pl.transProfile newpl pl.transform game,newpl,true class Ushinotokimairi extends Madman type:"Ushinotokimairi" jobname:"丑时之女" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineCursed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true @addGamelog game,"ushinotokimairi_curse",pl.type,@target null divined:(game,player)-> if @target? # 能力を使用していた場合は占われると死ぬ @die game,"curse" player.addGamelog game,"cursekill",null,@id super class Patissiere extends Player type: "Patissiere" jobname: "女糕点师" team:"Friend" midnightSort:100 sunset:(game)-> unless @flag? if @scapegoat # 替身君はチョコを配らない @setFlag true @setTarget "" else @setTarget null else @setTarget "" sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能送出巧克力" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的人" pl.touched game,@id @setTarget playerid @setFlag true log= mode: "skill" to: @id comment: "#{@name} 将 #{pl.name} 选为本命。" splashlog game.id, game, log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 全員にチョコを配る(1人本命) alives = game.players.filter((x)->!x.dead).map((x)-> x.id) for pid in alives p = game.getPlayer pid if p.id == pl.id # 本命 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateTrue newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log else if p.id != @id # 義理 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateFalse newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log # 自分は本命と恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag=pl.id top.transProfile newpl top.transferData newpl top.transform game,newpl,true log= mode: "skill" to: @id comment: "#{@name} 与 #{pl.name} 结为恋人。" splashlog game.id, game, log null # 内部処理用:チョコレートもらった class GotChocolate extends Player type: "GotChocolate" jobname: "巧克力" midnightSort:100 sleeping:->true jobdone:(game)-> @flag!="unselected" job_target:0 getTypeDisp:->if @flag=="done" then null else @type makeJobSelection:(game)-> if game.night [] else super sunset:(game)-> if !@flag? # 最初は選択できない @setTarget "" @setFlag "waiting" else if @flag=="waiting" # 選択できるようになった @setFlag "unselected" job:(game,playerid)-> unless @flag == "unselected" return "无法使用能力" # 食べると本命か義理か判明する flag = false top = game.getPlayer @id unless top? # ????? return "对象无效" while top?.isComplex() if top.cmplType=="GotChocolateTrue" && top.sub==this # 本命だ t=game.getPlayer top.cmplFlag if t? log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是本命巧克力。#{@name} 与 #{t.name} 结为恋人。" splashlog game.id, game, log @setFlag "done" # 本命を消す top.uncomplex game, false # 恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag = t.id top.transProfile newpl top.transform game,newpl,true top = game.getPlayer @id flag = true game.ss.publish.user top.id,"refresh",{id:game.id} break else if top.cmplType=="GotChocolateFalse" && top.sub==this # 義理だ @setFlag "selected:#{top.cmplFlag}" flag = true log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是义理巧克力。" splashlog game.id, game, log break top = top.main if flag == false # チョコレートをもらっていなかった log= mode:"skill" to: @id comment: "#{@name} 吃下了巧克力,什么都没有发生。" splashlog game.id, game, log null midnight:(game,midnightSort)-> re = @flag?.match /^selected:(.+)$/ if re? @setFlag "done" @uncomplex game, true # 義理チョコの効果発動 top = game.getPlayer @id r = Math.random() if r < 0.12 # 呪いのチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是被诅咒的巧克力,下一天白天不能发言。" splashlog game.id, game, log newpl = Player.factory null, top, null, Muted top.transProfile newpl top.transform game, newpl, true else if r < 0.30 # ブラックチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是黑巧克力,占卜·灵能结果将变为「LowB」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Blacked top.transProfile newpl top.transform game, newpl, true else if r < 0.45 # ホワイトチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是白巧克力,占卜·灵能结果将变为「母猪」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Whited top.transProfile newpl top.transform game, newpl, true else if r < 0.50 # 毒入りチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是毒巧克力,将被毒死。" splashlog game.id, game, log @die game, "poison", @id else if r < 0.57 # ストーカー化 topl = game.getPlayer re[1] if topl? newpl = Player.factory "Stalker" top.transProfile newpl # ストーカー先 newpl.setFlag re[1] top.transform game, newpl, true log= mode:"skill" to: @id comment: "#{@name} 凭借执念找到了巧克力的送出人,#{@name} 成为了 #{topl.name} 的跟踪狂。" splashlog game.id, game, log else if r < 0.65 # 血入りの…… log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力不知为何有铁锈的味道,占卜结果将变为「吸血鬼」。" splashlog game.id, game, log newpl = Player.factory null, top, null, VampireBlooded top.transProfile newpl top.transform game, newpl, true else if r < 0.75 # 聖職 log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力蕴含着神圣的力量,#{@name} 可以使用一次「圣职者」的力量。" splashlog game.id, game, log sub = Player.factory "Priest" top.transProfile sub newpl = Player.factory null, top, sub, Complex top.transProfile newpl top.transform game, newpl, true class MadDog extends Madman type:"MadDog" jobname:"狂犬" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # 襲撃実行 @setFlag true # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null class Hypnotist extends Madman type:"Hypnotist" jobname:"催眠师" midnightSort:50 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 催眠了 #{pl.name}。" splashlog game.id,game,log @setFlag true null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return if pl.isWerewolf() # LowBを襲撃した場合はLowBの襲撃を無効化する game.werewolf_target = [] game.werewolf_target_remain = 0 # 催眠術を付加する @addGamelog game,"hypnosis",pl.type,pl.id newpl=Player.factory null,pl,null,UnderHypnosis pl.transProfile newpl pl.transform game,newpl,true return null class CraftyWolf extends Werewolf type:"CraftyWolf" jobname:"狡猾的狼" jobdone:(game)->super && @flag == "going" deadJobdone:(game)->@flag != "revivable" midnightSort:100 isReviver:->!@dead || (@flag in ["reviving","revivable"]) sunset:(game)-> super # 生存状態で昼になったら死んだふり能力初期化 @setFlag "" job:(game,playerid,query)-> if query.jobtype!="CraftyWolf" return super if @dead # 死亡時 if @flag != "revivable" return "不能使用能力" @setFlag "reviving" log= mode:"skill" to:@id comment:"#{@name} 取消假死了。" splashlog game.id,game,log return null else # 生存時 if @flag != "" return "已经使用过能力" # 生存フラグを残しつつ死ぬ @setFlag "going" log= mode:"skill" to:@id comment:"#{@name} 假死了。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> if @flag=="going" @die game, "crafty" @addGamelog game,"craftydie" @setFlag "revivable" deadnight:(game,midnightSort)-> if @flag=="reviving" # 生存していた pl = game.getPlayer @id if pl? pl.setFlag "" pl.revive game pl.addGamelog game,"craftyrevive" else # 生存フラグが消えた @setFlag "" makejobinfo:(game,result)-> super result.open ?= [] if @dead && @flag=="revivable" # 死に戻り result.open = result.open.filter (x)->!(x in ["CraftyWolf","_Werewolf"]) result.open.push "CraftyWolf2" return result makeJobSelection:(game)-> if game.night && @dead && @flag=="revivable" # 死んだふりやめるときは選択肢がない [] else if game.night && game.werewolf_target_remain==0 # もう襲撃対象を選択しない [] else super checkJobValidity:(game,query)-> if query.jobtype in ["CraftyWolf","CraftyWolf2"] # 対象選択は不要 return true return super class Shishimai extends Player type:"Shishimai" jobname:"狮子舞" team:"" sleeping:->true jobdone:(game)->@target? isWinner:(game,team)-> # 生存者(自身を除く)を全員噛んだら勝利 alives = game.players.filter (x)->!x.dead bitten = JSON.parse (@flag || "[]") flg = true for pl in alives if pl.id == @id continue unless pl.id in bitten flg = false break return flg sunset:(game)-> alives = game.players.filter (x)->!x.dead if alives.length > 0 @setTarget null if @scapegoat r = Math.floor Math.random()*alives.length @job game, alives[r].id, {} else @setTarget "" job:(game,playerid)-> pl = game.getPlayer playerid unless pl? return "这个玩家不存在。" bitten = JSON.parse (@flag || "[]") if playerid in bitten return "这个玩家已经被咀嚼过了。" log= mode:"skill" to:@id comment:"#{@name} 咀嚼了 #{pl.name}。" splashlog game.id, game, log @setTarget playerid null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 票数が減る祝いをかける newpl = Player.factory null, pl, null, VoteGuarded pl.transProfile newpl pl.transform game, newpl, true newpl.touched game,@id # 噛んだ記録 arr = JSON.parse (@flag || "[]") arr.push newpl.id @setFlag (JSON.stringify arr) # かみかみ @addGamelog game, "shishimaibit", newpl.type, newpl.id null class Pumpkin extends Madman type: "Pumpkin" jobname: "南瓜魔" midnightSort: 90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives = game.players.filter (x)->!x.dead if alives.length == 0 @setTarget "" else r=Math.floor Math.random()*alives.length @job game,alives[r].id ,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid return unless pl? pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 变成了南瓜。" splashlog game.id,game,log @addGamelog game,"pumpkin",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead newpl=Player.factory null, t,null, PumpkinCostumed t.transProfile newpl t.transform game,newpl,true class MadScientist extends Madman type:"MadScientist" jobname:"疯狂科学家" midnightSort:100 isReviver:->!@dead && @flag!="done" sleeping:->true jobdone:->@flag=="done" || @target? job_target: Player.JOB_T_DEAD sunset:(game)-> @setTarget (if game.day<2 || @flag=="done" then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない job:(game,playerid)-> if game.day<2 return "现在还不能发动技能" if @flag == "done" return "已经不能发动技能" pl=game.getPlayer playerid unless pl? return "这个玩家不存在" unless pl.dead return "不能选择这名玩家" @setFlag "done" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 实施了复活手术。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 蘇生 @addGamelog game,"raise",true,pl.id pl.revive game pl = game.getPlayer @target return if pl.dead # 蘇生に成功したら胜利条件を変える newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:newpl.id comment:"#{newpl.name} 变成了狼的仆从。" splashlog game.id,game,log class SpiritPossessed extends Player type:"SpiritPossessed" jobname:"恶灵凭依" isReviver:->!@dead # ============================ # 処理上便宜的に使用 class GameMaster extends Player type:"GameMaster" jobname:"游戏管理员" team:"" jobdone:->false sleeping:->true isWinner:(game,team)->null # 例外的に昼でも発動する可能性がある job:(game,playerid,query)-> pl=game.getPlayer playerid unless pl? return "对象无效" pl.die game,"gmpunish" game.bury("other") null isListener:(game,log)->true # 全て見える getSpeakChoice:(game)-> pls=for pl in game.players "gmreply_#{pl.id}" ["gm","gmheaven","gmaudience","gmmonologue"].concat pls getSpeakChoiceDay:(game)->@getSpeakChoice game chooseJobDay:(game)->true # 昼でも対象选择 # 帮手 class Helper extends Player type:"Helper" jobname:"帮手" team:"" jobdone:->@flag? sleeping:->true voted:(game,votingbox)->true isWinner:(game,team)-> pl=game.getPlayer @flag return pl?.isWinner game,team # @flag: リッスン対象のid # 同じものが見える isListener:(game,log)-> pl=game.getPlayer @flag unless pl? # 自律行動帮手? return super if pl.isJobType "Helper" # 帮手の帮手の場合は听不到(無限ループ防止) return false return pl.isListener game,log getSpeakChoice:(game)-> if @flag? return ["helperwhisper_#{@flag}"] else return ["helperwhisper"] getSpeakChoiceDay:(game)->@getSpeakChoice game job:(game,playerid)-> if @flag? return "已经决定了帮助对象" pl=game.getPlayer playerid unless pl? return "帮助对象不存在" @flag=playerid log= mode:"skill" to:playerid comment:"#{@name} 成为了 #{pl.name} 的帮手。" splashlog game.id,game,log # 自己の表記を改める game.splashjobinfo [this] null makejobinfo:(game,result)-> super # ヘルプ先が分かる pl=game.getPlayer @flag if pl? helpedinfo={} pl.makejobinfo game,helpedinfo result.supporting=pl?.publicinfo() result.supportingJob=pl?.getJobDisp() for value in Shared.game.jobinfos if helpedinfo[value.name]? result[value.name]=helpedinfo[value.name] null # 开始前のやつだ!!!!!!!! class Waiting extends Player type:"Waiting" jobname:"尚未分配" team:"" sleeping:(game)->!game.rolerequestingphase || game.rolerequesttable[@id]? isListener:(game,log)-> if log.mode=="audience" true else super getSpeakChoice:(game)-> return ["prepare"] makejobinfo:(game,result)-> super # 自己で追加する result.open.push "Waiting" makeJobSelection:(game)-> if game.day==0 && game.rolerequestingphase # 开始前 result=[{ name:"放弃选择" value:"" }] for job,num of game.joblist if num result.push { name:Shared.game.getjobname job value:job } return result else super job:(game,target)-> # 希望职业 game.rolerequesttable[@id]=target if target log= mode:"skill" to:@id comment:"#{@name} 希望成为 #{Shared.game.getjobname target}。" else log= mode:"skill" to:@id comment:"#{@name} 放弃选择职业。" splashlog game.id,game,log null # Endless黑暗火锅でまだ入ってないやつ class Watching extends Player type:"Watching" jobname:"观战者" team:"" sleeping:(game)->true isWinner:(game,team)->true isListener:(game,log)-> if log.mode in ["audience","inlog"] # 参加前なので true else super getSpeakChoice:(game)-> return ["audience"] getSpeakChoiceDay:(game)-> return ["audience"] # 複合职业 Player.factoryで適切に生成されることを期待 # superはメイン职业 @mainにメイン @subにサブ # @cmplFlag も持っていい class Complex cmplType:"Complex" # 複合親そのものの名字 isComplex:->true getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() midnightSort: 100 #@mainのやつを呼ぶ mcall:(game,method,args...)-> if @main.isComplex() # そのまま return method.apply @main,args # 他は親が必要 top=game.participants.filter((x)=>x.id==@id)[0] if top? return method.apply top,args return null setDead:(@dead,@found)-> @main.setDead @dead,@found @sub?.setDead @dead,@found setWinner:(@winner)->@main.setWinner @winner setTarget:(@target)->@main.setTarget @target setFlag:(@flag)->@main.setFlag @flag setWill:(@will)->@main.setWill @will setOriginalType:(@originalType)->@main.setOriginalType @originalType setOriginalJobname:(@originalJobname)->@main.setOriginalJobname @originalJobname setNorevive:(@norevive)->@main.setNorevive @norevive jobdone:(game)-> @mcall(game,@main.jobdone,game) && (!@sub?.jobdone? || @sub.jobdone(game)) # ジョブの場合はサブも考慮 job:(game,playerid,query)-> # どちらの # query.jobtypeがない場合は内部処理なのでmainとして処理する? unless query? query={} unless query.jobtype? query.jobtype=@main.type if @main.isJobType(query.jobtype) && ((@main.dead && !@main.deadJobdone(game)) || (!@main.dead && !@main.jobdone(game))) @mcall game,@main.job,game,playerid,query else if @sub?.isJobType?(query.jobtype) && ((@sub.dead && !@sub.deadJobdone(game)) || (!@sub.dead && !@sub?.jobdone?(game))) @sub.job? game,playerid,query # Am I Walking Dead? isDead:-> isMainDead = @main.isDead() if isMainDead.dead && isMainDead.found # Dead! return isMainDead if @sub? isSubDead = @sub.isDead() if isSubDead.dead && isSubDead.found # Dead! return isSubDead # seems to be alive, who knows? return {dead:@dead,found:@found} isJobType:(type)-> @main.isJobType(type) || @sub?.isJobType?(type) getTeam:-> if @team then @team else @main.getTeam() #An access to @main.flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" unless @isJobType(type) return null if @main.isJobType(type) return @main.accessByJobType(type) else unless @sub? return null return @sub.accessByJobType(type) null gatherMidnightSort:-> mids=[@midnightSort] mids=mids.concat @main.gatherMidnightSort() if @sub? mids=mids.concat @sub.gatherMidnightSort() return mids sunset:(game)-> @mcall game,@main.sunset,game @sub?.sunset? game midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort deadnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.deadnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.deadnight? game,midnightSort deadsunset:(game)-> @mcall game,@main.deadsunset,game @sub?.deadsunset? game deadsunrise:(game)-> @mcall game,@main.deadsunrise,game @sub?.deadsunrise? game sunrise:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game votestart:(game)-> @mcall game,@main.votestart,game voted:(game,votingbox)->@mcall game,@main.voted,game,votingbox dovote:(game,target)-> @mcall game,@main.dovote,game,target voteafter:(game,target)-> @mcall game,@main.voteafter,game,target @sub?.voteafter game,target modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote @mcall game, @main.modifyMyVote, game, vote makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result,@main.getJobDisp() beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type # deal with Walking Dead unless @dead isPlDead = @isDead() if isPlDead.dead && isPlDead.found @setDead isPlDead.dead,isPlDead.found divined:(game,player)-> @mcall game,@main.divined,game,player @sub?.divined? game,player getjob_target:-> if @sub? @main.getjob_target() | @sub.getjob_target() # ビットフラグ else @main.getjob_target() die:(game,found,from)-> @mcall game,@main.die,game,found,from dying:(game,found,from)-> @mcall game,@main.dying,game,found,from @sub?.dying game,found,from revive:(game)-> # まずsubを蘇生 if @sub? @sub.revive game if @sub.dead # 蘇生できない類だ return # 次にmainを蘇生 @mcall game,@main.revive,game if @main.dead # 蘇生できなかった @setDead true, @main.found else # 蘇生できた @setDead false, null makeJobSelection:(game)-> result=@mcall game,@main.makeJobSelection,game if @sub? for obj in @sub.makeJobSelection game unless result.some((x)->x.value==obj.value) result.push obj result checkJobValidity:(game,query)-> if query.jobtype=="_day" return @mcall(game,@main.checkJobValidity,game,query) if @mcall(game,@main.isJobType,query.jobtype) && !@mcall(game,@main.jobdone,game) return @mcall(game,@main.checkJobValidity,game,query) else if @sub?.isJobType?(query.jobtype) && !@sub?.jobdone?(game) return @sub.checkJobValidity game,query else return true getSpeakChoiceDay:(game)-> result=@mcall game,@main.getSpeakChoiceDay,game if @sub? for obj in @sub.getSpeakChoiceDay game unless result.some((x)->x==obj) result.push obj result getSpeakChoice:(game)-> result=@mcall game,@main.getSpeakChoice,game if @sub? for obj in @sub.getSpeakChoice game unless result.some((x)->x==obj) result.push obj result isListener:(game,log)-> @mcall(game,@main.isListener,game,log) || @sub?.isListener(game,log) isReviver:->@main.isReviver() || @sub?.isReviver() isHuman:->@main.isHuman() isWerewolf:->@main.isWerewolf() isFox:->@main.isFox() isVampire:->@main.isVampire() isWinner:(game,team)->@main.isWinner game, team #superがつかえないので注意 class Friend extends Complex # 恋人 # cmplFlag: 相方のid cmplType:"Friend" isFriend:->true team:"Friend" getJobname:->"恋人(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type ato=false if game.rule.friendssplit=="split" # 独立 pl=game.getPlayer @cmplFlag if pl? && pl.dead && pl.isFriend() ato=true else # みんな friends=game.players.filter (x)->x.isFriend() #恋人たち if friends.length>1 && friends.some((x)->x.dead) ato=true # 恋人が誰か死んだら自殺 if ato @die game,"friendsuicide" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"恋人" type:"Friend" } if game.rule.friendssplit=="split" # 独立 fr=[this,game.getPlayer(@cmplFlag)].filter((x)->x?.isFriend()).map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr else # みんないっしょ result.friends=game.players.filter((x)->x.isFriend()).map (x)-> x.publicinfo() isWinner:(game,team)->@team==team && !@dead # 相手のIDは? getPartner:-> if @cmplType=="Friend" return @cmplFlag else return @main.getPartner() # 圣职者にまもられた人 class HolyProtected extends Complex # cmplFlag: 护卫元 cmplType:"HolyProtected" die:(game,found)-> # 一回耐える 死なない代わりに元に戻る log= mode:"skill" to:@id comment:"#{@name} 被神圣的力量守护了。" splashlog game.id,game,log game.getPlayer(@cmplFlag).addGamelog game,"holyGJ",found,@id @uncomplex game # カルトの信者になった人 class CultMember extends Complex cmplType:"CultMember" isCult:->true getJobname:->"教会信者(#{@main.getJobname()})" getJobDisp:->"教会信者(#{@main.getJobDisp()})" makejobinfo:(game,result)-> super # 信者の説明 result.desc?.push { name:"教会信者" type:"CultMember" } # 猎人に守られた人 class Guarded extends Complex # cmplFlag: 护卫元ID cmplType:"Guarded" die:(game,found,from)-> unless found in ["werewolf","vampire"] @mcall game,@main.die,game,found,from else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"GJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 成功守护了 #{@name}。" splashlog game.id,game,log sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunrise,game # 黙らされた人 class Muted extends Complex cmplType:"Muted" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game game.ss.publish.user @id,"refresh",{id:game.id} getSpeakChoiceDay:(game)-> ["monologue"] # 全员に喋ることができない # 狼的仆从 class WolfMinion extends Complex cmplType:"WolfMinion" team:"Werewolf" getJobname:->"狼的仆从(#{@main.getJobname()})" getJobDisp:->"狼的仆从(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"狼的仆从" type:"WolfMinion" } isWinner:(game,team)->@team==team # 酒鬼 class Drunk extends Complex cmplType:"Drunk" getJobname:->"酒鬼(#{@main.getJobname()})" getTypeDisp:->"Human" getJobDisp:->"母猪" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunset:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game if game.day>=3 # 3日目に目が覚める log= mode:"skill" to:@id comment:"#{@name} 酒醒了。" splashlog game.id,game,log @uncomplex game game.ss.publish.user @realid,"refresh",{id:game.id} makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj isDrunk:->true getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 陷阱师守られた人 class TrapGuarded extends Complex # cmplFlag: 护卫元ID cmplType:"TrapGuarded" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 return if midnightSort != @midnightSort wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 狩人がいた!(罠も無効) wholepl = game.getPlayer @id @checkTrap game, wholepl # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag # 罠し if tr? tr.addGamelog game,"trappedGuard",null,@id gu.die game,"trap" pl.uncomplex game # 消滅 # 子の調査を継続 @checkGuard game,pl.main return true checkTrap:(game,pl)-> # TrapGuardedも消す return unless pl.isComplex() if pl.cmplType=="TrapGuarded" pl.uncomplex game @checkTrap game, pl.main else @checkTrap game, pl.main if pl.sub? @checkTrap game, pl.sub die:(game,found,from)-> unless found in ["werewolf","vampire"] # 狼以外だとしぬ @mcall game,@main.die,game,found else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"trapGJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 的陷阱成功守护了 #{@name}。" splashlog game.id,game,log # 反撃する canbedead=[] ft=game.getPlayer from if ft.isWerewolf() canbedead=game.players.filter (x)->!x.dead && x.isWerewolf() else if ft.isVampire() canbedead=game.players.filter (x)->!x.dead && x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"trap" @addGamelog game,"trapkill",null,pl.id sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game # 黙らされた人 class Lycanized extends Complex cmplType:"Lycanized" fortuneResult:"LowB" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 策士によって更生させられた人 class Counseled extends Complex cmplType:"Counseled" team:"Human" getJobname:->"更生者(#{@main.getJobname()})" getJobDisp:->"更生者(#{@main.getJobDisp()})" isWinner:(game,team)->@team==team makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"更生者" type:"Counseled" } # 巫女のガードがある状态 class MikoProtected extends Complex cmplType:"MikoProtected" die:(game,found)-> # 耐える game.getPlayer(@id).addGamelog game,"mikoGJ",found sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 威嚇するLowBに威嚇された class Threatened extends Complex cmplType:"Threatened" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunrise:(game)-> # この昼からは戻る @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game sunset:(game)-> midnight:(game,midnightSort)-> job:(game,playerid,query)-> null dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 碍事的狂人に邪魔された(未完成) class DivineObstructed extends Complex # cmplFlag: 邪魔元ID cmplType:"DivineObstructed" sunset:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunset,game # 占いの影響なし divineeffect:(game)-> showdivineresult:(game)-> # 结果がでなかった pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,但是被不知道什么人妨碍了。" splashlog game.id,game,log dodivine:(game)-> # 占おうとした。邪魔成功 obstmad=game.getPlayer @cmplFlag if obstmad? obstmad.addGamelog game,"divineObstruct",null,@id class PhantomStolen extends Complex cmplType:"PhantomStolen" # cmplFlag: 保存されたアレ sunset:(game)-> # 夜になると怪盗になってしまう!!!!!!!!!!!! @sub?.sunrise? game newpl=Player.factory "Phantom" # アレがなぜか狂ってしまうので一時的に保存 saved=@originalJobname @uncomplex game pl=game.getPlayer @id pl.transProfile newpl pl.transferData newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 的职业被盗走了,变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 夜の初期化 pl=game.getPlayer @id pl.setOriginalJobname saved pl.setFlag true # もう盗めない pl.sunset game getJobname:->"怪盗" #灵界とかでは既に怪盗化 # 胜利条件関係は母猪化(昼の間だけだし) isWerewolf:->false isFox:->false isVampire:->false #team:"Human" #女王との兼ね合いで isWinner:(game,team)-> team=="Human" die:(game,found,from)-> # 抵抗もなく死ぬし if found=="punish" Player::die.apply this,arguments else super dying:(game,found)-> makejobinfo:(game,obj)-> super for key,value of @cmplFlag obj[key]=value class KeepedLover extends Complex # 恶女に手玉にとられた(見た目は恋人) # cmplFlag: 相方のid cmplType:"KeepedLover" getJobname:->"手玉(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"恋人" type:"Friend" } # 恋人だと思い込む fr=[this,game.getPlayer(@cmplFlag)].map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr # 花火を見ている class WatchingFireworks extends Complex # cmplFlag: 烟火师のid cmplType:"WatchingFireworks" sleeping:->true jobdone:->true sunrise:(game)-> @sub?.sunrise? game # もう终了 @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game deadsunrise:(game)->@sunrise game makejobinfo:(game,result)-> super result.watchingfireworks=true # 炸弹魔に爆弾を仕掛けられた人 class BombTrapped extends Complex # cmplFlag: 护卫元ID cmplType:"BombTrapped" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 if midnightSort != @midnightSort then return wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 猎人がいた!(罠も無効) @uncomplex game # bomb would explode for only once deadsunrise:(game)-> super @uncomplex game # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag #炸弹魔 if tr? tr.addGamelog game,"bombTrappedGuard",null,@id # 护卫元が死ぬ gu.die game,"bomb" # 自己も死ぬ @die game,"bomb" pl.uncomplex game # 罠は消滅 # 子の調査を継続 @checkGuard game,pl.main return true die:(game,found,from)-> if found=="punish" # 处刑された場合は处刑者の中から選んでしぬ # punishのときはfromがidの配列 if from? && from.length>0 pls=from.map (id)->game.getPlayer id pls=pls.filter (x)->!x.dead if pls.length>0 r=Math.floor Math.random()*pls.length pl=pls[r] if pl? pl.die game,"bomb" @addGamelog game,"bombkill",null,pl.id else if found in ["werewolf","vampire"] # 狼に噛まれた場合は襲撃者を巻き添えにする bomber=game.getPlayer @cmplFlag if bomber? bomber.addGamelog game,"bompGJ",null,@id # 反撃する wl=game.getPlayer from if wl? wl.die game,"bomb" @addGamelog game,"bombkill",null,wl.id # 自己もちゃんと死ぬ @mcall game,@main.die,game,found,from # 狐凭 class FoxMinion extends Complex cmplType:"FoxMinion" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true getJobname:->"狐凭(#{@main.getJobname()})" # 占われたら死ぬ divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # 丑时之女に呪いをかけられた class DivineCursed extends Complex cmplType:"DivineCursed" sunset:(game)-> # 1日で消える @uncomplex game @mcall game,@main.sunset,game divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # パティシエールに本命チョコをもらった class GotChocolateTrue extends Friend cmplType:"GotChocolateTrue" getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() getPartner:-> if @cmplType=="GotChocolateTrue" return @cmplFlag else return @main.getPartner() makejobinfo:(game,result)-> # 恋人情報はでない @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 本命ではない class GotChocolateFalse extends Complex cmplType:"GotChocolateFalse" # 黒になった class Blacked extends Complex cmplType:"Blacked" fortuneResult: "LowB" psychicResult:"LowB" # 白になった class Whited extends Complex cmplType:"Whited" fortuneResult: "母猪" psychicResult:"母猪" # 占い結果吸血鬼化 class VampireBlooded extends Complex cmplType:"VampireBlooded" fortuneResult: "吸血鬼" # 催眠術をかけられた class UnderHypnosis extends Complex cmplType:"UnderHypnosis" sunrise:(game)-> # 昼になったら戻る @uncomplex game pl=game.getPlayer @id if pl? pl.sunrise game midnight:(game,midnightSort)-> die:(game,found,from)-> Human.prototype.die.call @,game,found,from dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> # 狮子舞の加護 class VoteGuarded extends Complex cmplType:"VoteGuarded" modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote vote = @mcall game, @main.modifyMyVote, game, vote # 自分への投票を1票減らす if vote.votes > 0 vote.votes-- vote # 南瓜魔の呪い class PumpkinCostumed extends Complex cmplType:"PumpkinCostumed" fortuneResult: "南瓜" # 决定者 class Decider extends Complex cmplType:"Decider" getJobname:->"#{@main.getJobname()}(决定者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePriority this,1 #優先度を1上げる null # 权力者 class Authority extends Complex cmplType:"Authority" getJobname:->"#{@main.getJobname()}(权力者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePower this,1 #票をひとつ増やす null # 炼成LowBの职业 class Chemical extends Complex cmplType:"Chemical" getJobname:-> if @sub? "#{@main.getJobname()}×#{@sub.getJobname()}" else @main.getJobname() getJobDisp:-> if @sub? "#{@main.getJobDisp()}×#{@sub.getJobDisp()}" else @main.getJobDisp() sleeping:(game)->@main.sleeping(game) && (!@sub? || @sub.sleeping(game)) jobdone:(game)->@main.jobdone(game) && (!@sub? || @sub.jobdone(game)) isHuman:-> if @sub? @main.isHuman() && @sub.isHuman() else @main.isHuman() isWerewolf:-> @main.isWerewolf() || @sub?.isWerewolf() isFox:-> @main.isFox() || @sub?.isFox() isFoxVisible:-> @main.isFoxVisible() || @sub?.isFoxVisible() isVampire:-> @main.isVampire() || @sub?.isVampire() isAttacker:-> @main.isAttacker?() || @sub?.isAttacker?() humanCount:-> if @isFox() 0 else if @isWerewolf() 0 else if @isHuman() 1 else 0 werewolfCount:-> if @isFox() 0 else if @isWerewolf() if @sub? @main.werewolfCount() + @sub.werewolfCount() else @main.werewolfCount() else 0 vampireCount:-> if @isFox() 0 else if @isVampire() if @sub? @main.vampireCount() + @sub.vampireCount() else @main.vampireCount() else 0 getFortuneResult:-> fsm = @main.getFortuneResult() fss = @sub?.getFortuneResult() if "吸血鬼" in [fsm, fss] "吸血鬼" else if "LowB" in [fsm, fss] "LowB" else "母猪" getPsychicResult:-> fsm = @main.getPsychicResult() fss = @sub?.getPsychicResult() if "LowB" in [fsm, fss] "LowB" else "母猪" getTeam:-> myt = null maint = @main.getTeam() subt = @sub?.getTeam() if maint=="Cult" || subt=="Cult" myt = "Cult" else if maint=="Friend" || subt=="Friend" myt = "Friend" else if maint=="Fox" || subt=="Fox" myt = "Fox" else if maint=="Vampire" || subt=="Vampire" myt = "Vampire" else if maint=="Werewolf" || subt=="Werewolf" myt = "Werewolf" else if maint=="LoneWolf" || subt=="LoneWolf" myt = "LoneWolf" else if maint=="Human" || subt=="Human" myt = "Human" else myt = "" return myt isWinner:(game,team)-> myt = @getTeam() win = false maint = @main.getTeam() sunt = @sub?.getTeam() if maint == myt || maint == "" || maint == "Devil" win = win || @main.isWinner(game,team) if subt == myt || subt == "" || subt == "Devil" win = win || @sub.isWinner(game,team) return win die:(game, found, from)-> return if @dead if found=="werewolf" && (!@main.willDieWerewolf || (@sub? && !@sub.willDieWerewolf)) # LowBに対する襲撃耐性 return # main, subに対してdieをsimulateする(ただしdyingはdummyにする) d = Object.getOwnPropertyDescriptor(this, "dying") @dying = ()-> null # どちらかが耐えたら耐える @main.die game, found, from isdead = @dead @setDead false, null if @sub? @sub.die game, found, from isdead = isdead && @dead if d? Object.defineProperty this, "dying", d else delete @dying # XXX duplicate pl=game.getPlayer @id if isdead pl.setDead true, found pl.dying game, found, from else pl.setDead false, null touched:(game, from)-> @main.touched game, from @sub?.touched game, from makejobinfo:(game,result)-> @main.makejobinfo game,result @sub?.makejobinfo? game,result # 女王観戦者は母猪陣営×母猪陣営じゃないと見えない if result.queens? && (@main.getTeam() != "Human" || @sub?.getTeam() != "Human") delete result.queens # 陣営情報 result.myteam = @getTeam() games={} # 游戏のGC new cron.CronJob("0 0 * * * *", -> # いらないGameを消す tm=Date.now()-3600000 # 1时间前 games_length_b = 0 for id,game of games games_length_b++ for id,game of games if game.finished # 終わっているやつが消す候補 if (!game.last_time?) || (game.last_time<tm) # 十分古い console.log "delete game:"+id delete games[id] games_length_a = 0 for id,game of games games_length_a++ console.log "length of games before:"+games_length_b console.log "length of games after :"+games_length_a , null, true, "Asia/Shanghai") # 游戏を得る getGame=(id)-> # 仕事一览 jobs= Human:Human Werewolf:Werewolf Diviner:Diviner Psychic:Psychic Madman:Madman Guard:Guard Couple:Couple Fox:Fox Poisoner:Poisoner BigWolf:BigWolf TinyFox:TinyFox Bat:Bat Noble:Noble Slave:Slave Magician:Magician Spy:Spy WolfDiviner:WolfDiviner Fugitive:Fugitive Merchant:Merchant QueenSpectator:QueenSpectator MadWolf:MadWolf Neet:Neet Liar:Liar Spy2:Spy2 Copier:Copier Light:Light Fanatic:Fanatic Immoral:Immoral Devil:Devil ToughGuy:ToughGuy Cupid:Cupid Stalker:Stalker Cursed:Cursed ApprenticeSeer:ApprenticeSeer Diseased:Diseased Spellcaster:Spellcaster Lycan:Lycan Priest:Priest Prince:Prince PI:PI Sorcerer:Sorcerer Doppleganger:Doppleganger CultLeader:CultLeader Vampire:Vampire LoneWolf:LoneWolf Cat:Cat Witch:Witch Oldman:Oldman Tanner:Tanner OccultMania:OccultMania MinionSelector:MinionSelector WolfCub:WolfCub WhisperingMad:WhisperingMad Lover:Lover Thief:Thief Dog:Dog Dictator:Dictator SeersMama:SeersMama Trapper:Trapper WolfBoy:WolfBoy Hoodlum:Hoodlum QuantumPlayer:QuantumPlayer RedHood:RedHood Counselor:Counselor Miko:Miko GreedyWolf:GreedyWolf FascinatingWolf:FascinatingWolf SolitudeWolf:SolitudeWolf ToughWolf:ToughWolf ThreateningWolf:ThreateningWolf HolyMarked:HolyMarked WanderingGuard:WanderingGuard ObstructiveMad:ObstructiveMad TroubleMaker:TroubleMaker FrankensteinsMonster:FrankensteinsMonster BloodyMary:BloodyMary King:King PsychoKiller:PsychoKiller SantaClaus:SantaClaus Phantom:Phantom BadLady:BadLady DrawGirl:DrawGirl CautiousWolf:CautiousWolf Pyrotechnist:Pyrotechnist Baker:Baker Bomber:Bomber Blasphemy:Blasphemy Ushinotokimairi:Ushinotokimairi Patissiere:Patissiere GotChocolate:GotChocolate MadDog:MadDog Hypnotist:Hypnotist CraftyWolf:CraftyWolf Shishimai:Shishimai Pumpkin:Pumpkin MadScientist:MadScientist SpiritPossessed:SpiritPossessed # 特殊 GameMaster:GameMaster Helper:Helper # 开始前 Waiting:Waiting Watching:Watching complexes= Complex:Complex Friend:Friend HolyProtected:HolyProtected CultMember:CultMember Guarded:Guarded Muted:Muted WolfMinion:WolfMinion Drunk:Drunk Decider:Decider Authority:Authority TrapGuarded:TrapGuarded Lycanized:Lycanized Counseled:Counseled MikoProtected:MikoProtected Threatened:Threatened DivineObstructed:DivineObstructed PhantomStolen:PhantomStolen KeepedLover:KeepedLover WatchingFireworks:WatchingFireworks BombTrapped:BombTrapped FoxMinion:FoxMinion DivineCursed:DivineCursed GotChocolateTrue:GotChocolateTrue GotChocolateFalse:GotChocolateFalse Blacked:Blacked Whited:Whited VampireBlooded:VampireBlooded UnderHypnosis:UnderHypnosis VoteGuarded:VoteGuarded Chemical:Chemical PumpkinCostumed:PumpkinCostumed # 役職ごとの強さ jobStrength= Human:5 Werewolf:40 Diviner:25 Psychic:15 Madman:10 Guard:23 Couple:10 Fox:25 Poisoner:20 BigWolf:80 TinyFox:10 Bat:10 Noble:12 Slave:5 Magician:14 Spy:14 WolfDiviner:60 Fugitive:8 Merchant:18 QueenSpectator:20 MadWolf:40 Neet:50 Liar:8 Spy2:5 Copier:10 Light:30 Fanatic:20 Immoral:5 Devil:20 ToughGuy:11 Cupid:37 Stalker:10 Cursed:2 ApprenticeSeer:23 Diseased:16 Spellcaster:6 Lycan:5 Priest:17 Prince:17 PI:23 Sorcerer:14 Doppleganger:15 CultLeader:10 Vampire:40 LoneWolf:28 Cat:22 Witch:23 Oldman:4 Tanner:15 OccultMania:10 MinionSelector:0 WolfCub:70 WhisperingMad:20 Lover:25 Thief:0 Dog:7 Dictator:18 SeersMama:15 Trapper:13 WolfBoy:11 Hoodlum:5 QuantumPlayer:0 RedHood:16 Counselor:25 Miko:14 GreedyWolf:60 FascinatingWolf:52 SolitudeWolf:20 ToughWolf:55 ThreateningWolf:50 HolyMarked:6 WanderingGuard:10 ObstructiveMad:19 TroubleMaker:15 FrankensteinsMonster:50 BloodyMary:5 King:15 PsychoKiller:25 SantaClaus:20 Phantom:15 BadLady:30 DrawGirl:10 CautiousWolf:45 Pyrotechnist:20 Baker:16 Bomber:23 Blasphemy:10 Ushinotokimairi:19 Patissiere:10 MadDog:19 Hypnotist:17 CraftyWolf:48 Shishimai:10 Pumpkin:17 MadScientist:20 SpiritPossessed:4 module.exports.actions=(req,res,ss)-> req.use 'user.fire.wall' req.use 'session' #游戏开始処理 #成功:null gameStart:(roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return Server.game.rooms.oneRoomS roomid,(room)-> if room.error? res room.error return unless room.mode=="waiting" # すでに开始している res "游戏已经开始" return if room.players.some((x)->!x.start) res "全员尚未全部准备好" return if room.gm!=true && query.yaminabe_hidejobs!="" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"]) res "「配置公开」选项在黑暗火锅模式下,只有在有GM的房间才能使用" return # ルールオブジェクト用意 ruleobj={ number: room.players.length maxnumber:room.number blind:room.blind gm:room.gm day: parseInt(parseInt(query.day_minute)*60+parseInt(query.day_second)) night: parseInt(parseInt(query.night_minute)*60+parseInt(query.night_second)) remain: parseInt(parseInt(query.remain_minute)*60+parseInt(query.remain_second)) # (n=15)秒规则 silentrule: parseInt(query.silentrule) ? 0 } unless ruleobj.day && ruleobj.night && ruleobj.remain res "时间长度不是有效数字,或总时长为零。" return options={} # 选项ズ for opt in ["decider","authority","yaminabe_hidejobs"] options[opt]=query[opt] ? null joblist={} for job of jobs joblist[job]=0 # 一旦初期化 #frees=room.players.length # 参加者の数 # プレイヤーと其他に分類 players=[] supporters=[] for pl in room.players if pl.mode=="player" if players.filter((x)->x.realid==pl.realid).length>0 res "#{pl.name} 重复加入,游戏无法开始。" return players.push pl else supporters.push pl frees=players.length if query.scapegoat=="on" # 替身君 frees++ playersnumber=frees # 人数の確認 if frees<6 res "人数不足,不能开始。含替身君最少要有6人。" return if query.jobrule=="特殊规则.量子LowB" && frees>=20 # 多すぎてたえられない res "人数过多。量子LowB的人数应当在19人以下。" return # 炼成LowBの場合 if query.chemical=="on" # 黑暗火锅と量子LowBは無理 if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅","特殊规则.量子LowB"] res "本规则「#{query.jobrule}」无法使用炼成LowB。" return ruleinfo_str="" # 开始告知 if query.jobrule in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] # 自由のときはクエリを参考にする for job in Shared.game.jobs joblist[job]=parseInt(query[job]) || 0 # 仕事の数 # カテゴリも for type of Shared.game.categoryNames joblist["category_#{type}"]=parseInt(query["category_#{type}"]) || 0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] # カテゴリ内の人数の合計がわかる関数 countCategory=(categoryname)-> Shared.game.categories[categoryname].reduce(((prev,curr)->prev+(joblist[curr] ? 0)),0)+joblist["category_#{categoryname}"] # 黑暗火锅のときはランダムに決める pls=frees # プレイヤーの数をとっておく plsh=Math.floor pls/2 # 過半数 if query.jobrule=="特殊规则.手调黑暗火锅" # 手调黑暗火锅のときは母猪のみ黑暗火锅 frees=joblist.Human ? 0 joblist.Human=0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist safety={ jingais:false # 人外の数を調整 teams:false # 阵营の数を調整 jobs:false # 職どうしの数を調整 strength:false # 職の強さも考慮 reverse:false # 職の強さが逆 } switch query.yaminabe_safety when "low" # 低い safety.jingais=true when "middle" safety.jingais=true safety.teams=true when "high" safety.jingais=true safety.teams=true safety.jobs=true when "super" safety.jingais=true safety.teams=true safety.jobs=true safety.strength=true when "supersuper" safety.jobs=true safety.strength=true when "reverse" safety.jingais=true safety.strength=true safety.reverse=true # 黑暗火锅のときは入れないのがある exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] # ユーザーが指定した入れないの excluded_exceptions=[] # チェックボックスが外れてるやつは登場しない if query.jobrule=="特殊规则.手调黑暗火锅" for job in Shared.game.jobs if query["job_use_#{job}"] != "on" # これは出してはいけない指定になっている exceptions.push job excluded_exceptions.push job # メアリーの特殊処理(セーフティ高じゃないとでない) if query.yaminabe_hidejobs=="" || !safety.jobs exceptions.push "BloodyMary" # 悪霊憑き(人気がないので出ない) if safety.jingais || safety.jobs exceptions.push "SpiritPossessed" unless query.jobrule=="特殊规则.手调黑暗火锅" && countCategory("Werewolf")>0 #人外の数 if safety.jingais # いい感じに決めてあげる wolf_number=1 fox_number=0 vampire_number=0 devil_number=0 if frees>=9 wolf_number++ if frees>=12 if Math.random()<0.6 fox_number++ else if Math.random()<0.7 devil_number++ if frees>=14 wolf_number++ if frees>=16 if Math.random()<0.5 fox_number++ else if Math.random()<0.3 vampire_number++ else devil_number++ if frees>=18 wolf_number++ if frees>=22 if Math.random()<0.2 fox_number++ else if Math.random()<0.6 vampire_number++ else if Math.random()<0.9 devil_number++ if frees>=24 wolf_number++ if frees>=30 wolf_number++ # ランダム調整 if wolf_number>1 && Math.random()<0.1 wolf_number-- else if frees>0 && playersnumber>=10 && Math.random()<0.2 wolf_number++ if fox_number>1 && Math.random()<0.15 fox_number-- else if frees>=11 && Math.random()<0.25 fox_number++ else if frees>=8 && Math.random()<0.1 fox_number++ if frees>=11 && Math.random()<0.2 vampire_number++ if frees>=11 && Math.random()<0.2 devil_number++ # セットする if joblist.category_Werewolf>0 frees+=joblist.category_Werewolf joblist.category_Werewolf=wolf_number frees -= wolf_number if joblist.Fox>0 frees+=joblist.Fox if joblist.TinyFox>0 frees+=joblist.TinyFox if joblist.Blasphemy>0 frees+=joblist.Blasphemy joblist.Fox=0 joblist.TinyFox=0 joblist.Blasphemy=0 # 除外役職を入れないように気をつける nonavs = {} for job in exceptions nonavs[job] = true # 狐を振分け for i in [0...fox_number] if frees <= 0 break r = Math.random() if r<0.55 && !nonavs.Fox joblist.Fox++ frees-- else if r<0.85 && !nonavs.TinyFox joblist.TinyFox++ frees-- else if !nonavs.Blasphemy joblist.Blasphemy++ frees-- if joblist.Vampire>0 frees+=joblist.Vampire if vampire_number <= frees joblist.Vampire = vampire_number frees -= vampire_number else joblist.Vampire = frees frees = 0 if joblist.Devil>0 frees+=joblist.Devil if devil_number <= frees joblist.Devil = devil_number frees -= devil_number else joblist.Devil = frees frees = 0 # 人外は選んだのでもう選ばれなくする exceptions=exceptions.concat Shared.game.nonhumans exceptions.push "Blasphemy" else # 調整しない joblist.category_Werewolf=1 frees-- if safety.jingais || safety.jobs if joblist.Fox==0 && joblist.TinyFox==0 exceptions.push "Immoral" # 狐がいないのに背徳は出ない nonavs = {} for job in exceptions nonavs[job] = true if safety.teams # 阵营調整もする # 恋人阵营 if frees>0 if 17>=playersnumber>=12 if Math.random()<0.15 && !nonavs.Cupid joblist.Cupid++ frees-- else if Math.random()<0.12 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.BadLady joblist.BadLady++ frees-- else if playersnumber>=8 if Math.random()<0.15 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.Cupid joblist.Cupid++ frees-- # 妖狐陣営 if frees>0 && joblist.Fox>0 if joblist.Fox==1 if playersnumber>=14 # 1人くらいは… if Math.random()<0.3 && !nonavs.Immoral joblist.Immoral++ frees-- else # サプライズ的に… if Math.random()<0.1 && !nonavs.Immoral joblist.Immoral++ frees-- exceptions.push "Immoral" # LowB阵营 if frees>0 wolf_number = countCategory "Werewolf" if wolf_number<=playersnumber/8 # 確定狂人サービス joblist.category_Madman ?= 0 joblist.category_Madman++ frees-- # 占い確定 if safety.teams || safety.jobs # 母猪阵营 if frees>0 # 占い師いてほしい if Math.random()<0.8 && !nonavs.Diviner joblist.Diviner++ frees-- else if !safety.jobs && Math.random()<0.3 && !nonavs.ApprenticeSeer joblist.ApprenticeSeer++ frees-- if safety.teams # できれば猎人も if frees>0 if joblist.Diviner>0 if Math.random()<0.5 && !nonavs.Guard joblist.Guard++ frees-- else if Math.random()<0.2 && !nonavs.Guard joblist.Guard++ frees-- ((date)-> month=date.getMonth() d=date.getDate() if month==11 && 24<=d<=25 # 12/24〜12/25はサンタがよくでる if Math.random()<0.5 && frees>0 && !nonavs.SantaClaus joblist.SantaClaus ?= 0 joblist.SantaClaus++ frees-- else # サンタは出にくい if Math.random()<0.8 exceptions.push "SantaClaus" unless month==6 && 26<=d || month==7 && d<=16 # 期間外は烟火师は出にくい if Math.random()<0.7 exceptions.push "Pyrotechnist" else # ちょっと出やすい if Math.random()<0.11 && frees>0 && !nonavs.Pyrotechnist joblist.Pyrotechnist ?= 0 joblist.Pyrotechnist++ frees-- if month==11 && 24<=d<=25 || month==1 && d==14 # 爆弾魔がでやすい if Math.random()<0.5 && frees>0 && !nonavs.Bomber joblist.Bomber ?= 0 joblist.Bomber++ frees-- if month==1 && 13<=d<=14 # パティシエールが出やすい if Math.random()<0.4 && frees>0 && !nonavs.Patissiere joblist.Patissiere ?= 0 joblist.Patissiere++ frees-- else # 出にくい if Math.random()<0.84 exceptions.push "Patissiere" if month==0 && d<=3 # 正月は巫女がでやすい if Math.random()<0.35 && frees>0 && !nonavs.Miko joblist.Miko ?= 0 joblist.Miko++ frees-- if month==3 && d==1 # 4月1日は嘘つきがでやすい if Math.random()<0.5 && !nonavs.Liar while frees>0 joblist.Liar ?= 0 joblist.Liar++ frees-- if Math.random()<0.75 break if month==11 && d==31 || month==0 && 4<=d<=7 # 獅子舞の季節 if Math.random()<0.5 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else if month==0 && 1<=d<=3 # 獅子舞の季節(真) if Math.random()<0.7 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else # 狮子舞がでにくい季節 if Math.random()<0.8 exceptions.push "Shishimai" if month==9 && 30<=d<=31 # ハロウィンなので南瓜 if Math.random()<0.4 && frees>0 && !nonavs.Pumpkin joblist.Pumpkin ?= 0 joblist.Pumpkin++ frees-- else if Math.random()<0.2 exceptions.push "Pumpkin" )(new Date) possibility=Object.keys(jobs).filter (x)->!(x in exceptions) if possibility.length == 0 # 0はまずい possibility.push "Human" # 強制的に入れる関数 init=(jobname,categoryname)-> unless jobname in possibility return false if categoryname? && joblist["category_#{categoryname}"]>0 # あった joblist[jobname]++ joblist["category_#{categoryname}"]-- return true if frees>0 # あった joblist[jobname]++ frees-- return true return false # 安全性超用 trial_count=0 trial_max=if safety.strength then 40 else 1 best_list=null best_points=null if safety.reverse best_diff=-Infinity else best_diff=Infinity first_list=joblist first_frees=frees # チームのやつキャッシュ teamCache={} getTeam=(job)-> if teamCache[job]? return teamCache[job] for team of Shared.game.teams if job in Shared.game.teams[team] teamCache[job]=team return team return null while trial_count++ < trial_max joblist=copyObject first_list #wolf_teams=countCategory "Werewolf" wolf_teams=0 frees=first_frees while true category=null job=null #カテゴリ职业がまだあるか探す for type,arr of Shared.game.categories if joblist["category_#{type}"]>0 # カテゴリの中から候補をしぼる arr2 = arr.filter (x)->!(x in excluded_exceptions) if arr2.length > 0 r=Math.floor Math.random()*arr2.length job=arr2[r] category="category_#{type}" break else # これもう無理だわ joblist["category_#{type}"] = 0 unless job? # もうカテゴリがない if frees<=0 # もう空きがない break r=Math.floor Math.random()*possibility.length job=possibility[r] if safety.teams && !category? if job in Shared.game.teams.Werewolf if wolf_teams+1>=plsh # LowBが過半数を越えた(PP) continue if safety.jobs # 職どうしの兼ね合いを考慮 switch job when "Psychic","RedHood" # 1人のとき灵能は意味ない if countCategory("Werewolf")==1 # 狼1人だと灵能が意味ない continue when "Couple" # 共有者はひとりだと寂しい if joblist.Couple==0 unless init "Couple","Human" #共有者が入る隙間はない continue when "Noble" # 贵族は奴隶がほしい if joblist.Slave==0 unless init "Slave","Human" continue when "Slave" if joblist.Noble==0 unless init "Noble","Human" continue when "OccultMania" if joblist.Diviner==0 && Math.random()<0.5 # 占卜师いないと出现確率低い continue when "QueenSpectator" # 2人いたらだめ if joblist.QueenSpectator>0 || joblist.Spy2>0 || joblist.BloodyMary>0 continue if Math.random()>0.1 # 90%の確率で弾く continue # 女王观战者はガードがないと不安 if joblist.Guard==0 && joblist.Priest==0 && joblist.Trapper==0 unless Math.random()<0.4 && init "Guard","Human" unless Math.random()<0.5 && init "Priest","Human" unless init "Trapper","Human" # 护卫がいない continue when "Spy2" # 间谍IIは2人いるとかわいそうなので入れない if joblist.Spy2>0 || joblist.QueenSpectator>0 continue else if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "MadWolf" if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "Lycan","SeersMama","Sorcerer","WolfBoy","ObstructirveMad" # 占い系がいないと入れない if joblist.Diviner==0 && joblist.ApprenticeSeer==0 && joblist.PI==0 continue when "LoneWolf","FascinatingWolf","ToughWolf","WolfCub" # 魅惑的女狼はほかにLowBがいないと効果発揮しない # 硬汉LowBはほかに狼いないと微妙、一匹狼は1人だけででると狂人が絶望 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue when "BigWolf" # 強いので狼2以上 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue # 灵能を出す unless Math.random()<0.15 || init "Psychic","Human" continue when "BloodyMary" # 狼が2以上必要 if countCategory("Werewolf")<=1 continue # 女王とは共存できない if joblist.QueenSpectator>0 continue when "SpiritPossessed" # 2人いるとうるさい if joblist.SpiritPossessed > 0 continue joblist[job]++ # ひとつ追加 if category? joblist[category]-- else frees-- if safety.teams && (job in Shared.game.teams.Werewolf) wolf_teams++ # LowB阵营が増えた # 安全性超の場合判定が入る if safety.strength # ポイントを計算する points= Human:0 Werewolf:0 Others:0 for job of jobStrength if joblist[job]>0 switch getTeam(job) when "Human" points.Human+=jobStrength[job]*joblist[job] when "Werewolf" points.Werewolf+=jobStrength[job]*joblist[job] else points.Others+=jobStrength[job]*joblist[job] # 判定する if points.Others>points.Human || points.Others>points.Werewolf # だめだめ continue # jgs=Math.sqrt(points.Werewolf*points.Werewolf+points.Others*points.Others) jgs = points.Werewolf+points.Others diff=Math.abs(points.Human-jgs) if safety.reverse # 逆 diff+=points.Others if diff>best_diff best_list=copyObject joblist best_diff=diff best_points=points else if diff<best_diff best_list=copyObject joblist best_diff=diff best_points=points #console.log "diff:#{diff}" #console.log best_list if safety.strength && best_list? # 安全性超 joblist=best_list else if query.jobrule=="特殊规则.量子LowB" # 量子LowBのときは全员量子人类だけど职业はある func=Shared.game.getrulefunc "内部利用.量子LowB" joblist=func frees sum=0 for job of jobs if joblist[job] sum+=joblist[job] joblist.Human=frees-sum # 残りは母猪だ! list_for_rule = JSON.parse JSON.stringify joblist ruleobj.quantum_joblist=joblist # LowBの順位を決めていく i=1 while joblist.Werewolf>0 joblist["Werewolf#{i}"]=1 joblist.Werewolf-=1 i+=1 delete joblist.Werewolf # 量子LowB用 joblist={ QuantumPlayer:frees } for job of jobs unless joblist[job]? joblist[job]=0 ruleinfo_str=Shared.game.getrulestr query.jobrule,list_for_rule else if query.jobrule!="特殊规则.自由配置" # 配置に従ってアレする func=Shared.game.getrulefunc query.jobrule unless func res "不明的配置" return joblist=func frees sum=0 # 穴を埋めつつ合計数える for job of jobs unless joblist[job]? joblist[job]=0 else sum+=joblist[job] # カテゴリも for type of Shared.game.categoryNames if joblist["category_#{type}"]>0 sum-=parseInt joblist["category_#{type}"] # 残りは母猪だ! if query.chemical == "on" # 炼成LowBなので母猪が大い joblist.Human = frees * 2 - sum else joblist.Human=frees-sum ruleinfo_str=Shared.game.getrulestr query.jobrule,joblist if query.yaminabe_hidejobs!="" && query.jobrule!="特殊规则.黑暗火锅" && query.jobrule!="特殊规则.Endless黑暗火锅" # 黑暗火锅以外で配役情報を公開しないときはアレする ruleinfo_str = "" if query.chemical == "on" # ケミカルLowBの場合は表示 ruleinfo_str = "炼成LowB " + (ruleinfo_str ? "") if (joblist.WolfBoy>0 || joblist.ObstructiveMad>0 || joblist.Pumpkin>0) && query.divineresult=="immediate" query.divineresult="sunrise" log= mode:"system" comment:"由于存在能够左右占卜结果的职业,占卜结果从「立刻知道」变更为「天亮才知道」。" splashlog game.id,game,log if ruleinfo_str != "" # 表示すべき情報がない場合は表示しない log= mode:"system" comment:"配置: #{ruleinfo_str}" splashlog game.id,game,log if query.jobrule == "特殊规则.手调黑暗火锅" && excluded_exceptions.length > 0 # 除外职业の情報を表示する exclude_str = excluded_exceptions.map((job)-> Shared.game.getjobname job).join ", " log= mode:"system" comment:"除外职业:#{exclude_str}" splashlog game.id,game,log if query.yaminabe_hidejobs=="team" # 陣営のみ公開モード # 各陣営 teaminfos=[] for team,obj of Shared.game.jobinfo teamcount=0 for job,num of joblist #出现职业チェック continue if num==0 if obj[job]? # この阵营だ teamcount+=num if teamcount>0 teaminfos.push "#{obj.name}#{teamcount}" #阵营名 log= mode:"system" comment:"出场阵营信息: "+teaminfos.join(" ") splashlog game.id,game,log if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] if query.yaminabe_hidejobs=="" # 黑暗火锅用の职业公開ログ jobinfos=[] for job,num of joblist continue if num==0 jobinfos.push "#{Shared.game.getjobname job}#{num}" log= mode:"system" comment:"出场职业: "+jobinfos.join(" ") splashlog game.id,game,log for x in ["jobrule", "decider","authority","scapegoat","will","wolfsound","couplesound","heavenview", "wolfattack","guardmyself","votemyself","deadfox","deathnote","divineresult","psychicresult","waitingnight", "safety","friendsjudge","noticebitten","voteresult","GMpsychic","wolfminion","drunk","losemode","gjmessage","rolerequest","runoff","chemical", "poisonwolf", "friendssplit", "quantumwerewolf_table","quantumwerewolf_dead","quantumwerewolf_diviner","quantumwerewolf_firstattack","yaminabe_hidejobs","yaminabe_safety"] ruleobj[x]=query[x] ? null game.setrule ruleobj # 配置リストをセット game.joblist=joblist game.startoptions=options game.startplayers=players game.startsupporters=supporters if ruleobj.rolerequest=="on" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.量子LowB","特殊规则.Endless黑暗火锅"]) # 希望役职制あり # とりあえず入れなくする M.rooms.update {id:roomid},{$set:{mode:"playing"}} # 职业选择中 game.rolerequestingphase=true # ここ書いてないよ! game.rolerequesttable={} res null log= mode:"system" comment:"本场游戏采取了希望役职制,请选择希望就职的职业。" splashlog game.id,game,log game.timer() ss.publish.channel "room#{roomid}","refresh",{id:roomid} else game.setplayers (result)-> unless result? # プレイヤー初期化に成功 M.rooms.update {id:roomid},{ $set:{ mode:"playing", jobrule:query.jobrule } } game.nextturn() res null ss.publish.channel "room#{roomid}","refresh",{id:roomid} else res result # 情報を開示 getlog:(roomid)-> M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else unless games[roomid]? games[roomid] = Game.unserialize doc,ss game = games[roomid] # ゲーム後の行動 player=game.getPlayerReal req.session.userId result= #logs:game.logs.filter (x)-> islogOK game,player,x logs:game.makelogs (doc.logs ? []), player result=makejobinfo game,player,result result.timer=if game.timerid? game.timer_remain-(Date.now()/1000-game.timer_start) # 全体 - 経過时间 else null result.timer_mode=game.timer_mode if game.day==0 # 开始前はプレイヤー情報配信しない delete result.game.players res result speak: (roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless query? res "无效操作" return comment=query.comment unless comment res "没有简介" return player=game.getPlayerReal req.session.userId #console.log query,player log = comment:comment userid:req.session.userId name:player?.name ? req.session.user.name to:null if query.size in ["big","small"] log.size=query.size # ログを流す dosp=-> if !game.finished && game.voting # 投票犹豫时间は发言できない if player && !player.dead && !player.isJobType("GameMaster") return #まだ死んでいないプレイヤーの場合は发言できないよ! if game.day<=0 || game.finished #準備中 unless log.mode=="audience" log.mode="prepare" if player?.isJobType "GameMaster" log.mode="gm" #log.name="游戏管理员" else # 游戏している unless player? # 观战者 log.mode="audience" else if player.dead # 天国 if player.isJobType "Spy" && player.flag=="spygone" # 间谍なら会話に参加できない log.mode="monologue" log.to=player.id else if query.mode=="monologue" # 霊界の独り言 log.mode="heavenmonologue" else log.mode="heaven" else if !game.night # 昼 unless query.mode in player.getSpeakChoiceDay game return log.mode=query.mode if game.silentexpires && game.silentexpires>=Date.now() # まだ发言できない(15秒规则) return else # 夜 unless query.mode in player.getSpeakChoice game query.mode="monologue" log.mode=query.mode switch log.mode when "monologue","heavenmonologue","helperwhisper" # helperwhisper:守り先が決まっていないヘルパー log.to=player.id when "heaven" # 霊界の発言は悪霊憑きの発言になるかも if !game.night && !game.voting && !(game.silentexpires && game.silentexpires >= Date.now()) possessions = game.players.filter (x)-> !x.dead && x.isJobType "SpiritPossessed" if possessions.length > 0 # 悪魔憑き r = Math.floor (Math.random()*possessions.length) pl = possessions[r] # 悪魔憑きのプロパティ log.possess_name = pl.name log.possess_id = pl.id when "gm" log.name="GM→所有人" when "gmheaven" log.name="GM→灵界" when "gmaudience" log.name="GM→观战者" when "gmmonologue" log.name="GM自言自语" when "prepare" # ごちゃごちゃ言わない else if result=query.mode?.match /^gmreply_(.+)$/ log.mode="gmreply" pl=game.getPlayer result[1] unless pl? return log.to=pl.id log.name="GM→#{pl.name}" else if result=query.mode?.match /^helperwhisper_(.+)$/ log.mode="helperwhisper" log.to=result[1] splashlog roomid,game,log res null if player? log.name=player.name log.userid=player.id dosp() else # 房间情報から探す Server.game.rooms.oneRoomS roomid,(room)=> pl=room.players.filter((x)=>x.realid==req.session.userId)[0] if pl? log.name=pl.name else log.mode="audience" dosp() # 夜の仕事・投票 job:(roomid,query)-> game=games[roomid] unless game? res {error:"游戏不存在"} return unless req.session.userId res {error:"请登陆"} return player=game.getPlayerReal req.session.userId unless player? res {error:"没有加入游戏"} return unless player in game.participants res {error:"没有加入游戏"} return ### if player.dead && player.deadJobdone game res {error:"你已经死了"} return ### jt=player.getjob_target() sl=player.makeJobSelection game ### if !(to=game.players.filter((x)->x.id==query.target)[0]) && jt!=0 res {error:"这个对象不存在"} return if to?.dead && (!(jt & Player.JOB_T_DEAD) || !game.night) && (jt & Player.JOB_T_ALIVE) res {error:"对象已经死亡"} return ### unless player.checkJobValidity game,query res {error:"对象选择无效"} return if game.night || query.jobtype!="_day" # 昼の投票 # 夜 ### if !to?.dead && !(player.job_target & Player.JOB_T_ALIVE) && (player.job_target & Player.JOB_T_DEAD) res {error:"対象はまだ生きています"} return ### if (player.dead && player.deadJobdone(game)) || (!player.dead && player.jobdone(game)) res {error:"已经使用了能力"} return unless player.isJobType query.jobtype res {error:"职业错误"} return # 错误メッセージ if ret=player.job game,query.target,query console.log "err!",ret res {error:ret} return # 能力発動を記録 game.addGamelog { id:player.id type:query.jobtype target:query.target event:"job" } # 能力をすべて発動したかどうかチェック #res {sleeping:player.jobdone(game)} res makejobinfo game,player if game.night || game.day==0 game.checkjobs() else # 投票 ### if @votingbox.isVoteFinished player res {error:"既に投票しています"} return if query.target==player.id && game.rule.votemyself!="ok" res {error:"自己には投票できません"} return to=game.getPlayer query.target unless to? res {error:"その人には投票できません"} return ### unless player.checkJobValidity game,query res {error:"请选择对象"} return err=player.dovote game,query.target if err? res {error:err} return #player.dovote query.target # 投票が終わったかチェック game.addGamelog { id:player.id type:player.type target:query.target event:"vote" } res makejobinfo game,player game.execute() #遗言 will:(roomid,will)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless !game.rule || game.rule.will res "不能使用遗言" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.dead res "你已经死了" return player.setWill will res null #拒绝复活 norevive:(roomid)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.norevive res "已经不可复活" return player.setNorevive true log= mode:"userinfo" comment:"#{player.name} 拒绝复活。" to:player.id splashlog roomid,game,log # 全员に通知 game.splashjobinfo() res null splashlog=(roomid,game,log)-> log.time=Date.now() # 時間を付加 #DBに追加 M.games.update {id:roomid},{$push:{logs:log}} flash=(log)-> # まず観戦者 aulogs = makelogsFor game, null, log for x in aulogs x.roomid = roomid game.ss.publish.channel "room#{roomid}_audience","log",x # GM #if game.gm&&!rev # game.ss.publish.channel "room#{roomid}_gamemaster","log",log # 其他 game.participants.forEach (pl)-> ls = makelogsFor game, pl, log for x in ls x.roomid = roomid game.ss.publish.user pl.realid,"log",x flash log # ある人に見せたいログ makelogsFor=(game,player,log)-> if islogOK game, player, log if log.mode=="heaven" && log.possess_name? # 両方見える感じで otherslog= mode:"half-day" comment: log.comment name: log.possess_name time: log.time size: log.size return [log, otherslog] return [log] if log.mode=="werewolf" && game.rule.wolfsound=="aloud" # 狼的远吠が能听到 otherslog= mode:"werewolf" comment:"嗷呜・・・" name:"狼的远吠" time:log.time return [otherslog] if log.mode=="couple" && game.rule.couplesound=="aloud" # 共有者の小声が聞こえる otherslog= mode:"couple" comment:"沙沙・・・" name:"共有者的低语声" time:log.time return [otherslog] if log.mode=="heaven" && log.possess_name? # 昼の霊界発言 with 悪魔憑き otherslog = mode:"day" comment: log.comment name:log.possess_name time:log.time size:log.size return [otherslog] return [] # プレイヤーにログを見せてもよいか islogOK=(game,player,log)-> # player: Player / null return true if game.finished # 终了ならtrue return true if player?.isJobType "GameMaster" unless player? # 观战者 if log.mode in ["day","system","prepare","nextturn","audience","will","gm","gmaudience","probability_table"] !log.to? # 观战者にも公開 else if log.mode=="voteresult" game.rule.voteresult!="hide" # 投票结果公開なら公開 else false # 其他は非公開 else if log.mode=="gmmonologue" # GM自言自语はGMにしか見えない false else if player.dead && game.heavenview true else if log.mode=="heaven" && log.possess_name? # 恶灵凭依についている霊界発言 false else if log.to? && log.to!=player.id # 個人宛 if player.isJobType "Helper" log.to==player.flag # ヘルプ先のも見える else false else player.isListener game,log #job情報を makejobinfo = (game,player,result={})-> result.type= if player? then player.getTypeDisp() else null # job情報表示するか actpl=player if player? if player instanceof Helper actpl=game.getPlayer player.flag unless actpl? #あれっ actpl=player is_gm = actpl?.isJobType("GameMaster") openjob_flag=game.finished || (actpl?.dead && game.heavenview) || is_gm result.openjob_flag = openjob_flag result.game=game.publicinfo({ openjob: openjob_flag gm: is_gm }) # 終了か霊界(ルール設定あり)の場合は職情報公開 result.id=game.id if player # 参加者としての(perticipantsは除く) plpl=game.getPlayer player.id player.makejobinfo game,result result.dead=player.dead result.voteopen=false result.sleeping=true # 投票が终了したかどうか(表单表示するかどうか判断) if plpl? # 参加者として if game.night || game.day==0 if player.dead result.sleeping=player.deadJobdone game else result.sleeping=player.jobdone game else # 昼 result.sleeping=true unless player.dead || game.votingbox.isVoteFinished player # 投票ボックスオープン!!! result.voteopen=true result.sleeping=false if player.chooseJobDay game # 昼でも能力発動できる人 result.sleeping &&= player.jobdone game else # それ以外(participants) result.sleeping=if game.night then player.jobdone(game) else true result.jobname=player.getJobDisp() result.winner=player.winner if game.night || game.day==0 result.speak =player.getSpeakChoice game else result.speak =player.getSpeakChoiceDay game if game.rule?.will=="die" result.will=player.will result # 配列シャッフル(破壊的) shuffle= (arr)-> ret=[] while arr.length ret.push arr.splice(Math.floor(Math.random()*arr.length),1)[0] ret # 游戏情報ツイート tweet=(roomid,message)-> Server.oauth.template roomid,message,Config.admin.password
111496
#,type シェアするやつ Shared= game:require '../../../client/code/shared/game.coffee' prize:require '../../../client/code/shared/prize.coffee' cron=require 'cron' # 浅いコピー copyObject=(obj)-> result=Object.create Object.getPrototypeOf obj for key in Object.keys(obj) result[key]=obj[key] result # ゲームオブジェクトを読み込む loadGame = (roomid, ss, callback)-> if games[roomid]? callback null, games[roomid] else M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else games[roomid] = Game.unserialize doc,ss callback null, games[roomid] #内部用 module.exports= newGame: (room,ss)-> game=new Game ss,room games[room.id]=game M.games.insert game.serialize() # 游戏オブジェクトを読み込んで使用可能にする ### loadDB:(roomid,ss,cb)-> if games[roomid] # 既に読み込んでいる cb games[roomid] return M.games.find({finished:false}).each (err,doc)-> return unless doc? if err? console.log err throw err games[doc.id]=Game.unserialize doc,ss ### # 参加中のプレイヤー人数(Endless黑暗火锅用) endlessPlayersNumber:(roomid)-> game=games[roomid] if game? # 拒绝复活はカウントしない return game.players.filter((x)->!x.dead || !x.norevive).length else return Number.NaN # プレイヤーが入室したぞ! inlog:(room,player)-> name="#{player.name}" pr="" unless room.blind in ["complete","yes"] # 匿名模式のときは称号OFF player.nowprize?.forEach? (x)-> if x.type=="prize" prname=Server.prize.prizeName x.value if prname? pr+=prname else # 接続 pr+=x.value if room.blind in ["complete","yes"] && room.theme #如果房间使用了主题,匿名房间也可以有称号 theme = Server.game.themes[room.theme] if theme != null pr = theme.skins[player.userid].prize if pr name="#{Server.prize.prizeQuote pr}#{name}" if room.mode=="waiting" # 开始前(ふつう) log= comment:"#{name} 加入了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log # プレイヤーを追加 newpl=Player.factory "Waiting" newpl.setProfile { id:player.userid realid:player.realid name:player.<NAME> } newpl.setTarget null games[room.id].players.push newpl games[room.id].participants.push newpl else if room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅" # Endless黑暗火锅に途中参加 if games[room.id] game=games[room.id] log= comment:"#{name} 加入了游戏。" mode:"inlog" to:player.userid splashlog room.id,game,log # プレイヤーを追加(まだ参加しない系のひと) newpl=Player.factory "Watching" newpl.setProfile { id:player.userid realid:player.realid name:player.name } newpl.setTarget null # 头像追加 game.iconcollection[newpl.id]=player.icon # playersには追加しない(翌朝追加) games[room.id].participants.push newpl outlog:(room,player)-> log= comment:"#{player.name} 离开了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid kicklog:(room,player)-> log= comment:"#{player.name} 被踢出了游戏。" userid:-1 name:null mode:"system" console.log "game"+room.id+"存在" unless games[room.id]? # 检索数据库game是否不存在? M.games.findOne {id:room.id}, (err,doc)=> if err? console.log err throw err unless doc? M.rooms.remove {id:room.id} console.log "由于game不存在,room"+room.id+"被移除" return games[roomid]=game=Game.unserialize doc,ss ne() return if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid helperlog:(ss,room,player,topl)-> loadGame room.id, ss, (err,game)-> log=null if topl? log= comment:"#{player.name} 成为了 #{topl.name} 的帮手。" userid:-1 name:null mode:"system" else log= comment:"#{player.name} 放弃做帮手了。" userid:-1 name:null mode:"system" if game? splashlog room.id,game, log deletedlog:(ss,room)-> loadGame room.id, ss, (err,game)-> if game? log= comment:"这个房间已经废弃。" userid:-1 name:null mode:"system" splashlog room.id,game, log # 状況に応じたチャンネルを割り当てる playerchannel:(ss,roomid,session)-> loadGame roomid, ss, (err,game)-> unless game? return player=game.getPlayerReal session.userId unless player? session.channel.subscribe "room#{roomid}_audience" # session.channel.subscribe "room#{roomid}_notwerewolf" # session.channel.subscribe "room#{roomid}_notcouple" return if player.isJobType "GameMaster" session.channel.subscribe "room#{roomid}_gamemaster" return ### if player.dead session.channel.subscribe "room#{roomid}_heaven" if game.rule.heavenview!="view" || !player.dead if player.isWerewolf() session.channel.subscribe "room#{roomid}_werewolf" else session.channel.subscribe "room#{roomid}_notwerewolf" if game.rule.heavenview!="view" || !player.dead if player.isJobType "Couple" session.channel.subscribe "room#{roomid}_couple" else session.channel.subscribe "room#{roomid}_notcouple" if player.isJobType "Fox" session.channel.subscribe "room#{roomid}_fox" ### Server= game: game:module.exports rooms:require './rooms.coffee' themes:require './themes.coffee' prize:require '../../prize.coffee' oauth:require '../../oauth.coffee' class Game constructor:(@ss,room)-> # @ss: ss if room? @id=room.id # GMがいる場合 @gm= if room.gm then room.owner.userid else null @players=[] # 母猪たち @participants=[] # 参加者全て(@playersと同じ内容含む) @rule=null @finished=false #终了したかどうか @day=0 #何日目か(0=準備中) @night=false # false:昼 true:夜 @winner=null # 勝ったチーム名 @quantum_patterns=[] # 全部の場合を列挙({(id):{jobtype:"Jobname",dead:Boolean},...}) # DBには現れない @timerid=null @voting=false # 投票猶予時間 @timer_start=null # 残り時間のカウント開始時間(秒) @timer_remain=null # 残り時間全体(秒) @timer_mode=null # タイマーの名前 @revote_num=0 # 再投票を行った回数 @last_time=Date.now() # 最後に動きがあった時間 @werewolf_target=[] # LowBの襲い先 @werewolf_target_remain=0 #襲撃先をあと何人设定できるか @werewolf_flag=[] # LowB襲撃に関するフラグ @slientexpires=0 # 静かにしてろ!(この时间まで) @heavenview=false # 灵界表示がどうなっているか @gamelogs=[] @iconcollection={} #(id):(url) # 决定配置(DBに入らないかも・・・) @joblist=null # 游戏スタートに必要な情報 @startoptions=null @startplayers=null @startsupporters=null # 希望役职制のときに开始前に职业选择するフェーズ @rolerequestingphase=false @rolerequesttable={} # 一览{(id):(jobtype)} # 投票箱を用意しておく @votingbox=new VotingBox this # New Year Messageのためだけの変数 @currentyear = null ### さまざまな出来事 id: 動作した人 gamelogs=[ {id:(id),type:(type/null),target:(id,null),event:(String),flag:(String),day:(Number)}, {...}, ### # JSON用object化(DB保存用) serialize:-> { id:@id #logs:@logs rule:@rule players:@players.map (x)->x.serialize() # 差分 additionalParticipants: @participants?.filter((x)=>@players.indexOf(x)<0).map (x)->x.serialize() finished:@finished day:@day night:@night winner:@winner jobscount:@jobscount gamelogs:@gamelogs gm:@gm iconcollection:@iconcollection werewolf_flag:@werewolf_flag werewolf_target:@werewolf_target werewolf_target_remain:@werewolf_target_remain #quantum_patterns:@quantum_patterns } #DB用をもとにコンストラクト @unserialize:(obj,ss)-> game=new Game ss game.id=obj.id game.gm=obj.gm #game.logs=obj.logs game.rule=obj.rule game.players=obj.players.map (x)->Player.unserialize x # 追加する if obj.additionalParticipants game.participants=game.players.concat obj.additionalParticipants.map (x)->Player.unserialize x else game.participants=game.players.concat [] game.finished=obj.finished game.day=obj.day game.night=obj.night game.winner=obj.winner game.jobscount=obj.jobscount game.gamelogs=obj.gamelogs ? {} game.gm=obj.gm game.iconcollection=obj.iconcollection ? {} game.werewolf_flag=if Array.isArray obj.werewolf_flag # 配列ではなく文字列/nullだった時代のあれ obj.werewolf_flag else if obj.werewolf_flag? [obj.werewolf_flag] else [] game.werewolf_target=obj.werewolf_target ? [] game.werewolf_target_remain=obj.werewolf_target_remain ? 0 # 开始前なら準備中を用意してあげないと! if game.day==0 Server.game.rooms.oneRoomS game.id,(room)-> if room.error? return game.players=[] for plobj in room.players newpl=Player.factory "Waiting" newpl.setProfile { id:plobj.userid realid:plobj.realid name:plobj.name } newpl.setTarget null game.players.push newpl game.participants=game.players.concat [] game.quantum_patterns=obj.quantum_patterns ? [] unless game.finished if game.rule game.timer() if game.day>0 if !game.night # 昼の場合投票箱をつくる game.votingbox.setCandidates game.players.filter (x)->!x.dead game # 公開情報 publicinfo:(obj)-> #obj:选项 { rule:@rule finished:@finished players:@players.map (x)=> r=x.publicinfo() r.icon= @iconcollection[x.id] ? null if obj?.openjob r.jobname=x.getJobname() #r.option=x.optionString() r.option="" r.originalJobname=x.originalJobname r.winner=x.winner if obj?.gm || not (@rule?.blind=="complete" || (@rule?.blind=="yes" && !@finished)) # 公開してもよい r.realid=x.realid r day:@day night:@night jobscount:@jobscount } # IDからプレイヤー getPlayer:(id)-> @players.filter((x)->x.id==id)[0] getPlayerReal:(realid)-> #@players.filter((x)->x.realid==realid)[0] || if @gm && @gm==realid then new GameMaster realid,realid,"游戏管理员" @participants.filter((x)->x.realid==realid)[0] # DBにセーブ save:-> M.games.update {id:@id},{ $set: @serialize() $setOnInsert: { logs: [] } } # gamelogsに追加 addGamelog:(obj)-> @gamelogs ?= [] @gamelogs.push { id:obj.id ? null type:obj.type ? null target:obj.target ? null event:obj.event ? null flag:obj.flag ? null day:@day # 何気なく日付も追加 } setrule:(rule)->@rule=rule #成功:null #players: 参加者 supporters: 其他 setplayers:(res)-> options=@startoptions players=@startplayers supporters=@startsupporters jnumber=0 joblist=@joblist players=players.concat [] #模仿者 plsl=players.length #実際の参加人数(身代わり含む) if @rule.scapegoat=="on" plsl++ # 必要な职业の jallnum = plsl if @rule.chemical == "on" jallnum *= 2 @players=[] @iconcollection={} for job,num of joblist unless isNaN num jnumber+=parseInt num if parseInt(num)<0 res "玩家人数无效(#{job}:#{num})。多次重试可能解决这个错误。" return if jnumber!=jallnum # 数が合わない res "玩家人数无效 (#{jnumber}/#{jallnum}/#{players.length})。多次重试可能解决这个错误。" return # 名字と数を出したやつ @jobscount={} unless options.yaminabe_hidejobs # 公開モード for job,num of joblist continue unless num>0 testpl=new jobs[job] @jobscount[job]= name:testpl.jobname number:num # 盗賊の処理 thief_jobs=[] if joblist.Thief>0 # 小偷一人につき2回抜く for i in [0...(joblist.Thief*2)] # 1つ抜く keys=[] # 数に比例した职业一览を作る for job,num of joblist unless job in Shared.game.nonhumans for j in [0...num] keys.push job keys=shuffle keys until keys.length==0 || joblist[keys[0]]>0 # 抜けない keys.splice 0,1 # これは抜ける if keys.length==0 # もう無い res "小偷处理失败" return thief_jobs.push keys[0] joblist[keys[0]]-- # 代わりに母猪1つ入れる joblist.Human ?= 0 joblist.Human++ # 1人に対していくつ职业を選出するか jobperpl = 1 if @rule.chemical == "on" jobperpl = 2 # まず替身君を決めてあげる if @rule.scapegoat=="on" # LowB、妖狐にはならない nogoat=[] #身代わりがならない职业 if @rule.safety!="free" nogoat=nogoat.concat Shared.game.nonhumans #人外は除く if @rule.safety=="full" # 危ない nogoat=nogoat.concat ["QueenSpectator","Spy2","Poisoner","Cat","BloodyMary","Noble"] jobss=[] for job in Object.keys jobs continue if !joblist[job] || (job in nogoat) j=0 while j<joblist[job] jobss.push job j++ # 獲得した职业 gotjs = [] i=0 # 無限ループ防止 while ++i<100 && gotjs.length < jobperpl r=Math.floor Math.random()*jobss.length continue unless joblist[jobss[r]]>0 # 职业はjobss[r] gotjs.push jobss[r] joblist[jobss[r]]-- j++ if gotjs.length < jobperpl # 決まっていない res "角色分配失败" return # 替身君のプロフィール profile = { id:"<NAME>身君" realid:"替身君" name:"<NAME>" } if @rule.chemical == "on" # 炼成LowBなので合体职业にする pl1 = Player.factory gotjs[0] pl1.setProfile profile pl1.scapegoat = true pl2 = Player.factory gotjs[1] pl2.setProfile profile pl2.scapegoat = true # ケミカル合体 newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.scapegoat = true newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつーに newpl=Player.factory gotjs[0] #替身君 newpl.setProfile profile newpl.scapegoat = true @players.push newpl if @rule.rolerequest=="on" && @rule.chemical != "on" # 希望职业制ありの場合はまず希望を優先してあげる # (炼成LowBのときは面倒なのでパス) for job,num of joblist while num>0 # 候補を集める conpls=players.filter (x)=> @rolerequesttable[x.userid]==job if conpls.length==0 # もうない break # 候補がいたので決めてあげる r=Math.floor Math.random()*conpls.length pl=conpls[r] players=players.filter (x)->x!=pl newpl=Player.factory job newpl.setProfile { id:pl.userid realid:pl.realid name:pl.name } @players.push newpl if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true num-- # 残った分は戻す joblist[job]=num # 各プレイヤーの獲得职业の一覧 gotjs = [] for i in [0...(players.length)] gotjs.push [] # LowB系と妖狐系を全て数える(やや適当) all_wolves = 0 all_foxes = 0 for job,num of joblist unless isNaN num if job in Shared.game.categories.Werewolf all_wolves += num if job in Shared.game.categories.Fox all_foxes += num for job,num of joblist i=0 while i++<num r=Math.floor Math.random()*players.length if @rule.chemical == "on" && gotjs[r].length == 1 # 炼成LowBの場合調整が入る if all_wolves == 1 # LowBが1人のときはLowBを消さない if (gotjs[r][0] in Shared.game.categories.Werewolf && job in Shared.game.categories.Fox) || (gotjs[r][0] in Shared.game.categories.Fox && job in Shared.game.categories.Werewolf) # LowB×妖狐はまずい continue gotjs[r].push job if gotjs[r].length >= jobperpl # 必要な职业を獲得した pl=players[r] profile = { id:pl.userid realid:pl.realid name:pl.name } if @rule.chemical == "on" # 炼成LowB pl1 = Player.factory gotjs[r][0] pl1.setProfile profile pl2 = Player.factory gotjs[r][1] pl2.setProfile profile newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつうのLowB newpl=Player.factory gotjs[r][0] newpl.setProfile profile @players.push newpl players.splice r,1 gotjs.splice r,1 if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true if joblist.Thief>0 # 小偷がいる場合 thieves=@players.filter (x)->x.isJobType "Thief" for pl in thieves pl.setFlag JSON.stringify thief_jobs.splice 0,2 # サブ系 if options.decider # 决定者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Decider # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if options.authority # 权力者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Authority # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if @rule.wolfminion # 狼的仆从がいる場合、子分决定者を作る wolves=@players.filter((x)->x.isWerewolf()) if wolves.length>0 r=Math.floor Math.random()*wolves.length pl=wolves[r] sub=Player.factory "MinionSelector" # 子分决定者 pl.transProfile sub newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl pl.transform @,newpl,true if @rule.drunk # 酒鬼がいる場合 nonvillagers= @players.filter (x)->!x.isJobType "Human" if nonvillagers.length>0 r=Math.floor Math.random()*nonvillagers.length pl=nonvillagers[r] newpl=Player.factory null,pl,null,Drunk # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true # プレイヤーシャッフル @players=shuffle @players @participants=@players.concat [] # 模仿者 # ここでプレイヤー以外の処理をする for pl in supporters if pl.mode=="gm" # 游戏管理员だ gm=Player.factory "GameMaster" gm.setProfile { id:pl.userid realid:pl.realid name:pl.name } @participants.push gm else if result=pl.mode?.match /^helper_(.+)$/ # 帮手だ ppl=@players.filter((x)->x.id==result[1])[0] unless ppl? res "#{pl.name} 的帮助对象已不存在。" return helper=Player.factory "Helper" helper.setProfile { id:pl.realid realid:pl.realid name:pl.name } helper.setFlag ppl.id # ヘルプ先 @participants.push helper #@participants.push new GameMaster pl.userid,pl.realid,pl.name # 量子LowBの場合はここで可能性リストを作る if @rule.jobrule=="特殊规则.量子LowB" # パターンを初期化(最初は全パターン) quats=[] # のとみquantum_patterns pattern_no=0 # とばす # 职业を列挙した配列をつくる jobname_list=[] for job of jobs i=@rule.quantum_joblist[job] if i>0 jobname_list.push { type:job, number:i } # LowB用 i=1 while @rule.quantum_joblist["Werewolf#{i}"]>0 jobname_list.push { type:"Werewolf#{i}" number:@rule.quantum_joblist["Werewolf#{i}"] } i++ # プレイヤーIDを列挙した配列もつくる playerid_list=@players.map (pl)->pl.id # 0,1,...,(n-1)の中からkコ選んだ組み合わせを返す関数 combi=(n,k)-> `var i;` if k<=0 return [[]] if n<=k #n<kのときはないけど・・・ return [[0...n]] # 0からn-1まで resulty=[] for i in [0..(n-k)] # 0 <= i <= n-k for x in combi n-i-1,k-1 resulty.push [i].concat x.map (y)->y+i+1 resulty # 職をひとつ処理 makeonejob=(joblist,plids)-> cont=joblist[0] unless cont? return [[]] # 決めて抜く coms=combi plids.length,cont.number # その番号のを resulty2=[] for pat in coms #pat: 1つのパターン bas=[] pll=plids.concat [] i=0 for num in pat bas.push { id:pll[num-i] job:cont.type } pll.splice num-i,1 # 抜く i+=1 resulty2=resulty2.concat makeonejob(joblist.slice(1),pll).map (arr)-> bas.concat arr resulty2 jobsobj=makeonejob jobname_list,playerid_list # パターンを作る for arr in jobsobj obj={} for o in arr result=o.job.match /^Werewolf(\d+)$/ if result obj[o.id]={ jobtype:"Werewolf" rank:+result[1] # 狼の序列 dead:false } else obj[o.id]={ jobtype:o.job dead:false } quats.push obj # できた @quantum_patterns=quats if @rule.quantumwerewolf_table=="anonymous" # 概率表は数字で表示するので番号をつけてあげる for pl,i in shuffle @players.concat [] pl.setFlag JSON.stringify { number:i+1 } res null #======== 游戏進行の処理 #次のターンに進む nextturn:-> clearTimeout @timerid if @day<=0 # はじまる前 @day=1 @night=true # ゲーム開始時の年を記録 @currentyear = (new Date).getFullYear() else if @night==true @day++ @night=false else @night=true if @night==false && @currentyear+1 == (new Date).getFullYear() # 新年メッセージ @currentyear++ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"现在是 #{@currentyear} 年了。" splashlog @id,this,log else # 普通メッセージ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"第#{@day}天的#{if @night then '夜晚' else '白天'}到来了。" splashlog @id,this,log #死体処理 @bury(if @night then "night" else "day") if @rule.jobrule=="特殊规则.量子LowB" # 量子LowB # 全员の確率を出してあげるよーーーーー # 確率テーブルを probability_table={} numberref_table={} dead_flg=true while dead_flg dead_flg=false for x in @players if x.dead continue dead=0 for obj in @quantum_patterns if obj[x.id].dead==true dead++ if dead==@quantum_patterns.length # 死んだ!!!!!!!!!!!!!!!!! x.die this,"werewolf" dead_flg=true for x in @players count= Human:0 Diviner:0 Werewolf:0 dead:0 for obj in @quantum_patterns count[obj[x.id].jobtype]++ if obj[x.id].dead==true count.dead++ sum=count.Human+count.Diviner+count.Werewolf pflag=JSON.parse x.flag if sum==0 # 世界が崩壊した x.setFlag JSON.stringify { number:pflag?.number Human:0 Diviner:0 Werewolf:0 dead:0 } # ログ用 probability_table[x.id]={ name:x.name Human:0 Werewolf:0 } if @rule.quantumwerewolf_dead=="on" #死亡確率も probability_table[x.id].dead=0 if @rule.quantumwerewolf_diviner=="on" # 占卜师の確率も probability_table[x.id].Diviner=0 else x.setFlag JSON.stringify { number:pflag?.number Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum dead:count.dead/sum } # ログ用 if @rule.quantumwerewolf_diviner=="on" probability_table[x.id]={ name:x.name Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum } else probability_table[x.id]={ name:x.name Human:(count.Human+count.Diviner)/sum Werewolf:count.Werewolf/sum } if @rule.quantumwerewolf_dead!="no" || count.dead==sum # 死亡率も probability_table[x.id].dead=count.dead/sum if @rule.quantumwerewolf_table=="anonymous" # 番号を表示 numberref_table[pflag.number]=x probability_table[x.id].name="玩家 #{pflag.number}" if @rule.quantumwerewolf_table=="anonymous" # ソートしなおしてあげて痕跡を消す probability_table=((probability_table,numberref_table)-> result={} i=1 x=null while x=numberref_table[i] result["_$_player#{i}"]=probability_table[x.id] i++ result )(probability_table,numberref_table) # ログを出す log= mode:"probability_table" probability_table:probability_table splashlog @id,this,log # もう一回死体処理 @bury(if @night then "night" else "day") return if @judge() @voting=false if @night # job数据を作る # LowBの襲い先 @werewolf_target=[] unless @day==1 && @rule.scapegoat!="off" @werewolf_target_remain=1 else if @rule.scapegoat=="on" # 誰が襲ったかはランダム onewolf=@players.filter (x)->x.isWerewolf() if onewolf.length>0 r=Math.floor Math.random()*onewolf.length @werewolf_target.push { from:onewolf[r].id to:"替身君" # みがわり } @werewolf_target_remain=0 else # 誰も襲わない @werewolf_target_remain=0 werewolf_flag_result=[] for fl in @werewolf_flag if fl=="Diseased" # 病人フラグが立っている(今日は襲撃できない @werewolf_target_remain=0 log= mode:"wolfskill" comment:"LowB们染病了。今天无法出击。" splashlog @id,this,log else if fl=="WolfCub" # 狼之子フラグが立っている(2回襲撃できる) @werewolf_target_remain=2 log= mode:"wolfskill" comment:"为狼之子复仇吧,今天可以袭击两个人。" splashlog @id,this,log else werewolf_flag_result.push fl @werewolf_flag=werewolf_flag_result # Fireworks should be lit at just before sunset. x = @players.filter((pl)->pl.isJobType("Pyrotechnist") && pl.accessByJobType("Pyrotechnist")?.flag == "using") if x.length # 全员花火の虜にしてしまう for pl in @players newpl=Player.factory null,pl,null,WatchingFireworks pl.transProfile newpl newpl.cmplFlag=x[0].id                     pl.transform this,newpl,true                 # Pyrotechnist should break the blockade of Threatened.sunset                 for pyr in x                     pyr.accessByJobType("Pyrotechnist").sunset this alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunset this else player.deadsunset this else # 誤爆防止 @werewolf_target_remain=0 # 処理 if @rule.deathnote # 死亡笔记採用 alives=@players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] sub=Player.factory "Light" # 副を作る pl.transProfile sub sub.sunset this newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl @players.forEach (x,i)=> # 入れ替え if x.id==newpl.id @players[i]=newpl else x # Endless黑暗火锅用途中参加処理 if @rule.jobrule=="特殊规则.Endless黑暗火锅" exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] jobnames=Object.keys(jobs).filter (name)->!(name in exceptions) pcs=@participants.concat [] join_count=0 for player in pcs if player.isJobType "Watching" # 参加待機のひとだ if !@players.some((p)->p.id==player.id) # 本参加ではないのでOK # 职业をランダムに决定 newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob player.transProfile newpl player.transferData newpl # 观战者を除去 @participants=@participants.filter (x)->x!=player # プレイヤーとして追加 @players.push newpl @participants.push newpl # ログをだす log= mode:"system" comment:"#{newpl.name} 加入了游戏。" splashlog @id,@,log join_count++ # たまに転生 deads=shuffle @players.filter (x)->x.dead && !x.norevive # 転生確率 # 1人の転生確率をpとすると死者n人に対して転生人数の期待値はpn人。 # 1ターンに2人しぬとしてp(n+2)=2とおくとp=2/(n+2) 。 # 少し減らして人数を減少に持って行く p = 2/(deads.length+3) # 死者全员に対して転生判定 for pl in deads if Math.random()<p # でも参加者がいたら蘇生のかわりに if join_count>0 && Math.random()>p join_count-- continue newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob pl.transProfile newpl pl.transferData newpl # 蘇生 newpl.setDead false pl.transform @,newpl,true log= mode:"system" comment:"#{pl.name} 转生了。" splashlog @id,@,log @ss.publish.user newpl.id,"refresh",{id:@id} # 投票リセット処理 @votingbox.init() @votingbox.setCandidates @players.filter (x)->!x.dead alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunrise this else player.deadsunrise this for pl in @players if !pl.dead pl.votestart this @revote_num=0 # 重新投票の回数は0にリセット #死体処理 @bury "other" return if @judge() @splashjobinfo() if @night @checkjobs() else # 昼は15秒规则があるかも if @rule.silentrule>0 @silentexpires=Date.now()+@rule.silentrule*1000 # これまでは黙っていよう! @save() @timer() #全员に状況更新 pls:状況更新したい人を指定する場合の配列 splashjobinfo:(pls)-> unless pls? # プレイヤー以外にも @ss.publish.channel "room#{@id}_audience","getjob",makejobinfo this,null # GMにも if @gm? @ss.publish.channel "room#{@id}_gamemaster","getjob",makejobinfo this,@getPlayerReal @gm pls=@participants pls.forEach (x)=> @ss.publish.user x.realid,"getjob",makejobinfo this,x #全员寝たかチェック 寝たなら処理してtrue #timeoutがtrueならば时间切れなので时间でも待たない checkjobs:(timeout)-> if @day==0 # 开始前(希望役职制) if timeout || @players.every((x)=>@rolerequesttable[x.id]?) # 全员できたぞ @setplayers (result)=> unless result? @rolerequestingphase=false @nextturn() @ss.publish.channel "room#{@id}","refresh",{id:@id} true else false else if @players.every( (x)=>x.dead || x.sleeping(@)) if @voting || timeout || !@rule.night || @rule.waitingnight!="wait" #夜に时间がある場合は待ってあげる @midnight() @nextturn() true else false else false #夜の能力を処理する midnight:-> alives=[] deads=[] pids=[] mids=[] for player in @players pids.push player.id # gather all midnightSort mids = mids.concat player.gatherMidnightSort() if player.dead deads.push player.id else alives.push player.id # unique mids.sort (a, b)=> return a - b midsu=[mids[0]] for mid in mids if midsu[midsu.length-1] != mid then midsu.push mid # 処理順はmidnightSortでソート pids = shuffle pids for mid in midsu for pid in pids player=@getPlayer pid pmids = player.gatherMidnightSort() if player.id in alives if mid in pmids player.midnight this,mid else if mid in pmids player.deadnight this,mid # 狼の処理 for target in @werewolf_target t=@getPlayer target.to continue unless t? # 噛まれた t.addGamelog this,"bitten" if @rule.noticebitten=="notice" || t.isJobType "Devil" log= mode:"skill" to:t.id comment:"#{t.name} 被LowB袭击了。" splashlog @id,this,log if !t.dead # 死んだ t.die this,"werewolf",target.from # 逃亡者を探す runners=@players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==target.to runners.forEach (x)=> x.die this,"werewolf2",target.from # その家に逃げていたら逃亡者も死ぬ if !t.dead # 死んでない flg_flg=false # なにかのフラグ for fl in @werewolf_flag res = fl.match /^ToughWolf_(.+)$/ if res? # 硬汉LowBがすごい tw = @getPlayer res[1] t=@getPlayer target.to if t? t.setDead true,"werewolf2" t.dying this,"werewolf2",tw.id flg_flg=true if tw? unless tw.dead tw.die this,"werewolf2" tw.addGamelog this,"toughwolfKilled",t.type,t.id break unless flg_flg # 一途は発動しなかった for fl in @werewolf_flag res = fl.match /^GreedyWolf_(.+)$/ if res? # 欲張り狼がやられた! gw = @getPlayer res[1] if gw? gw.die this,"werewolf2" gw.addGamelog this,"greedyKilled",t.type,t.id # 以降は襲撃できない flg_flg=true break if flg_flg # 欲張りのあれで襲撃终了 break @werewolf_flag=@werewolf_flag.filter (fl)-> # こいつらは1夜限り return !(/^(?:GreedyWolf|ToughWolf)_/.test fl) # 死んだ人を処理する type: タイミング # type: "day": 夜が明けたタイミング "night": 处刑後 "other":其他(ターン変わり時の能力で死んだやつなど) bury:(type)-> deads=[] loop deads=@players.filter (x)->x.dead && x.found deadsl=deads.length alives=@players.filter (x)->!x.dead alives.forEach (x)=> x.beforebury this,type deads=@players.filter (x)->x.dead && x.found if deadsl>=deads.length # もう新しく死んだ人はいない break # 灵界で职业表示してよいかどうか更新 switch @rule.heavenview when "view" @heavenview=true when "norevive" @heavenview=!@players.some((x)->x.isReviver()) else @heavenview=false deads=shuffle deads # 順番バラバラ deads.forEach (x)=> situation=switch x.found #死因 when "werewolf","werewolf2","poison","hinamizawa","vampire","vampire2","witch","dog","trap","bomb","marycurse","psycho","crafty" "不成样子的尸体被发现了" when "curse" # 呪殺 if @rule.deadfox=="obvious" "被咒杀了" else "不成样子的尸体被发现了" when "punish" "被处刑了" when "spygone" "离开了村子" when "deathnote" "的尸体被发现了" when "foxsuicide" "追随着妖狐自尽了" when "friendsuicide" "追随着恋人自尽了" when "infirm" "衰老而死了" when "gmpunish" "被GM处死了" when "gone-day" "因为没有及时投票猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" when "gone-night" "因为没有及时使用夜间技能猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" else "死了" log= mode:"system" comment:"#{x.name} #{situation}" splashlog @id,this,log situation=switch x.found #死因 when "werewolf","werewolf2" "LowB的袭击" when "poison" "毒药" when "hinamizawa" "雏见泽症候群发作" when "vampire","vampire2" "吸血鬼的袭击" when "witch" "魔女的毒药" when "dog" "犬的袭击" when "trap" "陷阱" when "bomb" "炸弹" when "marycurse" "玛丽的诅咒" when "psycho" "变态杀人狂" when "curse" "咒杀" when "punish" "处刑" when "spygone" "失踪" when "deathnote" "心梗" when "foxsuicide" "追随妖狐自尽" when "friendsuicide" "追随恋人自尽" when "infirm" "老死" when "gmpunish" "被GM处死" when "gone-day" "昼间猝死" when "crafty" "假死" when "gone-night" "夜间猝死" else "未知原因" log= mode:"system" to:-1 comment:"#{x.name} 的死因是 #{situation}" splashlog @id,this,log ### if x.found=="punish" # 处刑→灵能 @players.forEach (y)=> if y.isJobType "Psychic" # 灵能 y.results.push x ### @addGamelog { # 死んだときと死因を記録 id:x.id type:x.type event:"found" flag:x.found } x.setDead x.dead,"" #発見されました @ss.publish.user x.realid,"refresh",{id:@id} if @rule.will=="die" && x.will # 死んだら遗言発表 log= mode:"will" name:x.name comment:x.will splashlog @id,this,log # 死者应该立刻从投票候选人中去除 @votingbox.candidates = @votingbox.candidates.filter (x)->!x.dead deads.length # 投票終わりチェック # 返り値意味ないんじゃないの? execute:-> return false unless @votingbox.isVoteAllFinished() [mode,player,tos,table]=@votingbox.check() if mode=="novote" # 誰も投票していない・・・ @revote_num=Infinity @judge() return false # 投票结果 log= mode:"voteresult" voteresult:table tos:tos splashlog @id,this,log if mode=="runoff" # 重新投票になった @dorevote "runoff" return false else if mode=="revote" # 重新投票になった @dorevote "revote" return false else if mode=="punish" # 投票 # 结果が出た 死んだ! # だれが投票したか調べる follower=table.filter((obj)-> obj.voteto==player.id).map (obj)->obj.id player.die this,"punish",follower if player.dead && @rule.GMpsychic=="on" # GM灵能 log= mode:"system" comment:"根据灵能的结论,被处刑的 #{player.name} 是 #{player.getPsychicResult()}。" splashlog @id,this,log @votingbox.remains-- if @votingbox.remains>0 # もっと殺したい!!!!!!!!! @bury "other" return false if @judge() log= mode:"system" comment:"今天还有#{@votingbox.remains}人将被处刑。请继续投票。" splashlog @id,this,log # 再び投票する処理(下と同じ… なんとかならないか?) @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() return false @nextturn() return true # 重新投票 dorevote:(mode)-> # mode: "runoff" - 决胜投票による重新投票 "revote" - 同数による重新投票 "gone" - 突然死による重新投票 if mode!="runoff" @revote_num++ if @revote_num>=4 # 4回重新投票 @judge() return remains=4-@revote_num if mode=="runoff" log= mode:"system" comment:"决胜投票。" else log= mode:"system" comment:"重新投票。" if isFinite remains log.comment += "如果在接下来的#{remains}轮投票中无法达成一致,本场游戏将以平局处理。" splashlog @id,this,log @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() # 勝敗决定 judge:-> aliveps=@players.filter (x)->!x.dead # 生きている人を集める # 数える alives=aliveps.length humans=aliveps.map((x)->x.humanCount()).reduce(((a,b)->a+b), 0) wolves=aliveps.map((x)->x.werewolfCount()).reduce(((a,b)->a+b), 0) vampires=aliveps.map((x)->x.vampireCount()).reduce(((a,b)->a+b), 0) team=null friends_count=null # 量子LowBのときは特殊ルーチン if @rule.jobrule=="特殊规则.量子LowB" assured_wolf= alive:0 dead:0 total_wolf=0 obj=@quantum_patterns[0] if obj? for key,value of obj if value.jobtype=="Werewolf" total_wolf++ for x in @players unless x.flag # まだだった・・・ break flag=JSON.parse x.flag if flag.Werewolf==1 # うわあああ絶対LowBだ!!!!!!!!!! if flag.dead==1 assured_wolf.dead++ else if flag.dead==0 assured_wolf.alive++ if alives<=assured_wolf.alive*2 # あーーーーーーー team="Werewolf" else if assured_wolf.dead==total_wolf # 全滅した team="Human" else # もうひとつもないんだ・・・ log= mode:"system" comment:"世界崩坏,概率无法定义。" splashlog @id,this,log team="Draw" else if alives==0 # 全滅 team="Draw" else if wolves==0 && vampires==0 # 母猪胜利 team="Human" else if humans<=wolves && vampires==0 # LowB胜利 team="Werewolf" else if humans<=vampires && wolves==0 # 吸血鬼胜利 team="Vampire" if team=="Werewolf" && wolves==1 # 一匹狼判定 lw=aliveps.filter((x)->x.isWerewolf())[0] if lw?.isJobType "LoneWolf" team="LoneWolf" if team? # 妖狐判定 if @players.some((x)->!x.dead && x.isFox()) team="Fox" # 恋人判定 if @players.some((x)->x.isFriend()) # 终了時に恋人生存 friends=@players.filter (x)->x.isFriend() && !x.dead gid=0 friends_count=0 friends_table={} for pl in friends unless friends_table[pl.id]? pt=pl.getPartner() unless friends_table[pt]? friends_count++ gid++ friends_table[pl.id]=gid friends_table[pt]=gid else # 合併 friends_table[pl.id]=friends_table[pt] else unless friends_table[pt]? friends_table[pt]=friends_table[pl.id] else if friends_table[pt]!=friends_table[pl.id] # 食い違っている c=Math.min friends_table[pt],friends_table[pl.id] d=Math.max friends_table[pt],friends_table[pl.id] for key,value of friends_table if value==d friends_table[key]=c # グループが合併した friends_count-- if friends_count==1 # 1組しかいない if @rule.friendsjudge=="alive" team="Friend" else if friends.length==alives team="Friend" else if friends_count>1 if alives==friends.length team="Friend" else # 恋人バトル team=null # カルト判定 if alives>0 && aliveps.every((x)->x.isCult() || x.isJobType("CultLeader") && x.getTeam()=="Cult" ) # 全員信者 team="Cult" # 悪魔くん判定 isDevilWinner = (pl)-> # 悪魔くんが勝利したか判定する return false unless pl? return false unless pl.isJobType "Devil" if pl.isComplex() return isDevilWinner(pl.sub) || (pl.getTeam() == "Devil" && isDevilWinner(pl.main)) else return pl.flag == "winner" if @players.some(isDevilWinner) team="Devil" if @revote_num>=4 && !team? # 重新投票多すぎ team="Draw" # 平局 if team? # 勝敗决定 @finished=true @last_time=Date.now() @winner=team if team!="Draw" @players.forEach (x)=> iswin=x.isWinner this,team if @rule.losemode # 败北村(負けたら勝ち) if iswin==true iswin=false else if iswin==false iswin=true # ただし突然死したら負け if @gamelogs.some((log)-> log.id==x.id && log.event=="found" && log.flag in ["gone-day","gone-night"] ) iswin=false x.setWinner iswin #胜利か # ユーザー情報 if x.winner M.users.update {userid:x.realid},{$push: {win:@id}} else M.users.update {userid:x.realid},{$push: {lose:@id}} log= mode:"nextturn" finished:true resultstring=null#结果 teamstring=null #阵营 [resultstring,teamstring]=switch team when "Human" if alives>0 && aliveps.every((x)->x.isJobType "Neet") ["村子变成了NEET的乐园。","母猪胜利"] else ["村子里的LowB已经被赶尽杀绝。","母猪胜利"] when "Werewolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","LowB胜利"] when "Fox" ["村子成了妖狐的玩物。","妖狐胜利"] when "Devil" ["村子成了恶魔的玩物。","恶魔胜利"] when "Friend" if friends_count>1 # みんなで胜利(珍しい) ["村子被恋人们支配了。","恋人胜利"] else friends=@players.filter (x)->x.isFriend() if friends.length==2 && friends.some((x)->x.isJobType "Noble") && friends.some((x)->x.isJobType "Slave") ["在主仆两人跨越世俗禁忌的爱情面前,所有阻碍都无法与之匹敌。","恋人胜利"] else ["在#{@players.filter((x)->x.isFriend() && !x.dead).length}人爱的力量面前,所有阻碍都无法与之匹敌。","恋人胜利"] when "Cult" ["村子被教会支配了。","邪教胜利"] when "Vampire" ["吸血鬼饮尽了最后一个村民的鲜血,向着下一个住满了猎物的村庄前进了…","吸血鬼胜利"] when "LoneWolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","一匹狼胜利"] when "Draw" ["平局。",""] # 替身君单独胜利 winpl = @players.filter (x)->x.winner if(winpl.length==1 && winpl[0].realid=="替身君") resultstring="村子成了替身君的玩物。" log.comment="#{if teamstring then "【#{teamstring}】" else ""}#{resultstring}" splashlog @id,this,log # 房间を终了状态にする M.rooms.update {id:@id},{$set:{mode:"end"}} @ss.publish.channel "room#{@id}","refresh",{id:@id} @save() @prize_check() clearTimeout @timerid # 向房间成员通报猝死统计 norevivers=@gamelogs.filter((x)->x.event=="found" && x.flag in ["gone-day","gone-night"]).map((x)->x.id) if norevivers.length message = id:@id userlist:[] time:parseInt(60/@players.length) for x in norevivers pl = @getPlayer x message.userlist.push {"userid":pl.realid,"name":pl.name} @ss.publish.channel "room#{@id}",'punishalert',message # DBからとってきて告知ツイート M.rooms.findOne {id:@id},(err,doc)-> return unless doc? tweet doc.id,"「#{doc.name}」的结果: #{log.comment} #月下LowB" return true else return false timer:-> return if @finished func=null time=null mode=null # なんのカウントか timeout= => # 残り时间を知らせるぞ! @timer_start=parseInt Date.now()/1000 @timer_remain=time @timer_mode=mode @ss.publish.channel "room#{@id}","time",{time:time, mode:mode} if time>30 @timerid=setTimeout timeout,30000 time-=30 else if time>0 @timerid=setTimeout timeout,time*1000 time=0 else # 时间切れ func() if @rolerequestingphase # 希望役职制 time=60 mode="希望选择" func= => # 強制开始 @checkjobs true else if @night && !@voting # 夜 time=@rule.night mode="夜" return unless time func= => # ね な い こ だ れ だ unless @checkjobs true if @rule.remain # 犹豫时间があるよ @voting=true @timer() else @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else return else if @night # 夜の犹豫 time=@rule.remain mode="犹豫" func= => # ね な い こ だ れ だ @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else if !@voting # 昼 time=@rule.day mode="昼" return unless time func= => unless @execute() if @rule.remain # 犹豫があるよ @voting=true log= mode:"system" comment:"白天的讨论时间到此结束。请投票决定要处死的人。" splashlog @id,this,log @timer() else # 突然死 revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return else # 犹豫时间も過ぎたよ! time=@rule.remain mode="犹豫" func= => unless @execute() revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return timeout() # プレイヤーごとに 見せてもよいログをリストにする makelogs:(logs,player)-> result = [] for x in logs ls = makelogsFor this, player, x result.push ls... return result prize_check:-> Server.prize.checkPrize @,(obj)=> # obj: {(userid):[prize]} # 賞を算出した pls=@players.filter (x)->x.realid!="替身君" # 各々に対して処理 query={userid:{$in:pls.map (x)->x.realid}} M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # いままでの賞の一览 # 差分をとる newprize=obj[doc.userid].filter (x)->!(x in oldprize) if newprize.length>0 M.users.update {userid:doc.userid},{$set:{prize:obj[doc.userid]}} pl=@getPlayerReal doc.userid pnames=newprize.map (plzid)-> Server.prize.prizeQuote Server.prize.prizeName plzid log= mode:"system" comment:"#{pl.name} 获得了称号 #{pnames.join ''}。" splashlog @id,this,log ### M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # 賞の一览 # 賞を算出しなおしてもらう Server.prize.checkPrize doc.userid,(prize)=> prize=prize.concat doc.ownprize if doc.ownprize? # 新規に獲得した賞を探す newprizes= prize.filter (x)->!(x in oldprize) if newprizes.length>0 M.users.update {userid:doc.userid},{$set:{prize:prize}} pl=@getPlayerReal doc.userid newprizes.forEach (x)=> log= mode:"system" comment:"#{pl.name}は#{Server.prize.prizeQuote Server.prize.prizeName x}を獲得しました。" splashlog @id,this,log @addGamelog { id: pl.id type:pl.type event:"getprize" flag:x target:null } ### ### logs:[{ mode:"day"(昼) / "system"(システムメッセージ) / "werewolf"(狼) / "heaven"(天国) / "prepare"(开始前/终了後) / "skill"(能力ログ) / "nextturn"(游戏進行) / "audience"(观战者のひとりごと) / "monologue"(夜のひとりごと) / "voteresult" (投票结果) / "couple"(共有者) / "fox"(妖狐) / "will"(遗言) comment: String userid:Userid name?:String to:Userid / null (あると、その人だけ) (nextturnの場合) day:Number night:Boolean finished?:Boolean (voteresultの場合) voteresult:[] tos:Object },...] rule:{ number: Number # プレイヤー数 scapegoat : "on"(身代わり君が死ぬ) "off"(参加者が死ぬ) "no"(誰も死なない) } ### # 投票箱 class VotingBox constructor:(@game)-> @init() init:-> # 投票箱を空にする @remains=1 # 残り处刑人数 @runoffmode=false # 重新投票中か @candidates=[] @start() start:-> @votes=[] #{player:Player, to:Player} setCandidates:(@candidates)-> # 候補者をセットする[Player] isVoteFinished:(player)->@votes.some (x)->x.player.id==player.id vote:(player,voteto)-> # power: 票数 pl=@game.getPlayer voteto unless pl? return "这个玩家不存在" if pl.dead return "这个人已经死了" me=@game.getPlayer player.id unless me? return "你没有加入游戏" if @isVoteFinished player return "你已经投过票了" if pl.id==player.id && @game.rule.votemyself!="ok" return "不能向自己投票" @votes.push { player:@game.getPlayer player.id to:pl power:1 priority:0 } log= mode:"voteto" to:player.id comment:"#{player.name} 向 #{pl.name} 投票了" splashlog @game.id,@game,log null # その人の投票オブジェクトを得る getHisVote:(player)-> @votes.filter((x)->x.player.id==player.id)[0] # 票のパワーを变更する votePower:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.power=value else v.power+=value # 優先度つける votePriority:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.priority=value else v.priority+=value # 处刑人数を増やす addPunishedNumber:(num)-> @remains+=num isVoteAllFinished:-> alives=@game.players.filter (x)->!x.dead alives.every (x)=> x.voted @game,@ compareGots:(a,b)-> # aとbをsort用に(gots) # aのほうが小さい: -1 < # bのほうが小さい: 1 > if a.votes>b.votes return 1 else if a.votes<b.votes return -1 else if a.priority>b.priority return 1 else if a.priority<b.priority return -1 else return 0 check:-> # return [mode,result,tos,table] # 投票が終わったのでアレする # 投票表を作る tos={} table=[] gots={} #for obj in @votes alives = @game.players.filter (x)->!x.dead for pl in alives obj=@getHisVote pl o=pl.publicinfo() if obj? gots[obj.to.id] ?= { votes:0 priority:-Infinity } go=gots[obj.to.id] go.votes+=obj.power if go.priority<obj.priority go.priority=obj.priority tos[obj.to.id]=go.votes o.voteto=obj.to.id # 投票先情報を付け加える table.push o for pl in alives vote = gots[pl.id] if vote? vote = pl.modifyMyVote @game, vote gots[pl.id] = vote tos[pl.id] = vote.votes # 獲得票数が少ない順に並べる cands=Object.keys(gots).sort (a,b)=> @compareGots gots[a],gots[b] # 獲得票数多い一览 back=null tops=[] for id in cands by -1 if !back? || @compareGots(gots[back],gots[id])==0 tops.push id back=id else break if tops.length==0 # 誰も投票していない return ["novote",null,tos,table] if tops.length>1 # 決まらない! 重新投票になった if @game.rule.runoff!="no" && !@runoffmode @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] else return ["revote",null,tos,table] if @game.rule.runoff=="yes" && !@runoffmode # 候補は1人だけど决胜投票をしないといけない if tops.length<=1 # 候補がたりない back=null flag=false tops=[] for id in cands by -1 ok=false if !back? ok=true else if @compareGots(gots[back],gots[id])==0 ok=true else if flag==false # 决胜投票なので1回だけOK! flag=true ok=true else break if ok tops.push id back=id if tops.length>1 @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] # 结果を教える return ["punish",@game.getPlayer(tops[0]),tos,table] class Player constructor:-> # realid:本当のid id:仮のidかもしれない name:名字 icon:头像URL @dead=false @found=null # 死体の発見状況 @winner=null # 勝敗 @scapegoat=false # 替身君かどうか @flag=null # 职业ごとの自由なフラグ @will=null # 遗言 # もと的职业 @originalType=@type @originalJobname=@getJobname() # 拒绝复活 @norevive=false @factory:(type,main=null,sub=null,cmpl=null)-> p=null if cmpl? # 複合 mainとsubを使用 #cmpl: 複合の親として使用するオブジェクト myComplex=Object.create main #Complexから sample=new cmpl # 手動でComplexを継承したい Object.keys(sample).forEach (x)-> delete sample[x] # own propertyは全部消す for name of sample # sampleのown Propertyは一つもない myComplex[name]=sample[name] # 混合职业 p=Object.create myComplex p.main=main p.sub=sub p.cmplFlag=null else if !jobs[type]? p=new Player else p=new jobs[type] p serialize:-> r= type:@type id:@id realid:@realid name:@name dead:@dead scapegoat:@scapegoat will:@will flag:@flag winner:@winner originalType:@originalType originalJobname:@originalJobname norevive:@norevive if @isComplex() r.type="Complex" r.Complex_main=@main.serialize() r.Complex_sub=@sub?.serialize() r.Complex_type=@cmplType r.Complex_flag=@cmplFlag r @unserialize:(obj)-> unless obj? return null p=if obj.type=="Complex" # 複合 cmplobj=complexes[obj.Complex_type ? "Complex"] Player.factory null, Player.unserialize(obj.Complex_main), Player.unserialize(obj.Complex_sub),cmplobj else # 普通 Player.factory obj.type p.setProfile obj #id,realid,name... p.dead=obj.dead p.scapegoat=obj.scapegoat p.will=obj.will p.flag=obj.flag p.winner=obj.winner p.originalType=obj.originalType p.originalJobname=obj.originalJobname p.norevive=!!obj.norevive # backward compatibility if p.isComplex() p.cmplFlag=obj.Complex_flag p # 汎用関数: Complexを再構築する(chain:Complexの列(上から)) @reconstruct:(chain,base)-> for cmpl,i in chain by -1 newpl=Player.factory null,base,cmpl.sub,complexes[cmpl.cmplType] ### for ok in Object.keys cmpl # 自己のプロパティのみ unless ok=="main" || ok=="sub" newpl[ok]=cmpl[ok] ### newpl.cmplFlag=cmpl.cmplFlag base=newpl base publicinfo:-> # 見せてもいい情報 { id:@id name:@name dead:@dead norevive:@norevive } # プロパティセット系(Complex対応) setDead:(@dead,@found)-> setWinner:(@winner)-> setTarget:(@target)-> setFlag:(@flag)-> setWill:(@will)-> setOriginalType:(@originalType)-> setOriginalJobname:(@originalJobname)-> setNorevive:(@norevive)-> # ログが見えるかどうか(通常の游戏中、個人宛は除外) isListener:(game,log)-> if log.mode in ["day","system","nextturn","prepare","monologue","heavenmonologue","skill","will","voteto","gm","gmreply","helperwhisper","probability_table","userinfo"] # 全員に見える true else if log.mode in ["heaven","gmheaven"] # 死んでたら見える @dead else if log.mode=="voteresult" game.rule.voteresult!="hide" # 隠すかどうか else false # midnightの実行順(小さいほうが先) midnightSort: 100 # 本人に見える职业名 getJobDisp:->@jobname # 本人に見える职业タイプ getTypeDisp:->@type # 职业名を得る getJobname:->@jobname # 母猪かどうか isHuman:->!@isWerewolf() # LowBかどうか isWerewolf:->false # 洋子かどうか isFox:->false # 妖狐の仲間としてみえるか isFoxVisible:->false # 恋人かどうか isFriend:->false # Complexかどうか isComplex:->false # 教会信者かどうか isCult:->false # 吸血鬼かどうか isVampire:->false # 酒鬼かどうか isDrunk:->false # 蘇生可能性を秘めているか isReviver:->false # Am I Dead? isDead:->{dead:@dead,found:@found} # get my team getTeam:-> @team # 終了時の人間カウント humanCount:-> if !@isFox() && @isHuman() 1 else 0 werewolfCount:-> if !@isFox() && @isWerewolf() 1 else 0 vampireCount:-> if !@isFox() && @isVampire() 1 else 0 # jobtypeが合っているかどうか(夜) isJobType:(type)->type==@type #An access to @flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" if @isJobType(type) return this null gatherMidnightSort:-> return [@midnightSort] # complexのJobTypeを調べる isCmplType:(type)->false # 投票先决定 dovote:(game,target)-> # 戻り値にも意味があるよ! err=game.votingbox.vote this,target,1 if err? return err @voteafter game,target return null voteafter:(game,target)-> # 昼のはじまり(死体処理よりも前) sunrise:(game)-> deadsunrise:(game)-> # 昼の投票準備 votestart:(game)-> #@voteto=null return if @dead if @scapegoat # 替身君は投票 alives=game.players.filter (x)=>!x.dead && x!=this r=Math.floor Math.random()*alives.length # 投票先 return unless alives[r]? #@voteto=alives[r].id @dovote game,alives[r].id # 夜のはじまり(死体処理よりも前) sunset:(game)-> deadsunset:(game)-> # 夜にもう寝たか sleeping:(game)->true # 夜に仕事を追えたか(基本sleepingと一致) jobdone:(game)->@sleeping game # 死んだ後でも仕事があるとfalse deadJobdone:(game)->true # 昼に投票を終えたか voted:(game,votingbox)->game.votingbox.isVoteFinished this # 夜の仕事 job:(game,playerid,query)-> @setTarget playerid null # 夜の仕事を行う midnight:(game,midnightSort)-> # 夜死んでいたときにmidnightの代わりに呼ばれる deadnight:(game,midnightSort)-> # 対象 job_target:1 # ビットフラグ # 対象用の値 @JOB_T_ALIVE:1 # 生きた人が対象 @JOB_T_DEAD :2 # 死んだ人が対象 #LowBに食われて死ぬかどうか willDieWerewolf:true #占いの结果 fortuneResult:"母猪" getFortuneResult:->@fortuneResult #霊能の結果 psychicResult:"母猪" getPsychicResult:->@psychicResult #チーム Human/Werewolf team: "Human" #胜利かどうか team:胜利阵营名 isWinner:(game,team)-> team==@team # 自己の阵营かどうか # 殺されたとき(found:死因。fromは場合によりplayerid。punishの場合は[playerid])) die:(game,found,from)-> return if @dead if found=="werewolf" && !@willDieWerewolf # 襲撃耐性あり return pl=game.getPlayer @id pl.setDead true,found pl.dying game,found,from # 死んだとき dying:(game,found)-> # 行きかえる revive:(game)-> # logging: ログを表示するか if @norevive # 蘇生しない return @setDead false,null p=@getParent game unless p?.sub==this # サブのときはいいや・・・ log= mode:"system" comment:"#{@name} 复活了。" splashlog game.id,game,log @addGamelog game,"revive",null,null game.ss.publish.user @id,"refresh",{id:game.id} # 埋葬するまえに全员呼ばれる(foundが見られる状況で) beforebury: (game,type)-> # 占われたとき(结果は別にとられる player:占い元) divined:(game,player)-> # ちょっかいを出されたとき(jobのとき) touched:(game,from)-> # 选择肢を返す makeJobSelection:(game)-> if game.night # 夜の能力 jt=@job_target if jt>0 # 参加者を选择する result=[] for pl in game.players if (pl.dead && (jt&Player.JOB_T_DEAD))||(!pl.dead && (jt&Player.JOB_T_ALIVE)) result.push { name:pl.name value:pl.id } else result=[] else # 昼の投票 result=[] if game?.votingbox for pl in game.votingbox.candidates result.push { name:pl.name value:pl.id } result checkJobValidity:(game,query)-> sl=@makeJobSelection game return sl.length==0 || sl.some((x)->x.value==query.target) # 职业情報を載せる makejobinfo:(game,obj,jobdisp)-> # 開くべきフォームを配列で(生きている場合) obj.open ?=[] if !@jobdone(game) && (game.night || @chooseJobDay(game)) obj.open.push @type # 职业解説のアレ obj.desc ?= [] type = @getTypeDisp() if type? obj.desc.push { name:jobdisp ? @getJobDisp() type:type } obj.job_target=@getjob_target() # 选择肢を教える {name:"名字",value:"値"} obj.job_selection ?= [] obj.job_selection=obj.job_selection.concat @makeJobSelection game # 重複を取り除くのはクライアント側にやってもらおうかな… # 女王观战者が見える if @team=="Human" obj.queens=game.players.filter((x)->x.isJobType "QueenSpectator").map (x)-> x.publicinfo() else # セットなどによる漏洩を防止 delete obj.queens # 昼でも対象选择を行えるか chooseJobDay:(game)->false # 仕事先情報を教える getjob_target:->@job_target # 昼の发言の选择肢 getSpeakChoiceDay:(game)-> ["day","monologue"] # 夜の发言の选择肢を得る getSpeakChoice:(game)-> ["monologue"] # 自分宛の投票を書き換えられる modifyMyVote:(game, vote)-> vote # Complexから抜ける uncomplex:(game,flag=false)-> #flag: 自己がComplexで自己が消滅するならfalse 自己がmainまたはsubで親のComplexを消すならtrue(その際subは消滅) befpl=game.getPlayer @id # objがPlayerであること calleeは呼び出し元のオブジェクト chainは継承連鎖 # index: game.playersの番号 chk=(obj,index,callee,chain)-> return unless obj? chc=chain.concat obj if obj.isComplex() if flag # mainまたはsubである if obj.main==callee || obj.sub==callee # 自己は消える game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc else # 自己がComplexである if obj==callee game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc game.players.forEach (x,i)=> if x.id==@id chk x,i,this,[] # participantsも for pl,j in game.participants if pl.id==@id game.participants[j]=game.players[i] break aftpl=game.getPlayer @id #前と後で比較 if befpl.getJobname()!=aftpl.getJobname() aftpl.setOriginalJobname "#{befpl.originalJobname}→#{aftpl.getJobname()}" # 自己自身を変える transform:(game,newpl,override,initial=false)-> # override: trueなら全部変える falseならメイン职业のみ変える @addGamelog game,"transform",newpl.type # 职业変化ログ if override || !@isComplex() # 全部取っ払ってnewplになる newpl.setOriginalType @originalType if @getJobname()!=newpl.getJobname() unless initial # ふつうの変化 newpl.setOriginalJobname "#{@originalJobname}→#{newpl.getJobname()}" else # 最初の変化(ログに残さない) newpl.setOriginalJobname newpl.getJobname() pa=@getParent game unless pa? # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=newpl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=newpl else # 親がいた if pa.main==this # 親書き換え newparent=Player.factory null,newpl,pa.sub,complexes[pa.cmplType] newparent.cmplFlag=pa.cmplFlag newpl.transProfile newparent pa.transform game,newparent,override # たのしい再帰 else # サブだった pa.sub=newpl else # 中心のみ変える pa=game.getPlayer @id orig_originalJobname=pa.originalJobname chain=[pa] while pa.main.isComplex() pa=pa.main chain.push pa # pa.mainはComplexではない toppl=Player.reconstruct chain,newpl toppl.setOriginalJobname "#{orig_originalJobname}→#{toppl.getJobname()}" # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=toppl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=toppl getParent:(game)-> chk=(parent,name)=> if parent[name]?.isComplex?() if parent[name].main==this || parent[name].sub==this return parent[name] else return chk(parent[name],"main") || chk(parent[name],"sub") else return null for pl,i in game.players c=chk game.players,i return c if c? return null # 親なんていない # 自己のイベントを記述 addGamelog:(game,event,flag,target,type=@type)-> game.addGamelog { id:@id type:type target:target event:event flag:flag } # 個人情報的なことをセット setProfile:(obj={})-> @id=obj.id @realid=obj.realid @name=obj.name # 個人情報的なことを移動 transProfile:(newpl)-> newpl.setProfile this # フラグ類を新しいPlayerオブジェクトへ移動 transferData:(newpl)-> return unless newpl? newpl.scapegoat=@scapegoat newpl.setDead @dead,@found class Human extends Player type:"Human" jobname:"母猪" class Werewolf extends Player type:"Werewolf" jobname:"LowB" sunset:(game)-> @setTarget null unless game.day==1 && game.rule.scapegoat!="off" if @scapegoat && @isAttacker() && game.players.filter((x)->!x.dead && x.isWerewolf() && x.isAttacker()).length==1 # 自己しかLowBがいない hus=game.players.filter (x)->!x.dead && !x.isWerewolf() while hus.length>0 && game.werewolf_target_remain>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } hus.splice r,1 if game.werewolf_target_remain>0 # 襲撃したい人全员襲撃したけどまだ襲撃できるときは重複襲撃 hus=game.players.filter (x)->!x.dead && !x.isWerewolf() # safety counter i = 100 while hus.length>0 && game.werewolf_target_remain>0 && i > 0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } i-- sleeping:(game)->game.werewolf_target_remain<=0 || !game.night job:(game,playerid)-> tp = game.getPlayer playerid if game.werewolf_target_remain<=0 return "已经决定了袭击对象" if game.rule.wolfattack!="ok" && tp?.isWerewolf() # LowBはLowBに攻撃できない return "LowB之间不能相互袭击" game.werewolf_target.push { from:@id to:playerid } game.werewolf_target_remain-- tp.touched game,@id log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚袭击 #{tp.name}。" if @isJobType "SolitudeWolf" # 孤独的狼なら自己だけ… log.to=@id splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null isHuman:->false isWerewolf:->true # おおかみ専用メソッド:襲撃できるか isAttacker:->!@dead isListener:(game,log)-> if log.mode in ["werewolf","wolfskill"] true else super isJobType:(type)-> # 便宜的 if type=="_Werewolf" return true super willDieWerewolf:false fortuneResult:"LowB" psychicResult:"LowB" team: "Werewolf" makejobinfo:(game,result)-> super if game.night && game.werewolf_target_remain>0 # まだ襲える result.open.push "_Werewolf" # LowBは仲間が分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() # 间谍2も分かる result.spy2s=game.players.filter((x)->x.isJobType "Spy2").map (x)-> x.publicinfo() getSpeakChoice:(game)-> ["werewolf"].concat super class Diviner extends Player type:"Diviner" jobname:"占卜师" midnightSort: 100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid)-> super pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> unless game.rule.divineresult=="immediate" @dodivine game @divineeffect game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @target if p? p.divined game,this #占い実行 dodivine:(game)-> p=game.getPlayer @target if p? @results.push { player: p.publicinfo() result: "#{@name} 占卜了 #{p.name} 的身份,他是 #{p.getFortuneResult()}。" } @addGamelog game,"divine",p.type,@target # 占った showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Psychic extends Player type:"Psychic" jobname:"<NAME>" constructor:-> super @setFlag "" # ここにメッセージを入れよう sunset:(game)-> super if game.rule.psychicresult=="sunset" @showpsychicresult game sunrise:(game)-> super unless game.rule.psychicresult=="sunset" @showpsychicresult game showpsychicresult:(game)-> return unless @flag? @flag.split("\n").forEach (x)=> return unless x log= mode:"skill" to:@id comment:x splashlog game.id,game,log @setFlag "" # 处刑で死んだ人を調べる beforebury:(game,type)-> @setFlag if @flag? then @flag else "" game.players.filter((x)->x.dead && x.found=="punish").forEach (x)=> @setFlag @flag+"根据 #{@name} 的灵能结论,被处刑的 #{x.name} 是 #{x.getPsychicResult()}。\n" class Madman extends Player type:"Madman" jobname:"<NAME>" team:"Werewolf" makejobinfo:(game,result)-> super delete result.queens class Guard extends Player type:"Guard" jobname:"<NAME>" midnightSort: 80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} # 失敗した @setTarget "" job:(game,playerid)-> if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" else @setTarget playerid pl=game.getPlayer(playerid) log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true newpl.touched game,@id null class Couple extends Player type:"Couple" jobname:"<NAME>" makejobinfo:(game,result)-> super # 共有者は仲間が分かる result.peers=game.players.filter((x)->x.isJobType "Couple").map (x)-> x.publicinfo() isListener:(game,log)-> if log.mode=="couple" true else super getSpeakChoice:(game)-> ["couple"].concat super class Fox extends Player type:"Fox" jobname:"<NAME>" team:"Fox" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true makejobinfo:(game,result)-> super # 妖狐は仲間が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() divined:(game,player)-> super # 妖狐呪殺 @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した isListener:(game,log)-> if log.mode=="fox" true else super getSpeakChoice:(game)-> ["fox"].concat super class Poisoner extends Player type:"Poisoner" jobname:"<NAME>" dying:(game,found,from)-> super # 埋毒者の逆襲 canbedead = game.players.filter (x)->!x.dead # 生きている人たち if found=="werewolf" # 噛まれた場合は狼のみ if game.rule.poisonwolf == "selector" # 襲撃者を道連れにする canbedead = canbedead.filter (x)->x.id==from else canbedead=canbedead.filter (x)->x.isWerewolf() else if found=="vampire" canbedead=canbedead.filter (x)->x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"poison" @addGamelog game,"poisonkill",null,pl.id class BigWolf extends Werewolf type:"BigWolf" jobname:"<NAME>" fortuneResult:"母猪" psychicResult:"大LowB" class TinyFox extends Diviner type:"TinyFox" jobname:"<NAME>" fortuneResult:"母猪" psychicResult:"小狐" team:"F<NAME>" midnightSort:100 isHuman:->false isFox:->true makejobinfo:(game,result)-> super # 子狐は妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() dodivine:(game)-> p=game.getPlayer @target if p? success= Math.random()<0.5 # 成功したかどうか re=if success then "是 #{p.getFortuneResult()}" else "是一个看不透的可疑人物" @results.push { player: p.publicinfo() result: "根据 #{@name} 的占卜结果,#{p.name} #{re},大概。" } @addGamelog game,"foxdivine",success,p.id showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Bat extends Player type:"Bat" jobname:"<NAME>" team:"" isWinner:(game,team)-> !@dead # 生きて入ればとにかく胜利 class Noble extends Player type:"Noble" jobname:"贵族" die:(game,found)-> if found=="werewolf" return if @dead # 奴隶たち slaves = game.players.filter (x)->!x.dead && x.isJobType "Slave" unless slaves.length super # 自己が死ぬ else # 奴隶が代わりに死ぬ slaves.forEach (x)-> x.die game,"werewolf2" x.addGamelog game,"slavevictim" @addGamelog game,"nobleavoid" else super class Slave extends Player type:"Slave" jobname:"<NAME>" isWinner:(game,team)-> nobles=game.players.filter (x)->!x.dead && x.isJobType "Noble" if team==@team && nobles.length==0 true # 母猪阵营の勝ちで贵族は死んだ else false makejobinfo:(game,result)-> super # 奴隶は贵族が分かる result.nobles=game.players.filter((x)->x.isJobType "Noble").map (x)-> x.publicinfo() class Magician extends Player type:"Magician" jobname:"<NAME>" midnightSort:100 isReviver:->!@dead sunset:(game)-> @setTarget (if game.day<3 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> if game.day<3 # まだ発動できない return "现在还不能发动技能" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null sleeping:(game)->game.day<3 || @target? midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=if pl.scapegoat then 0.6 else 0.3 unless Math.random()<r # 失敗 @addGamelog game,"raise",false,pl.id return # 蘇生 目を覚まさせる @addGamelog game,"raise",true,pl.id pl.revive game job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Spy extends Player type:"Spy" jobname:"<NAME>" team:"Werewolf" midnightSort:100 sleeping:->true # 能力使わなくてもいい jobdone:->@flag in ["spygone","day1"] # 能力を使ったか sunrise:(game)-> if game.day<=1 @setFlag "day1" # まだ去れない else @setFlag null job:(game,playerid)-> return "已经发动了技能" if @flag=="spygone" @setFlag "spygone" log= mode:"skill" to:@id comment:"#{@name} 决定要离开村子。" splashlog game.id,game,log null midnight:(game,midnightSort)-> if !@dead && @flag=="spygone" # 村を去る @setFlag "spygone" @die game,"spygone" job_target:0 isWinner:(game,team)-> team==@team && @dead && @flag=="spygone" # LowBが勝った上で自己は任務完了の必要あり makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class WolfDiviner extends Werewolf type:"WolfDiviner" jobname:"LowB占卜师" midnightSort:100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> @setTarget null @setFlag null # 占い対象 @result=null # 占卜结果 super sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && @flag? job:(game,playerid,query)-> if query.jobtype!="WolfDiviner" # LowBの仕事 return super # 占い if @flag? return "已经决定占卜对象" pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" @setFlag playerid unless pl.getTeam()=="Werewolf" && pl.isHuman() # 狂人は変化するので pl.touched game,@id log= mode:"skill" to:@id comment:"LowB占卜师<NAME> #{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> super @divineeffect game unless game.rule.divineresult=="immediate" @dodivine game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @flag if p? p.divined game,this if p.isJobType "Diviner" # 逆呪殺 @die game,"curse" showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log dodivine:(game)-> p=game.getPlayer @flag if p? @results.push { player: p.publicinfo() result: "LowB占卜师<NAME> #{@name} 占卜了 #{p.name} 的身份,他是 #{p.jobname}。" } @addGamelog game,"wolfdivine",null,@flag # 占った if p.getTeam()=="Werewolf" && p.isHuman() # 狂人変化 #避免狂人成为某些职业,"GameMaster"保留 jobnames=Object.keys jobs jobnames=jobnames.filter((x)->!(x in ["MinionSelector","Thief","Helper","QuantumPlayer","Waiting","Watching"])) newjob = jobnames[Math.floor(Math.random() * jobnames.length)] plobj=p.serialize() plobj.type=newjob newpl=Player.unserialize plobj # 新生狂人 newpl.setFlag null p.transferData newpl p.transform game,newpl,false p=game.getPlayer @flag p.sunset game log= mode:"skill" to:p.id comment:"#{p.name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.splashjobinfo [game.getPlayer newpl.id] makejobinfo:(game,result)-> super if game.night if @flag? # もう占いは終わった result.open = result.open?.filter (x)=>x!="WolfDiviner" class Fugitive extends Player type:"Fugitive" jobname:"<NAME>" midnightSort:100 sunset:(game)-> @setTarget null if game.day<=1 #&& game.rule.scapegoat!="off" # 一日目は逃げない @setTarget "" else if @scapegoat # 身代わり君の自動占い als=game.players.filter (x)=>!x.dead && x.id!=@id if als.length==0 @setTarget "" return r=Math.floor Math.random()*als.length if @job game,als[r].id,{} @setTarget "" sleeping:->@target? job:(game,playerid)-> # 逃亡先 pl=game.getPlayer playerid if pl?.dead return "不能逃到死者的家里去" if playerid==@id return "不能逃到自己的家里去" @setTarget playerid pl?.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 逃亡到 #{pl.name} 的家里去了。" splashlog game.id,game,log @addGamelog game,"runto",null,pl.id null die:(game,found)-> # 狼の襲撃・吸血鬼の襲撃・魔女の毒薬は回避 if found in ["werewolf","vampire","witch"] if @target!="" return else super else super midnight:(game,midnightSort)-> # LowBの家に逃げていたら即死 pl=game.getPlayer @target return unless pl? if !pl.dead && pl.isWerewolf() && pl.getTeam() in ["Werewolf","LoneWolf"] @die game,"werewolf2" else if !pl.dead && pl.isVampire() && pl.getTeam()=="Vampire" @die game,"vampire2" isWinner:(game,team)-> team==@team && !@dead # 母猪胜利で生存 class Merchant extends Player type:"Merchant" jobname:"商人" constructor:-> super @setFlag null # 発送済みかどうか sleeping:->true jobdone:(game)->game.day<=1 || @flag? job:(game,playerid,query)-> if @flag? return "商品已经送出" # 即時発送 unless query.Merchant_kit in ["Diviner","Psychic","Guard"] return "要送出的商品无效" kit_names= "Diviner":"占卜套装" "Psychic":"灵能套装" "Guard":"守护套装" pl=game.getPlayer playerid unless pl? return "发送无效" if pl.dead return "发送对象已经死亡" if pl.id==@id return "不能发送给自己" pl.touched game,@id # 複合させる sub=Player.factory query.Merchant_kit # 副を作る pl.transProfile sub sub.sunset game newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 寄出了 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log # 入れ替え先は気づいてもらう log= mode:"skill" to:newpl.id comment:"#{newpl.name} 收到了礼物 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} @setFlag query.Merchant_kit # 発送済み @addGamelog game,"sendkit",@flag,newpl.id null class QueenSpectator extends Player type:"QueenSpectator" jobname:"女王观战者" dying:(game,found)-> super # 感染 humans = game.players.filter (x)->!x.dead && x.isHuman() # 生きている人たち humans.forEach (x)-> x.die game,"hinamizawa" class MadWolf extends Werewolf type:"MadWolf" jobname:"狂LowB" team:"Human" sleeping:->true class Neet extends Player type:"Neet" jobname:"NEET" team:"" sleeping:->true voted:(game,votingbox)->true isWinner:->true class Liar extends Player type:"Liar" jobname:"<NAME>" midnightSort:100 job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も constructor:-> super @results=[] sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid,query)-> # 占い if @target? return "已经决定占卜对象" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log null sunrise:(game)-> super return if !@results? || @results.length==0 log= mode:"skill" to:@id comment:"虽然不是很自信,根据骗子占卜的结果 #{@results[@results.length-1].player.name} 大概是 #{@results[@results.length-1].result},大概。" splashlog game.id,game,log midnight:(game,midnightSort)-> p=game.getPlayer @target if p? @addGamelog game,"liardivine",null,p.id @results.push { player: p.publicinfo() result: if Math.random()<0.3 # 成功 p.getFortuneResult() else # 逆 fr = p.getFortuneResult() switch fr when "母猪" "LowB" when "LowB" "母猪" else fr } isWinner:(game,team)->team==@team && !@dead # 母猪胜利で生存 class Spy2 extends Player type:"Spy2" jobname:"<NAME>" team:"Werewolf" makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() dying:(game,found)-> super @publishdocument game publishdocument:(game)-> str=game.players.map (x)-> "#{x.name}:#{x.jobname}" .join " \n" log= mode:"system" comment:"发现了 #{@name} 的调查报告书。" splashlog game.id,game,log log2= mode:"will" comment:str splashlog game.id,game,log2 isWinner:(game,team)-> team==@team && !@dead class Copier extends Player type:"Copier" jobname:"<NAME>" team:"" isHuman:->false sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} job:(game,playerid,query)-> # 模仿者先 if @target? return "已经模仿了其他人" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 模仿了 #{pl.name} 的能力。" splashlog game.id,game,log p=game.getPlayer playerid newpl=Player.factory p.type @transProfile newpl @transferData newpl @transform game,newpl,false pl=game.getPlayer @id pl.sunset game # 初期化してあげる #game.ss.publish.user newpl.id,"refresh",{id:game.id} game.splashjobinfo [game.getPlayer @id] null isWinner:(game,team)->false # 模仿者しないと負け class Light extends Player type:"Light" jobname:"<NAME>" midnightSort:100 sleeping:->true jobdone:(game)->@target? || game.day==1 sunset:(game)-> @setTarget null job:(game,playerid,query)-> # 模仿者先 if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 在死亡笔记上写下了 #{pl.name} 的名字。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"deathnote" # 誰かに移る処理 @uncomplex game,true # 自己からは抜ける class Fanatic extends Madman type:"Fanatic" jobname:"<NAME>" makejobinfo:(game,result)-> super # 狂信者はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() class Immoral extends Player type:"Immoral" jobname:"<NAME>" team:"Fox" beforebury:(game,type)-> # 狐が全員死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" makejobinfo:(game,result)-> super # 妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() class Devil extends Player type:"Devil" jobname:"<NAME>" team:"Devil" psychicResult:"LowB" die:(game,found)-> return if @dead if found=="werewolf" # 死なないぞ! unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="punish" # 处刑されたぞ! if @flag=="bitten" # 噛まれたあと处刑された @setFlag "winner" else super else super isWinner:(game,team)->team==@team && @flag=="winner" class ToughGuy extends Player type:"ToughGuy" jobname:"<NAME>" die:(game,found)-> if found=="werewolf" # 狼の襲撃に耐える @setFlag "bitten" else super sunrise:(game)-> super if @flag=="bitten" @setFlag "dying" # 死にそう! sunset:(game)-> super if @flag=="dying" # 噛まれた次の夜 @setFlag null @setDead true,"werewolf" class Cupid extends Player type:"Cupid" jobname:"<NAME>" team:"Friend" constructor:-> super @setFlag null # 恋人1 @setTarget null # 恋人2 sunset:(game)-> if game.day>=2 && @flag? # 2日目以降はもう遅い @setFlag "" @setTarget "" else @setFlag null @setTarget null if @scapegoat # 身代わり君の自動占い alives=game.players.filter (x)->!x.dead i=0 while i++<2 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@flag? && @target? job:(game,playerid,query)-> if @flag? && @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" unless @flag? @setFlag playerid log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 定为恋人中的一人。" splashlog game.id,game,log return null if @flag==playerid return "请选择另一个恋人" @setTarget playerid # 恋人二人が决定した plpls=[game.getPlayer(@flag), game.getPlayer(@target)] for pl,i in plpls # 2人ぶん処理 pl.touched game,@id newpl=Player.factory null,pl,null,Friend # 恋人だ! newpl.cmplFlag=plpls[1-i].id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 射出了爱之箭。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{newpl.name} 成为了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [game.getPlayer(@flag), game.getPlayer(@target)] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 跟踪狂 class Stalker extends Player type:"Stalker" jobname:"跟踪狂" team:"" sunset:(game)-> super if !@flag # ストーキング先を決めていない @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setTarget "" sleeping:->@flag? job:(game,playerid,query)-> if @target? || @flag? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 跟踪了 #{pl.name}(#{pl.jobname})。" splashlog game.id,game,log @setFlag playerid # ストーキング対象プレイヤー null isWinner:(game,team)-> @isWinnerStalk game,team,[] # 跟踪狂連鎖対応版 isWinnerStalk:(game,team,ids)-> if @id in ids # ループしてるので負け return false pl=game.getPlayer @flag return false unless pl? if team==pl.getTeam() return true if pl.isJobType "Stalker" # 跟踪狂を追跡 return pl.isWinnerStalk game,team,ids.concat @id else return pl.isWinner game,team makejobinfo:(game,result)-> super p=game.getPlayer @flag if p? result.stalking=p.publicinfo() # 被诅咒者 class Cursed extends Player type:"Cursed" jobname:"<NAME>" die:(game,found)-> return if @dead if found=="werewolf" # 噛まれた場合LowB侧になる unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="vampire" # 吸血鬼にもなる!!! unless @flag # まだ噛まれていない @setFlag "vampire" else super sunset:(game)-> if @flag in ["bitten","vampire"] # この夜から変化する log=null newpl=null if @flag=="bitten" log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了LowB。" newpl=Player.factory "Werewolf" else log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了吸血鬼。" newpl=Player.factory "Vampire" @transProfile newpl @transferData newpl @transform game,newpl,false newpl.sunset game splashlog game.id,game,log if @flag=="bitten" # LowB侧に知らせる #game.ss.publish.channel "room#{game.id}_werewolf","refresh",{id:game.id} game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() else # 吸血鬼に知らせる game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isVampire() # 自己も知らせる #game.ss.publish.user newpl.realid,"refresh",{id:game.id} game.splashjobinfo [this] class ApprenticeSeer extends Player type:"ApprenticeSeer" jobname:"<NAME>" beforebury:(game,type)-> # 占卜师が誰か死んでいたら占卜师に進化 if game.players.some((x)->x.dead && x.isJobType("Diviner")) || game.players.every((x)->!x.isJobType("Diviner")) newpl=Player.factory "Diviner" @transProfile newpl @transferData newpl log= mode:"skill" to:@id comment:"#{@name} 从 #{@jobname} 变成了 #{newpl.jobname}。" splashlog game.id,game,log @transform game,newpl,false # 更新 game.ss.publish.user newpl.realid,"refresh",{id:game.id} class Diseased extends Player type:"Diseased" jobname:"<NAME>" dying:(game,found)-> super if found=="werewolf" # 噛まれた場合次の日LowB襲撃できない! game.werewolf_flag.push "Diseased" # 病人フラグを立てる class Spellcaster extends Player type:"Spellcaster" jobname:"<NAME>" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 初日は発動できません @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" arr=[] try arr=JSON.parse @flag catch error arr=[] unless arr instanceof Array arr=[] if playerid in arr # 既に呪いをかけたことがある return "这个对象已经被咒言诅咒过了。" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 夺去了 #{pl.name} 的声音。" splashlog game.id,game,log arr.push playerid @setFlag JSON.stringify arr null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 的声音被夺去了。今天白天无法发言。" splashlog game.id,game,log # 複合させる newpl=Player.factory null,t,null,Muted # 黙る人 t.transProfile newpl t.transform game,newpl,true class Lycan extends Player type:"Lycan" jobname:"<NAME>" fortuneResult:"LowB" class Priest extends Player type:"Priest" jobname:"<NAME>" midnightSort:70 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid,query)-> if @flag? return "已经使用了能力" if @target? return "已经选择了对象" pl=game.getPlayer playerid unless pl? return "这个对象不存在" if playerid==@id return "不能将自己选为对象" pl.touched game,@id @setTarget playerid @setFlag "done" # すでに能力を発動している log= mode:"skill" to:@id comment:"#{@name} 以神圣的力量守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,HolyProtected # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元 pl.transform game,newpl,true null class Prince extends Player type:"Prince" jobname:"<NAME>" die:(game,found)-> if found=="punish" && !@flag? # 处刑された @setFlag "used" # 能力使用済 log= mode:"system" comment:"#{@name} 是 #{@jobname}。本次处刑被取消了。" splashlog game.id,game,log @addGamelog game,"princeCO" else super # Paranormal Investigator class PI extends Diviner type:"PI" jobname:"超常现象研究者" sleeping:->true jobdone:->@flag? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 调查了 #{pl.name} 和他的左右邻居。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game @setFlag "done" # 能力一回限り null #占い実行 dodivine:(game)-> pls=[] game.players.forEach (x,i)=> if x.id==@target pls.push x # 前 if i==0 pls.push game.players[game.players.length-1] else pls.push game.players[i-1] # 後 if i>=game.players.length-1 pls.push game.players[0] else pls.push game.players[i+1] if pls.length>0 rs=pls.map((x)->x?.getFortuneResult()).filter((x)->x!="母猪") # 母猪以外 # 重複をとりのぞく nrs=[] rs.forEach (x,i)-> if rs.indexOf(x,i+1)<0 nrs.push x tpl=game.getPlayer @target resultstring=if nrs.length>0 @addGamelog game,"PIdivine",true,tpl.id "发现了 #{nrs.join ","} 活动的迹象" else @addGamelog game,"PIdivine",false,tpl.id "发现全员都是母猪" @results.push { player:game.getPlayer(@target).publicinfo() result:"#{@name} 调查了 #{tpl.name} 和他的左右邻居,#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Sorcerer extends Diviner type:"Sorcerer" jobname:"<NAME>" team:"Werewolf" sleeping:->@target? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 用妖术调查了 #{pl.name}。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null #占い実行 dodivine:(game)-> pl=game.getPlayer @target if pl? resultstring=if pl.isJobType "Diviner" "是占卜师" else "不是占卜师" @results.push { player: game.getPlayer(@target).publicinfo() result: "#{@name} 用妖术调查了 #{pl.name},他#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Doppleganger extends Player type:"Doppleganger" jobname:"<NAME>" sleeping:->true jobdone:->@flag? team:"" # 最初はチームに属さない! job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能将自己选为对象" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 成为了 #{game.getPlayer(playerid).name} 的二重身。" splashlog game.id,game,log @setFlag playerid # 二重身先 null beforebury:(game,type)-> founds=game.players.filter (x)->x.dead && x.found # 対象が死んだら移る if founds.some((x)=>x.id==@flag) p=game.getPlayer @flag # その人 newplmain=Player.factory p.type @transProfile newplmain @transferData newplmain me=game.getPlayer @id # まだ二重身できる sub=Player.factory "Doppleganger" @transProfile sub newpl=Player.factory null, newplmain,sub,Complex # 合体 @transProfile newpl pa=@getParent game # 親を得る unless pa? # 親はいない @transform game,newpl,false else # 親がいる if pa.sub==this # subなら親ごと置換 pa.transform game,newpl,false else # mainなら自己だけ置換 @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"dopplemove",newpl.type,newpl.id game.ss.publish.user newpl.realid,"refresh",{id:game.id} class CultLeader extends Player type:"CultLeader" jobname:"<NAME>" team:"Cult" midnightSort:100 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 发展 #{pl.name} 成为信者。" splashlog game.id,game,log @addGamelog game,"brainwash",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 成为了教会的信者。" # 信者 splashlog game.id,game,log newpl=Player.factory null, t,null,CultMember # 合体 t.transProfile newpl t.transform game,newpl,true makejobinfo:(game,result)-> super # 信者は分かる result.cultmembers=game.players.filter((x)->x.isCult()).map (x)-> x.publicinfo() class Vampire extends Player type:"Vampire" jobname:"<NAME>" team:"Vampire" willDieWerewolf:false fortuneResult:"吸血鬼" midnightSort:100 sleeping:(game)->@target? || game.day==1 isHuman:->false isVampire:->true sunset:(game)-> @setTarget null if game.day>1 && @scapegoat r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid,query)-> # 襲う先 if @target? return "已经选择了对象" if game.day==1 return "今天不能袭击" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"vampire",@id # 逃亡者を探す runners=game.players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==t.id runners.forEach (x)=> x.die game,"vampire2",@id # その家に逃げていたら逃亡者も死ぬ makejobinfo:(game,result)-> super # 吸血鬼が分かる result.vampires=game.players.filter((x)->x.isVampire()).map (x)-> x.publicinfo() class LoneWolf extends Werewolf type:"LoneWolf" jobname:"一匹狼" team:"LoneWolf" isWinner:(game,team)->team==@team && !@dead class Cat extends Poisoner type:"Cat" jobname:"猫又" midnightSort:100 isReviver:->true sunset:(game)-> @setTarget (if game.day<2 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null jobdone:->@target? sleeping:->true midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=Math.random() # 0<=r<1 unless r<=0.25 # 失敗 @addGamelog game,"catraise",false,pl.id return if r<=0.05 # 5%の確率で誤爆 deads=game.players.filter (x)->x.dead if deads.length==0 # 誰もいないじゃん @addGamelog game,"catraise",false,pl.id return pl=deads[Math.floor(Math.random()*deads.length)] @addGamelog game,"catraise",pl.id,@target else @addGamelog game,"catraise",true,@target # 蘇生 目を覚まさせる pl.revive game deadnight:(game,midnightSort)-> @setTarget @id @midnight game, midnightSort job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Witch extends Player type:"Witch" jobname:"<NAME>" midnightSort:100 isReviver:->!@dead job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も sleeping:->true jobdone:->@target? || (@flag in [3,5,6]) # @flag:ビットフラグ 1:殺害1使用済 2:殺害2使用済 4:蘇生使用済 8:今晩蘇生使用 16:今晩殺人使用 constructor:-> super @setFlag 0 # 発送済みかどうか sunset:(game)-> @setTarget null unless @flag @setFlag 0 else # jobだけ実行してmidnightがなかったときの処理 if @flag & 8 @setFlag @flag^8 if @flag & 16 @setFlag @flag^16 job:(game,playerid,query)-> # query.Witch_drug pl=game.getPlayer playerid unless pl? return "魔药使用无效" if pl.id==@id return "不能对自己使用魔药" if query.Witch_drug=="kill" # 毒薬 if game.day==1 return "今天不能使用毒药" if (@flag&3)==3 # 蘇生薬は使い切った return "已经不能使用毒药了" else if (@flag&4) && (@flag&3) # すでに薬は2つ使っている return "已经不能使用毒药了" if pl.dead return "使用目标已经死亡" # 薬を使用 pl.touched game,@id @flag |= 16 # 今晩殺害使用 if (@flag&1)==0 @flag |= 1 # 1つ目 else @flag |= 2 # 2つ目 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了毒药。" splashlog game.id,game,log else # 蘇生薬 if (@flag&3)==3 || (@flag&4) return "已经不能使用复活药了" if !pl.dead return "使用对象活着" # 薬を使用 pl.touched game,@id @flag |= 12 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了复活药。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? if @flag & 8 # 蘇生 @setFlag @flag^8 # 蘇生 目を覚まさせる @addGamelog game,"witchraise",null,pl.id pl.revive game else if @flag & 16 # 殺害 @setFlag @flag^16 @addGamelog game,"witchkill",null,pl.id pl.die game,"witch" class Oldman extends Player type:"Oldman" jobname:"<NAME>" midnight:(game,midnightSort)-> # 夜の終わり wolves=game.players.filter (x)->x.isWerewolf() && !x.dead if wolves.length*2<=game.day # 寿命 @die game,"infirm" class Tanner extends Player type:"Tanner" jobname:"<NAME>" team:"" die:(game,found)-> if found in ["gone-day","gone-night"] # 突然死はダメ @setFlag "gone" super isWinner:(game,team)->@dead && @flag!="gone" class OccultMania extends Player type:"OccultMania" jobname:"怪诞狂热者" midnightSort:100 sleeping:(game)->@target? || game.day<2 sunset:(game)-> @setTarget (if game.day>=2 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在不能使用能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 指定了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> p=game.getPlayer @target return unless p? # 変化先决定 type="Human" if p.isJobType "Diviner" type="Diviner" else if p.isWerewolf() type="Werewolf" newpl=Player.factory type @transProfile newpl @transferData newpl newpl.sunset game # 初期化してあげる @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.realid,"refresh",{id:game.id} null # 狼之子 class WolfCub extends Werewolf type:"WolfCub" jobname:"狼之子" dying:(game,found)-> super game.werewolf_flag.push "WolfCub" # 低语狂人 class WhisperingMad extends Fanatic type:"WhisperingMad" jobname:"低语狂人" getSpeakChoice:(game)-> ["werewolf"].concat super isListener:(game,log)-> if log.mode=="werewolf" true else super class Lover extends Player type:"Lover" jobname:"<NAME>爱者" team:"Friend" constructor:-> super @setTarget null # 相手 sunset:(game)-> unless @flag? if @scapegoat # 替身君は求愛しない @setFlag true @setTarget "" else @setTarget null sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能射出爱之箭" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的对象" pl.touched game,@id @setTarget playerid @setFlag true # 恋人二人が决定した plpls=[this,pl] for x,i in plpls newpl=Player.factory null,x,null,Friend # 恋人だ! x.transProfile newpl x.transform game,newpl,true # 入れ替え newpl.cmplFlag=plpls[1-i].id log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 求爱了。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{pl.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [this, pl] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 仆从选择者 class MinionSelector extends Player type:"MinionSelector" jobname:"仆从选择者" team:"Werewolf" sleeping:(game)->@target? || game.day>1 # 初日のみ sunset:(game)-> @setTarget (if game.day==1 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day!=1 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" # 複合させる newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"wolfskill" comment:"#{@name} 指定 #{pl.name}(#{pl.jobname})成为了狼的仆从。" splashlog game.id,game,log log= mode:"skill" to:pl.id comment:"#{pl.name} 变成了狼的仆从。" splashlog game.id,game,log null # 小偷 class Thief extends Player type:"Thief" jobname:"<NAME>" team:"" sleeping:(game)->@target? || game.day>1 sunset:(game)-> @setTarget (if game.day==1 then null else "") # @flag:JSON的职业候補配列 if !target? arr=JSON.parse(@flag ? '["Human"]') jobnames=arr.map (x)-> testpl=new jobs[x] testpl.getJobDisp() log= mode:"skill" to:@id comment:"#{@name} 可以选择的职业有 #{jobnames.join(",")}。" splashlog game.id,game,log if @scapegoat # 身代わり君 r=Math.floor Math.random()*arr.length @job game,arr[r] job:(game,target)-> @setTarget target unless jobs[target]? return "不能变成那个职业" newpl=Player.factory target @transProfile newpl @transferData newpl newpl.sunset game @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} null makeJobSelection:(game)-> if game.night # 职业から选择 arr=JSON.parse(@flag ? '["Human"]') arr.map (x)-> testpl=new jobs[x] { name:testpl.getJobDisp() value:x } else super class Dog extends Player type:"Dog" jobname:"<NAME>" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 sunset:(game)-> super @setTarget null # 1日目:飼い主选择 选择後:かみ殺す人选择 if !@flag? # 飼い主を決めていない if @scapegoat alives=game.players.filter (x)=>!x.dead && x.id!=@id if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setFlag "" @setTarget "" else # 飼い主を护卫する pl=game.getPlayer @flag if pl? if pl.dead # もう死んでるじゃん @setTarget "" # 洗濯済み else newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true sleeping:->@flag? jobdone:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" unless @flag? pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能成为自己的饲主。" pl.touched game,@id # 飼い主を选择した log= mode:"skill" to:@id comment:"#{@name} 选择 #{pl.name} 成为了自己的饲主。" splashlog game.id,game,log @setFlag playerid # 飼い主 @setTarget "" # 襲撃対象はなし else # 襲う pl=game.getPlayer @flag @setTarget @flag log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night if @flag? # 飼い主いる pl=game.getPlayer @flag if pl? if !pl.read result.open.push "Dog1" result.dogOwner=pl.publicinfo() else result.open.push "Dog2" makeJobSelection:(game)-> # 噛むときは対象选择なし if game.night && @flag? [] else super class Dictator extends Player type:"Dictator" jobname:"<NAME>裁<NAME>" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能发的能力" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid # 处刑する人 log= mode:"system" comment:"独裁者 #{@name} 宣布将要处刑 #{pl.name}。" splashlog game.id,game,log @setFlag true # 使用済 # その場で殺す!!! pl.die game,"punish",[@id] # 天黑了 log= mode:"system" comment:"独裁者 #{@name} 宣布,现在天黑了。" splashlog game.id,game,log # 強制的に次のターンへ game.nextturn() null class SeersMama extends Player type:"SeersMama" jobname:"占卜师的妈妈" sleeping:->true sunset:(game)-> unless @flag # まだ能力を実行していない # 占卜师を探す divs = game.players.filter (pl)->pl.isJobType "Diviner" divsstr=if divs.length>0 "#{divs.map((x)->x.name).join ','} 是占卜师" else "没有占卜师" log= mode:"skill" to:@id comment:"#{@name} 是占卜师的妈妈。#{divsstr}。" splashlog game.id,game,log @setFlag true #使用済 class Trapper extends Player type:"Trapper" jobname:"<NAME>" midnightSort:81 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目は护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> unless playerid==@id && game.rule.guardmyself!="ok" if playerid==@flag # 前も护卫した return "不能连续两天守护一个人" @setTarget playerid @setFlag playerid pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 的陷阱守护了 #{pl.name}。" splashlog game.id,game,log null else "不能守护自己" midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,TrapGuarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class WolfBoy extends Madman type:"WolfBoy" jobname:"<NAME>" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 伪装成了LowB。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Lycanized pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class Hoodlum extends Player type:"Hoodlum" jobname:"无赖" team:"" constructor:-> super @setFlag "[]" # 殺したい対象IDを入れておく @setTarget null sunset:(game)-> unless @target? # 2人選んでもらう @setTarget null if @scapegoat # 身代わり alives=game.players.filter (x)=>!x.dead && x!=this i=0 while i++<2 && alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" plids=JSON.parse(@flag||"[]") if pl.id in plids # 既にいる return "#{pl.name} 已经被选为对象" plids.push pl.id @setFlag JSON.stringify plids log= mode:"skill" to:@id comment:"#{@name} 憎恨 #{pl.name}。" splashlog game.id,game,log if plids.length>=2 @setTarget "" else # 2人目を選んでほしい @setTarget null null isWinner:(game,team)-> if @dead # 死んでたらだめ return false pls=JSON.parse(@flag).map (id)->game.getPlayer id return pls.every (pl)->pl?.dead==true class QuantumPlayer extends Player type:"QuantumPlayer" jobname:"量子人类" midnightSort:100 getJobname:-> flag=JSON.parse(@flag||"{}") jobname=null if flag.Human==1 jobname="母猪" else if flag.Diviner==1 jobname="占卜师" else if flag.Werewolf==1 jobname="LowB" numstr="" if flag.number? numstr="##{flag.number}" ret=if jobname? "量子人类#{numstr}(#{jobname})" else "量子人类#{numstr}" if @originalJobname != ret # 収束したぞ! @setOriginalJobname ret return ret sleeping:-> tarobj=JSON.parse(@target || "{}") tarobj.Diviner? && tarobj.Werewolf? # 両方指定してあるか sunset:(game)-> # @flagに{Human:(確率),Diviner:(確率),Werewolf:(確率),dead:(確率)}的なのが入っているぞ! obj=JSON.parse(@flag || "{}") tarobj= Diviner:null Werewolf:null if obj.Diviner==0 tarobj.Diviner="" # なし if obj.Werewolf==0 || (game.rule.quantumwerewolf_firstattack!="on" && game.day==1) tarobj.Werewolf="" @setTarget JSON.stringify tarobj if @scapegoat # 身代わり君の自動占い unless tarobj.Diviner? r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{ jobtype:"_Quantum_Diviner" } unless tarobj.Werewolf? nonme =game.players.filter (pl)=> pl!=this r=Math.floor Math.random()*nonme.length @job game,nonme[r].id,{ jobtype:"_Quantum_Werewolf" } isJobType:(type)-> # 便宜的 if type=="_Quantum_Diviner" || type=="_Quantum_Werewolf" return true super job:(game,playerid,query)-> tarobj=JSON.parse(@target||"{}") pl=game.getPlayer playerid unless pl? return "这个对象不存在" if query.jobtype=="_Quantum_Diviner" && !tarobj.Diviner? tarobj.Diviner=playerid log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log else if query.jobtype=="_Quantum_Werewolf" && !tarobj.Werewolf? if @id==playerid return "不能袭击自己。" tarobj.Werewolf=playerid log= mode:"skill" to:@id comment:"#{@name} 决定要袭击 #{pl.name}。" splashlog game.id,game,log else return "对象选择无效" @setTarget JSON.stringify tarobj null midnight:(game,midnightSort)-> # ここで処理 tarobj=JSON.parse(@target||"{}") if tarobj.Diviner pl=game.getPlayer tarobj.Diviner if pl? # 一旦自己が占卜师のやつ以外排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].jobtype=="Diviner" && obj[@id].dead==false # 1つ選んで占卜结果を决定 if pats.length>0 index=Math.floor Math.random()*pats.length j=pats[index][tarobj.Diviner].jobtype if j == "Werewolf" log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 LowB。" splashlog game.id,game,log # LowBのやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype == "Werewolf" else true else log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 母猪。" splashlog game.id,game,log # 母猪のやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype!="Werewolf" else true else # 占えない log= mode:"skill" to:@id comment:"#{@name} 已经不可能是占卜师,不能进行占卜。" splashlog game.id,game,log if tarobj.Werewolf pl=game.getPlayer tarobj.Werewolf if pl? game.quantum_patterns=game.quantum_patterns.filter (obj)=> # 何番が筆頭かを求める min=Infinity for key,value of obj if value.jobtype=="Werewolf" && value.dead==false && value.rank<min min=value.rank if obj[@id].jobtype=="Werewolf" && obj[@id].rank==min && obj[@id].dead==false # 自己が筆頭LowB if obj[pl.id].jobtype == "Werewolf"# || obj[pl.id].dead==true # 襲えない false else # さらに対応するやつを死亡させる obj[pl.id].dead=true true else true isWinner:(game,team)-> flag=JSON.parse @flag unless flag? return false if flag.Werewolf==1 && team=="Werewolf" # LowBがかったぞ!!!!! true else if flag.Werewolf==0 && team=="Human" # 人类がかったぞ!!!!! true else # よくわからないぞ! false makejobinfo:(game,result)-> super tarobj=JSON.parse(@target||"{}") unless tarobj.Diviner? result.open.push "_Quantum_Diviner" unless tarobj.Werewolf? result.open.push "_Quantum_Werewolf" if game.rule.quantumwerewolf_table=="anonymous" # 番号がある flag=JSON.parse @flag result.quantumwerewolf_number=flag.number die:(game,found)-> super # 可能性を排除する pats=[] if found=="punish" # 处刑されたときは既に死んでいた可能性を排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].dead==false else pats=game.quantum_patterns if pats.length # 1つ選んで职业を决定 index=Math.floor Math.random()*pats.length tjt=pats[index][@id].jobtype trk=pats[index][@id].rank if trk? pats=pats.filter (obj)=> obj[@id].jobtype==tjt && obj[@id].rank==trk else pats=pats.filter (obj)=> obj[@id].jobtype==tjt # ワタシハシンダ pats.forEach (obj)=> obj[@id].dead=true game.quantum_patterns=pats class RedHood extends Player type:"RedHood" jobname:"<NAME>" sleeping:->true isReviver:->!@dead || @flag? dying:(game,found,from)-> super if found=="werewolf" # 狼に襲われた # 誰に襲われたか覚えておく @setFlag from else @setFlag null deadsunset:(game)-> if @flag w=game.getPlayer @flag if w?.dead # 殺した狼が死んだ!復活する @revive game deadsunrise:(game)-> # 同じ @deadsunset game class Counselor extends Player type:"Counselor" jobname:"<NAME>" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目はカウンセリングできない @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 尝试了策反 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead tteam = t.getTeam() if t.isWerewolf() && tteam in ["Werewolf","LoneWolf"] # LowBとかヴァンパイアを襲ったら殺される @die game,"werewolf2" @addGamelog game,"counselKilled",t.type,@target return if t.isVampire() && tteam=="Vampire" @die game,"vampire2" @addGamelog game,"counselKilled",t.type,@target return if tteam!="Human" log= mode:"skill" to:t.id comment:"#{t.name} 被策反了。" splashlog game.id,game,log @addGamelog game,"counselSuccess",t.type,@target # 複合させる newpl=Player.factory null,t,null,Counseled # カウンセリングされた t.transProfile newpl t.transform game,newpl,true else @addGamelog game,"counselFailure",t.type,@target # 巫女 class Miko extends Player type:"Miko" jobname:"<NAME>" midnightSort:71 sleeping:->true jobdone:->!!@flag job:(game,playerid,query)-> if @flag return "已经使用了能力" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 用神圣的力量守护了自己。" splashlog game.id,game,log @setFlag "using" null midnight:(game,midnightSort)-> # 複合させる if @flag=="using" pl = game.getPlayer @id newpl=Player.factory null,pl,null,MikoProtected # 守られた人 pl.transProfile newpl pl.transform game,newpl,true @setFlag "done" null makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class GreedyWolf extends Werewolf type:"GreedyWolf" jobname:"贪婪的狼" sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && (@flag || game.day==1) job:(game,playerid,query)-> if query.jobtype!="GreedyWolf" # LowBの仕事 return super if @flag return "已经使用了能力" @setFlag true if game.werewolf_target_remain+game.werewolf_target.length ==0 return "今晚不能袭击" log= mode:"wolfskill" comment:"为了满足 #{@name} 的贪欲。LowB们今晚可以多袭击一个人。" splashlog game.id,game,log game.werewolf_target_remain++ game.werewolf_flag.push "GreedyWolf_#{@id}" game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() null makejobinfo:(game,result)-> super if game.night if @sleeping game # 襲撃は必要ない result.open = result.open?.filter (x)=>x!="_Werewolf" if !@flag && game.day>=2 result.open?.push "GreedyWolf" makeJobSelection:(game)-> if game.night && @sleeping(game) && !@jobdone(game) # 欲張る选择肢のみある return [] else return super checkJobValidity:(game,query)-> if query.jobtype=="GreedyWolf" # なしでOK! return true return super class FascinatingWolf extends Werewolf type:"FascinatingWolf" jobname:"魅惑的女狼" sleeping:(game)->super && @flag? sunset:(game)-> super if @scapegoat && !@flag? # 誘惑する hus=game.players.filter (x)->!x.dead && !x.isWerewolf() if hus.length>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{jobtype:"FascinatingWolf"} else @setFlag "" job:(game,playerid,query)-> if query.jobtype!="FascinatingWolf" # LowBの仕事 return super if @flag return "已经使用了能力" pl=game.getPlayer playerid unless pl? return "对象玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 魅惑了 #{pl.name}。" @setFlag playerid splashlog game.id,game,log null dying:(game,found)-> # 死んだぞーーーーーーーーーーーーーー super # LWなら変えない if game.players.filter((x)->x.isWerewolf() && !x.dead).length==0 return pl=game.getPlayer @flag unless pl? # あれれーーー return if pl.dead # 既に死んでいた return unless pl.isHuman() && pl.getTeam()!="Werewolf" # 誘惑できない return newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:pl.id comment:"#{pl.name} 被狼魅惑了。" splashlog game.id,game,log makejobinfo:(game,result)-> super if game.night if @flag # もう誘惑は必要ない result.open = result.open?.filter (x)=>x!="FascinatingWolf" class SolitudeWolf extends Werewolf type:"SolitudeWolf" jobname:"孤独的狼" sleeping:(game)-> !@flag || super isListener:(game,log)-> if (log.mode in ["werewolf","wolfskill"]) && (log.to != @id) # 狼の声は听不到(自己のスキルは除く) false else super job:(game,playerid,query)-> if !@flag return "现在还不能袭击" super isAttacker:->!@dead && @flag sunset:(game)-> wolves=game.players.filter (x)->x.isWerewolf() attackers=wolves.filter (x)->!x.dead && x.isAttacker() if !@flag && attackers.length==0 # 襲えるやつ誰もいない @setFlag true log= mode:"skill" to:@id comment:"#{@name} 现在可以袭击他人了。" splashlog game.id,game,log else if @flag && attackers.length>1 # 複数いるのでやめる @setFlag false log= mode:"skill" to:@id comment:"其他的LowB还活着。#{@name} 现在不能袭击他人。" splashlog game.id,game,log super getSpeakChoice:(game)-> res=super return res.filter (x)->x!="werewolf" makejobinfo:(game,result)-> super delete result.wolves delete result.spy2s class ToughWolf extends Werewolf type:"ToughWolf" jobname:"硬汉LowB" job:(game,playerid,query)-> if query.jobtype!="ToughWolf" # LowBの仕事 return super if @flag return "已经使用了能力" res=super if res? return res @setFlag true game.werewolf_flag.push "ToughWolf_#{@id}" tp=game.getPlayer playerid unless tp? return "这个对象不存在" log= mode:"wolfskill" comment:"#{@name} 抱着舍身的觉悟袭击了 #{tp.name}。" splashlog game.id,game,log null class ThreateningWolf extends Werewolf type:"ThreateningWolf" jobname:"威吓的狼" jobdone:(game)-> if game.night super else @flag? chooseJobDay:(game)->true sunrise:(game)-> super @setTarget null job:(game,playerid,query)-> if query.jobtype!="ThreateningWolf" # LowBの仕事 return super if @flag return "已经使用了能力" if game.night return "夜晚不能使用能力" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid @setFlag true log= mode:"skill" to:@id comment:"#{@name} 威吓了 #{pl.name}。" splashlog game.id,game,log null sunset:(game)-> t=game.getPlayer @target return unless t? return if t.dead # 威嚇して能力無しにする @addGamelog game,"threaten",t.type,@target # 複合させる log= mode:"skill" to:t.id comment:"#{t.name} 受到了威吓。今晚的能力无法发动。" splashlog game.id,game,log newpl=Player.factory null,t,null,Threatened # カウンセリングされた t.transProfile newpl t.transform game,newpl,true super makejobinfo:(game,result)-> super if game.night # 夜は威嚇しない result.open = result.open?.filter (x)=>x!="ThreateningWolf" class HolyMarked extends Human type:"HolyMarked" jobname:"圣痕者" class WanderingGuard extends Player type:"WanderingGuard" jobname:"<NAME>" midnightSort:80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else fl=JSON.parse(@flag ? "[]") alives=game.players.filter (x)->!x.dead if alives.every((pl)=>(pl.id in fl) || (game.rule.guardmyself!="ok" && pl.id==@id)) # もう护卫対象がいない @setTarget "" else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> fl=JSON.parse(@flag ? "[]") if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" fl=JSON.parse(@flag ? "[]") if playerid in fl return "这个人已经不能守护了" @setTarget playerid # OK! pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null beforebury:(game,type)-> if type=="day" # 昼になったとき if game.players.filter((x)->x.dead && x.found).length==0 # 誰も死ななかった!护卫できない pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 不能护卫 #{pl.name}。" splashlog game.id,game,log fl=JSON.parse(@flag ? "[]") fl.push pl.id @setFlag JSON.stringify fl makeJobSelection:(game)-> if game.night fl=JSON.parse(@flag ? "[]") a=super return a.filter (obj)->!(obj.value in fl) else return super class ObstructiveMad extends Madman type:"ObstructiveMad" jobname:"碍事的狂人" midnightSort:90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 妨碍了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineObstructed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true null class TroubleMaker extends Player type:"TroubleMaker" jobname:"<NAME>" midnightSort:100 sleeping:->true jobdone:->!!@flag makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super job:(game,playerid)-> return "已经使用了能力" if @flag @setFlag "using" log= mode:"skill" to:@id comment:"#{@name} 在村子里引发了混乱。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # ここが無効化されたら発動しないように if @flag=="using" @setFlag "using2" null sunrise:(game)-> if @flag=="using2" game.votingbox.addPunishedNumber 1 # トラブルがおきた log= mode:"system" comment:"闹事者在村子里引发了混乱。今日将会处刑 #{game.votingbox.remains} 个人。" splashlog game.id,game,log @setFlag "done" else if @flag=="using" # 不発だった @setFlag "done" deadsunrise:(game)->@sunrise game class FrankensteinsMonster extends Player type:"FrankensteinsMonster" jobname:"<NAME>肯斯坦的怪物" die:(game,found)-> super if found=="punish" # 处刑で死んだらもうひとり处刑できる game.votingbox.addPunishedNumber 1 beforebury:(game)-> # 新しく死んだひとたちで母猪阵营ひとたち # 不吸收弗兰肯斯坦的怪物 founds=game.players.filter (x)->x.dead && x.found && x.getTeam()=="Human" && !x.isJobType("FrankensteinsMonster") # 吸収する thispl=this for pl in founds log= mode:"skill" to:@id comment:"#{@name} 从 #{pl.name} 的尸体里吸收了 #{pl.getJobname()} 的能力。" splashlog game.id,game,log # 同じ能力を subpl = Player.factory pl.type thispl.transProfile subpl newpl=Player.factory null, thispl,subpl,Complex # 合成する thispl.transProfile newpl # 置き換える thispl.transform game,newpl,true thispl=newpl thispl.addGamelog game,"frankeneat",pl.type,pl.id if founds.length>0 game.splashjobinfo [thispl] class B<NAME>Mary extends Player type:"BloodyMary" jobname:"<NAME>" isReviver:->true getJobname:->if @flag then @jobname else "<NAME>" getJobDisp:->@getJobname() getTypeDisp:->if @flag then @type else "Mary" sleeping:->true deadJobdone:(game)-> if @target? true else if @flag=="punish" !(game.players.some (x)->!x.dead && x.getTeam()=="Human") else if @flag=="werewolf" if game.players.filter((x)->!x.dead && x.isWerewolf()).length>1 !(game.players.some (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"]) else # 狼が残り1匹だと何もない true else true dying:(game,found,from)-> if found in ["punish","werewolf"] # 能力が… orig_jobname=@getJobname() @setFlag found if orig_jobname != @getJobname() # 変わった! @setOriginalJobname @originalJobname.replace("血腥玛丽","玛丽").replace("玛丽","血腥玛丽") super sunset:(game)-> @setTarget null deadsunset:(game)-> @sunset game job:(game,playerid)-> unless @flag in ["punish","werewolf"] return "不能使用能力" pl=game.getPlayer playerid unless pl? return "对象不存在" log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log @setTarget playerid null # 呪い殺す!!!!!!!!! deadnight:(game,midnightSort)-> pl=game.getPlayer @target unless pl? return pl.die game,"marycurse",@id # 蘇生できない revive:-> isWinner:(game,team)-> if @flag=="punish" team in ["Werewolf","LoneWolf"] else team==@team makeJobSelection:(game)-> if game.night pls=[] if @flag=="punish" # 母猪を…… pls=game.players.filter (x)->!x.dead && x.getTeam()=="Human" else if @flag=="werewolf" # LowBを…… pls=game.players.filter (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"] return (for pl in pls { name:pl.name value:pl.id } ) else super makejobinfo:(game,obj)-> super if @flag && !("BloodyMary" in obj.open) obj.open.push "Bloody<NAME>" class King extends Player type:"King" jobname:"国王" voteafter:(game,target)-> super game.votingbox.votePower this,1 class PsychoKiller extends Madman type:"PsychoKiller" jobname:"变态杀人狂" midnightSort:110 constructor:-> super @flag="[]" touched:(game,from)-> # 殺すリストに追加する fl=try JSON.parse @flag || "[]" catch e [] fl.push from @setFlag JSON.stringify fl sunset:(game)-> @setFlag "[]" midnight:(game,midnightSort)-> fl=try JSON.parse @flag || "[]" catch e [] for id in fl pl=game.getPlayer id if pl? && !pl.dead pl.die game,"psycho",@id @setFlag "[]" deadnight:(game,midnightSort)-> @midnight game, midnightSort class SantaClaus extends Player type:"SantaClaus" jobname:"<NAME>诞老人" midnightSort:100 sleeping:->@target? constructor:-> super @setFlag "[]" isWinner:(game,team)->@flag=="gone" || super sunset:(game)-> # まだ届けられる人がいるかチェック fl=JSON.parse(@flag ? "[]") if game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) @setTarget null if @scapegoat cons=game.players.filter((x)=>!x.dead && x.id!=@id && !(x.id in fl)) if cons.length>0 r=Math.floor Math.random()*cons.length @job game,cons[r].id,{} else @setTarget "" else @setTarget "" sunrise:(game)-> # 全员に配ったかチェック fl=JSON.parse(@flag ? "[]") unless game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) # 村を去る @setFlag "gone" @die game,"spygone" job:(game,playerid)-> if @flag=="gone" return "已经离开了村子" fl=JSON.parse(@flag ? "[]") if playerid == @id return "不能把礼物送给自己" if playerid in fl return "这个人已经不能继续接受礼物了" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 赠送了礼物。" splashlog game.id,game,log fl.push playerid @setFlag JSON.stringify fl null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return if @flag=="gone" # プレゼントを送る r=Math.random() settype="" setname="" if r<0.05 # 毒だった log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了剧毒的礼物。" splashlog game.id,game,log pl.die game,"poison",@id @addGamelog game,"sendpresent","poison",pl.id return else if r<0.1 settype="HolyMarked" setname="圣痕者套装" else if r<0.15 settype="Oldman" setname="玉手箱" else if r<0.225 settype="Priest" setname="圣职者套装" else if r<0.3 settype="Miko" setname="Cosplay套装(巫女)" else if r<0.55 settype="Diviner" setname="占卜套装" else if r<0.8 settype="Guard" setname="守护套装" else settype="Psychic" setname="灵能套装" # 複合させる log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了礼物 #{setname}。" splashlog game.id,game,log # 複合させる sub=Player.factory settype # 副を作る pl.transProfile sub newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true @addGamelog game,"sendpresent",settype,pl.id #怪盗 class Phantom extends Player type:"Phantom" jobname:"怪盗" sleeping:->@target? sunset:(game)-> if @flag==true # もう交換済みだ @setTarget "" else @setTarget null if @scapegoat rs=@makeJobSelection game if rs.length>0 r=Math.floor Math.random()*rs.length @job game,rs[r].value,{ jobtype:@type } makeJobSelection:(game)-> if game.night res=[{ name:"放弃盗取" value:"" }] sup=super for obj in sup pl=game.getPlayer obj.value unless pl?.scapegoat res.push obj return res else super job:(game,playerid)-> @setTarget playerid if playerid=="" # 交換しない log= mode:"skill" to:@id comment:"#{@name} 没有盗取职业。" splashlog game.id,game,log return pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 盗取了 #{pl.name} 的职业。#{pl.name} 是 #{pl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"phantom",pl.type,playerid null sunrise:(game)-> @setFlag true pl=game.getPlayer @target unless pl? return savedobj={} pl.makejobinfo game,savedobj flagobj={} # jobinfo表示のみ抜粋 for value in Shared.game.jobinfos if savedobj[value.name]? flagobj[value.name]=savedobj[value.name] # 自己はそ的职业に変化する newpl=Player.factory pl.type @transProfile newpl @transferData newpl @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 盗まれた側は怪盗予備軍のフラグを立てる newpl2=Player.factory null,pl,null,PhantomStolen newpl2.cmplFlag=flagobj pl.transProfile newpl2 pl.transform game,newpl2,true class BadLady extends Player type:"BadLady" jobname:"<NAME>" team:"Friend" sleeping:->@flag?.set sunset:(game)-> unless @flag?.set # まだ恋人未设定 if @scapegoat @flag={ set:true } job:(game,playerid,query)-> fl=@flag ? {} if fl.set return "已经决定了对象" if playerid==@id return "请选择自己以外的对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id unless fl.main? # 本命を決める fl.main=playerid log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为自己的本命对象。" splashlog game.id,game,log @setFlag fl @addGamelog game,"badlady_main",pl.type,playerid return null unless fl.keep? # キープ相手を決める fl.keep=playerid fl.set=true @setFlag fl log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为玩弄的对象。" splashlog game.id,game,log # 2人を恋人、1人をキープに plm=game.getPlayer fl.main for pll in [plm,pl] if pll? log= mode:"skill" to:pll.id comment:"#{pll.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 自己恋人 newpl=Player.factory null,this,null,Friend # 恋人だ! newpl.cmplFlag=fl.main @transProfile newpl @transform game,newpl,true # 入れ替え # 相手恋人 newpl=Player.factory null,plm,null,Friend # 恋人だ! newpl.cmplFlag=@id plm.transProfile newpl plm.transform game,newpl,true # 入れ替え # キープ newpl=Player.factory null,pl,null,KeepedLover # 恋人か? newpl.cmplFlag=@id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え game.splashjobinfo [@id,plm.id,pl.id].map (id)->game.getPlayer id @addGamelog game,"badlady_keep",pl.type,playerid null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night # 夜の选择肢 fl=@flag ? {} unless fl.set unless fl.main # 本命を決める result.open.push "BadLady1" else if !fl.keep # 手玉に取る result.open.push "BadLady2" # 看板娘 class DrawGirl extends Player type:"DrawGirl" jobname:"<NAME>" sleeping:->true dying:(game,found)-> if found=="werewolf" # 狼に噛まれた @setFlag "bitten" else @setFlag "" super deadsunrise:(game)-> # 夜明けで死亡していた場合 if @flag=="bitten" # 噛まれて死亡した場合 game.votingbox.addPunishedNumber 1 log= mode:"system" comment:"#{@name} 是看板娘。今日将有 #{game.votingbox.remains} 人被处刑。" splashlog game.id,game,log @setFlag "" @addGamelog game,"drawgirlpower",null,null # 慎重的狼 class CautiousWolf extends Werewolf type:"CautiousWolf" jobname:"慎重的狼" makeJobSelection:(game)-> if game.night r=super return r.concat { name:"不袭击" value:"" } else return super job:(game,playerid)-> if playerid!="" super return # 不袭击場合 game.werewolf_target.push { from:@id to:"" } game.werewolf_target_remain-- log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚不发动袭击。" splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null # 烟火师 class Pyrotechnist extends Player type:"Pyrotechnist" jobname:"<NAME>火师" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能使用此能力" log= mode:"skill" to:@id comment:"#{@name} 准备释放烟火了。" splashlog game.id,game,log # 使用済 @setFlag "using" null sunset:(game)-> if @flag=="using" log= mode:"system" comment:"美丽的烟火被打上了天空。今晚不能使用能力。" splashlog game.id,game,log @setFlag "done" deadsunset:(game)-> @sunset game checkJobValidity:(game,query)-> if query.jobtype=="Pyrotechnist" # 対象选择は不要 return true return super # 面包店 class Baker extends Player type:"Baker" jobname:"面包店" sleeping:->true sunrise:(game)-> # 最初の1人が面包店ログを管理 bakers=game.players.filter (x)->x.isJobType "Baker" firstBakery=bakers[0] if firstBakery?.id==@id # わ た し だ if bakers.some((x)->!x.dead) # 生存面包店がいる if @flag=="done" @setFlag null log= mode:"system" comment:"面包店烤好了美味的面包。" splashlog game.id,game,log else if @flag!="done" # 全员死亡していてまたログを出していない log= mode:"system" comment:"今天开始没有美味的面包吃了。" splashlog game.id,game,log @setFlag "done" deadsunrise:(game)-> @sunrise game class Bomber extends Madman type:"Bomber" jobname:"<NAME> <NAME>" midnightSort:81 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效。" pl.touched game,@id @setTarget playerid @setFlag true # 爆弾を仕掛ける log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 送出了炸弹。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,BombTrapped pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true @addGamelog game,"bomber_set",pl.type,@target null class Blasphemy extends Player type:"Blasphemy" jobname:"<NAME>" team:"Fox" midnightSort:100 sleeping:(game)->@target? || @flag constructor:-> super @setFlag null sunset:(game)-> if @flag @setTarget "" else @setTarget null if @scapegoat # 替身君 alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" beforebury:(game,type)-> if @flag # まだ狐を作ってないときは耐える # 狐が全员死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" job:(game,playerid)-> if @flag || @target? return "已经不能发动能力了" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 亵渎了 #{pl.name}。" splashlog game.id,game,log @addGamelog game,"blasphemy",pl.type,playerid return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # まずい対象だと自己が冒涜される if pl.type in ["Fugitive","QueenSpectator","Liar","Spy2","LoneWolf"] pl=this return if pl.dead @setFlag true # 狐凭をつける newpl=Player.factory null,pl,null,FoxMinion pl.transProfile newpl pl.transform game,newpl,true class Ushinotokimairi extends Madman type:"Ushinotokimairi" jobname:"<NAME>时之女" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineCursed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true @addGamelog game,"ushinotokimairi_curse",pl.type,@target null divined:(game,player)-> if @target? # 能力を使用していた場合は占われると死ぬ @die game,"curse" player.addGamelog game,"cursekill",null,@id super class Patissiere extends Player type: "Patissiere" jobname: "<NAME>" team:"Friend" midnightSort:100 sunset:(game)-> unless @flag? if @scapegoat # 替身君はチョコを配らない @setFlag true @setTarget "" else @setTarget null else @setTarget "" sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能送出巧克力" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的人" pl.touched game,@id @setTarget playerid @setFlag true log= mode: "skill" to: @id comment: "#{@name} 将 #{pl.name} 选为本命。" splashlog game.id, game, log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 全員にチョコを配る(1人本命) alives = game.players.filter((x)->!x.dead).map((x)-> x.id) for pid in alives p = game.getPlayer pid if p.id == pl.id # 本命 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateTrue newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log else if p.id != @id # 義理 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateFalse newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log # 自分は本命と恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag=pl.id top.transProfile newpl top.transferData newpl top.transform game,newpl,true log= mode: "skill" to: @id comment: "#{@name} 与 #{pl.name} 结为恋人。" splashlog game.id, game, log null # 内部処理用:チョコレートもらった class GotChocolate extends Player type: "GotChocolate" jobname: "巧克力" midnightSort:100 sleeping:->true jobdone:(game)-> @flag!="unselected" job_target:0 getTypeDisp:->if @flag=="done" then null else @type makeJobSelection:(game)-> if game.night [] else super sunset:(game)-> if !@flag? # 最初は選択できない @setTarget "" @setFlag "waiting" else if @flag=="waiting" # 選択できるようになった @setFlag "unselected" job:(game,playerid)-> unless @flag == "unselected" return "无法使用能力" # 食べると本命か義理か判明する flag = false top = game.getPlayer @id unless top? # ????? return "对象无效" while top?.isComplex() if top.cmplType=="GotChocolateTrue" && top.sub==this # 本命だ t=game.getPlayer top.cmplFlag if t? log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是本命巧克力。#{@name} 与 #{t.name} 结为恋人。" splashlog game.id, game, log @setFlag "done" # 本命を消す top.uncomplex game, false # 恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag = t.id top.transProfile newpl top.transform game,newpl,true top = game.getPlayer @id flag = true game.ss.publish.user top.id,"refresh",{id:game.id} break else if top.cmplType=="GotChocolateFalse" && top.sub==this # 義理だ @setFlag "selected:#{top.cmplFlag}" flag = true log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是义理巧克力。" splashlog game.id, game, log break top = top.main if flag == false # チョコレートをもらっていなかった log= mode:"skill" to: @id comment: "#{@name} 吃下了巧克力,什么都没有发生。" splashlog game.id, game, log null midnight:(game,midnightSort)-> re = @flag?.match /^selected:(.+)$/ if re? @setFlag "done" @uncomplex game, true # 義理チョコの効果発動 top = game.getPlayer @id r = Math.random() if r < 0.12 # 呪いのチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是被诅咒的巧克力,下一天白天不能发言。" splashlog game.id, game, log newpl = Player.factory null, top, null, Muted top.transProfile newpl top.transform game, newpl, true else if r < 0.30 # ブラックチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是黑巧克力,占卜·灵能结果将变为「LowB」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Blacked top.transProfile newpl top.transform game, newpl, true else if r < 0.45 # ホワイトチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是白巧克力,占卜·灵能结果将变为「母猪」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Whited top.transProfile newpl top.transform game, newpl, true else if r < 0.50 # 毒入りチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是毒巧克力,将被毒死。" splashlog game.id, game, log @die game, "poison", @id else if r < 0.57 # ストーカー化 topl = game.getPlayer re[1] if topl? newpl = Player.factory "Stalker" top.transProfile newpl # ストーカー先 newpl.setFlag re[1] top.transform game, newpl, true log= mode:"skill" to: @id comment: "#{@name} 凭借执念找到了巧克力的送出人,#{@name} 成为了 #{topl.name} 的跟踪狂。" splashlog game.id, game, log else if r < 0.65 # 血入りの…… log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力不知为何有铁锈的味道,占卜结果将变为「吸血鬼」。" splashlog game.id, game, log newpl = Player.factory null, top, null, VampireBlooded top.transProfile newpl top.transform game, newpl, true else if r < 0.75 # 聖職 log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力蕴含着神圣的力量,#{@name} 可以使用一次「圣职者」的力量。" splashlog game.id, game, log sub = Player.factory "Priest" top.transProfile sub newpl = Player.factory null, top, sub, Complex top.transProfile newpl top.transform game, newpl, true class MadDog extends Madman type:"MadDog" jobname:"狂犬" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # 襲撃実行 @setFlag true # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null class Hypnotist extends Madman type:"Hypnotist" jobname:"催眠师" midnightSort:50 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 催眠了 #{pl.name}。" splashlog game.id,game,log @setFlag true null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return if pl.isWerewolf() # LowBを襲撃した場合はLowBの襲撃を無効化する game.werewolf_target = [] game.werewolf_target_remain = 0 # 催眠術を付加する @addGamelog game,"hypnosis",pl.type,pl.id newpl=Player.factory null,pl,null,UnderHypnosis pl.transProfile newpl pl.transform game,newpl,true return null class CraftyWolf extends Werewolf type:"CraftyWolf" jobname:"狡猾的狼" jobdone:(game)->super && @flag == "going" deadJobdone:(game)->@flag != "revivable" midnightSort:100 isReviver:->!@dead || (@flag in ["reviving","revivable"]) sunset:(game)-> super # 生存状態で昼になったら死んだふり能力初期化 @setFlag "" job:(game,playerid,query)-> if query.jobtype!="CraftyWolf" return super if @dead # 死亡時 if @flag != "revivable" return "不能使用能力" @setFlag "reviving" log= mode:"skill" to:@id comment:"#{@name} 取消假死了。" splashlog game.id,game,log return null else # 生存時 if @flag != "" return "已经使用过能力" # 生存フラグを残しつつ死ぬ @setFlag "going" log= mode:"skill" to:@id comment:"#{@name} 假死了。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> if @flag=="going" @die game, "crafty" @addGamelog game,"craftydie" @setFlag "revivable" deadnight:(game,midnightSort)-> if @flag=="reviving" # 生存していた pl = game.getPlayer @id if pl? pl.setFlag "" pl.revive game pl.addGamelog game,"craftyrevive" else # 生存フラグが消えた @setFlag "" makejobinfo:(game,result)-> super result.open ?= [] if @dead && @flag=="revivable" # 死に戻り result.open = result.open.filter (x)->!(x in ["CraftyWolf","_Werewolf"]) result.open.push "CraftyWolf2" return result makeJobSelection:(game)-> if game.night && @dead && @flag=="revivable" # 死んだふりやめるときは選択肢がない [] else if game.night && game.werewolf_target_remain==0 # もう襲撃対象を選択しない [] else super checkJobValidity:(game,query)-> if query.jobtype in ["CraftyWolf","CraftyWolf2"] # 対象選択は不要 return true return super class Shishimai extends Player type:"Shishimai" jobname:"<NAME>" team:"" sleeping:->true jobdone:(game)->@target? isWinner:(game,team)-> # 生存者(自身を除く)を全員噛んだら勝利 alives = game.players.filter (x)->!x.dead bitten = JSON.parse (@flag || "[]") flg = true for pl in alives if pl.id == @id continue unless pl.id in bitten flg = false break return flg sunset:(game)-> alives = game.players.filter (x)->!x.dead if alives.length > 0 @setTarget null if @scapegoat r = Math.floor Math.random()*alives.length @job game, alives[r].id, {} else @setTarget "" job:(game,playerid)-> pl = game.getPlayer playerid unless pl? return "这个玩家不存在。" bitten = JSON.parse (@flag || "[]") if playerid in bitten return "这个玩家已经被咀嚼过了。" log= mode:"skill" to:@id comment:"#{@name} 咀嚼了 #{pl.name}。" splashlog game.id, game, log @setTarget playerid null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 票数が減る祝いをかける newpl = Player.factory null, pl, null, VoteGuarded pl.transProfile newpl pl.transform game, newpl, true newpl.touched game,@id # 噛んだ記録 arr = JSON.parse (@flag || "[]") arr.push newpl.id @setFlag (JSON.stringify arr) # かみかみ @addGamelog game, "shishimaibit", newpl.type, newpl.id null class Pumpkin extends Madman type: "Pumpkin" jobname: "南瓜魔" midnightSort: 90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives = game.players.filter (x)->!x.dead if alives.length == 0 @setTarget "" else r=Math.floor Math.random()*alives.length @job game,alives[r].id ,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid return unless pl? pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 变成了南瓜。" splashlog game.id,game,log @addGamelog game,"pumpkin",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead newpl=Player.factory null, t,null, PumpkinCostumed t.transProfile newpl t.transform game,newpl,true class MadScientist extends Madman type:"MadScientist" jobname:"疯狂科学家" midnightSort:100 isReviver:->!@dead && @flag!="done" sleeping:->true jobdone:->@flag=="done" || @target? job_target: Player.JOB_T_DEAD sunset:(game)-> @setTarget (if game.day<2 || @flag=="done" then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない job:(game,playerid)-> if game.day<2 return "现在还不能发动技能" if @flag == "done" return "已经不能发动技能" pl=game.getPlayer playerid unless pl? return "这个玩家不存在" unless pl.dead return "不能选择这名玩家" @setFlag "done" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 实施了复活手术。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 蘇生 @addGamelog game,"raise",true,pl.id pl.revive game pl = game.getPlayer @target return if pl.dead # 蘇生に成功したら胜利条件を変える newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:newpl.id comment:"#{newpl.name} 变成了狼的仆从。" splashlog game.id,game,log class SpiritPossessed extends Player type:"SpiritPossessed" jobname:"恶灵凭依" isReviver:->!@dead # ============================ # 処理上便宜的に使用 class GameMaster extends Player type:"GameMaster" jobname:"游戏管理员" team:"" jobdone:->false sleeping:->true isWinner:(game,team)->null # 例外的に昼でも発動する可能性がある job:(game,playerid,query)-> pl=game.getPlayer playerid unless pl? return "对象无效" pl.die game,"gmpunish" game.bury("other") null isListener:(game,log)->true # 全て見える getSpeakChoice:(game)-> pls=for pl in game.players "gmreply_#{pl.id}" ["gm","gmheaven","gmaudience","gmmonologue"].concat pls getSpeakChoiceDay:(game)->@getSpeakChoice game chooseJobDay:(game)->true # 昼でも対象选择 # 帮手 class Helper extends Player type:"Helper" jobname:"<NAME>" team:"" jobdone:->@flag? sleeping:->true voted:(game,votingbox)->true isWinner:(game,team)-> pl=game.getPlayer @flag return pl?.isWinner game,team # @flag: リッスン対象のid # 同じものが見える isListener:(game,log)-> pl=game.getPlayer @flag unless pl? # 自律行動帮手? return super if pl.isJobType "Helper" # 帮手の帮手の場合は听不到(無限ループ防止) return false return pl.isListener game,log getSpeakChoice:(game)-> if @flag? return ["helperwhisper_#{@flag}"] else return ["helperwhisper"] getSpeakChoiceDay:(game)->@getSpeakChoice game job:(game,playerid)-> if @flag? return "已经决定了帮助对象" pl=game.getPlayer playerid unless pl? return "帮助对象不存在" @flag=playerid log= mode:"skill" to:playerid comment:"#{@name} 成为了 #{pl.name} 的帮手。" splashlog game.id,game,log # 自己の表記を改める game.splashjobinfo [this] null makejobinfo:(game,result)-> super # ヘルプ先が分かる pl=game.getPlayer @flag if pl? helpedinfo={} pl.makejobinfo game,helpedinfo result.supporting=pl?.publicinfo() result.supportingJob=pl?.getJobDisp() for value in Shared.game.jobinfos if helpedinfo[value.name]? result[value.name]=helpedinfo[value.name] null # 开始前のやつだ!!!!!!!! class Waiting extends Player type:"Waiting" jobname:"尚未分配" team:"" sleeping:(game)->!game.rolerequestingphase || game.rolerequesttable[@id]? isListener:(game,log)-> if log.mode=="audience" true else super getSpeakChoice:(game)-> return ["prepare"] makejobinfo:(game,result)-> super # 自己で追加する result.open.push "Waiting" makeJobSelection:(game)-> if game.day==0 && game.rolerequestingphase # 开始前 result=[{ name:"放弃选择" value:"" }] for job,num of game.joblist if num result.push { name:Shared.game.getjobname job value:job } return result else super job:(game,target)-> # 希望职业 game.rolerequesttable[@id]=target if target log= mode:"skill" to:@id comment:"#{@name} 希望成为 #{Shared.game.getjobname target}。" else log= mode:"skill" to:@id comment:"#{@name} 放弃选择职业。" splashlog game.id,game,log null # Endless黑暗火锅でまだ入ってないやつ class Watching extends Player type:"Watching" jobname:"<NAME>战<NAME>" team:"" sleeping:(game)->true isWinner:(game,team)->true isListener:(game,log)-> if log.mode in ["audience","inlog"] # 参加前なので true else super getSpeakChoice:(game)-> return ["audience"] getSpeakChoiceDay:(game)-> return ["audience"] # 複合职业 Player.factoryで適切に生成されることを期待 # superはメイン职业 @mainにメイン @subにサブ # @cmplFlag も持っていい class Complex cmplType:"Complex" # 複合親そのものの名字 isComplex:->true getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() midnightSort: 100 #@mainのやつを呼ぶ mcall:(game,method,args...)-> if @main.isComplex() # そのまま return method.apply @main,args # 他は親が必要 top=game.participants.filter((x)=>x.id==@id)[0] if top? return method.apply top,args return null setDead:(@dead,@found)-> @main.setDead @dead,@found @sub?.setDead @dead,@found setWinner:(@winner)->@main.setWinner @winner setTarget:(@target)->@main.setTarget @target setFlag:(@flag)->@main.setFlag @flag setWill:(@will)->@main.setWill @will setOriginalType:(@originalType)->@main.setOriginalType @originalType setOriginalJobname:(@originalJobname)->@main.setOriginalJobname @originalJobname setNorevive:(@norevive)->@main.setNorevive @norevive jobdone:(game)-> @mcall(game,@main.jobdone,game) && (!@sub?.jobdone? || @sub.jobdone(game)) # ジョブの場合はサブも考慮 job:(game,playerid,query)-> # どちらの # query.jobtypeがない場合は内部処理なのでmainとして処理する? unless query? query={} unless query.jobtype? query.jobtype=@main.type if @main.isJobType(query.jobtype) && ((@main.dead && !@main.deadJobdone(game)) || (!@main.dead && !@main.jobdone(game))) @mcall game,@main.job,game,playerid,query else if @sub?.isJobType?(query.jobtype) && ((@sub.dead && !@sub.deadJobdone(game)) || (!@sub.dead && !@sub?.jobdone?(game))) @sub.job? game,playerid,query # Am I Walking Dead? isDead:-> isMainDead = @main.isDead() if isMainDead.dead && isMainDead.found # Dead! return isMainDead if @sub? isSubDead = @sub.isDead() if isSubDead.dead && isSubDead.found # Dead! return isSubDead # seems to be alive, who knows? return {dead:@dead,found:@found} isJobType:(type)-> @main.isJobType(type) || @sub?.isJobType?(type) getTeam:-> if @team then @team else @main.getTeam() #An access to @main.flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" unless @isJobType(type) return null if @main.isJobType(type) return @main.accessByJobType(type) else unless @sub? return null return @sub.accessByJobType(type) null gatherMidnightSort:-> mids=[@midnightSort] mids=mids.concat @main.gatherMidnightSort() if @sub? mids=mids.concat @sub.gatherMidnightSort() return mids sunset:(game)-> @mcall game,@main.sunset,game @sub?.sunset? game midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort deadnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.deadnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.deadnight? game,midnightSort deadsunset:(game)-> @mcall game,@main.deadsunset,game @sub?.deadsunset? game deadsunrise:(game)-> @mcall game,@main.deadsunrise,game @sub?.deadsunrise? game sunrise:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game votestart:(game)-> @mcall game,@main.votestart,game voted:(game,votingbox)->@mcall game,@main.voted,game,votingbox dovote:(game,target)-> @mcall game,@main.dovote,game,target voteafter:(game,target)-> @mcall game,@main.voteafter,game,target @sub?.voteafter game,target modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote @mcall game, @main.modifyMyVote, game, vote makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result,@main.getJobDisp() beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type # deal with Walking Dead unless @dead isPlDead = @isDead() if isPlDead.dead && isPlDead.found @setDead isPlDead.dead,isPlDead.found divined:(game,player)-> @mcall game,@main.divined,game,player @sub?.divined? game,player getjob_target:-> if @sub? @main.getjob_target() | @sub.getjob_target() # ビットフラグ else @main.getjob_target() die:(game,found,from)-> @mcall game,@main.die,game,found,from dying:(game,found,from)-> @mcall game,@main.dying,game,found,from @sub?.dying game,found,from revive:(game)-> # まずsubを蘇生 if @sub? @sub.revive game if @sub.dead # 蘇生できない類だ return # 次にmainを蘇生 @mcall game,@main.revive,game if @main.dead # 蘇生できなかった @setDead true, @main.found else # 蘇生できた @setDead false, null makeJobSelection:(game)-> result=@mcall game,@main.makeJobSelection,game if @sub? for obj in @sub.makeJobSelection game unless result.some((x)->x.value==obj.value) result.push obj result checkJobValidity:(game,query)-> if query.jobtype=="_day" return @mcall(game,@main.checkJobValidity,game,query) if @mcall(game,@main.isJobType,query.jobtype) && !@mcall(game,@main.jobdone,game) return @mcall(game,@main.checkJobValidity,game,query) else if @sub?.isJobType?(query.jobtype) && !@sub?.jobdone?(game) return @sub.checkJobValidity game,query else return true getSpeakChoiceDay:(game)-> result=@mcall game,@main.getSpeakChoiceDay,game if @sub? for obj in @sub.getSpeakChoiceDay game unless result.some((x)->x==obj) result.push obj result getSpeakChoice:(game)-> result=@mcall game,@main.getSpeakChoice,game if @sub? for obj in @sub.getSpeakChoice game unless result.some((x)->x==obj) result.push obj result isListener:(game,log)-> @mcall(game,@main.isListener,game,log) || @sub?.isListener(game,log) isReviver:->@main.isReviver() || @sub?.isReviver() isHuman:->@main.isHuman() isWerewolf:->@main.isWerewolf() isFox:->@main.isFox() isVampire:->@main.isVampire() isWinner:(game,team)->@main.isWinner game, team #superがつかえないので注意 class Friend extends Complex # 恋人 # cmplFlag: 相方のid cmplType:"Friend" isFriend:->true team:"Friend" getJobname:->"恋人(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type ato=false if game.rule.friendssplit=="split" # 独立 pl=game.getPlayer @cmplFlag if pl? && pl.dead && pl.isFriend() ato=true else # みんな friends=game.players.filter (x)->x.isFriend() #恋人たち if friends.length>1 && friends.some((x)->x.dead) ato=true # 恋人が誰か死んだら自殺 if ato @die game,"friendsuicide" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"<NAME>" type:"Friend" } if game.rule.friendssplit=="split" # 独立 fr=[this,game.getPlayer(@cmplFlag)].filter((x)->x?.isFriend()).map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr else # みんないっしょ result.friends=game.players.filter((x)->x.isFriend()).map (x)-> x.publicinfo() isWinner:(game,team)->@team==team && !@dead # 相手のIDは? getPartner:-> if @cmplType=="Friend" return @cmplFlag else return @main.getPartner() # 圣职者にまもられた人 class HolyProtected extends Complex # cmplFlag: 护卫元 cmplType:"HolyProtected" die:(game,found)-> # 一回耐える 死なない代わりに元に戻る log= mode:"skill" to:@id comment:"#{@name} 被神圣的力量守护了。" splashlog game.id,game,log game.getPlayer(@cmplFlag).addGamelog game,"holyGJ",found,@id @uncomplex game # カルトの信者になった人 class CultMember extends Complex cmplType:"CultMember" isCult:->true getJobname:->"教会信者(#{@main.getJobname()})" getJobDisp:->"教会信者(#{@main.getJobDisp()})" makejobinfo:(game,result)-> super # 信者の説明 result.desc?.push { name:"<NAME>" type:"CultMember" } # 猎人に守られた人 class Guarded extends Complex # cmplFlag: 护卫元ID cmplType:"Guarded" die:(game,found,from)-> unless found in ["werewolf","vampire"] @mcall game,@main.die,game,found,from else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"GJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 成功守护了 #{@name}。" splashlog game.id,game,log sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunrise,game # 黙らされた人 class Muted extends Complex cmplType:"Muted" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game game.ss.publish.user @id,"refresh",{id:game.id} getSpeakChoiceDay:(game)-> ["monologue"] # 全员に喋ることができない # 狼的仆从 class WolfMinion extends Complex cmplType:"WolfMinion" team:"Werewolf" getJobname:->"狼的仆从(#{@main.getJobname()})" getJobDisp:->"狼的仆从(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"狼的仆从" type:"WolfMinion" } isWinner:(game,team)->@team==team # 酒鬼 class Drunk extends Complex cmplType:"Drunk" getJobname:->"酒鬼(#{@main.getJobname()})" getTypeDisp:->"Human" getJobDisp:->"母猪" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunset:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game if game.day>=3 # 3日目に目が覚める log= mode:"skill" to:@id comment:"#{@name} 酒醒了。" splashlog game.id,game,log @uncomplex game game.ss.publish.user @realid,"refresh",{id:game.id} makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj isDrunk:->true getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 陷阱师守られた人 class TrapGuarded extends Complex # cmplFlag: 护卫元ID cmplType:"TrapGuarded" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 return if midnightSort != @midnightSort wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 狩人がいた!(罠も無効) wholepl = game.getPlayer @id @checkTrap game, wholepl # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag # 罠し if tr? tr.addGamelog game,"trappedGuard",null,@id gu.die game,"trap" pl.uncomplex game # 消滅 # 子の調査を継続 @checkGuard game,pl.main return true checkTrap:(game,pl)-> # TrapGuardedも消す return unless pl.isComplex() if pl.cmplType=="TrapGuarded" pl.uncomplex game @checkTrap game, pl.main else @checkTrap game, pl.main if pl.sub? @checkTrap game, pl.sub die:(game,found,from)-> unless found in ["werewolf","vampire"] # 狼以外だとしぬ @mcall game,@main.die,game,found else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"trapGJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 的陷阱成功守护了 #{@name}。" splashlog game.id,game,log # 反撃する canbedead=[] ft=game.getPlayer from if ft.isWerewolf() canbedead=game.players.filter (x)->!x.dead && x.isWerewolf() else if ft.isVampire() canbedead=game.players.filter (x)->!x.dead && x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"trap" @addGamelog game,"trapkill",null,pl.id sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game # 黙らされた人 class Lycanized extends Complex cmplType:"Lycanized" fortuneResult:"LowB" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 策士によって更生させられた人 class Counseled extends Complex cmplType:"Counseled" team:"Human" getJobname:->"更生者(#{@main.getJobname()})" getJobDisp:->"更生者(#{@main.getJobDisp()})" isWinner:(game,team)->@team==team makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"更生者" type:"Counseled" } # 巫女のガードがある状态 class MikoProtected extends Complex cmplType:"MikoProtected" die:(game,found)-> # 耐える game.getPlayer(@id).addGamelog game,"mikoGJ",found sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 威嚇するLowBに威嚇された class Threatened extends Complex cmplType:"Threatened" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunrise:(game)-> # この昼からは戻る @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game sunset:(game)-> midnight:(game,midnightSort)-> job:(game,playerid,query)-> null dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 碍事的狂人に邪魔された(未完成) class DivineObstructed extends Complex # cmplFlag: 邪魔元ID cmplType:"DivineObstructed" sunset:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunset,game # 占いの影響なし divineeffect:(game)-> showdivineresult:(game)-> # 结果がでなかった pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,但是被不知道什么人妨碍了。" splashlog game.id,game,log dodivine:(game)-> # 占おうとした。邪魔成功 obstmad=game.getPlayer @cmplFlag if obstmad? obstmad.addGamelog game,"divineObstruct",null,@id class PhantomStolen extends Complex cmplType:"PhantomStolen" # cmplFlag: 保存されたアレ sunset:(game)-> # 夜になると怪盗になってしまう!!!!!!!!!!!! @sub?.sunrise? game newpl=Player.factory "Phantom" # アレがなぜか狂ってしまうので一時的に保存 saved=@originalJobname @uncomplex game pl=game.getPlayer @id pl.transProfile newpl pl.transferData newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 的职业被盗走了,变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 夜の初期化 pl=game.getPlayer @id pl.setOriginalJobname saved pl.setFlag true # もう盗めない pl.sunset game getJobname:->"怪盗" #灵界とかでは既に怪盗化 # 胜利条件関係は母猪化(昼の間だけだし) isWerewolf:->false isFox:->false isVampire:->false #team:"Human" #女王との兼ね合いで isWinner:(game,team)-> team=="Human" die:(game,found,from)-> # 抵抗もなく死ぬし if found=="punish" Player::die.apply this,arguments else super dying:(game,found)-> makejobinfo:(game,obj)-> super for key,value of @cmplFlag obj[key]=value class KeepedLover extends Complex # 恶女に手玉にとられた(見た目は恋人) # cmplFlag: 相方のid cmplType:"KeepedLover" getJobname:->"手玉(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"<NAME>人" type:"Friend" } # 恋人だと思い込む fr=[this,game.getPlayer(@cmplFlag)].map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr # 花火を見ている class WatchingFireworks extends Complex # cmplFlag: 烟火师のid cmplType:"WatchingFireworks" sleeping:->true jobdone:->true sunrise:(game)-> @sub?.sunrise? game # もう终了 @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game deadsunrise:(game)->@sunrise game makejobinfo:(game,result)-> super result.watchingfireworks=true # 炸弹魔に爆弾を仕掛けられた人 class BombTrapped extends Complex # cmplFlag: 护卫元ID cmplType:"BombTrapped" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 if midnightSort != @midnightSort then return wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 猎人がいた!(罠も無効) @uncomplex game # bomb would explode for only once deadsunrise:(game)-> super @uncomplex game # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag #炸弹魔 if tr? tr.addGamelog game,"bombTrappedGuard",null,@id # 护卫元が死ぬ gu.die game,"bomb" # 自己も死ぬ @die game,"bomb" pl.uncomplex game # 罠は消滅 # 子の調査を継続 @checkGuard game,pl.main return true die:(game,found,from)-> if found=="punish" # 处刑された場合は处刑者の中から選んでしぬ # punishのときはfromがidの配列 if from? && from.length>0 pls=from.map (id)->game.getPlayer id pls=pls.filter (x)->!x.dead if pls.length>0 r=Math.floor Math.random()*pls.length pl=pls[r] if pl? pl.die game,"bomb" @addGamelog game,"bombkill",null,pl.id else if found in ["werewolf","vampire"] # 狼に噛まれた場合は襲撃者を巻き添えにする bomber=game.getPlayer @cmplFlag if bomber? bomber.addGamelog game,"bompGJ",null,@id # 反撃する wl=game.getPlayer from if wl? wl.die game,"bomb" @addGamelog game,"bombkill",null,wl.id # 自己もちゃんと死ぬ @mcall game,@main.die,game,found,from # 狐凭 class FoxMinion extends Complex cmplType:"FoxMinion" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true getJobname:->"狐凭(#{@main.getJobname()})" # 占われたら死ぬ divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # 丑时之女に呪いをかけられた class DivineCursed extends Complex cmplType:"DivineCursed" sunset:(game)-> # 1日で消える @uncomplex game @mcall game,@main.sunset,game divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # パティシエールに本命チョコをもらった class GotChocolateTrue extends Friend cmplType:"GotChocolateTrue" getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() getPartner:-> if @cmplType=="GotChocolateTrue" return @cmplFlag else return @main.getPartner() makejobinfo:(game,result)-> # 恋人情報はでない @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 本命ではない class GotChocolateFalse extends Complex cmplType:"GotChocolateFalse" # 黒になった class Blacked extends Complex cmplType:"Blacked" fortuneResult: "LowB" psychicResult:"LowB" # 白になった class Whited extends Complex cmplType:"Whited" fortuneResult: "母猪" psychicResult:"母猪" # 占い結果吸血鬼化 class VampireBlooded extends Complex cmplType:"VampireBlooded" fortuneResult: "吸血鬼" # 催眠術をかけられた class UnderHypnosis extends Complex cmplType:"UnderHypnosis" sunrise:(game)-> # 昼になったら戻る @uncomplex game pl=game.getPlayer @id if pl? pl.sunrise game midnight:(game,midnightSort)-> die:(game,found,from)-> Human.prototype.die.call @,game,found,from dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> # 狮子舞の加護 class VoteGuarded extends Complex cmplType:"VoteGuarded" modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote vote = @mcall game, @main.modifyMyVote, game, vote # 自分への投票を1票減らす if vote.votes > 0 vote.votes-- vote # 南瓜魔の呪い class PumpkinCostumed extends Complex cmplType:"PumpkinCostumed" fortuneResult: "南瓜" # 决定者 class Decider extends Complex cmplType:"Decider" getJobname:->"#{@main.getJobname()}(决定者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePriority this,1 #優先度を1上げる null # 权力者 class Authority extends Complex cmplType:"Authority" getJobname:->"#{@main.getJobname()}(权力者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePower this,1 #票をひとつ増やす null # 炼成LowBの职业 class Chemical extends Complex cmplType:"Chemical" getJobname:-> if @sub? "#{@main.getJobname()}×#{@sub.getJobname()}" else @main.getJobname() getJobDisp:-> if @sub? "#{@main.getJobDisp()}×#{@sub.getJobDisp()}" else @main.getJobDisp() sleeping:(game)->@main.sleeping(game) && (!@sub? || @sub.sleeping(game)) jobdone:(game)->@main.jobdone(game) && (!@sub? || @sub.jobdone(game)) isHuman:-> if @sub? @main.isHuman() && @sub.isHuman() else @main.isHuman() isWerewolf:-> @main.isWerewolf() || @sub?.isWerewolf() isFox:-> @main.isFox() || @sub?.isFox() isFoxVisible:-> @main.isFoxVisible() || @sub?.isFoxVisible() isVampire:-> @main.isVampire() || @sub?.isVampire() isAttacker:-> @main.isAttacker?() || @sub?.isAttacker?() humanCount:-> if @isFox() 0 else if @isWerewolf() 0 else if @isHuman() 1 else 0 werewolfCount:-> if @isFox() 0 else if @isWerewolf() if @sub? @main.werewolfCount() + @sub.werewolfCount() else @main.werewolfCount() else 0 vampireCount:-> if @isFox() 0 else if @isVampire() if @sub? @main.vampireCount() + @sub.vampireCount() else @main.vampireCount() else 0 getFortuneResult:-> fsm = @main.getFortuneResult() fss = @sub?.getFortuneResult() if "吸血鬼" in [fsm, fss] "吸血鬼" else if "LowB" in [fsm, fss] "LowB" else "母猪" getPsychicResult:-> fsm = @main.getPsychicResult() fss = @sub?.getPsychicResult() if "LowB" in [fsm, fss] "LowB" else "母猪" getTeam:-> myt = null maint = @main.getTeam() subt = @sub?.getTeam() if maint=="Cult" || subt=="Cult" myt = "Cult" else if maint=="Friend" || subt=="Friend" myt = "Friend" else if maint=="Fox" || subt=="Fox" myt = "Fox" else if maint=="Vampire" || subt=="Vampire" myt = "Vampire" else if maint=="Werewolf" || subt=="Werewolf" myt = "Werewolf" else if maint=="LoneWolf" || subt=="LoneWolf" myt = "LoneWolf" else if maint=="Human" || subt=="Human" myt = "Human" else myt = "" return myt isWinner:(game,team)-> myt = @getTeam() win = false maint = @main.getTeam() sunt = @sub?.getTeam() if maint == myt || maint == "" || maint == "Devil" win = win || @main.isWinner(game,team) if subt == myt || subt == "" || subt == "Devil" win = win || @sub.isWinner(game,team) return win die:(game, found, from)-> return if @dead if found=="werewolf" && (!@main.willDieWerewolf || (@sub? && !@sub.willDieWerewolf)) # LowBに対する襲撃耐性 return # main, subに対してdieをsimulateする(ただしdyingはdummyにする) d = Object.getOwnPropertyDescriptor(this, "dying") @dying = ()-> null # どちらかが耐えたら耐える @main.die game, found, from isdead = @dead @setDead false, null if @sub? @sub.die game, found, from isdead = isdead && @dead if d? Object.defineProperty this, "dying", d else delete @dying # XXX duplicate pl=game.getPlayer @id if isdead pl.setDead true, found pl.dying game, found, from else pl.setDead false, null touched:(game, from)-> @main.touched game, from @sub?.touched game, from makejobinfo:(game,result)-> @main.makejobinfo game,result @sub?.makejobinfo? game,result # 女王観戦者は母猪陣営×母猪陣営じゃないと見えない if result.queens? && (@main.getTeam() != "Human" || @sub?.getTeam() != "Human") delete result.queens # 陣営情報 result.myteam = @getTeam() games={} # 游戏のGC new cron.CronJob("0 0 * * * *", -> # いらないGameを消す tm=Date.now()-3600000 # 1时间前 games_length_b = 0 for id,game of games games_length_b++ for id,game of games if game.finished # 終わっているやつが消す候補 if (!game.last_time?) || (game.last_time<tm) # 十分古い console.log "delete game:"+id delete games[id] games_length_a = 0 for id,game of games games_length_a++ console.log "length of games before:"+games_length_b console.log "length of games after :"+games_length_a , null, true, "Asia/Shanghai") # 游戏を得る getGame=(id)-> # 仕事一览 jobs= Human:Human Werewolf:Werewolf Diviner:Diviner Psychic:Psychic Madman:Madman Guard:Guard Couple:Couple Fox:Fox Poisoner:Poisoner BigWolf:BigWolf TinyFox:TinyFox Bat:Bat Noble:Noble Slave:Slave Magician:Magician Spy:Spy WolfDiviner:WolfDiviner Fugitive:Fugitive Merchant:Merchant QueenSpectator:QueenSpectator MadWolf:MadWolf Neet:Neet Liar:Liar Spy2:Spy2 Copier:Copier Light:Light Fanatic:Fanatic Immoral:Immoral Devil:Devil ToughGuy:ToughGuy Cupid:Cupid Stalker:Stalker Cursed:Cursed ApprenticeSeer:ApprenticeSeer Diseased:Diseased Spellcaster:Spellcaster Lycan:Lycan Priest:Priest Prince:Prince PI:PI Sorcerer:Sorcerer Doppleganger:Doppleganger CultLeader:CultLeader Vampire:Vampire LoneWolf:LoneWolf Cat:Cat Witch:Witch Oldman:Oldman Tanner:Tanner OccultMania:OccultMania MinionSelector:MinionSelector WolfCub:WolfCub WhisperingMad:WhisperingMad Lover:Lover Thief:Thief Dog:Dog Dictator:Dictator SeersMama:SeersMama Trapper:Trapper WolfBoy:WolfBoy Hoodlum:Hoodlum QuantumPlayer:QuantumPlayer RedHood:RedHood Counselor:Counselor Miko:Miko GreedyWolf:GreedyWolf FascinatingWolf:FascinatingWolf SolitudeWolf:SolitudeWolf ToughWolf:ToughWolf ThreateningWolf:ThreateningWolf HolyMarked:HolyMarked WanderingGuard:WanderingGuard ObstructiveMad:ObstructiveMad TroubleMaker:TroubleMaker FrankensteinsMonster:FrankensteinsMonster BloodyMary:BloodyMary King:King PsychoKiller:PsychoKiller SantaClaus:SantaClaus Phantom:Phantom BadLady:BadLady DrawGirl:DrawGirl CautiousWolf:CautiousWolf Pyrotechnist:Pyrotechnist Baker:Baker Bomber:Bomber Blasphemy:Blasphemy Ushinotokimairi:Ushinotokimairi Patissiere:Patissiere GotChocolate:GotChocolate MadDog:MadDog Hypnotist:Hypnotist CraftyWolf:CraftyWolf Shishimai:Shishimai Pumpkin:Pumpkin MadScientist:MadScientist SpiritPossessed:SpiritPossessed # 特殊 GameMaster:GameMaster Helper:Helper # 开始前 Waiting:Waiting Watching:Watching complexes= Complex:Complex Friend:Friend HolyProtected:HolyProtected CultMember:CultMember Guarded:Guarded Muted:Muted WolfMinion:WolfMinion Drunk:Drunk Decider:Decider Authority:Authority TrapGuarded:TrapGuarded Lycanized:Lycanized Counseled:Counseled MikoProtected:MikoProtected Threatened:Threatened DivineObstructed:DivineObstructed PhantomStolen:PhantomStolen KeepedLover:KeepedLover WatchingFireworks:WatchingFireworks BombTrapped:BombTrapped FoxMinion:FoxMinion DivineCursed:DivineCursed GotChocolateTrue:GotChocolateTrue GotChocolateFalse:GotChocolateFalse Blacked:Blacked Whited:Whited VampireBlooded:VampireBlooded UnderHypnosis:UnderHypnosis VoteGuarded:VoteGuarded Chemical:Chemical PumpkinCostumed:PumpkinCostumed # 役職ごとの強さ jobStrength= Human:5 Werewolf:40 Diviner:25 Psychic:15 Madman:10 Guard:23 Couple:10 Fox:25 Poisoner:20 BigWolf:80 TinyFox:10 Bat:10 Noble:12 Slave:5 Magician:14 Spy:14 WolfDiviner:60 Fugitive:8 Merchant:18 QueenSpectator:20 MadWolf:40 Neet:50 Liar:8 Spy2:5 Copier:10 Light:30 Fanatic:20 Immoral:5 Devil:20 ToughGuy:11 Cupid:37 Stalker:10 Cursed:2 ApprenticeSeer:23 Diseased:16 Spellcaster:6 Lycan:5 Priest:17 Prince:17 PI:23 Sorcerer:14 Doppleganger:15 CultLeader:10 Vampire:40 LoneWolf:28 Cat:22 Witch:23 Oldman:4 Tanner:15 OccultMania:10 MinionSelector:0 WolfCub:70 WhisperingMad:20 Lover:25 Thief:0 Dog:7 Dictator:18 SeersMama:15 Trapper:13 WolfBoy:11 Hoodlum:5 QuantumPlayer:0 RedHood:16 Counselor:25 Miko:14 GreedyWolf:60 FascinatingWolf:52 SolitudeWolf:20 ToughWolf:55 ThreateningWolf:50 HolyMarked:6 WanderingGuard:10 ObstructiveMad:19 TroubleMaker:15 FrankensteinsMonster:50 BloodyMary:5 King:15 PsychoKiller:25 SantaClaus:20 Phantom:15 BadLady:30 DrawGirl:10 CautiousWolf:45 Pyrotechnist:20 Baker:16 Bomber:23 Blasphemy:10 Ushinotokimairi:19 Patissiere:10 MadDog:19 Hypnotist:17 CraftyWolf:48 Shishimai:10 Pumpkin:17 MadScientist:20 SpiritPossessed:4 module.exports.actions=(req,res,ss)-> req.use 'user.fire.wall' req.use 'session' #游戏开始処理 #成功:null gameStart:(roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return Server.game.rooms.oneRoomS roomid,(room)-> if room.error? res room.error return unless room.mode=="waiting" # すでに开始している res "游戏已经开始" return if room.players.some((x)->!x.start) res "全员尚未全部准备好" return if room.gm!=true && query.yaminabe_hidejobs!="" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"]) res "「配置公开」选项在黑暗火锅模式下,只有在有GM的房间才能使用" return # ルールオブジェクト用意 ruleobj={ number: room.players.length maxnumber:room.number blind:room.blind gm:room.gm day: parseInt(parseInt(query.day_minute)*60+parseInt(query.day_second)) night: parseInt(parseInt(query.night_minute)*60+parseInt(query.night_second)) remain: parseInt(parseInt(query.remain_minute)*60+parseInt(query.remain_second)) # (n=15)秒规则 silentrule: parseInt(query.silentrule) ? 0 } unless ruleobj.day && ruleobj.night && ruleobj.remain res "时间长度不是有效数字,或总时长为零。" return options={} # 选项ズ for opt in ["decider","authority","yaminabe_hidejobs"] options[opt]=query[opt] ? null joblist={} for job of jobs joblist[job]=0 # 一旦初期化 #frees=room.players.length # 参加者の数 # プレイヤーと其他に分類 players=[] supporters=[] for pl in room.players if pl.mode=="player" if players.filter((x)->x.realid==pl.realid).length>0 res "#{pl.name} 重复加入,游戏无法开始。" return players.push pl else supporters.push pl frees=players.length if query.scapegoat=="on" # 替身君 frees++ playersnumber=frees # 人数の確認 if frees<6 res "人数不足,不能开始。含替身君最少要有6人。" return if query.jobrule=="特殊规则.量子LowB" && frees>=20 # 多すぎてたえられない res "人数过多。量子LowB的人数应当在19人以下。" return # 炼成LowBの場合 if query.chemical=="on" # 黑暗火锅と量子LowBは無理 if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅","特殊规则.量子LowB"] res "本规则「#{query.jobrule}」无法使用炼成LowB。" return ruleinfo_str="" # 开始告知 if query.jobrule in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] # 自由のときはクエリを参考にする for job in Shared.game.jobs joblist[job]=parseInt(query[job]) || 0 # 仕事の数 # カテゴリも for type of Shared.game.categoryNames joblist["category_#{type}"]=parseInt(query["category_#{type}"]) || 0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] # カテゴリ内の人数の合計がわかる関数 countCategory=(categoryname)-> Shared.game.categories[categoryname].reduce(((prev,curr)->prev+(joblist[curr] ? 0)),0)+joblist["category_#{categoryname}"] # 黑暗火锅のときはランダムに決める pls=frees # プレイヤーの数をとっておく plsh=Math.floor pls/2 # 過半数 if query.jobrule=="特殊规则.手调黑暗火锅" # 手调黑暗火锅のときは母猪のみ黑暗火锅 frees=joblist.Human ? 0 joblist.Human=0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist safety={ jingais:false # 人外の数を調整 teams:false # 阵营の数を調整 jobs:false # 職どうしの数を調整 strength:false # 職の強さも考慮 reverse:false # 職の強さが逆 } switch query.yaminabe_safety when "low" # 低い safety.jingais=true when "middle" safety.jingais=true safety.teams=true when "high" safety.jingais=true safety.teams=true safety.jobs=true when "super" safety.jingais=true safety.teams=true safety.jobs=true safety.strength=true when "supersuper" safety.jobs=true safety.strength=true when "reverse" safety.jingais=true safety.strength=true safety.reverse=true # 黑暗火锅のときは入れないのがある exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] # ユーザーが指定した入れないの excluded_exceptions=[] # チェックボックスが外れてるやつは登場しない if query.jobrule=="特殊规则.手调黑暗火锅" for job in Shared.game.jobs if query["job_use_#{job}"] != "on" # これは出してはいけない指定になっている exceptions.push job excluded_exceptions.push job # メアリーの特殊処理(セーフティ高じゃないとでない) if query.yaminabe_hidejobs=="" || !safety.jobs exceptions.push "BloodyMary" # 悪霊憑き(人気がないので出ない) if safety.jingais || safety.jobs exceptions.push "SpiritPossessed" unless query.jobrule=="特殊规则.手调黑暗火锅" && countCategory("Werewolf")>0 #人外の数 if safety.jingais # いい感じに決めてあげる wolf_number=1 fox_number=0 vampire_number=0 devil_number=0 if frees>=9 wolf_number++ if frees>=12 if Math.random()<0.6 fox_number++ else if Math.random()<0.7 devil_number++ if frees>=14 wolf_number++ if frees>=16 if Math.random()<0.5 fox_number++ else if Math.random()<0.3 vampire_number++ else devil_number++ if frees>=18 wolf_number++ if frees>=22 if Math.random()<0.2 fox_number++ else if Math.random()<0.6 vampire_number++ else if Math.random()<0.9 devil_number++ if frees>=24 wolf_number++ if frees>=30 wolf_number++ # ランダム調整 if wolf_number>1 && Math.random()<0.1 wolf_number-- else if frees>0 && playersnumber>=10 && Math.random()<0.2 wolf_number++ if fox_number>1 && Math.random()<0.15 fox_number-- else if frees>=11 && Math.random()<0.25 fox_number++ else if frees>=8 && Math.random()<0.1 fox_number++ if frees>=11 && Math.random()<0.2 vampire_number++ if frees>=11 && Math.random()<0.2 devil_number++ # セットする if joblist.category_Werewolf>0 frees+=joblist.category_Werewolf joblist.category_Werewolf=wolf_number frees -= wolf_number if joblist.Fox>0 frees+=joblist.Fox if joblist.TinyFox>0 frees+=joblist.TinyFox if joblist.Blasphemy>0 frees+=joblist.Blasphemy joblist.Fox=0 joblist.TinyFox=0 joblist.Blasphemy=0 # 除外役職を入れないように気をつける nonavs = {} for job in exceptions nonavs[job] = true # 狐を振分け for i in [0...fox_number] if frees <= 0 break r = Math.random() if r<0.55 && !nonavs.Fox joblist.Fox++ frees-- else if r<0.85 && !nonavs.TinyFox joblist.TinyFox++ frees-- else if !nonavs.Blasphemy joblist.Blasphemy++ frees-- if joblist.Vampire>0 frees+=joblist.Vampire if vampire_number <= frees joblist.Vampire = vampire_number frees -= vampire_number else joblist.Vampire = frees frees = 0 if joblist.Devil>0 frees+=joblist.Devil if devil_number <= frees joblist.Devil = devil_number frees -= devil_number else joblist.Devil = frees frees = 0 # 人外は選んだのでもう選ばれなくする exceptions=exceptions.concat Shared.game.nonhumans exceptions.push "Blasphemy" else # 調整しない joblist.category_Werewolf=1 frees-- if safety.jingais || safety.jobs if joblist.Fox==0 && joblist.TinyFox==0 exceptions.push "Immoral" # 狐がいないのに背徳は出ない nonavs = {} for job in exceptions nonavs[job] = true if safety.teams # 阵营調整もする # 恋人阵营 if frees>0 if 17>=playersnumber>=12 if Math.random()<0.15 && !nonavs.Cupid joblist.Cupid++ frees-- else if Math.random()<0.12 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.BadLady joblist.BadLady++ frees-- else if playersnumber>=8 if Math.random()<0.15 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.Cupid joblist.Cupid++ frees-- # 妖狐陣営 if frees>0 && joblist.Fox>0 if joblist.Fox==1 if playersnumber>=14 # 1人くらいは… if Math.random()<0.3 && !nonavs.Immoral joblist.Immoral++ frees-- else # サプライズ的に… if Math.random()<0.1 && !nonavs.Immoral joblist.Immoral++ frees-- exceptions.push "Immoral" # LowB阵营 if frees>0 wolf_number = countCategory "Werewolf" if wolf_number<=playersnumber/8 # 確定狂人サービス joblist.category_Madman ?= 0 joblist.category_Madman++ frees-- # 占い確定 if safety.teams || safety.jobs # 母猪阵营 if frees>0 # 占い師いてほしい if Math.random()<0.8 && !nonavs.Diviner joblist.Diviner++ frees-- else if !safety.jobs && Math.random()<0.3 && !nonavs.ApprenticeSeer joblist.ApprenticeSeer++ frees-- if safety.teams # できれば猎人も if frees>0 if joblist.Diviner>0 if Math.random()<0.5 && !nonavs.Guard joblist.Guard++ frees-- else if Math.random()<0.2 && !nonavs.Guard joblist.Guard++ frees-- ((date)-> month=date.getMonth() d=date.getDate() if month==11 && 24<=d<=25 # 12/24〜12/25はサンタがよくでる if Math.random()<0.5 && frees>0 && !nonavs.SantaClaus joblist.SantaClaus ?= 0 joblist.SantaClaus++ frees-- else # サンタは出にくい if Math.random()<0.8 exceptions.push "SantaClaus" unless month==6 && 26<=d || month==7 && d<=16 # 期間外は烟火师は出にくい if Math.random()<0.7 exceptions.push "Pyrotechnist" else # ちょっと出やすい if Math.random()<0.11 && frees>0 && !nonavs.Pyrotechnist joblist.Pyrotechnist ?= 0 joblist.Pyrotechnist++ frees-- if month==11 && 24<=d<=25 || month==1 && d==14 # 爆弾魔がでやすい if Math.random()<0.5 && frees>0 && !nonavs.Bomber joblist.Bomber ?= 0 joblist.Bomber++ frees-- if month==1 && 13<=d<=14 # パティシエールが出やすい if Math.random()<0.4 && frees>0 && !nonavs.Patissiere joblist.Patissiere ?= 0 joblist.Patissiere++ frees-- else # 出にくい if Math.random()<0.84 exceptions.push "Patissiere" if month==0 && d<=3 # 正月は巫女がでやすい if Math.random()<0.35 && frees>0 && !nonavs.Miko joblist.Miko ?= 0 joblist.Miko++ frees-- if month==3 && d==1 # 4月1日は嘘つきがでやすい if Math.random()<0.5 && !nonavs.Liar while frees>0 joblist.Liar ?= 0 joblist.Liar++ frees-- if Math.random()<0.75 break if month==11 && d==31 || month==0 && 4<=d<=7 # 獅子舞の季節 if Math.random()<0.5 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else if month==0 && 1<=d<=3 # 獅子舞の季節(真) if Math.random()<0.7 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else # 狮子舞がでにくい季節 if Math.random()<0.8 exceptions.push "Shishimai" if month==9 && 30<=d<=31 # ハロウィンなので南瓜 if Math.random()<0.4 && frees>0 && !nonavs.Pumpkin joblist.Pumpkin ?= 0 joblist.Pumpkin++ frees-- else if Math.random()<0.2 exceptions.push "Pumpkin" )(new Date) possibility=Object.keys(jobs).filter (x)->!(x in exceptions) if possibility.length == 0 # 0はまずい possibility.push "Human" # 強制的に入れる関数 init=(jobname,categoryname)-> unless jobname in possibility return false if categoryname? && joblist["category_#{categoryname}"]>0 # あった joblist[jobname]++ joblist["category_#{categoryname}"]-- return true if frees>0 # あった joblist[jobname]++ frees-- return true return false # 安全性超用 trial_count=0 trial_max=if safety.strength then 40 else 1 best_list=null best_points=null if safety.reverse best_diff=-Infinity else best_diff=Infinity first_list=joblist first_frees=frees # チームのやつキャッシュ teamCache={} getTeam=(job)-> if teamCache[job]? return teamCache[job] for team of Shared.game.teams if job in Shared.game.teams[team] teamCache[job]=team return team return null while trial_count++ < trial_max joblist=copyObject first_list #wolf_teams=countCategory "Werewolf" wolf_teams=0 frees=first_frees while true category=null job=null #カテゴリ职业がまだあるか探す for type,arr of Shared.game.categories if joblist["category_#{type}"]>0 # カテゴリの中から候補をしぼる arr2 = arr.filter (x)->!(x in excluded_exceptions) if arr2.length > 0 r=Math.floor Math.random()*arr2.length job=arr2[r] category="category_#{type}" break else # これもう無理だわ joblist["category_#{type}"] = 0 unless job? # もうカテゴリがない if frees<=0 # もう空きがない break r=Math.floor Math.random()*possibility.length job=possibility[r] if safety.teams && !category? if job in Shared.game.teams.Werewolf if wolf_teams+1>=plsh # LowBが過半数を越えた(PP) continue if safety.jobs # 職どうしの兼ね合いを考慮 switch job when "Psychic","RedHood" # 1人のとき灵能は意味ない if countCategory("Werewolf")==1 # 狼1人だと灵能が意味ない continue when "Couple" # 共有者はひとりだと寂しい if joblist.Couple==0 unless init "Couple","Human" #共有者が入る隙間はない continue when "Noble" # 贵族は奴隶がほしい if joblist.Slave==0 unless init "Slave","Human" continue when "Slave" if joblist.Noble==0 unless init "Noble","Human" continue when "OccultMania" if joblist.Diviner==0 && Math.random()<0.5 # 占卜师いないと出现確率低い continue when "QueenSpectator" # 2人いたらだめ if joblist.QueenSpectator>0 || joblist.Spy2>0 || joblist.BloodyMary>0 continue if Math.random()>0.1 # 90%の確率で弾く continue # 女王观战者はガードがないと不安 if joblist.Guard==0 && joblist.Priest==0 && joblist.Trapper==0 unless Math.random()<0.4 && init "Guard","Human" unless Math.random()<0.5 && init "Priest","Human" unless init "Trapper","Human" # 护卫がいない continue when "Spy2" # 间谍IIは2人いるとかわいそうなので入れない if joblist.Spy2>0 || joblist.QueenSpectator>0 continue else if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "MadWolf" if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "Lycan","SeersMama","Sorcerer","WolfBoy","ObstructirveMad" # 占い系がいないと入れない if joblist.Diviner==0 && joblist.ApprenticeSeer==0 && joblist.PI==0 continue when "LoneWolf","FascinatingWolf","ToughWolf","WolfCub" # 魅惑的女狼はほかにLowBがいないと効果発揮しない # 硬汉LowBはほかに狼いないと微妙、一匹狼は1人だけででると狂人が絶望 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue when "BigWolf" # 強いので狼2以上 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue # 灵能を出す unless Math.random()<0.15 || init "Psychic","Human" continue when "B<NAME>odyMary" # 狼が2以上必要 if countCategory("Werewolf")<=1 continue # 女王とは共存できない if joblist.QueenSpectator>0 continue when "SpiritPossessed" # 2人いるとうるさい if joblist.SpiritPossessed > 0 continue joblist[job]++ # ひとつ追加 if category? joblist[category]-- else frees-- if safety.teams && (job in Shared.game.teams.Werewolf) wolf_teams++ # LowB阵营が増えた # 安全性超の場合判定が入る if safety.strength # ポイントを計算する points= Human:0 Werewolf:0 Others:0 for job of jobStrength if joblist[job]>0 switch getTeam(job) when "Human" points.Human+=jobStrength[job]*joblist[job] when "Werewolf" points.Werewolf+=jobStrength[job]*joblist[job] else points.Others+=jobStrength[job]*joblist[job] # 判定する if points.Others>points.Human || points.Others>points.Werewolf # だめだめ continue # jgs=Math.sqrt(points.Werewolf*points.Werewolf+points.Others*points.Others) jgs = points.Werewolf+points.Others diff=Math.abs(points.Human-jgs) if safety.reverse # 逆 diff+=points.Others if diff>best_diff best_list=copyObject joblist best_diff=diff best_points=points else if diff<best_diff best_list=copyObject joblist best_diff=diff best_points=points #console.log "diff:#{diff}" #console.log best_list if safety.strength && best_list? # 安全性超 joblist=best_list else if query.jobrule=="特殊规则.量子LowB" # 量子LowBのときは全员量子人类だけど职业はある func=Shared.game.getrulefunc "内部利用.量子LowB" joblist=func frees sum=0 for job of jobs if joblist[job] sum+=joblist[job] joblist.Human=frees-sum # 残りは母猪だ! list_for_rule = JSON.parse JSON.stringify joblist ruleobj.quantum_joblist=joblist # LowBの順位を決めていく i=1 while joblist.Werewolf>0 joblist["Werewolf#{i}"]=1 joblist.Werewolf-=1 i+=1 delete joblist.Werewolf # 量子LowB用 joblist={ QuantumPlayer:frees } for job of jobs unless joblist[job]? joblist[job]=0 ruleinfo_str=Shared.game.getrulestr query.jobrule,list_for_rule else if query.jobrule!="特殊规则.自由配置" # 配置に従ってアレする func=Shared.game.getrulefunc query.jobrule unless func res "不明的配置" return joblist=func frees sum=0 # 穴を埋めつつ合計数える for job of jobs unless joblist[job]? joblist[job]=0 else sum+=joblist[job] # カテゴリも for type of Shared.game.categoryNames if joblist["category_#{type}"]>0 sum-=parseInt joblist["category_#{type}"] # 残りは母猪だ! if query.chemical == "on" # 炼成LowBなので母猪が大い joblist.Human = frees * 2 - sum else joblist.Human=frees-sum ruleinfo_str=Shared.game.getrulestr query.jobrule,joblist if query.yaminabe_hidejobs!="" && query.jobrule!="特殊规则.黑暗火锅" && query.jobrule!="特殊规则.Endless黑暗火锅" # 黑暗火锅以外で配役情報を公開しないときはアレする ruleinfo_str = "" if query.chemical == "on" # ケミカルLowBの場合は表示 ruleinfo_str = "炼成LowB " + (ruleinfo_str ? "") if (joblist.WolfBoy>0 || joblist.ObstructiveMad>0 || joblist.Pumpkin>0) && query.divineresult=="immediate" query.divineresult="sunrise" log= mode:"system" comment:"由于存在能够左右占卜结果的职业,占卜结果从「立刻知道」变更为「天亮才知道」。" splashlog game.id,game,log if ruleinfo_str != "" # 表示すべき情報がない場合は表示しない log= mode:"system" comment:"配置: #{ruleinfo_str}" splashlog game.id,game,log if query.jobrule == "特殊规则.手调黑暗火锅" && excluded_exceptions.length > 0 # 除外职业の情報を表示する exclude_str = excluded_exceptions.map((job)-> Shared.game.getjobname job).join ", " log= mode:"system" comment:"除外职业:#{exclude_str}" splashlog game.id,game,log if query.yaminabe_hidejobs=="team" # 陣営のみ公開モード # 各陣営 teaminfos=[] for team,obj of Shared.game.jobinfo teamcount=0 for job,num of joblist #出现职业チェック continue if num==0 if obj[job]? # この阵营だ teamcount+=num if teamcount>0 teaminfos.push "#{obj.name}#{teamcount}" #阵营名 log= mode:"system" comment:"出场阵营信息: "+teaminfos.join(" ") splashlog game.id,game,log if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] if query.yaminabe_hidejobs=="" # 黑暗火锅用の职业公開ログ jobinfos=[] for job,num of joblist continue if num==0 jobinfos.push "#{Shared.game.getjobname job}#{num}" log= mode:"system" comment:"出场职业: "+jobinfos.join(" ") splashlog game.id,game,log for x in ["jobrule", "decider","authority","scapegoat","will","wolfsound","couplesound","heavenview", "wolfattack","guardmyself","votemyself","deadfox","deathnote","divineresult","psychicresult","waitingnight", "safety","friendsjudge","noticebitten","voteresult","GMpsychic","wolfminion","drunk","losemode","gjmessage","rolerequest","runoff","chemical", "poisonwolf", "friendssplit", "quantumwerewolf_table","quantumwerewolf_dead","quantumwerewolf_diviner","quantumwerewolf_firstattack","yaminabe_hidejobs","yaminabe_safety"] ruleobj[x]=query[x] ? null game.setrule ruleobj # 配置リストをセット game.joblist=joblist game.startoptions=options game.startplayers=players game.startsupporters=supporters if ruleobj.rolerequest=="on" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.量子LowB","特殊规则.Endless黑暗火锅"]) # 希望役职制あり # とりあえず入れなくする M.rooms.update {id:roomid},{$set:{mode:"playing"}} # 职业选择中 game.rolerequestingphase=true # ここ書いてないよ! game.rolerequesttable={} res null log= mode:"system" comment:"本场游戏采取了希望役职制,请选择希望就职的职业。" splashlog game.id,game,log game.timer() ss.publish.channel "room#{roomid}","refresh",{id:roomid} else game.setplayers (result)-> unless result? # プレイヤー初期化に成功 M.rooms.update {id:roomid},{ $set:{ mode:"playing", jobrule:query.jobrule } } game.nextturn() res null ss.publish.channel "room#{roomid}","refresh",{id:roomid} else res result # 情報を開示 getlog:(roomid)-> M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else unless games[roomid]? games[roomid] = Game.unserialize doc,ss game = games[roomid] # ゲーム後の行動 player=game.getPlayerReal req.session.userId result= #logs:game.logs.filter (x)-> islogOK game,player,x logs:game.makelogs (doc.logs ? []), player result=makejobinfo game,player,result result.timer=if game.timerid? game.timer_remain-(Date.now()/1000-game.timer_start) # 全体 - 経過时间 else null result.timer_mode=game.timer_mode if game.day==0 # 开始前はプレイヤー情報配信しない delete result.game.players res result speak: (roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless query? res "无效操作" return comment=query.comment unless comment res "没有简介" return player=game.getPlayerReal req.session.userId #console.log query,player log = comment:comment userid:req.session.userId name:player?.name ? req.session.user.name to:null if query.size in ["big","small"] log.size=query.size # ログを流す dosp=-> if !game.finished && game.voting # 投票犹豫时间は发言できない if player && !player.dead && !player.isJobType("GameMaster") return #まだ死んでいないプレイヤーの場合は发言できないよ! if game.day<=0 || game.finished #準備中 unless log.mode=="audience" log.mode="prepare" if player?.isJobType "GameMaster" log.mode="gm" #log.name="游戏管理员" else # 游戏している unless player? # 观战者 log.mode="audience" else if player.dead # 天国 if player.isJobType "Spy" && player.flag=="spygone" # 间谍なら会話に参加できない log.mode="monologue" log.to=player.id else if query.mode=="monologue" # 霊界の独り言 log.mode="heavenmonologue" else log.mode="heaven" else if !game.night # 昼 unless query.mode in player.getSpeakChoiceDay game return log.mode=query.mode if game.silentexpires && game.silentexpires>=Date.now() # まだ发言できない(15秒规则) return else # 夜 unless query.mode in player.getSpeakChoice game query.mode="monologue" log.mode=query.mode switch log.mode when "monologue","heavenmonologue","helperwhisper" # helperwhisper:守り先が決まっていないヘルパー log.to=player.id when "heaven" # 霊界の発言は悪霊憑きの発言になるかも if !game.night && !game.voting && !(game.silentexpires && game.silentexpires >= Date.now()) possessions = game.players.filter (x)-> !x.dead && x.isJobType "SpiritPossessed" if possessions.length > 0 # 悪魔憑き r = Math.floor (Math.random()*possessions.length) pl = possessions[r] # 悪魔憑きのプロパティ log.possess_name = pl.name log.possess_id = pl.id when "gm" log.name="GM→所有人" when "gmheaven" log.name="GM→灵界" when "gmaudience" log.name="GM→观战者" when "gmmonologue" log.name="GM自言自语" when "prepare" # ごちゃごちゃ言わない else if result=query.mode?.match /^gmreply_(.+)$/ log.mode="gmreply" pl=game.getPlayer result[1] unless pl? return log.to=pl.id log.name="GM→#{pl.name}" else if result=query.mode?.match /^helperwhisper_(.+)$/ log.mode="helperwhisper" log.to=result[1] splashlog roomid,game,log res null if player? log.name=player.name log.userid=player.id dosp() else # 房间情報から探す Server.game.rooms.oneRoomS roomid,(room)=> pl=room.players.filter((x)=>x.realid==req.session.userId)[0] if pl? log.name=pl.name else log.mode="audience" dosp() # 夜の仕事・投票 job:(roomid,query)-> game=games[roomid] unless game? res {error:"游戏不存在"} return unless req.session.userId res {error:"请登陆"} return player=game.getPlayerReal req.session.userId unless player? res {error:"没有加入游戏"} return unless player in game.participants res {error:"没有加入游戏"} return ### if player.dead && player.deadJobdone game res {error:"你已经死了"} return ### jt=player.getjob_target() sl=player.makeJobSelection game ### if !(to=game.players.filter((x)->x.id==query.target)[0]) && jt!=0 res {error:"这个对象不存在"} return if to?.dead && (!(jt & Player.JOB_T_DEAD) || !game.night) && (jt & Player.JOB_T_ALIVE) res {error:"对象已经死亡"} return ### unless player.checkJobValidity game,query res {error:"对象选择无效"} return if game.night || query.jobtype!="_day" # 昼の投票 # 夜 ### if !to?.dead && !(player.job_target & Player.JOB_T_ALIVE) && (player.job_target & Player.JOB_T_DEAD) res {error:"対象はまだ生きています"} return ### if (player.dead && player.deadJobdone(game)) || (!player.dead && player.jobdone(game)) res {error:"已经使用了能力"} return unless player.isJobType query.jobtype res {error:"职业错误"} return # 错误メッセージ if ret=player.job game,query.target,query console.log "err!",ret res {error:ret} return # 能力発動を記録 game.addGamelog { id:player.id type:query.jobtype target:query.target event:"job" } # 能力をすべて発動したかどうかチェック #res {sleeping:player.jobdone(game)} res makejobinfo game,player if game.night || game.day==0 game.checkjobs() else # 投票 ### if @votingbox.isVoteFinished player res {error:"既に投票しています"} return if query.target==player.id && game.rule.votemyself!="ok" res {error:"自己には投票できません"} return to=game.getPlayer query.target unless to? res {error:"その人には投票できません"} return ### unless player.checkJobValidity game,query res {error:"请选择对象"} return err=player.dovote game,query.target if err? res {error:err} return #player.dovote query.target # 投票が終わったかチェック game.addGamelog { id:player.id type:player.type target:query.target event:"vote" } res makejobinfo game,player game.execute() #遗言 will:(roomid,will)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless !game.rule || game.rule.will res "不能使用遗言" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.dead res "你已经死了" return player.setWill will res null #拒绝复活 norevive:(roomid)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.norevive res "已经不可复活" return player.setNorevive true log= mode:"userinfo" comment:"#{player.name} 拒绝复活。" to:player.id splashlog roomid,game,log # 全员に通知 game.splashjobinfo() res null splashlog=(roomid,game,log)-> log.time=Date.now() # 時間を付加 #DBに追加 M.games.update {id:roomid},{$push:{logs:log}} flash=(log)-> # まず観戦者 aulogs = makelogsFor game, null, log for x in aulogs x.roomid = roomid game.ss.publish.channel "room#{roomid}_audience","log",x # GM #if game.gm&&!rev # game.ss.publish.channel "room#{roomid}_gamemaster","log",log # 其他 game.participants.forEach (pl)-> ls = makelogsFor game, pl, log for x in ls x.roomid = roomid game.ss.publish.user pl.realid,"log",x flash log # ある人に見せたいログ makelogsFor=(game,player,log)-> if islogOK game, player, log if log.mode=="heaven" && log.possess_name? # 両方見える感じで otherslog= mode:"half-day" comment: log.comment name: log.possess_name time: log.time size: log.size return [log, otherslog] return [log] if log.mode=="werewolf" && game.rule.wolfsound=="aloud" # 狼的远吠が能听到 otherslog= mode:"werewolf" comment:"嗷呜・・・" name:"狼的远吠" time:log.time return [otherslog] if log.mode=="couple" && game.rule.couplesound=="aloud" # 共有者の小声が聞こえる otherslog= mode:"couple" comment:"沙沙・・・" name:"共有者的低语声" time:log.time return [otherslog] if log.mode=="heaven" && log.possess_name? # 昼の霊界発言 with 悪魔憑き otherslog = mode:"day" comment: log.comment name:log.possess_name time:log.time size:log.size return [otherslog] return [] # プレイヤーにログを見せてもよいか islogOK=(game,player,log)-> # player: Player / null return true if game.finished # 终了ならtrue return true if player?.isJobType "GameMaster" unless player? # 观战者 if log.mode in ["day","system","prepare","nextturn","audience","will","gm","gmaudience","probability_table"] !log.to? # 观战者にも公開 else if log.mode=="voteresult" game.rule.voteresult!="hide" # 投票结果公開なら公開 else false # 其他は非公開 else if log.mode=="gmmonologue" # GM自言自语はGMにしか見えない false else if player.dead && game.heavenview true else if log.mode=="heaven" && log.possess_name? # 恶灵凭依についている霊界発言 false else if log.to? && log.to!=player.id # 個人宛 if player.isJobType "Helper" log.to==player.flag # ヘルプ先のも見える else false else player.isListener game,log #job情報を makejobinfo = (game,player,result={})-> result.type= if player? then player.getTypeDisp() else null # job情報表示するか actpl=player if player? if player instanceof Helper actpl=game.getPlayer player.flag unless actpl? #あれっ actpl=player is_gm = actpl?.isJobType("GameMaster") openjob_flag=game.finished || (actpl?.dead && game.heavenview) || is_gm result.openjob_flag = openjob_flag result.game=game.publicinfo({ openjob: openjob_flag gm: is_gm }) # 終了か霊界(ルール設定あり)の場合は職情報公開 result.id=game.id if player # 参加者としての(perticipantsは除く) plpl=game.getPlayer player.id player.makejobinfo game,result result.dead=player.dead result.voteopen=false result.sleeping=true # 投票が终了したかどうか(表单表示するかどうか判断) if plpl? # 参加者として if game.night || game.day==0 if player.dead result.sleeping=player.deadJobdone game else result.sleeping=player.jobdone game else # 昼 result.sleeping=true unless player.dead || game.votingbox.isVoteFinished player # 投票ボックスオープン!!! result.voteopen=true result.sleeping=false if player.chooseJobDay game # 昼でも能力発動できる人 result.sleeping &&= player.jobdone game else # それ以外(participants) result.sleeping=if game.night then player.jobdone(game) else true result.jobname=player.getJobDisp() result.winner=player.winner if game.night || game.day==0 result.speak =player.getSpeakChoice game else result.speak =player.getSpeakChoiceDay game if game.rule?.will=="die" result.will=player.will result # 配列シャッフル(破壊的) shuffle= (arr)-> ret=[] while arr.length ret.push arr.splice(Math.floor(Math.random()*arr.length),1)[0] ret # 游戏情報ツイート tweet=(roomid,message)-> Server.oauth.template roomid,message,Config.<PASSWORD>
true
#,type シェアするやつ Shared= game:require '../../../client/code/shared/game.coffee' prize:require '../../../client/code/shared/prize.coffee' cron=require 'cron' # 浅いコピー copyObject=(obj)-> result=Object.create Object.getPrototypeOf obj for key in Object.keys(obj) result[key]=obj[key] result # ゲームオブジェクトを読み込む loadGame = (roomid, ss, callback)-> if games[roomid]? callback null, games[roomid] else M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else games[roomid] = Game.unserialize doc,ss callback null, games[roomid] #内部用 module.exports= newGame: (room,ss)-> game=new Game ss,room games[room.id]=game M.games.insert game.serialize() # 游戏オブジェクトを読み込んで使用可能にする ### loadDB:(roomid,ss,cb)-> if games[roomid] # 既に読み込んでいる cb games[roomid] return M.games.find({finished:false}).each (err,doc)-> return unless doc? if err? console.log err throw err games[doc.id]=Game.unserialize doc,ss ### # 参加中のプレイヤー人数(Endless黑暗火锅用) endlessPlayersNumber:(roomid)-> game=games[roomid] if game? # 拒绝复活はカウントしない return game.players.filter((x)->!x.dead || !x.norevive).length else return Number.NaN # プレイヤーが入室したぞ! inlog:(room,player)-> name="#{player.name}" pr="" unless room.blind in ["complete","yes"] # 匿名模式のときは称号OFF player.nowprize?.forEach? (x)-> if x.type=="prize" prname=Server.prize.prizeName x.value if prname? pr+=prname else # 接続 pr+=x.value if room.blind in ["complete","yes"] && room.theme #如果房间使用了主题,匿名房间也可以有称号 theme = Server.game.themes[room.theme] if theme != null pr = theme.skins[player.userid].prize if pr name="#{Server.prize.prizeQuote pr}#{name}" if room.mode=="waiting" # 开始前(ふつう) log= comment:"#{name} 加入了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log # プレイヤーを追加 newpl=Player.factory "Waiting" newpl.setProfile { id:player.userid realid:player.realid name:player.PI:NAME:<NAME>END_PI } newpl.setTarget null games[room.id].players.push newpl games[room.id].participants.push newpl else if room.mode=="playing" && room.jobrule=="特殊规则.Endless黑暗火锅" # Endless黑暗火锅に途中参加 if games[room.id] game=games[room.id] log= comment:"#{name} 加入了游戏。" mode:"inlog" to:player.userid splashlog room.id,game,log # プレイヤーを追加(まだ参加しない系のひと) newpl=Player.factory "Watching" newpl.setProfile { id:player.userid realid:player.realid name:player.name } newpl.setTarget null # 头像追加 game.iconcollection[newpl.id]=player.icon # playersには追加しない(翌朝追加) games[room.id].participants.push newpl outlog:(room,player)-> log= comment:"#{player.name} 离开了游戏。" userid:-1 name:null mode:"system" if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid kicklog:(room,player)-> log= comment:"#{player.name} 被踢出了游戏。" userid:-1 name:null mode:"system" console.log "game"+room.id+"存在" unless games[room.id]? # 检索数据库game是否不存在? M.games.findOne {id:room.id}, (err,doc)=> if err? console.log err throw err unless doc? M.rooms.remove {id:room.id} console.log "由于game不存在,room"+room.id+"被移除" return games[roomid]=game=Game.unserialize doc,ss ne() return if games[room.id] splashlog room.id,games[room.id], log games[room.id].players=games[room.id].players.filter (pl)->pl.realid!=player.realid games[room.id].participants=games[room.id].participants.filter (pl)->pl.realid!=player.realid helperlog:(ss,room,player,topl)-> loadGame room.id, ss, (err,game)-> log=null if topl? log= comment:"#{player.name} 成为了 #{topl.name} 的帮手。" userid:-1 name:null mode:"system" else log= comment:"#{player.name} 放弃做帮手了。" userid:-1 name:null mode:"system" if game? splashlog room.id,game, log deletedlog:(ss,room)-> loadGame room.id, ss, (err,game)-> if game? log= comment:"这个房间已经废弃。" userid:-1 name:null mode:"system" splashlog room.id,game, log # 状況に応じたチャンネルを割り当てる playerchannel:(ss,roomid,session)-> loadGame roomid, ss, (err,game)-> unless game? return player=game.getPlayerReal session.userId unless player? session.channel.subscribe "room#{roomid}_audience" # session.channel.subscribe "room#{roomid}_notwerewolf" # session.channel.subscribe "room#{roomid}_notcouple" return if player.isJobType "GameMaster" session.channel.subscribe "room#{roomid}_gamemaster" return ### if player.dead session.channel.subscribe "room#{roomid}_heaven" if game.rule.heavenview!="view" || !player.dead if player.isWerewolf() session.channel.subscribe "room#{roomid}_werewolf" else session.channel.subscribe "room#{roomid}_notwerewolf" if game.rule.heavenview!="view" || !player.dead if player.isJobType "Couple" session.channel.subscribe "room#{roomid}_couple" else session.channel.subscribe "room#{roomid}_notcouple" if player.isJobType "Fox" session.channel.subscribe "room#{roomid}_fox" ### Server= game: game:module.exports rooms:require './rooms.coffee' themes:require './themes.coffee' prize:require '../../prize.coffee' oauth:require '../../oauth.coffee' class Game constructor:(@ss,room)-> # @ss: ss if room? @id=room.id # GMがいる場合 @gm= if room.gm then room.owner.userid else null @players=[] # 母猪たち @participants=[] # 参加者全て(@playersと同じ内容含む) @rule=null @finished=false #终了したかどうか @day=0 #何日目か(0=準備中) @night=false # false:昼 true:夜 @winner=null # 勝ったチーム名 @quantum_patterns=[] # 全部の場合を列挙({(id):{jobtype:"Jobname",dead:Boolean},...}) # DBには現れない @timerid=null @voting=false # 投票猶予時間 @timer_start=null # 残り時間のカウント開始時間(秒) @timer_remain=null # 残り時間全体(秒) @timer_mode=null # タイマーの名前 @revote_num=0 # 再投票を行った回数 @last_time=Date.now() # 最後に動きがあった時間 @werewolf_target=[] # LowBの襲い先 @werewolf_target_remain=0 #襲撃先をあと何人设定できるか @werewolf_flag=[] # LowB襲撃に関するフラグ @slientexpires=0 # 静かにしてろ!(この时间まで) @heavenview=false # 灵界表示がどうなっているか @gamelogs=[] @iconcollection={} #(id):(url) # 决定配置(DBに入らないかも・・・) @joblist=null # 游戏スタートに必要な情報 @startoptions=null @startplayers=null @startsupporters=null # 希望役职制のときに开始前に职业选择するフェーズ @rolerequestingphase=false @rolerequesttable={} # 一览{(id):(jobtype)} # 投票箱を用意しておく @votingbox=new VotingBox this # New Year Messageのためだけの変数 @currentyear = null ### さまざまな出来事 id: 動作した人 gamelogs=[ {id:(id),type:(type/null),target:(id,null),event:(String),flag:(String),day:(Number)}, {...}, ### # JSON用object化(DB保存用) serialize:-> { id:@id #logs:@logs rule:@rule players:@players.map (x)->x.serialize() # 差分 additionalParticipants: @participants?.filter((x)=>@players.indexOf(x)<0).map (x)->x.serialize() finished:@finished day:@day night:@night winner:@winner jobscount:@jobscount gamelogs:@gamelogs gm:@gm iconcollection:@iconcollection werewolf_flag:@werewolf_flag werewolf_target:@werewolf_target werewolf_target_remain:@werewolf_target_remain #quantum_patterns:@quantum_patterns } #DB用をもとにコンストラクト @unserialize:(obj,ss)-> game=new Game ss game.id=obj.id game.gm=obj.gm #game.logs=obj.logs game.rule=obj.rule game.players=obj.players.map (x)->Player.unserialize x # 追加する if obj.additionalParticipants game.participants=game.players.concat obj.additionalParticipants.map (x)->Player.unserialize x else game.participants=game.players.concat [] game.finished=obj.finished game.day=obj.day game.night=obj.night game.winner=obj.winner game.jobscount=obj.jobscount game.gamelogs=obj.gamelogs ? {} game.gm=obj.gm game.iconcollection=obj.iconcollection ? {} game.werewolf_flag=if Array.isArray obj.werewolf_flag # 配列ではなく文字列/nullだった時代のあれ obj.werewolf_flag else if obj.werewolf_flag? [obj.werewolf_flag] else [] game.werewolf_target=obj.werewolf_target ? [] game.werewolf_target_remain=obj.werewolf_target_remain ? 0 # 开始前なら準備中を用意してあげないと! if game.day==0 Server.game.rooms.oneRoomS game.id,(room)-> if room.error? return game.players=[] for plobj in room.players newpl=Player.factory "Waiting" newpl.setProfile { id:plobj.userid realid:plobj.realid name:plobj.name } newpl.setTarget null game.players.push newpl game.participants=game.players.concat [] game.quantum_patterns=obj.quantum_patterns ? [] unless game.finished if game.rule game.timer() if game.day>0 if !game.night # 昼の場合投票箱をつくる game.votingbox.setCandidates game.players.filter (x)->!x.dead game # 公開情報 publicinfo:(obj)-> #obj:选项 { rule:@rule finished:@finished players:@players.map (x)=> r=x.publicinfo() r.icon= @iconcollection[x.id] ? null if obj?.openjob r.jobname=x.getJobname() #r.option=x.optionString() r.option="" r.originalJobname=x.originalJobname r.winner=x.winner if obj?.gm || not (@rule?.blind=="complete" || (@rule?.blind=="yes" && !@finished)) # 公開してもよい r.realid=x.realid r day:@day night:@night jobscount:@jobscount } # IDからプレイヤー getPlayer:(id)-> @players.filter((x)->x.id==id)[0] getPlayerReal:(realid)-> #@players.filter((x)->x.realid==realid)[0] || if @gm && @gm==realid then new GameMaster realid,realid,"游戏管理员" @participants.filter((x)->x.realid==realid)[0] # DBにセーブ save:-> M.games.update {id:@id},{ $set: @serialize() $setOnInsert: { logs: [] } } # gamelogsに追加 addGamelog:(obj)-> @gamelogs ?= [] @gamelogs.push { id:obj.id ? null type:obj.type ? null target:obj.target ? null event:obj.event ? null flag:obj.flag ? null day:@day # 何気なく日付も追加 } setrule:(rule)->@rule=rule #成功:null #players: 参加者 supporters: 其他 setplayers:(res)-> options=@startoptions players=@startplayers supporters=@startsupporters jnumber=0 joblist=@joblist players=players.concat [] #模仿者 plsl=players.length #実際の参加人数(身代わり含む) if @rule.scapegoat=="on" plsl++ # 必要な职业の jallnum = plsl if @rule.chemical == "on" jallnum *= 2 @players=[] @iconcollection={} for job,num of joblist unless isNaN num jnumber+=parseInt num if parseInt(num)<0 res "玩家人数无效(#{job}:#{num})。多次重试可能解决这个错误。" return if jnumber!=jallnum # 数が合わない res "玩家人数无效 (#{jnumber}/#{jallnum}/#{players.length})。多次重试可能解决这个错误。" return # 名字と数を出したやつ @jobscount={} unless options.yaminabe_hidejobs # 公開モード for job,num of joblist continue unless num>0 testpl=new jobs[job] @jobscount[job]= name:testpl.jobname number:num # 盗賊の処理 thief_jobs=[] if joblist.Thief>0 # 小偷一人につき2回抜く for i in [0...(joblist.Thief*2)] # 1つ抜く keys=[] # 数に比例した职业一览を作る for job,num of joblist unless job in Shared.game.nonhumans for j in [0...num] keys.push job keys=shuffle keys until keys.length==0 || joblist[keys[0]]>0 # 抜けない keys.splice 0,1 # これは抜ける if keys.length==0 # もう無い res "小偷处理失败" return thief_jobs.push keys[0] joblist[keys[0]]-- # 代わりに母猪1つ入れる joblist.Human ?= 0 joblist.Human++ # 1人に対していくつ职业を選出するか jobperpl = 1 if @rule.chemical == "on" jobperpl = 2 # まず替身君を決めてあげる if @rule.scapegoat=="on" # LowB、妖狐にはならない nogoat=[] #身代わりがならない职业 if @rule.safety!="free" nogoat=nogoat.concat Shared.game.nonhumans #人外は除く if @rule.safety=="full" # 危ない nogoat=nogoat.concat ["QueenSpectator","Spy2","Poisoner","Cat","BloodyMary","Noble"] jobss=[] for job in Object.keys jobs continue if !joblist[job] || (job in nogoat) j=0 while j<joblist[job] jobss.push job j++ # 獲得した职业 gotjs = [] i=0 # 無限ループ防止 while ++i<100 && gotjs.length < jobperpl r=Math.floor Math.random()*jobss.length continue unless joblist[jobss[r]]>0 # 职业はjobss[r] gotjs.push jobss[r] joblist[jobss[r]]-- j++ if gotjs.length < jobperpl # 決まっていない res "角色分配失败" return # 替身君のプロフィール profile = { id:"PI:NAME:<NAME>END_PI身君" realid:"替身君" name:"PI:NAME:<NAME>END_PI" } if @rule.chemical == "on" # 炼成LowBなので合体职业にする pl1 = Player.factory gotjs[0] pl1.setProfile profile pl1.scapegoat = true pl2 = Player.factory gotjs[1] pl2.setProfile profile pl2.scapegoat = true # ケミカル合体 newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.scapegoat = true newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつーに newpl=Player.factory gotjs[0] #替身君 newpl.setProfile profile newpl.scapegoat = true @players.push newpl if @rule.rolerequest=="on" && @rule.chemical != "on" # 希望职业制ありの場合はまず希望を優先してあげる # (炼成LowBのときは面倒なのでパス) for job,num of joblist while num>0 # 候補を集める conpls=players.filter (x)=> @rolerequesttable[x.userid]==job if conpls.length==0 # もうない break # 候補がいたので決めてあげる r=Math.floor Math.random()*conpls.length pl=conpls[r] players=players.filter (x)->x!=pl newpl=Player.factory job newpl.setProfile { id:pl.userid realid:pl.realid name:pl.name } @players.push newpl if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true num-- # 残った分は戻す joblist[job]=num # 各プレイヤーの獲得职业の一覧 gotjs = [] for i in [0...(players.length)] gotjs.push [] # LowB系と妖狐系を全て数える(やや適当) all_wolves = 0 all_foxes = 0 for job,num of joblist unless isNaN num if job in Shared.game.categories.Werewolf all_wolves += num if job in Shared.game.categories.Fox all_foxes += num for job,num of joblist i=0 while i++<num r=Math.floor Math.random()*players.length if @rule.chemical == "on" && gotjs[r].length == 1 # 炼成LowBの場合調整が入る if all_wolves == 1 # LowBが1人のときはLowBを消さない if (gotjs[r][0] in Shared.game.categories.Werewolf && job in Shared.game.categories.Fox) || (gotjs[r][0] in Shared.game.categories.Fox && job in Shared.game.categories.Werewolf) # LowB×妖狐はまずい continue gotjs[r].push job if gotjs[r].length >= jobperpl # 必要な职业を獲得した pl=players[r] profile = { id:pl.userid realid:pl.realid name:pl.name } if @rule.chemical == "on" # 炼成LowB pl1 = Player.factory gotjs[r][0] pl1.setProfile profile pl2 = Player.factory gotjs[r][1] pl2.setProfile profile newpl = Player.factory null, pl1, pl2, Chemical newpl.setProfile profile newpl.setOriginalJobname newpl.getJobname() @players.push newpl else # ふつうのLowB newpl=Player.factory gotjs[r][0] newpl.setProfile profile @players.push newpl players.splice r,1 gotjs.splice r,1 if pl.icon @iconcollection[newpl.id]=pl.icon if pl.scapegoat # 替身君 newpl.scapegoat=true if joblist.Thief>0 # 小偷がいる場合 thieves=@players.filter (x)->x.isJobType "Thief" for pl in thieves pl.setFlag JSON.stringify thief_jobs.splice 0,2 # サブ系 if options.decider # 决定者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Decider # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if options.authority # 权力者を作る r=Math.floor Math.random()*@players.length pl=@players[r] newpl=Player.factory null,pl,null,Authority # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true if @rule.wolfminion # 狼的仆从がいる場合、子分决定者を作る wolves=@players.filter((x)->x.isWerewolf()) if wolves.length>0 r=Math.floor Math.random()*wolves.length pl=wolves[r] sub=Player.factory "MinionSelector" # 子分决定者 pl.transProfile sub newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl pl.transform @,newpl,true if @rule.drunk # 酒鬼がいる場合 nonvillagers= @players.filter (x)->!x.isJobType "Human" if nonvillagers.length>0 r=Math.floor Math.random()*nonvillagers.length pl=nonvillagers[r] newpl=Player.factory null,pl,null,Drunk # 酒鬼 pl.transProfile newpl pl.transform @,newpl,true,true # プレイヤーシャッフル @players=shuffle @players @participants=@players.concat [] # 模仿者 # ここでプレイヤー以外の処理をする for pl in supporters if pl.mode=="gm" # 游戏管理员だ gm=Player.factory "GameMaster" gm.setProfile { id:pl.userid realid:pl.realid name:pl.name } @participants.push gm else if result=pl.mode?.match /^helper_(.+)$/ # 帮手だ ppl=@players.filter((x)->x.id==result[1])[0] unless ppl? res "#{pl.name} 的帮助对象已不存在。" return helper=Player.factory "Helper" helper.setProfile { id:pl.realid realid:pl.realid name:pl.name } helper.setFlag ppl.id # ヘルプ先 @participants.push helper #@participants.push new GameMaster pl.userid,pl.realid,pl.name # 量子LowBの場合はここで可能性リストを作る if @rule.jobrule=="特殊规则.量子LowB" # パターンを初期化(最初は全パターン) quats=[] # のとみquantum_patterns pattern_no=0 # とばす # 职业を列挙した配列をつくる jobname_list=[] for job of jobs i=@rule.quantum_joblist[job] if i>0 jobname_list.push { type:job, number:i } # LowB用 i=1 while @rule.quantum_joblist["Werewolf#{i}"]>0 jobname_list.push { type:"Werewolf#{i}" number:@rule.quantum_joblist["Werewolf#{i}"] } i++ # プレイヤーIDを列挙した配列もつくる playerid_list=@players.map (pl)->pl.id # 0,1,...,(n-1)の中からkコ選んだ組み合わせを返す関数 combi=(n,k)-> `var i;` if k<=0 return [[]] if n<=k #n<kのときはないけど・・・ return [[0...n]] # 0からn-1まで resulty=[] for i in [0..(n-k)] # 0 <= i <= n-k for x in combi n-i-1,k-1 resulty.push [i].concat x.map (y)->y+i+1 resulty # 職をひとつ処理 makeonejob=(joblist,plids)-> cont=joblist[0] unless cont? return [[]] # 決めて抜く coms=combi plids.length,cont.number # その番号のを resulty2=[] for pat in coms #pat: 1つのパターン bas=[] pll=plids.concat [] i=0 for num in pat bas.push { id:pll[num-i] job:cont.type } pll.splice num-i,1 # 抜く i+=1 resulty2=resulty2.concat makeonejob(joblist.slice(1),pll).map (arr)-> bas.concat arr resulty2 jobsobj=makeonejob jobname_list,playerid_list # パターンを作る for arr in jobsobj obj={} for o in arr result=o.job.match /^Werewolf(\d+)$/ if result obj[o.id]={ jobtype:"Werewolf" rank:+result[1] # 狼の序列 dead:false } else obj[o.id]={ jobtype:o.job dead:false } quats.push obj # できた @quantum_patterns=quats if @rule.quantumwerewolf_table=="anonymous" # 概率表は数字で表示するので番号をつけてあげる for pl,i in shuffle @players.concat [] pl.setFlag JSON.stringify { number:i+1 } res null #======== 游戏進行の処理 #次のターンに進む nextturn:-> clearTimeout @timerid if @day<=0 # はじまる前 @day=1 @night=true # ゲーム開始時の年を記録 @currentyear = (new Date).getFullYear() else if @night==true @day++ @night=false else @night=true if @night==false && @currentyear+1 == (new Date).getFullYear() # 新年メッセージ @currentyear++ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"现在是 #{@currentyear} 年了。" splashlog @id,this,log else # 普通メッセージ log= mode:"nextturn" day:@day night:@night userid:-1 name:null comment:"第#{@day}天的#{if @night then '夜晚' else '白天'}到来了。" splashlog @id,this,log #死体処理 @bury(if @night then "night" else "day") if @rule.jobrule=="特殊规则.量子LowB" # 量子LowB # 全员の確率を出してあげるよーーーーー # 確率テーブルを probability_table={} numberref_table={} dead_flg=true while dead_flg dead_flg=false for x in @players if x.dead continue dead=0 for obj in @quantum_patterns if obj[x.id].dead==true dead++ if dead==@quantum_patterns.length # 死んだ!!!!!!!!!!!!!!!!! x.die this,"werewolf" dead_flg=true for x in @players count= Human:0 Diviner:0 Werewolf:0 dead:0 for obj in @quantum_patterns count[obj[x.id].jobtype]++ if obj[x.id].dead==true count.dead++ sum=count.Human+count.Diviner+count.Werewolf pflag=JSON.parse x.flag if sum==0 # 世界が崩壊した x.setFlag JSON.stringify { number:pflag?.number Human:0 Diviner:0 Werewolf:0 dead:0 } # ログ用 probability_table[x.id]={ name:x.name Human:0 Werewolf:0 } if @rule.quantumwerewolf_dead=="on" #死亡確率も probability_table[x.id].dead=0 if @rule.quantumwerewolf_diviner=="on" # 占卜师の確率も probability_table[x.id].Diviner=0 else x.setFlag JSON.stringify { number:pflag?.number Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum dead:count.dead/sum } # ログ用 if @rule.quantumwerewolf_diviner=="on" probability_table[x.id]={ name:x.name Human:count.Human/sum Diviner:count.Diviner/sum Werewolf:count.Werewolf/sum } else probability_table[x.id]={ name:x.name Human:(count.Human+count.Diviner)/sum Werewolf:count.Werewolf/sum } if @rule.quantumwerewolf_dead!="no" || count.dead==sum # 死亡率も probability_table[x.id].dead=count.dead/sum if @rule.quantumwerewolf_table=="anonymous" # 番号を表示 numberref_table[pflag.number]=x probability_table[x.id].name="玩家 #{pflag.number}" if @rule.quantumwerewolf_table=="anonymous" # ソートしなおしてあげて痕跡を消す probability_table=((probability_table,numberref_table)-> result={} i=1 x=null while x=numberref_table[i] result["_$_player#{i}"]=probability_table[x.id] i++ result )(probability_table,numberref_table) # ログを出す log= mode:"probability_table" probability_table:probability_table splashlog @id,this,log # もう一回死体処理 @bury(if @night then "night" else "day") return if @judge() @voting=false if @night # job数据を作る # LowBの襲い先 @werewolf_target=[] unless @day==1 && @rule.scapegoat!="off" @werewolf_target_remain=1 else if @rule.scapegoat=="on" # 誰が襲ったかはランダム onewolf=@players.filter (x)->x.isWerewolf() if onewolf.length>0 r=Math.floor Math.random()*onewolf.length @werewolf_target.push { from:onewolf[r].id to:"替身君" # みがわり } @werewolf_target_remain=0 else # 誰も襲わない @werewolf_target_remain=0 werewolf_flag_result=[] for fl in @werewolf_flag if fl=="Diseased" # 病人フラグが立っている(今日は襲撃できない @werewolf_target_remain=0 log= mode:"wolfskill" comment:"LowB们染病了。今天无法出击。" splashlog @id,this,log else if fl=="WolfCub" # 狼之子フラグが立っている(2回襲撃できる) @werewolf_target_remain=2 log= mode:"wolfskill" comment:"为狼之子复仇吧,今天可以袭击两个人。" splashlog @id,this,log else werewolf_flag_result.push fl @werewolf_flag=werewolf_flag_result # Fireworks should be lit at just before sunset. x = @players.filter((pl)->pl.isJobType("Pyrotechnist") && pl.accessByJobType("Pyrotechnist")?.flag == "using") if x.length # 全员花火の虜にしてしまう for pl in @players newpl=Player.factory null,pl,null,WatchingFireworks pl.transProfile newpl newpl.cmplFlag=x[0].id                     pl.transform this,newpl,true                 # Pyrotechnist should break the blockade of Threatened.sunset                 for pyr in x                     pyr.accessByJobType("Pyrotechnist").sunset this alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunset this else player.deadsunset this else # 誤爆防止 @werewolf_target_remain=0 # 処理 if @rule.deathnote # 死亡笔记採用 alives=@players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] sub=Player.factory "Light" # 副を作る pl.transProfile sub sub.sunset this newpl=Player.factory null,pl,sub,Complex pl.transProfile newpl @players.forEach (x,i)=> # 入れ替え if x.id==newpl.id @players[i]=newpl else x # Endless黑暗火锅用途中参加処理 if @rule.jobrule=="特殊规则.Endless黑暗火锅" exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] jobnames=Object.keys(jobs).filter (name)->!(name in exceptions) pcs=@participants.concat [] join_count=0 for player in pcs if player.isJobType "Watching" # 参加待機のひとだ if !@players.some((p)->p.id==player.id) # 本参加ではないのでOK # 职业をランダムに决定 newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob player.transProfile newpl player.transferData newpl # 观战者を除去 @participants=@participants.filter (x)->x!=player # プレイヤーとして追加 @players.push newpl @participants.push newpl # ログをだす log= mode:"system" comment:"#{newpl.name} 加入了游戏。" splashlog @id,@,log join_count++ # たまに転生 deads=shuffle @players.filter (x)->x.dead && !x.norevive # 転生確率 # 1人の転生確率をpとすると死者n人に対して転生人数の期待値はpn人。 # 1ターンに2人しぬとしてp(n+2)=2とおくとp=2/(n+2) 。 # 少し減らして人数を減少に持って行く p = 2/(deads.length+3) # 死者全员に対して転生判定 for pl in deads if Math.random()<p # でも参加者がいたら蘇生のかわりに if join_count>0 && Math.random()>p join_count-- continue newjob=jobnames[Math.floor Math.random()*jobnames.length] newpl=Player.factory newjob pl.transProfile newpl pl.transferData newpl # 蘇生 newpl.setDead false pl.transform @,newpl,true log= mode:"system" comment:"#{pl.name} 转生了。" splashlog @id,@,log @ss.publish.user newpl.id,"refresh",{id:@id} # 投票リセット処理 @votingbox.init() @votingbox.setCandidates @players.filter (x)->!x.dead alives=[] deads=[] for player in @players if player.dead deads.push player.id else alives.push player.id for i in (shuffle [0...(@players.length)]) player=@players[i] if player.id in alives player.sunrise this else player.deadsunrise this for pl in @players if !pl.dead pl.votestart this @revote_num=0 # 重新投票の回数は0にリセット #死体処理 @bury "other" return if @judge() @splashjobinfo() if @night @checkjobs() else # 昼は15秒规则があるかも if @rule.silentrule>0 @silentexpires=Date.now()+@rule.silentrule*1000 # これまでは黙っていよう! @save() @timer() #全员に状況更新 pls:状況更新したい人を指定する場合の配列 splashjobinfo:(pls)-> unless pls? # プレイヤー以外にも @ss.publish.channel "room#{@id}_audience","getjob",makejobinfo this,null # GMにも if @gm? @ss.publish.channel "room#{@id}_gamemaster","getjob",makejobinfo this,@getPlayerReal @gm pls=@participants pls.forEach (x)=> @ss.publish.user x.realid,"getjob",makejobinfo this,x #全员寝たかチェック 寝たなら処理してtrue #timeoutがtrueならば时间切れなので时间でも待たない checkjobs:(timeout)-> if @day==0 # 开始前(希望役职制) if timeout || @players.every((x)=>@rolerequesttable[x.id]?) # 全员できたぞ @setplayers (result)=> unless result? @rolerequestingphase=false @nextturn() @ss.publish.channel "room#{@id}","refresh",{id:@id} true else false else if @players.every( (x)=>x.dead || x.sleeping(@)) if @voting || timeout || !@rule.night || @rule.waitingnight!="wait" #夜に时间がある場合は待ってあげる @midnight() @nextturn() true else false else false #夜の能力を処理する midnight:-> alives=[] deads=[] pids=[] mids=[] for player in @players pids.push player.id # gather all midnightSort mids = mids.concat player.gatherMidnightSort() if player.dead deads.push player.id else alives.push player.id # unique mids.sort (a, b)=> return a - b midsu=[mids[0]] for mid in mids if midsu[midsu.length-1] != mid then midsu.push mid # 処理順はmidnightSortでソート pids = shuffle pids for mid in midsu for pid in pids player=@getPlayer pid pmids = player.gatherMidnightSort() if player.id in alives if mid in pmids player.midnight this,mid else if mid in pmids player.deadnight this,mid # 狼の処理 for target in @werewolf_target t=@getPlayer target.to continue unless t? # 噛まれた t.addGamelog this,"bitten" if @rule.noticebitten=="notice" || t.isJobType "Devil" log= mode:"skill" to:t.id comment:"#{t.name} 被LowB袭击了。" splashlog @id,this,log if !t.dead # 死んだ t.die this,"werewolf",target.from # 逃亡者を探す runners=@players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==target.to runners.forEach (x)=> x.die this,"werewolf2",target.from # その家に逃げていたら逃亡者も死ぬ if !t.dead # 死んでない flg_flg=false # なにかのフラグ for fl in @werewolf_flag res = fl.match /^ToughWolf_(.+)$/ if res? # 硬汉LowBがすごい tw = @getPlayer res[1] t=@getPlayer target.to if t? t.setDead true,"werewolf2" t.dying this,"werewolf2",tw.id flg_flg=true if tw? unless tw.dead tw.die this,"werewolf2" tw.addGamelog this,"toughwolfKilled",t.type,t.id break unless flg_flg # 一途は発動しなかった for fl in @werewolf_flag res = fl.match /^GreedyWolf_(.+)$/ if res? # 欲張り狼がやられた! gw = @getPlayer res[1] if gw? gw.die this,"werewolf2" gw.addGamelog this,"greedyKilled",t.type,t.id # 以降は襲撃できない flg_flg=true break if flg_flg # 欲張りのあれで襲撃终了 break @werewolf_flag=@werewolf_flag.filter (fl)-> # こいつらは1夜限り return !(/^(?:GreedyWolf|ToughWolf)_/.test fl) # 死んだ人を処理する type: タイミング # type: "day": 夜が明けたタイミング "night": 处刑後 "other":其他(ターン変わり時の能力で死んだやつなど) bury:(type)-> deads=[] loop deads=@players.filter (x)->x.dead && x.found deadsl=deads.length alives=@players.filter (x)->!x.dead alives.forEach (x)=> x.beforebury this,type deads=@players.filter (x)->x.dead && x.found if deadsl>=deads.length # もう新しく死んだ人はいない break # 灵界で职业表示してよいかどうか更新 switch @rule.heavenview when "view" @heavenview=true when "norevive" @heavenview=!@players.some((x)->x.isReviver()) else @heavenview=false deads=shuffle deads # 順番バラバラ deads.forEach (x)=> situation=switch x.found #死因 when "werewolf","werewolf2","poison","hinamizawa","vampire","vampire2","witch","dog","trap","bomb","marycurse","psycho","crafty" "不成样子的尸体被发现了" when "curse" # 呪殺 if @rule.deadfox=="obvious" "被咒杀了" else "不成样子的尸体被发现了" when "punish" "被处刑了" when "spygone" "离开了村子" when "deathnote" "的尸体被发现了" when "foxsuicide" "追随着妖狐自尽了" when "friendsuicide" "追随着恋人自尽了" when "infirm" "衰老而死了" when "gmpunish" "被GM处死了" when "gone-day" "因为没有及时投票猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" when "gone-night" "因为没有及时使用夜间技能猝死了。猝死是十分令人困扰的行为,请务必不要再犯。" else "死了" log= mode:"system" comment:"#{x.name} #{situation}" splashlog @id,this,log situation=switch x.found #死因 when "werewolf","werewolf2" "LowB的袭击" when "poison" "毒药" when "hinamizawa" "雏见泽症候群发作" when "vampire","vampire2" "吸血鬼的袭击" when "witch" "魔女的毒药" when "dog" "犬的袭击" when "trap" "陷阱" when "bomb" "炸弹" when "marycurse" "玛丽的诅咒" when "psycho" "变态杀人狂" when "curse" "咒杀" when "punish" "处刑" when "spygone" "失踪" when "deathnote" "心梗" when "foxsuicide" "追随妖狐自尽" when "friendsuicide" "追随恋人自尽" when "infirm" "老死" when "gmpunish" "被GM处死" when "gone-day" "昼间猝死" when "crafty" "假死" when "gone-night" "夜间猝死" else "未知原因" log= mode:"system" to:-1 comment:"#{x.name} 的死因是 #{situation}" splashlog @id,this,log ### if x.found=="punish" # 处刑→灵能 @players.forEach (y)=> if y.isJobType "Psychic" # 灵能 y.results.push x ### @addGamelog { # 死んだときと死因を記録 id:x.id type:x.type event:"found" flag:x.found } x.setDead x.dead,"" #発見されました @ss.publish.user x.realid,"refresh",{id:@id} if @rule.will=="die" && x.will # 死んだら遗言発表 log= mode:"will" name:x.name comment:x.will splashlog @id,this,log # 死者应该立刻从投票候选人中去除 @votingbox.candidates = @votingbox.candidates.filter (x)->!x.dead deads.length # 投票終わりチェック # 返り値意味ないんじゃないの? execute:-> return false unless @votingbox.isVoteAllFinished() [mode,player,tos,table]=@votingbox.check() if mode=="novote" # 誰も投票していない・・・ @revote_num=Infinity @judge() return false # 投票结果 log= mode:"voteresult" voteresult:table tos:tos splashlog @id,this,log if mode=="runoff" # 重新投票になった @dorevote "runoff" return false else if mode=="revote" # 重新投票になった @dorevote "revote" return false else if mode=="punish" # 投票 # 结果が出た 死んだ! # だれが投票したか調べる follower=table.filter((obj)-> obj.voteto==player.id).map (obj)->obj.id player.die this,"punish",follower if player.dead && @rule.GMpsychic=="on" # GM灵能 log= mode:"system" comment:"根据灵能的结论,被处刑的 #{player.name} 是 #{player.getPsychicResult()}。" splashlog @id,this,log @votingbox.remains-- if @votingbox.remains>0 # もっと殺したい!!!!!!!!! @bury "other" return false if @judge() log= mode:"system" comment:"今天还有#{@votingbox.remains}人将被处刑。请继续投票。" splashlog @id,this,log # 再び投票する処理(下と同じ… なんとかならないか?) @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() return false @nextturn() return true # 重新投票 dorevote:(mode)-> # mode: "runoff" - 决胜投票による重新投票 "revote" - 同数による重新投票 "gone" - 突然死による重新投票 if mode!="runoff" @revote_num++ if @revote_num>=4 # 4回重新投票 @judge() return remains=4-@revote_num if mode=="runoff" log= mode:"system" comment:"决胜投票。" else log= mode:"system" comment:"重新投票。" if isFinite remains log.comment += "如果在接下来的#{remains}轮投票中无法达成一致,本场游戏将以平局处理。" splashlog @id,this,log @votingbox.start() @players.forEach (player)=> return if player.dead player.votestart this @ss.publish.channel "room#{@id}","voteform",true @splashjobinfo() if @voting # 投票犹豫の場合初期化 clearTimeout @timerid @timer() # 勝敗决定 judge:-> aliveps=@players.filter (x)->!x.dead # 生きている人を集める # 数える alives=aliveps.length humans=aliveps.map((x)->x.humanCount()).reduce(((a,b)->a+b), 0) wolves=aliveps.map((x)->x.werewolfCount()).reduce(((a,b)->a+b), 0) vampires=aliveps.map((x)->x.vampireCount()).reduce(((a,b)->a+b), 0) team=null friends_count=null # 量子LowBのときは特殊ルーチン if @rule.jobrule=="特殊规则.量子LowB" assured_wolf= alive:0 dead:0 total_wolf=0 obj=@quantum_patterns[0] if obj? for key,value of obj if value.jobtype=="Werewolf" total_wolf++ for x in @players unless x.flag # まだだった・・・ break flag=JSON.parse x.flag if flag.Werewolf==1 # うわあああ絶対LowBだ!!!!!!!!!! if flag.dead==1 assured_wolf.dead++ else if flag.dead==0 assured_wolf.alive++ if alives<=assured_wolf.alive*2 # あーーーーーーー team="Werewolf" else if assured_wolf.dead==total_wolf # 全滅した team="Human" else # もうひとつもないんだ・・・ log= mode:"system" comment:"世界崩坏,概率无法定义。" splashlog @id,this,log team="Draw" else if alives==0 # 全滅 team="Draw" else if wolves==0 && vampires==0 # 母猪胜利 team="Human" else if humans<=wolves && vampires==0 # LowB胜利 team="Werewolf" else if humans<=vampires && wolves==0 # 吸血鬼胜利 team="Vampire" if team=="Werewolf" && wolves==1 # 一匹狼判定 lw=aliveps.filter((x)->x.isWerewolf())[0] if lw?.isJobType "LoneWolf" team="LoneWolf" if team? # 妖狐判定 if @players.some((x)->!x.dead && x.isFox()) team="Fox" # 恋人判定 if @players.some((x)->x.isFriend()) # 终了時に恋人生存 friends=@players.filter (x)->x.isFriend() && !x.dead gid=0 friends_count=0 friends_table={} for pl in friends unless friends_table[pl.id]? pt=pl.getPartner() unless friends_table[pt]? friends_count++ gid++ friends_table[pl.id]=gid friends_table[pt]=gid else # 合併 friends_table[pl.id]=friends_table[pt] else unless friends_table[pt]? friends_table[pt]=friends_table[pl.id] else if friends_table[pt]!=friends_table[pl.id] # 食い違っている c=Math.min friends_table[pt],friends_table[pl.id] d=Math.max friends_table[pt],friends_table[pl.id] for key,value of friends_table if value==d friends_table[key]=c # グループが合併した friends_count-- if friends_count==1 # 1組しかいない if @rule.friendsjudge=="alive" team="Friend" else if friends.length==alives team="Friend" else if friends_count>1 if alives==friends.length team="Friend" else # 恋人バトル team=null # カルト判定 if alives>0 && aliveps.every((x)->x.isCult() || x.isJobType("CultLeader") && x.getTeam()=="Cult" ) # 全員信者 team="Cult" # 悪魔くん判定 isDevilWinner = (pl)-> # 悪魔くんが勝利したか判定する return false unless pl? return false unless pl.isJobType "Devil" if pl.isComplex() return isDevilWinner(pl.sub) || (pl.getTeam() == "Devil" && isDevilWinner(pl.main)) else return pl.flag == "winner" if @players.some(isDevilWinner) team="Devil" if @revote_num>=4 && !team? # 重新投票多すぎ team="Draw" # 平局 if team? # 勝敗决定 @finished=true @last_time=Date.now() @winner=team if team!="Draw" @players.forEach (x)=> iswin=x.isWinner this,team if @rule.losemode # 败北村(負けたら勝ち) if iswin==true iswin=false else if iswin==false iswin=true # ただし突然死したら負け if @gamelogs.some((log)-> log.id==x.id && log.event=="found" && log.flag in ["gone-day","gone-night"] ) iswin=false x.setWinner iswin #胜利か # ユーザー情報 if x.winner M.users.update {userid:x.realid},{$push: {win:@id}} else M.users.update {userid:x.realid},{$push: {lose:@id}} log= mode:"nextturn" finished:true resultstring=null#结果 teamstring=null #阵营 [resultstring,teamstring]=switch team when "Human" if alives>0 && aliveps.every((x)->x.isJobType "Neet") ["村子变成了NEET的乐园。","母猪胜利"] else ["村子里的LowB已经被赶尽杀绝。","母猪胜利"] when "Werewolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","LowB胜利"] when "Fox" ["村子成了妖狐的玩物。","妖狐胜利"] when "Devil" ["村子成了恶魔的玩物。","恶魔胜利"] when "Friend" if friends_count>1 # みんなで胜利(珍しい) ["村子被恋人们支配了。","恋人胜利"] else friends=@players.filter (x)->x.isFriend() if friends.length==2 && friends.some((x)->x.isJobType "Noble") && friends.some((x)->x.isJobType "Slave") ["在主仆两人跨越世俗禁忌的爱情面前,所有阻碍都无法与之匹敌。","恋人胜利"] else ["在#{@players.filter((x)->x.isFriend() && !x.dead).length}人爱的力量面前,所有阻碍都无法与之匹敌。","恋人胜利"] when "Cult" ["村子被教会支配了。","邪教胜利"] when "Vampire" ["吸血鬼饮尽了最后一个村民的鲜血,向着下一个住满了猎物的村庄前进了…","吸血鬼胜利"] when "LoneWolf" ["LowB吃掉了最后一个村民,向着下一个住满了猎物的村庄前进了…","一匹狼胜利"] when "Draw" ["平局。",""] # 替身君单独胜利 winpl = @players.filter (x)->x.winner if(winpl.length==1 && winpl[0].realid=="替身君") resultstring="村子成了替身君的玩物。" log.comment="#{if teamstring then "【#{teamstring}】" else ""}#{resultstring}" splashlog @id,this,log # 房间を终了状态にする M.rooms.update {id:@id},{$set:{mode:"end"}} @ss.publish.channel "room#{@id}","refresh",{id:@id} @save() @prize_check() clearTimeout @timerid # 向房间成员通报猝死统计 norevivers=@gamelogs.filter((x)->x.event=="found" && x.flag in ["gone-day","gone-night"]).map((x)->x.id) if norevivers.length message = id:@id userlist:[] time:parseInt(60/@players.length) for x in norevivers pl = @getPlayer x message.userlist.push {"userid":pl.realid,"name":pl.name} @ss.publish.channel "room#{@id}",'punishalert',message # DBからとってきて告知ツイート M.rooms.findOne {id:@id},(err,doc)-> return unless doc? tweet doc.id,"「#{doc.name}」的结果: #{log.comment} #月下LowB" return true else return false timer:-> return if @finished func=null time=null mode=null # なんのカウントか timeout= => # 残り时间を知らせるぞ! @timer_start=parseInt Date.now()/1000 @timer_remain=time @timer_mode=mode @ss.publish.channel "room#{@id}","time",{time:time, mode:mode} if time>30 @timerid=setTimeout timeout,30000 time-=30 else if time>0 @timerid=setTimeout timeout,time*1000 time=0 else # 时间切れ func() if @rolerequestingphase # 希望役职制 time=60 mode="希望选择" func= => # 強制开始 @checkjobs true else if @night && !@voting # 夜 time=@rule.night mode="夜" return unless time func= => # ね な い こ だ れ だ unless @checkjobs true if @rule.remain # 犹豫时间があるよ @voting=true @timer() else @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else return else if @night # 夜の犹豫 time=@rule.remain mode="犹豫" func= => # ね な い こ だ れ だ @players.forEach (x)=> return if x.dead || x.sleeping(@) x.die this,"gone-night" # 突然死 x.setNorevive true # 突然死記録 M.users.update {userid:x.realid},{$push:{gone:@id}} @bury("other") @checkjobs true else if !@voting # 昼 time=@rule.day mode="昼" return unless time func= => unless @execute() if @rule.remain # 犹豫があるよ @voting=true log= mode:"system" comment:"白天的讨论时间到此结束。请投票决定要处死的人。" splashlog @id,this,log @timer() else # 突然死 revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return else # 犹豫时间も過ぎたよ! time=@rule.remain mode="犹豫" func= => unless @execute() revoting=false @players.forEach (x)=> return if x.dead || x.voted(this,@votingbox) x.die this,"gone-day" x.setNorevive true revoting=true @bury("other") @judge() if revoting @dorevote "gone" else @execute() else return timeout() # プレイヤーごとに 見せてもよいログをリストにする makelogs:(logs,player)-> result = [] for x in logs ls = makelogsFor this, player, x result.push ls... return result prize_check:-> Server.prize.checkPrize @,(obj)=> # obj: {(userid):[prize]} # 賞を算出した pls=@players.filter (x)->x.realid!="替身君" # 各々に対して処理 query={userid:{$in:pls.map (x)->x.realid}} M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # いままでの賞の一览 # 差分をとる newprize=obj[doc.userid].filter (x)->!(x in oldprize) if newprize.length>0 M.users.update {userid:doc.userid},{$set:{prize:obj[doc.userid]}} pl=@getPlayerReal doc.userid pnames=newprize.map (plzid)-> Server.prize.prizeQuote Server.prize.prizeName plzid log= mode:"system" comment:"#{pl.name} 获得了称号 #{pnames.join ''}。" splashlog @id,this,log ### M.users.find(query).each (err,doc)=> return unless doc? oldprize=doc.prize # 賞の一览 # 賞を算出しなおしてもらう Server.prize.checkPrize doc.userid,(prize)=> prize=prize.concat doc.ownprize if doc.ownprize? # 新規に獲得した賞を探す newprizes= prize.filter (x)->!(x in oldprize) if newprizes.length>0 M.users.update {userid:doc.userid},{$set:{prize:prize}} pl=@getPlayerReal doc.userid newprizes.forEach (x)=> log= mode:"system" comment:"#{pl.name}は#{Server.prize.prizeQuote Server.prize.prizeName x}を獲得しました。" splashlog @id,this,log @addGamelog { id: pl.id type:pl.type event:"getprize" flag:x target:null } ### ### logs:[{ mode:"day"(昼) / "system"(システムメッセージ) / "werewolf"(狼) / "heaven"(天国) / "prepare"(开始前/终了後) / "skill"(能力ログ) / "nextturn"(游戏進行) / "audience"(观战者のひとりごと) / "monologue"(夜のひとりごと) / "voteresult" (投票结果) / "couple"(共有者) / "fox"(妖狐) / "will"(遗言) comment: String userid:Userid name?:String to:Userid / null (あると、その人だけ) (nextturnの場合) day:Number night:Boolean finished?:Boolean (voteresultの場合) voteresult:[] tos:Object },...] rule:{ number: Number # プレイヤー数 scapegoat : "on"(身代わり君が死ぬ) "off"(参加者が死ぬ) "no"(誰も死なない) } ### # 投票箱 class VotingBox constructor:(@game)-> @init() init:-> # 投票箱を空にする @remains=1 # 残り处刑人数 @runoffmode=false # 重新投票中か @candidates=[] @start() start:-> @votes=[] #{player:Player, to:Player} setCandidates:(@candidates)-> # 候補者をセットする[Player] isVoteFinished:(player)->@votes.some (x)->x.player.id==player.id vote:(player,voteto)-> # power: 票数 pl=@game.getPlayer voteto unless pl? return "这个玩家不存在" if pl.dead return "这个人已经死了" me=@game.getPlayer player.id unless me? return "你没有加入游戏" if @isVoteFinished player return "你已经投过票了" if pl.id==player.id && @game.rule.votemyself!="ok" return "不能向自己投票" @votes.push { player:@game.getPlayer player.id to:pl power:1 priority:0 } log= mode:"voteto" to:player.id comment:"#{player.name} 向 #{pl.name} 投票了" splashlog @game.id,@game,log null # その人の投票オブジェクトを得る getHisVote:(player)-> @votes.filter((x)->x.player.id==player.id)[0] # 票のパワーを变更する votePower:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.power=value else v.power+=value # 優先度つける votePriority:(player,value,absolute=false)-> v=@getHisVote player if v? if absolute v.priority=value else v.priority+=value # 处刑人数を増やす addPunishedNumber:(num)-> @remains+=num isVoteAllFinished:-> alives=@game.players.filter (x)->!x.dead alives.every (x)=> x.voted @game,@ compareGots:(a,b)-> # aとbをsort用に(gots) # aのほうが小さい: -1 < # bのほうが小さい: 1 > if a.votes>b.votes return 1 else if a.votes<b.votes return -1 else if a.priority>b.priority return 1 else if a.priority<b.priority return -1 else return 0 check:-> # return [mode,result,tos,table] # 投票が終わったのでアレする # 投票表を作る tos={} table=[] gots={} #for obj in @votes alives = @game.players.filter (x)->!x.dead for pl in alives obj=@getHisVote pl o=pl.publicinfo() if obj? gots[obj.to.id] ?= { votes:0 priority:-Infinity } go=gots[obj.to.id] go.votes+=obj.power if go.priority<obj.priority go.priority=obj.priority tos[obj.to.id]=go.votes o.voteto=obj.to.id # 投票先情報を付け加える table.push o for pl in alives vote = gots[pl.id] if vote? vote = pl.modifyMyVote @game, vote gots[pl.id] = vote tos[pl.id] = vote.votes # 獲得票数が少ない順に並べる cands=Object.keys(gots).sort (a,b)=> @compareGots gots[a],gots[b] # 獲得票数多い一览 back=null tops=[] for id in cands by -1 if !back? || @compareGots(gots[back],gots[id])==0 tops.push id back=id else break if tops.length==0 # 誰も投票していない return ["novote",null,tos,table] if tops.length>1 # 決まらない! 重新投票になった if @game.rule.runoff!="no" && !@runoffmode @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] else return ["revote",null,tos,table] if @game.rule.runoff=="yes" && !@runoffmode # 候補は1人だけど决胜投票をしないといけない if tops.length<=1 # 候補がたりない back=null flag=false tops=[] for id in cands by -1 ok=false if !back? ok=true else if @compareGots(gots[back],gots[id])==0 ok=true else if flag==false # 决胜投票なので1回だけOK! flag=true ok=true else break if ok tops.push id back=id if tops.length>1 @setCandidates @game.players.filter (x)->x.id in tops @runoffmode=true return ["runoff",null,tos,table] # 结果を教える return ["punish",@game.getPlayer(tops[0]),tos,table] class Player constructor:-> # realid:本当のid id:仮のidかもしれない name:名字 icon:头像URL @dead=false @found=null # 死体の発見状況 @winner=null # 勝敗 @scapegoat=false # 替身君かどうか @flag=null # 职业ごとの自由なフラグ @will=null # 遗言 # もと的职业 @originalType=@type @originalJobname=@getJobname() # 拒绝复活 @norevive=false @factory:(type,main=null,sub=null,cmpl=null)-> p=null if cmpl? # 複合 mainとsubを使用 #cmpl: 複合の親として使用するオブジェクト myComplex=Object.create main #Complexから sample=new cmpl # 手動でComplexを継承したい Object.keys(sample).forEach (x)-> delete sample[x] # own propertyは全部消す for name of sample # sampleのown Propertyは一つもない myComplex[name]=sample[name] # 混合职业 p=Object.create myComplex p.main=main p.sub=sub p.cmplFlag=null else if !jobs[type]? p=new Player else p=new jobs[type] p serialize:-> r= type:@type id:@id realid:@realid name:@name dead:@dead scapegoat:@scapegoat will:@will flag:@flag winner:@winner originalType:@originalType originalJobname:@originalJobname norevive:@norevive if @isComplex() r.type="Complex" r.Complex_main=@main.serialize() r.Complex_sub=@sub?.serialize() r.Complex_type=@cmplType r.Complex_flag=@cmplFlag r @unserialize:(obj)-> unless obj? return null p=if obj.type=="Complex" # 複合 cmplobj=complexes[obj.Complex_type ? "Complex"] Player.factory null, Player.unserialize(obj.Complex_main), Player.unserialize(obj.Complex_sub),cmplobj else # 普通 Player.factory obj.type p.setProfile obj #id,realid,name... p.dead=obj.dead p.scapegoat=obj.scapegoat p.will=obj.will p.flag=obj.flag p.winner=obj.winner p.originalType=obj.originalType p.originalJobname=obj.originalJobname p.norevive=!!obj.norevive # backward compatibility if p.isComplex() p.cmplFlag=obj.Complex_flag p # 汎用関数: Complexを再構築する(chain:Complexの列(上から)) @reconstruct:(chain,base)-> for cmpl,i in chain by -1 newpl=Player.factory null,base,cmpl.sub,complexes[cmpl.cmplType] ### for ok in Object.keys cmpl # 自己のプロパティのみ unless ok=="main" || ok=="sub" newpl[ok]=cmpl[ok] ### newpl.cmplFlag=cmpl.cmplFlag base=newpl base publicinfo:-> # 見せてもいい情報 { id:@id name:@name dead:@dead norevive:@norevive } # プロパティセット系(Complex対応) setDead:(@dead,@found)-> setWinner:(@winner)-> setTarget:(@target)-> setFlag:(@flag)-> setWill:(@will)-> setOriginalType:(@originalType)-> setOriginalJobname:(@originalJobname)-> setNorevive:(@norevive)-> # ログが見えるかどうか(通常の游戏中、個人宛は除外) isListener:(game,log)-> if log.mode in ["day","system","nextturn","prepare","monologue","heavenmonologue","skill","will","voteto","gm","gmreply","helperwhisper","probability_table","userinfo"] # 全員に見える true else if log.mode in ["heaven","gmheaven"] # 死んでたら見える @dead else if log.mode=="voteresult" game.rule.voteresult!="hide" # 隠すかどうか else false # midnightの実行順(小さいほうが先) midnightSort: 100 # 本人に見える职业名 getJobDisp:->@jobname # 本人に見える职业タイプ getTypeDisp:->@type # 职业名を得る getJobname:->@jobname # 母猪かどうか isHuman:->!@isWerewolf() # LowBかどうか isWerewolf:->false # 洋子かどうか isFox:->false # 妖狐の仲間としてみえるか isFoxVisible:->false # 恋人かどうか isFriend:->false # Complexかどうか isComplex:->false # 教会信者かどうか isCult:->false # 吸血鬼かどうか isVampire:->false # 酒鬼かどうか isDrunk:->false # 蘇生可能性を秘めているか isReviver:->false # Am I Dead? isDead:->{dead:@dead,found:@found} # get my team getTeam:-> @team # 終了時の人間カウント humanCount:-> if !@isFox() && @isHuman() 1 else 0 werewolfCount:-> if !@isFox() && @isWerewolf() 1 else 0 vampireCount:-> if !@isFox() && @isVampire() 1 else 0 # jobtypeが合っているかどうか(夜) isJobType:(type)->type==@type #An access to @flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" if @isJobType(type) return this null gatherMidnightSort:-> return [@midnightSort] # complexのJobTypeを調べる isCmplType:(type)->false # 投票先决定 dovote:(game,target)-> # 戻り値にも意味があるよ! err=game.votingbox.vote this,target,1 if err? return err @voteafter game,target return null voteafter:(game,target)-> # 昼のはじまり(死体処理よりも前) sunrise:(game)-> deadsunrise:(game)-> # 昼の投票準備 votestart:(game)-> #@voteto=null return if @dead if @scapegoat # 替身君は投票 alives=game.players.filter (x)=>!x.dead && x!=this r=Math.floor Math.random()*alives.length # 投票先 return unless alives[r]? #@voteto=alives[r].id @dovote game,alives[r].id # 夜のはじまり(死体処理よりも前) sunset:(game)-> deadsunset:(game)-> # 夜にもう寝たか sleeping:(game)->true # 夜に仕事を追えたか(基本sleepingと一致) jobdone:(game)->@sleeping game # 死んだ後でも仕事があるとfalse deadJobdone:(game)->true # 昼に投票を終えたか voted:(game,votingbox)->game.votingbox.isVoteFinished this # 夜の仕事 job:(game,playerid,query)-> @setTarget playerid null # 夜の仕事を行う midnight:(game,midnightSort)-> # 夜死んでいたときにmidnightの代わりに呼ばれる deadnight:(game,midnightSort)-> # 対象 job_target:1 # ビットフラグ # 対象用の値 @JOB_T_ALIVE:1 # 生きた人が対象 @JOB_T_DEAD :2 # 死んだ人が対象 #LowBに食われて死ぬかどうか willDieWerewolf:true #占いの结果 fortuneResult:"母猪" getFortuneResult:->@fortuneResult #霊能の結果 psychicResult:"母猪" getPsychicResult:->@psychicResult #チーム Human/Werewolf team: "Human" #胜利かどうか team:胜利阵营名 isWinner:(game,team)-> team==@team # 自己の阵营かどうか # 殺されたとき(found:死因。fromは場合によりplayerid。punishの場合は[playerid])) die:(game,found,from)-> return if @dead if found=="werewolf" && !@willDieWerewolf # 襲撃耐性あり return pl=game.getPlayer @id pl.setDead true,found pl.dying game,found,from # 死んだとき dying:(game,found)-> # 行きかえる revive:(game)-> # logging: ログを表示するか if @norevive # 蘇生しない return @setDead false,null p=@getParent game unless p?.sub==this # サブのときはいいや・・・ log= mode:"system" comment:"#{@name} 复活了。" splashlog game.id,game,log @addGamelog game,"revive",null,null game.ss.publish.user @id,"refresh",{id:game.id} # 埋葬するまえに全员呼ばれる(foundが見られる状況で) beforebury: (game,type)-> # 占われたとき(结果は別にとられる player:占い元) divined:(game,player)-> # ちょっかいを出されたとき(jobのとき) touched:(game,from)-> # 选择肢を返す makeJobSelection:(game)-> if game.night # 夜の能力 jt=@job_target if jt>0 # 参加者を选择する result=[] for pl in game.players if (pl.dead && (jt&Player.JOB_T_DEAD))||(!pl.dead && (jt&Player.JOB_T_ALIVE)) result.push { name:pl.name value:pl.id } else result=[] else # 昼の投票 result=[] if game?.votingbox for pl in game.votingbox.candidates result.push { name:pl.name value:pl.id } result checkJobValidity:(game,query)-> sl=@makeJobSelection game return sl.length==0 || sl.some((x)->x.value==query.target) # 职业情報を載せる makejobinfo:(game,obj,jobdisp)-> # 開くべきフォームを配列で(生きている場合) obj.open ?=[] if !@jobdone(game) && (game.night || @chooseJobDay(game)) obj.open.push @type # 职业解説のアレ obj.desc ?= [] type = @getTypeDisp() if type? obj.desc.push { name:jobdisp ? @getJobDisp() type:type } obj.job_target=@getjob_target() # 选择肢を教える {name:"名字",value:"値"} obj.job_selection ?= [] obj.job_selection=obj.job_selection.concat @makeJobSelection game # 重複を取り除くのはクライアント側にやってもらおうかな… # 女王观战者が見える if @team=="Human" obj.queens=game.players.filter((x)->x.isJobType "QueenSpectator").map (x)-> x.publicinfo() else # セットなどによる漏洩を防止 delete obj.queens # 昼でも対象选择を行えるか chooseJobDay:(game)->false # 仕事先情報を教える getjob_target:->@job_target # 昼の发言の选择肢 getSpeakChoiceDay:(game)-> ["day","monologue"] # 夜の发言の选择肢を得る getSpeakChoice:(game)-> ["monologue"] # 自分宛の投票を書き換えられる modifyMyVote:(game, vote)-> vote # Complexから抜ける uncomplex:(game,flag=false)-> #flag: 自己がComplexで自己が消滅するならfalse 自己がmainまたはsubで親のComplexを消すならtrue(その際subは消滅) befpl=game.getPlayer @id # objがPlayerであること calleeは呼び出し元のオブジェクト chainは継承連鎖 # index: game.playersの番号 chk=(obj,index,callee,chain)-> return unless obj? chc=chain.concat obj if obj.isComplex() if flag # mainまたはsubである if obj.main==callee || obj.sub==callee # 自己は消える game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc else # 自己がComplexである if obj==callee game.players[index]=Player.reconstruct chain,obj.main else chk obj.main,index,callee,chc # TODO これはよくない chk obj.sub,index,callee,chc game.players.forEach (x,i)=> if x.id==@id chk x,i,this,[] # participantsも for pl,j in game.participants if pl.id==@id game.participants[j]=game.players[i] break aftpl=game.getPlayer @id #前と後で比較 if befpl.getJobname()!=aftpl.getJobname() aftpl.setOriginalJobname "#{befpl.originalJobname}→#{aftpl.getJobname()}" # 自己自身を変える transform:(game,newpl,override,initial=false)-> # override: trueなら全部変える falseならメイン职业のみ変える @addGamelog game,"transform",newpl.type # 职业変化ログ if override || !@isComplex() # 全部取っ払ってnewplになる newpl.setOriginalType @originalType if @getJobname()!=newpl.getJobname() unless initial # ふつうの変化 newpl.setOriginalJobname "#{@originalJobname}→#{newpl.getJobname()}" else # 最初の変化(ログに残さない) newpl.setOriginalJobname newpl.getJobname() pa=@getParent game unless pa? # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=newpl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=newpl else # 親がいた if pa.main==this # 親書き換え newparent=Player.factory null,newpl,pa.sub,complexes[pa.cmplType] newparent.cmplFlag=pa.cmplFlag newpl.transProfile newparent pa.transform game,newparent,override # たのしい再帰 else # サブだった pa.sub=newpl else # 中心のみ変える pa=game.getPlayer @id orig_originalJobname=pa.originalJobname chain=[pa] while pa.main.isComplex() pa=pa.main chain.push pa # pa.mainはComplexではない toppl=Player.reconstruct chain,newpl toppl.setOriginalJobname "#{orig_originalJobname}→#{toppl.getJobname()}" # 親なんていない game.players.forEach (x,i)=> if x.id==@id game.players[i]=toppl game.participants.forEach (x,i)=> if x.id==@id game.participants[i]=toppl getParent:(game)-> chk=(parent,name)=> if parent[name]?.isComplex?() if parent[name].main==this || parent[name].sub==this return parent[name] else return chk(parent[name],"main") || chk(parent[name],"sub") else return null for pl,i in game.players c=chk game.players,i return c if c? return null # 親なんていない # 自己のイベントを記述 addGamelog:(game,event,flag,target,type=@type)-> game.addGamelog { id:@id type:type target:target event:event flag:flag } # 個人情報的なことをセット setProfile:(obj={})-> @id=obj.id @realid=obj.realid @name=obj.name # 個人情報的なことを移動 transProfile:(newpl)-> newpl.setProfile this # フラグ類を新しいPlayerオブジェクトへ移動 transferData:(newpl)-> return unless newpl? newpl.scapegoat=@scapegoat newpl.setDead @dead,@found class Human extends Player type:"Human" jobname:"母猪" class Werewolf extends Player type:"Werewolf" jobname:"LowB" sunset:(game)-> @setTarget null unless game.day==1 && game.rule.scapegoat!="off" if @scapegoat && @isAttacker() && game.players.filter((x)->!x.dead && x.isWerewolf() && x.isAttacker()).length==1 # 自己しかLowBがいない hus=game.players.filter (x)->!x.dead && !x.isWerewolf() while hus.length>0 && game.werewolf_target_remain>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } hus.splice r,1 if game.werewolf_target_remain>0 # 襲撃したい人全员襲撃したけどまだ襲撃できるときは重複襲撃 hus=game.players.filter (x)->!x.dead && !x.isWerewolf() # safety counter i = 100 while hus.length>0 && game.werewolf_target_remain>0 && i > 0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{ jobtype: "_Werewolf" } i-- sleeping:(game)->game.werewolf_target_remain<=0 || !game.night job:(game,playerid)-> tp = game.getPlayer playerid if game.werewolf_target_remain<=0 return "已经决定了袭击对象" if game.rule.wolfattack!="ok" && tp?.isWerewolf() # LowBはLowBに攻撃できない return "LowB之间不能相互袭击" game.werewolf_target.push { from:@id to:playerid } game.werewolf_target_remain-- tp.touched game,@id log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚袭击 #{tp.name}。" if @isJobType "SolitudeWolf" # 孤独的狼なら自己だけ… log.to=@id splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null isHuman:->false isWerewolf:->true # おおかみ専用メソッド:襲撃できるか isAttacker:->!@dead isListener:(game,log)-> if log.mode in ["werewolf","wolfskill"] true else super isJobType:(type)-> # 便宜的 if type=="_Werewolf" return true super willDieWerewolf:false fortuneResult:"LowB" psychicResult:"LowB" team: "Werewolf" makejobinfo:(game,result)-> super if game.night && game.werewolf_target_remain>0 # まだ襲える result.open.push "_Werewolf" # LowBは仲間が分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() # 间谍2も分かる result.spy2s=game.players.filter((x)->x.isJobType "Spy2").map (x)-> x.publicinfo() getSpeakChoice:(game)-> ["werewolf"].concat super class Diviner extends Player type:"Diviner" jobname:"占卜师" midnightSort: 100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid)-> super pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> unless game.rule.divineresult=="immediate" @dodivine game @divineeffect game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @target if p? p.divined game,this #占い実行 dodivine:(game)-> p=game.getPlayer @target if p? @results.push { player: p.publicinfo() result: "#{@name} 占卜了 #{p.name} 的身份,他是 #{p.getFortuneResult()}。" } @addGamelog game,"divine",p.type,@target # 占った showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Psychic extends Player type:"Psychic" jobname:"PI:NAME:<NAME>END_PI" constructor:-> super @setFlag "" # ここにメッセージを入れよう sunset:(game)-> super if game.rule.psychicresult=="sunset" @showpsychicresult game sunrise:(game)-> super unless game.rule.psychicresult=="sunset" @showpsychicresult game showpsychicresult:(game)-> return unless @flag? @flag.split("\n").forEach (x)=> return unless x log= mode:"skill" to:@id comment:x splashlog game.id,game,log @setFlag "" # 处刑で死んだ人を調べる beforebury:(game,type)-> @setFlag if @flag? then @flag else "" game.players.filter((x)->x.dead && x.found=="punish").forEach (x)=> @setFlag @flag+"根据 #{@name} 的灵能结论,被处刑的 #{x.name} 是 #{x.getPsychicResult()}。\n" class Madman extends Player type:"Madman" jobname:"PI:NAME:<NAME>END_PI" team:"Werewolf" makejobinfo:(game,result)-> super delete result.queens class Guard extends Player type:"Guard" jobname:"PI:NAME:<NAME>END_PI" midnightSort: 80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} # 失敗した @setTarget "" job:(game,playerid)-> if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" else @setTarget playerid pl=game.getPlayer(playerid) log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true newpl.touched game,@id null class Couple extends Player type:"Couple" jobname:"PI:NAME:<NAME>END_PI" makejobinfo:(game,result)-> super # 共有者は仲間が分かる result.peers=game.players.filter((x)->x.isJobType "Couple").map (x)-> x.publicinfo() isListener:(game,log)-> if log.mode=="couple" true else super getSpeakChoice:(game)-> ["couple"].concat super class Fox extends Player type:"Fox" jobname:"PI:NAME:<NAME>END_PI" team:"Fox" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true makejobinfo:(game,result)-> super # 妖狐は仲間が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() divined:(game,player)-> super # 妖狐呪殺 @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した isListener:(game,log)-> if log.mode=="fox" true else super getSpeakChoice:(game)-> ["fox"].concat super class Poisoner extends Player type:"Poisoner" jobname:"PI:NAME:<NAME>END_PI" dying:(game,found,from)-> super # 埋毒者の逆襲 canbedead = game.players.filter (x)->!x.dead # 生きている人たち if found=="werewolf" # 噛まれた場合は狼のみ if game.rule.poisonwolf == "selector" # 襲撃者を道連れにする canbedead = canbedead.filter (x)->x.id==from else canbedead=canbedead.filter (x)->x.isWerewolf() else if found=="vampire" canbedead=canbedead.filter (x)->x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"poison" @addGamelog game,"poisonkill",null,pl.id class BigWolf extends Werewolf type:"BigWolf" jobname:"PI:NAME:<NAME>END_PI" fortuneResult:"母猪" psychicResult:"大LowB" class TinyFox extends Diviner type:"TinyFox" jobname:"PI:NAME:<NAME>END_PI" fortuneResult:"母猪" psychicResult:"小狐" team:"FPI:NAME:<NAME>END_PI" midnightSort:100 isHuman:->false isFox:->true makejobinfo:(game,result)-> super # 子狐は妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() dodivine:(game)-> p=game.getPlayer @target if p? success= Math.random()<0.5 # 成功したかどうか re=if success then "是 #{p.getFortuneResult()}" else "是一个看不透的可疑人物" @results.push { player: p.publicinfo() result: "根据 #{@name} 的占卜结果,#{p.name} #{re},大概。" } @addGamelog game,"foxdivine",success,p.id showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Bat extends Player type:"Bat" jobname:"PI:NAME:<NAME>END_PI" team:"" isWinner:(game,team)-> !@dead # 生きて入ればとにかく胜利 class Noble extends Player type:"Noble" jobname:"贵族" die:(game,found)-> if found=="werewolf" return if @dead # 奴隶たち slaves = game.players.filter (x)->!x.dead && x.isJobType "Slave" unless slaves.length super # 自己が死ぬ else # 奴隶が代わりに死ぬ slaves.forEach (x)-> x.die game,"werewolf2" x.addGamelog game,"slavevictim" @addGamelog game,"nobleavoid" else super class Slave extends Player type:"Slave" jobname:"PI:NAME:<NAME>END_PI" isWinner:(game,team)-> nobles=game.players.filter (x)->!x.dead && x.isJobType "Noble" if team==@team && nobles.length==0 true # 母猪阵营の勝ちで贵族は死んだ else false makejobinfo:(game,result)-> super # 奴隶は贵族が分かる result.nobles=game.players.filter((x)->x.isJobType "Noble").map (x)-> x.publicinfo() class Magician extends Player type:"Magician" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 isReviver:->!@dead sunset:(game)-> @setTarget (if game.day<3 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> if game.day<3 # まだ発動できない return "现在还不能发动技能" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null sleeping:(game)->game.day<3 || @target? midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=if pl.scapegoat then 0.6 else 0.3 unless Math.random()<r # 失敗 @addGamelog game,"raise",false,pl.id return # 蘇生 目を覚まさせる @addGamelog game,"raise",true,pl.id pl.revive game job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Spy extends Player type:"Spy" jobname:"PI:NAME:<NAME>END_PI" team:"Werewolf" midnightSort:100 sleeping:->true # 能力使わなくてもいい jobdone:->@flag in ["spygone","day1"] # 能力を使ったか sunrise:(game)-> if game.day<=1 @setFlag "day1" # まだ去れない else @setFlag null job:(game,playerid)-> return "已经发动了技能" if @flag=="spygone" @setFlag "spygone" log= mode:"skill" to:@id comment:"#{@name} 决定要离开村子。" splashlog game.id,game,log null midnight:(game,midnightSort)-> if !@dead && @flag=="spygone" # 村を去る @setFlag "spygone" @die game,"spygone" job_target:0 isWinner:(game,team)-> team==@team && @dead && @flag=="spygone" # LowBが勝った上で自己は任務完了の必要あり makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class WolfDiviner extends Werewolf type:"WolfDiviner" jobname:"LowB占卜师" midnightSort:100 constructor:-> super @results=[] # {player:Player, result:String} sunset:(game)-> @setTarget null @setFlag null # 占い対象 @result=null # 占卜结果 super sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && @flag? job:(game,playerid,query)-> if query.jobtype!="WolfDiviner" # LowBの仕事 return super # 占い if @flag? return "已经决定占卜对象" pl=game.getPlayer playerid unless pl? return "这个玩家不存在。" @setFlag playerid unless pl.getTeam()=="Werewolf" && pl.isHuman() # 狂人は変化するので pl.touched game,@id log= mode:"skill" to:@id comment:"LowB占卜师PI:NAME:<NAME>END_PI #{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null sunrise:(game)-> super unless game.rule.divineresult=="immediate" @showdivineresult game midnight:(game,midnightSort)-> super @divineeffect game unless game.rule.divineresult=="immediate" @dodivine game #占った影響を与える divineeffect:(game)-> p=game.getPlayer @flag if p? p.divined game,this if p.isJobType "Diviner" # 逆呪殺 @die game,"curse" showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log dodivine:(game)-> p=game.getPlayer @flag if p? @results.push { player: p.publicinfo() result: "LowB占卜师PI:NAME:<NAME>END_PI #{@name} 占卜了 #{p.name} 的身份,他是 #{p.jobname}。" } @addGamelog game,"wolfdivine",null,@flag # 占った if p.getTeam()=="Werewolf" && p.isHuman() # 狂人変化 #避免狂人成为某些职业,"GameMaster"保留 jobnames=Object.keys jobs jobnames=jobnames.filter((x)->!(x in ["MinionSelector","Thief","Helper","QuantumPlayer","Waiting","Watching"])) newjob = jobnames[Math.floor(Math.random() * jobnames.length)] plobj=p.serialize() plobj.type=newjob newpl=Player.unserialize plobj # 新生狂人 newpl.setFlag null p.transferData newpl p.transform game,newpl,false p=game.getPlayer @flag p.sunset game log= mode:"skill" to:p.id comment:"#{p.name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.splashjobinfo [game.getPlayer newpl.id] makejobinfo:(game,result)-> super if game.night if @flag? # もう占いは終わった result.open = result.open?.filter (x)=>x!="WolfDiviner" class Fugitive extends Player type:"Fugitive" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 sunset:(game)-> @setTarget null if game.day<=1 #&& game.rule.scapegoat!="off" # 一日目は逃げない @setTarget "" else if @scapegoat # 身代わり君の自動占い als=game.players.filter (x)=>!x.dead && x.id!=@id if als.length==0 @setTarget "" return r=Math.floor Math.random()*als.length if @job game,als[r].id,{} @setTarget "" sleeping:->@target? job:(game,playerid)-> # 逃亡先 pl=game.getPlayer playerid if pl?.dead return "不能逃到死者的家里去" if playerid==@id return "不能逃到自己的家里去" @setTarget playerid pl?.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 逃亡到 #{pl.name} 的家里去了。" splashlog game.id,game,log @addGamelog game,"runto",null,pl.id null die:(game,found)-> # 狼の襲撃・吸血鬼の襲撃・魔女の毒薬は回避 if found in ["werewolf","vampire","witch"] if @target!="" return else super else super midnight:(game,midnightSort)-> # LowBの家に逃げていたら即死 pl=game.getPlayer @target return unless pl? if !pl.dead && pl.isWerewolf() && pl.getTeam() in ["Werewolf","LoneWolf"] @die game,"werewolf2" else if !pl.dead && pl.isVampire() && pl.getTeam()=="Vampire" @die game,"vampire2" isWinner:(game,team)-> team==@team && !@dead # 母猪胜利で生存 class Merchant extends Player type:"Merchant" jobname:"商人" constructor:-> super @setFlag null # 発送済みかどうか sleeping:->true jobdone:(game)->game.day<=1 || @flag? job:(game,playerid,query)-> if @flag? return "商品已经送出" # 即時発送 unless query.Merchant_kit in ["Diviner","Psychic","Guard"] return "要送出的商品无效" kit_names= "Diviner":"占卜套装" "Psychic":"灵能套装" "Guard":"守护套装" pl=game.getPlayer playerid unless pl? return "发送无效" if pl.dead return "发送对象已经死亡" if pl.id==@id return "不能发送给自己" pl.touched game,@id # 複合させる sub=Player.factory query.Merchant_kit # 副を作る pl.transProfile sub sub.sunset game newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 寄出了 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log # 入れ替え先は気づいてもらう log= mode:"skill" to:newpl.id comment:"#{newpl.name} 收到了礼物 #{kit_names[query.Merchant_kit]}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} @setFlag query.Merchant_kit # 発送済み @addGamelog game,"sendkit",@flag,newpl.id null class QueenSpectator extends Player type:"QueenSpectator" jobname:"女王观战者" dying:(game,found)-> super # 感染 humans = game.players.filter (x)->!x.dead && x.isHuman() # 生きている人たち humans.forEach (x)-> x.die game,"hinamizawa" class MadWolf extends Werewolf type:"MadWolf" jobname:"狂LowB" team:"Human" sleeping:->true class Neet extends Player type:"Neet" jobname:"NEET" team:"" sleeping:->true voted:(game,votingbox)->true isWinner:->true class Liar extends Player type:"Liar" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も constructor:-> super @results=[] sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} sleeping:->@target? job:(game,playerid,query)-> # 占い if @target? return "已经决定占卜对象" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log null sunrise:(game)-> super return if !@results? || @results.length==0 log= mode:"skill" to:@id comment:"虽然不是很自信,根据骗子占卜的结果 #{@results[@results.length-1].player.name} 大概是 #{@results[@results.length-1].result},大概。" splashlog game.id,game,log midnight:(game,midnightSort)-> p=game.getPlayer @target if p? @addGamelog game,"liardivine",null,p.id @results.push { player: p.publicinfo() result: if Math.random()<0.3 # 成功 p.getFortuneResult() else # 逆 fr = p.getFortuneResult() switch fr when "母猪" "LowB" when "LowB" "母猪" else fr } isWinner:(game,team)->team==@team && !@dead # 母猪胜利で生存 class Spy2 extends Player type:"Spy2" jobname:"PI:NAME:<NAME>END_PI" team:"Werewolf" makejobinfo:(game,result)-> super # 间谍はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() dying:(game,found)-> super @publishdocument game publishdocument:(game)-> str=game.players.map (x)-> "#{x.name}:#{x.jobname}" .join " \n" log= mode:"system" comment:"发现了 #{@name} 的调查报告书。" splashlog game.id,game,log log2= mode:"will" comment:str splashlog game.id,game,log2 isWinner:(game,team)-> team==@team && !@dead class Copier extends Player type:"Copier" jobname:"PI:NAME:<NAME>END_PI" team:"" isHuman:->false sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} job:(game,playerid,query)-> # 模仿者先 if @target? return "已经模仿了其他人" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 模仿了 #{pl.name} 的能力。" splashlog game.id,game,log p=game.getPlayer playerid newpl=Player.factory p.type @transProfile newpl @transferData newpl @transform game,newpl,false pl=game.getPlayer @id pl.sunset game # 初期化してあげる #game.ss.publish.user newpl.id,"refresh",{id:game.id} game.splashjobinfo [game.getPlayer @id] null isWinner:(game,team)->false # 模仿者しないと負け class Light extends Player type:"Light" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 sleeping:->true jobdone:(game)->@target? || game.day==1 sunset:(game)-> @setTarget null job:(game,playerid,query)-> # 模仿者先 if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 在死亡笔记上写下了 #{pl.name} 的名字。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"deathnote" # 誰かに移る処理 @uncomplex game,true # 自己からは抜ける class Fanatic extends Madman type:"Fanatic" jobname:"PI:NAME:<NAME>END_PI" makejobinfo:(game,result)-> super # 狂信者はLowBが分かる result.wolves=game.players.filter((x)->x.isWerewolf()).map (x)-> x.publicinfo() class Immoral extends Player type:"Immoral" jobname:"PI:NAME:<NAME>END_PI" team:"Fox" beforebury:(game,type)-> # 狐が全員死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" makejobinfo:(game,result)-> super # 妖狐が分かる result.foxes=game.players.filter((x)->x.isFoxVisible()).map (x)-> x.publicinfo() class Devil extends Player type:"Devil" jobname:"PI:NAME:<NAME>END_PI" team:"Devil" psychicResult:"LowB" die:(game,found)-> return if @dead if found=="werewolf" # 死なないぞ! unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="punish" # 处刑されたぞ! if @flag=="bitten" # 噛まれたあと处刑された @setFlag "winner" else super else super isWinner:(game,team)->team==@team && @flag=="winner" class ToughGuy extends Player type:"ToughGuy" jobname:"PI:NAME:<NAME>END_PI" die:(game,found)-> if found=="werewolf" # 狼の襲撃に耐える @setFlag "bitten" else super sunrise:(game)-> super if @flag=="bitten" @setFlag "dying" # 死にそう! sunset:(game)-> super if @flag=="dying" # 噛まれた次の夜 @setFlag null @setDead true,"werewolf" class Cupid extends Player type:"Cupid" jobname:"PI:NAME:<NAME>END_PI" team:"Friend" constructor:-> super @setFlag null # 恋人1 @setTarget null # 恋人2 sunset:(game)-> if game.day>=2 && @flag? # 2日目以降はもう遅い @setFlag "" @setTarget "" else @setFlag null @setTarget null if @scapegoat # 身代わり君の自動占い alives=game.players.filter (x)->!x.dead i=0 while i++<2 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@flag? && @target? job:(game,playerid,query)-> if @flag? && @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" unless @flag? @setFlag playerid log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 定为恋人中的一人。" splashlog game.id,game,log return null if @flag==playerid return "请选择另一个恋人" @setTarget playerid # 恋人二人が决定した plpls=[game.getPlayer(@flag), game.getPlayer(@target)] for pl,i in plpls # 2人ぶん処理 pl.touched game,@id newpl=Player.factory null,pl,null,Friend # 恋人だ! newpl.cmplFlag=plpls[1-i].id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え log= mode:"skill" to:@id comment:"#{@name} 向 #{newpl.name} 射出了爱之箭。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{newpl.name} 成为了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [game.getPlayer(@flag), game.getPlayer(@target)] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 跟踪狂 class Stalker extends Player type:"Stalker" jobname:"跟踪狂" team:"" sunset:(game)-> super if !@flag # ストーキング先を決めていない @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setTarget "" sleeping:->@flag? job:(game,playerid,query)-> if @target? || @flag? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 跟踪了 #{pl.name}(#{pl.jobname})。" splashlog game.id,game,log @setFlag playerid # ストーキング対象プレイヤー null isWinner:(game,team)-> @isWinnerStalk game,team,[] # 跟踪狂連鎖対応版 isWinnerStalk:(game,team,ids)-> if @id in ids # ループしてるので負け return false pl=game.getPlayer @flag return false unless pl? if team==pl.getTeam() return true if pl.isJobType "Stalker" # 跟踪狂を追跡 return pl.isWinnerStalk game,team,ids.concat @id else return pl.isWinner game,team makejobinfo:(game,result)-> super p=game.getPlayer @flag if p? result.stalking=p.publicinfo() # 被诅咒者 class Cursed extends Player type:"Cursed" jobname:"PI:NAME:<NAME>END_PI" die:(game,found)-> return if @dead if found=="werewolf" # 噛まれた場合LowB侧になる unless @flag # まだ噛まれていない @setFlag "bitten" else if found=="vampire" # 吸血鬼にもなる!!! unless @flag # まだ噛まれていない @setFlag "vampire" else super sunset:(game)-> if @flag in ["bitten","vampire"] # この夜から変化する log=null newpl=null if @flag=="bitten" log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了LowB。" newpl=Player.factory "Werewolf" else log= mode:"skill" to:@id comment:"#{@name} 受到诅咒变成了吸血鬼。" newpl=Player.factory "Vampire" @transProfile newpl @transferData newpl @transform game,newpl,false newpl.sunset game splashlog game.id,game,log if @flag=="bitten" # LowB侧に知らせる #game.ss.publish.channel "room#{game.id}_werewolf","refresh",{id:game.id} game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() else # 吸血鬼に知らせる game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isVampire() # 自己も知らせる #game.ss.publish.user newpl.realid,"refresh",{id:game.id} game.splashjobinfo [this] class ApprenticeSeer extends Player type:"ApprenticeSeer" jobname:"PI:NAME:<NAME>END_PI" beforebury:(game,type)-> # 占卜师が誰か死んでいたら占卜师に進化 if game.players.some((x)->x.dead && x.isJobType("Diviner")) || game.players.every((x)->!x.isJobType("Diviner")) newpl=Player.factory "Diviner" @transProfile newpl @transferData newpl log= mode:"skill" to:@id comment:"#{@name} 从 #{@jobname} 变成了 #{newpl.jobname}。" splashlog game.id,game,log @transform game,newpl,false # 更新 game.ss.publish.user newpl.realid,"refresh",{id:game.id} class Diseased extends Player type:"Diseased" jobname:"PI:NAME:<NAME>END_PI" dying:(game,found)-> super if found=="werewolf" # 噛まれた場合次の日LowB襲撃できない! game.werewolf_flag.push "Diseased" # 病人フラグを立てる class Spellcaster extends Player type:"Spellcaster" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 初日は発動できません @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" arr=[] try arr=JSON.parse @flag catch error arr=[] unless arr instanceof Array arr=[] if playerid in arr # 既に呪いをかけたことがある return "这个对象已经被咒言诅咒过了。" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 夺去了 #{pl.name} 的声音。" splashlog game.id,game,log arr.push playerid @setFlag JSON.stringify arr null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 的声音被夺去了。今天白天无法发言。" splashlog game.id,game,log # 複合させる newpl=Player.factory null,t,null,Muted # 黙る人 t.transProfile newpl t.transform game,newpl,true class Lycan extends Player type:"Lycan" jobname:"PI:NAME:<NAME>END_PI" fortuneResult:"LowB" class Priest extends Player type:"Priest" jobname:"PI:NAME:<NAME>END_PI" midnightSort:70 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid,query)-> if @flag? return "已经使用了能力" if @target? return "已经选择了对象" pl=game.getPlayer playerid unless pl? return "这个对象不存在" if playerid==@id return "不能将自己选为对象" pl.touched game,@id @setTarget playerid @setFlag "done" # すでに能力を発動している log= mode:"skill" to:@id comment:"#{@name} 以神圣的力量守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,HolyProtected # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元 pl.transform game,newpl,true null class Prince extends Player type:"Prince" jobname:"PI:NAME:<NAME>END_PI" die:(game,found)-> if found=="punish" && !@flag? # 处刑された @setFlag "used" # 能力使用済 log= mode:"system" comment:"#{@name} 是 #{@jobname}。本次处刑被取消了。" splashlog game.id,game,log @addGamelog game,"princeCO" else super # Paranormal Investigator class PI extends Diviner type:"PI" jobname:"超常现象研究者" sleeping:->true jobdone:->@flag? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 调查了 #{pl.name} 和他的左右邻居。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game @setFlag "done" # 能力一回限り null #占い実行 dodivine:(game)-> pls=[] game.players.forEach (x,i)=> if x.id==@target pls.push x # 前 if i==0 pls.push game.players[game.players.length-1] else pls.push game.players[i-1] # 後 if i>=game.players.length-1 pls.push game.players[0] else pls.push game.players[i+1] if pls.length>0 rs=pls.map((x)->x?.getFortuneResult()).filter((x)->x!="母猪") # 母猪以外 # 重複をとりのぞく nrs=[] rs.forEach (x,i)-> if rs.indexOf(x,i+1)<0 nrs.push x tpl=game.getPlayer @target resultstring=if nrs.length>0 @addGamelog game,"PIdivine",true,tpl.id "发现了 #{nrs.join ","} 活动的迹象" else @addGamelog game,"PIdivine",false,tpl.id "发现全员都是母猪" @results.push { player:game.getPlayer(@target).publicinfo() result:"#{@name} 调查了 #{tpl.name} 和他的左右邻居,#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log class Sorcerer extends Diviner type:"Sorcerer" jobname:"PI:NAME:<NAME>END_PI" team:"Werewolf" sleeping:->@target? job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 用妖术调查了 #{pl.name}。" splashlog game.id,game,log if game.rule.divineresult=="immediate" @dodivine game @showdivineresult game null #占い実行 dodivine:(game)-> pl=game.getPlayer @target if pl? resultstring=if pl.isJobType "Diviner" "是占卜师" else "不是占卜师" @results.push { player: game.getPlayer(@target).publicinfo() result: "#{@name} 用妖术调查了 #{pl.name},他#{resultstring}。" } showdivineresult:(game)-> r=@results[@results.length-1] return unless r? log= mode:"skill" to:@id comment:r.result splashlog game.id,game,log divineeffect:(game)-> class Doppleganger extends Player type:"Doppleganger" jobname:"PI:NAME:<NAME>END_PI" sleeping:->true jobdone:->@flag? team:"" # 最初はチームに属さない! job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能将自己选为对象" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 成为了 #{game.getPlayer(playerid).name} 的二重身。" splashlog game.id,game,log @setFlag playerid # 二重身先 null beforebury:(game,type)-> founds=game.players.filter (x)->x.dead && x.found # 対象が死んだら移る if founds.some((x)=>x.id==@flag) p=game.getPlayer @flag # その人 newplmain=Player.factory p.type @transProfile newplmain @transferData newplmain me=game.getPlayer @id # まだ二重身できる sub=Player.factory "Doppleganger" @transProfile sub newpl=Player.factory null, newplmain,sub,Complex # 合体 @transProfile newpl pa=@getParent game # 親を得る unless pa? # 親はいない @transform game,newpl,false else # 親がいる if pa.sub==this # subなら親ごと置換 pa.transform game,newpl,false else # mainなら自己だけ置換 @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"dopplemove",newpl.type,newpl.id game.ss.publish.user newpl.realid,"refresh",{id:game.id} class CultLeader extends Player type:"CultLeader" jobname:"PI:NAME:<NAME>END_PI" team:"Cult" midnightSort:100 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 发展 #{pl.name} 成为信者。" splashlog game.id,game,log @addGamelog game,"brainwash",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead log= mode:"skill" to:t.id comment:"#{t.name} 成为了教会的信者。" # 信者 splashlog game.id,game,log newpl=Player.factory null, t,null,CultMember # 合体 t.transProfile newpl t.transform game,newpl,true makejobinfo:(game,result)-> super # 信者は分かる result.cultmembers=game.players.filter((x)->x.isCult()).map (x)-> x.publicinfo() class Vampire extends Player type:"Vampire" jobname:"PI:NAME:<NAME>END_PI" team:"Vampire" willDieWerewolf:false fortuneResult:"吸血鬼" midnightSort:100 sleeping:(game)->@target? || game.day==1 isHuman:->false isVampire:->true sunset:(game)-> @setTarget null if game.day>1 && @scapegoat r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid,query)-> # 襲う先 if @target? return "已经选择了对象" if game.day==1 return "今天不能袭击" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead t.die game,"vampire",@id # 逃亡者を探す runners=game.players.filter (x)=>!x.dead && x.isJobType("Fugitive") && x.target==t.id runners.forEach (x)=> x.die game,"vampire2",@id # その家に逃げていたら逃亡者も死ぬ makejobinfo:(game,result)-> super # 吸血鬼が分かる result.vampires=game.players.filter((x)->x.isVampire()).map (x)-> x.publicinfo() class LoneWolf extends Werewolf type:"LoneWolf" jobname:"一匹狼" team:"LoneWolf" isWinner:(game,team)->team==@team && !@dead class Cat extends Poisoner type:"Cat" jobname:"猫又" midnightSort:100 isReviver:->true sunset:(game)-> @setTarget (if game.day<2 then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 复活了 #{pl.name}。" splashlog game.id,game,log null jobdone:->@target? sleeping:->true midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 確率判定 r=Math.random() # 0<=r<1 unless r<=0.25 # 失敗 @addGamelog game,"catraise",false,pl.id return if r<=0.05 # 5%の確率で誤爆 deads=game.players.filter (x)->x.dead if deads.length==0 # 誰もいないじゃん @addGamelog game,"catraise",false,pl.id return pl=deads[Math.floor(Math.random()*deads.length)] @addGamelog game,"catraise",pl.id,@target else @addGamelog game,"catraise",true,@target # 蘇生 目を覚まさせる pl.revive game deadnight:(game,midnightSort)-> @setTarget @id @midnight game, midnightSort job_target:Player.JOB_T_DEAD makejobinfo:(game,result)-> super class Witch extends Player type:"Witch" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 isReviver:->!@dead job_target:Player.JOB_T_ALIVE | Player.JOB_T_DEAD # 死人も生存も sleeping:->true jobdone:->@target? || (@flag in [3,5,6]) # @flag:ビットフラグ 1:殺害1使用済 2:殺害2使用済 4:蘇生使用済 8:今晩蘇生使用 16:今晩殺人使用 constructor:-> super @setFlag 0 # 発送済みかどうか sunset:(game)-> @setTarget null unless @flag @setFlag 0 else # jobだけ実行してmidnightがなかったときの処理 if @flag & 8 @setFlag @flag^8 if @flag & 16 @setFlag @flag^16 job:(game,playerid,query)-> # query.Witch_drug pl=game.getPlayer playerid unless pl? return "魔药使用无效" if pl.id==@id return "不能对自己使用魔药" if query.Witch_drug=="kill" # 毒薬 if game.day==1 return "今天不能使用毒药" if (@flag&3)==3 # 蘇生薬は使い切った return "已经不能使用毒药了" else if (@flag&4) && (@flag&3) # すでに薬は2つ使っている return "已经不能使用毒药了" if pl.dead return "使用目标已经死亡" # 薬を使用 pl.touched game,@id @flag |= 16 # 今晩殺害使用 if (@flag&1)==0 @flag |= 1 # 1つ目 else @flag |= 2 # 2つ目 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了毒药。" splashlog game.id,game,log else # 蘇生薬 if (@flag&3)==3 || (@flag&4) return "已经不能使用复活药了" if !pl.dead return "使用对象活着" # 薬を使用 pl.touched game,@id @flag |= 12 @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 使用了复活药。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? if @flag & 8 # 蘇生 @setFlag @flag^8 # 蘇生 目を覚まさせる @addGamelog game,"witchraise",null,pl.id pl.revive game else if @flag & 16 # 殺害 @setFlag @flag^16 @addGamelog game,"witchkill",null,pl.id pl.die game,"witch" class Oldman extends Player type:"Oldman" jobname:"PI:NAME:<NAME>END_PI" midnight:(game,midnightSort)-> # 夜の終わり wolves=game.players.filter (x)->x.isWerewolf() && !x.dead if wolves.length*2<=game.day # 寿命 @die game,"infirm" class Tanner extends Player type:"Tanner" jobname:"PI:NAME:<NAME>END_PI" team:"" die:(game,found)-> if found in ["gone-day","gone-night"] # 突然死はダメ @setFlag "gone" super isWinner:(game,team)->@dead && @flag!="gone" class OccultMania extends Player type:"OccultMania" jobname:"怪诞狂热者" midnightSort:100 sleeping:(game)->@target? || game.day<2 sunset:(game)-> @setTarget (if game.day>=2 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day<2 # まだ発動できない return "现在不能使用能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 指定了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> p=game.getPlayer @target return unless p? # 変化先决定 type="Human" if p.isJobType "Diviner" type="Diviner" else if p.isWerewolf() type="Werewolf" newpl=Player.factory type @transProfile newpl @transferData newpl newpl.sunset game # 初期化してあげる @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.realid,"refresh",{id:game.id} null # 狼之子 class WolfCub extends Werewolf type:"WolfCub" jobname:"狼之子" dying:(game,found)-> super game.werewolf_flag.push "WolfCub" # 低语狂人 class WhisperingMad extends Fanatic type:"WhisperingMad" jobname:"低语狂人" getSpeakChoice:(game)-> ["werewolf"].concat super isListener:(game,log)-> if log.mode=="werewolf" true else super class Lover extends Player type:"Lover" jobname:"PI:NAME:<NAME>END_PI爱者" team:"Friend" constructor:-> super @setTarget null # 相手 sunset:(game)-> unless @flag? if @scapegoat # 替身君は求愛しない @setFlag true @setTarget "" else @setTarget null sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能射出爱之箭" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的对象" pl.touched game,@id @setTarget playerid @setFlag true # 恋人二人が决定した plpls=[this,pl] for x,i in plpls newpl=Player.factory null,x,null,Friend # 恋人だ! x.transProfile newpl x.transform game,newpl,true # 入れ替え newpl.cmplFlag=plpls[1-i].id log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 求爱了。" splashlog game.id,game,log log= mode:"skill" to:newpl.id comment:"#{pl.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 2人とも更新する for pl in [this, pl] game.ss.publish.user pl.id,"refresh",{id:game.id} null # 仆从选择者 class MinionSelector extends Player type:"MinionSelector" jobname:"仆从选择者" team:"Werewolf" sleeping:(game)->@target? || game.day>1 # 初日のみ sunset:(game)-> @setTarget (if game.day==1 then null else "") if !@target? && @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @setTarget "" job:(game,playerid)-> if game.day!=1 # まだ発動できない return "现在还不能发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" # 複合させる newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"wolfskill" comment:"#{@name} 指定 #{pl.name}(#{pl.jobname})成为了狼的仆从。" splashlog game.id,game,log log= mode:"skill" to:pl.id comment:"#{pl.name} 变成了狼的仆从。" splashlog game.id,game,log null # 小偷 class Thief extends Player type:"Thief" jobname:"PI:NAME:<NAME>END_PI" team:"" sleeping:(game)->@target? || game.day>1 sunset:(game)-> @setTarget (if game.day==1 then null else "") # @flag:JSON的职业候補配列 if !target? arr=JSON.parse(@flag ? '["Human"]') jobnames=arr.map (x)-> testpl=new jobs[x] testpl.getJobDisp() log= mode:"skill" to:@id comment:"#{@name} 可以选择的职业有 #{jobnames.join(",")}。" splashlog game.id,game,log if @scapegoat # 身代わり君 r=Math.floor Math.random()*arr.length @job game,arr[r] job:(game,target)-> @setTarget target unless jobs[target]? return "不能变成那个职业" newpl=Player.factory target @transProfile newpl @transferData newpl newpl.sunset game @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log game.ss.publish.user newpl.id,"refresh",{id:game.id} null makeJobSelection:(game)-> if game.night # 职业から选择 arr=JSON.parse(@flag ? '["Human"]') arr.map (x)-> testpl=new jobs[x] { name:testpl.getJobDisp() value:x } else super class Dog extends Player type:"Dog" jobname:"PI:NAME:<NAME>END_PI" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 sunset:(game)-> super @setTarget null # 1日目:飼い主选择 选择後:かみ殺す人选择 if !@flag? # 飼い主を決めていない if @scapegoat alives=game.players.filter (x)=>!x.dead && x.id!=@id if alives.length>0 r=Math.floor Math.random()*alives.length pl=alives[r] @job game,pl.id,{} else @setFlag "" @setTarget "" else # 飼い主を护卫する pl=game.getPlayer @flag if pl? if pl.dead # もう死んでるじゃん @setTarget "" # 洗濯済み else newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true sleeping:->@flag? jobdone:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" unless @flag? pl=game.getPlayer playerid unless pl? return "对象无效" if pl.id==@id return "不能成为自己的饲主。" pl.touched game,@id # 飼い主を选择した log= mode:"skill" to:@id comment:"#{@name} 选择 #{pl.name} 成为了自己的饲主。" splashlog game.id,game,log @setFlag playerid # 飼い主 @setTarget "" # 襲撃対象はなし else # 襲う pl=game.getPlayer @flag @setTarget @flag log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night if @flag? # 飼い主いる pl=game.getPlayer @flag if pl? if !pl.read result.open.push "Dog1" result.dogOwner=pl.publicinfo() else result.open.push "Dog2" makeJobSelection:(game)-> # 噛むときは対象选择なし if game.night && @flag? [] else super class Dictator extends Player type:"Dictator" jobname:"PI:NAME:<NAME>END_PI裁PI:NAME:<NAME>END_PI" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能发的能力" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id @setTarget playerid # 处刑する人 log= mode:"system" comment:"独裁者 #{@name} 宣布将要处刑 #{pl.name}。" splashlog game.id,game,log @setFlag true # 使用済 # その場で殺す!!! pl.die game,"punish",[@id] # 天黑了 log= mode:"system" comment:"独裁者 #{@name} 宣布,现在天黑了。" splashlog game.id,game,log # 強制的に次のターンへ game.nextturn() null class SeersMama extends Player type:"SeersMama" jobname:"占卜师的妈妈" sleeping:->true sunset:(game)-> unless @flag # まだ能力を実行していない # 占卜师を探す divs = game.players.filter (pl)->pl.isJobType "Diviner" divsstr=if divs.length>0 "#{divs.map((x)->x.name).join ','} 是占卜师" else "没有占卜师" log= mode:"skill" to:@id comment:"#{@name} 是占卜师的妈妈。#{divsstr}。" splashlog game.id,game,log @setFlag true #使用済 class Trapper extends Player type:"Trapper" jobname:"PI:NAME:<NAME>END_PI" midnightSort:81 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目は护卫しない @setTarget "" # 誰も守らない else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> unless playerid==@id && game.rule.guardmyself!="ok" if playerid==@flag # 前も护卫した return "不能连续两天守护一个人" @setTarget playerid @setFlag playerid pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 的陷阱守护了 #{pl.name}。" splashlog game.id,game,log null else "不能守护自己" midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return # 複合させる newpl=Player.factory null,pl,null,TrapGuarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class WolfBoy extends Madman type:"WolfBoy" jobname:"PI:NAME:<NAME>END_PI" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 伪装成了LowB。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Lycanized pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null class Hoodlum extends Player type:"Hoodlum" jobname:"无赖" team:"" constructor:-> super @setFlag "[]" # 殺したい対象IDを入れておく @setTarget null sunset:(game)-> unless @target? # 2人選んでもらう @setTarget null if @scapegoat # 身代わり alives=game.players.filter (x)=>!x.dead && x!=this i=0 while i++<2 && alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} alives.splice r,1 sleeping:->@target? job:(game,playerid,query)-> if @target? return "已经决定了对象" pl=game.getPlayer playerid unless pl? return "对象无效" plids=JSON.parse(@flag||"[]") if pl.id in plids # 既にいる return "#{pl.name} 已经被选为对象" plids.push pl.id @setFlag JSON.stringify plids log= mode:"skill" to:@id comment:"#{@name} 憎恨 #{pl.name}。" splashlog game.id,game,log if plids.length>=2 @setTarget "" else # 2人目を選んでほしい @setTarget null null isWinner:(game,team)-> if @dead # 死んでたらだめ return false pls=JSON.parse(@flag).map (id)->game.getPlayer id return pls.every (pl)->pl?.dead==true class QuantumPlayer extends Player type:"QuantumPlayer" jobname:"量子人类" midnightSort:100 getJobname:-> flag=JSON.parse(@flag||"{}") jobname=null if flag.Human==1 jobname="母猪" else if flag.Diviner==1 jobname="占卜师" else if flag.Werewolf==1 jobname="LowB" numstr="" if flag.number? numstr="##{flag.number}" ret=if jobname? "量子人类#{numstr}(#{jobname})" else "量子人类#{numstr}" if @originalJobname != ret # 収束したぞ! @setOriginalJobname ret return ret sleeping:-> tarobj=JSON.parse(@target || "{}") tarobj.Diviner? && tarobj.Werewolf? # 両方指定してあるか sunset:(game)-> # @flagに{Human:(確率),Diviner:(確率),Werewolf:(確率),dead:(確率)}的なのが入っているぞ! obj=JSON.parse(@flag || "{}") tarobj= Diviner:null Werewolf:null if obj.Diviner==0 tarobj.Diviner="" # なし if obj.Werewolf==0 || (game.rule.quantumwerewolf_firstattack!="on" && game.day==1) tarobj.Werewolf="" @setTarget JSON.stringify tarobj if @scapegoat # 身代わり君の自動占い unless tarobj.Diviner? r=Math.floor Math.random()*game.players.length @job game,game.players[r].id,{ jobtype:"_Quantum_Diviner" } unless tarobj.Werewolf? nonme =game.players.filter (pl)=> pl!=this r=Math.floor Math.random()*nonme.length @job game,nonme[r].id,{ jobtype:"_Quantum_Werewolf" } isJobType:(type)-> # 便宜的 if type=="_Quantum_Diviner" || type=="_Quantum_Werewolf" return true super job:(game,playerid,query)-> tarobj=JSON.parse(@target||"{}") pl=game.getPlayer playerid unless pl? return "这个对象不存在" if query.jobtype=="_Quantum_Diviner" && !tarobj.Diviner? tarobj.Diviner=playerid log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份。" splashlog game.id,game,log else if query.jobtype=="_Quantum_Werewolf" && !tarobj.Werewolf? if @id==playerid return "不能袭击自己。" tarobj.Werewolf=playerid log= mode:"skill" to:@id comment:"#{@name} 决定要袭击 #{pl.name}。" splashlog game.id,game,log else return "对象选择无效" @setTarget JSON.stringify tarobj null midnight:(game,midnightSort)-> # ここで処理 tarobj=JSON.parse(@target||"{}") if tarobj.Diviner pl=game.getPlayer tarobj.Diviner if pl? # 一旦自己が占卜师のやつ以外排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].jobtype=="Diviner" && obj[@id].dead==false # 1つ選んで占卜结果を决定 if pats.length>0 index=Math.floor Math.random()*pats.length j=pats[index][tarobj.Diviner].jobtype if j == "Werewolf" log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 LowB。" splashlog game.id,game,log # LowBのやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype == "Werewolf" else true else log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,是 母猪。" splashlog game.id,game,log # 母猪のやつ以外排除 game.quantum_patterns=game.quantum_patterns.filter (obj)=> if obj[@id].jobtype=="Diviner"# && obj[@id].dead==false obj[pl.id].jobtype!="Werewolf" else true else # 占えない log= mode:"skill" to:@id comment:"#{@name} 已经不可能是占卜师,不能进行占卜。" splashlog game.id,game,log if tarobj.Werewolf pl=game.getPlayer tarobj.Werewolf if pl? game.quantum_patterns=game.quantum_patterns.filter (obj)=> # 何番が筆頭かを求める min=Infinity for key,value of obj if value.jobtype=="Werewolf" && value.dead==false && value.rank<min min=value.rank if obj[@id].jobtype=="Werewolf" && obj[@id].rank==min && obj[@id].dead==false # 自己が筆頭LowB if obj[pl.id].jobtype == "Werewolf"# || obj[pl.id].dead==true # 襲えない false else # さらに対応するやつを死亡させる obj[pl.id].dead=true true else true isWinner:(game,team)-> flag=JSON.parse @flag unless flag? return false if flag.Werewolf==1 && team=="Werewolf" # LowBがかったぞ!!!!! true else if flag.Werewolf==0 && team=="Human" # 人类がかったぞ!!!!! true else # よくわからないぞ! false makejobinfo:(game,result)-> super tarobj=JSON.parse(@target||"{}") unless tarobj.Diviner? result.open.push "_Quantum_Diviner" unless tarobj.Werewolf? result.open.push "_Quantum_Werewolf" if game.rule.quantumwerewolf_table=="anonymous" # 番号がある flag=JSON.parse @flag result.quantumwerewolf_number=flag.number die:(game,found)-> super # 可能性を排除する pats=[] if found=="punish" # 处刑されたときは既に死んでいた可能性を排除 pats=game.quantum_patterns.filter (obj)=> obj[@id].dead==false else pats=game.quantum_patterns if pats.length # 1つ選んで职业を决定 index=Math.floor Math.random()*pats.length tjt=pats[index][@id].jobtype trk=pats[index][@id].rank if trk? pats=pats.filter (obj)=> obj[@id].jobtype==tjt && obj[@id].rank==trk else pats=pats.filter (obj)=> obj[@id].jobtype==tjt # ワタシハシンダ pats.forEach (obj)=> obj[@id].dead=true game.quantum_patterns=pats class RedHood extends Player type:"RedHood" jobname:"PI:NAME:<NAME>END_PI" sleeping:->true isReviver:->!@dead || @flag? dying:(game,found,from)-> super if found=="werewolf" # 狼に襲われた # 誰に襲われたか覚えておく @setFlag from else @setFlag null deadsunset:(game)-> if @flag w=game.getPlayer @flag if w?.dead # 殺した狼が死んだ!復活する @revive game deadsunrise:(game)-> # 同じ @deadsunset game class Counselor extends Player type:"Counselor" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 sleeping:->true jobdone:->@target? sunset:(game)-> @setTarget null if game.day==1 # 一日目はカウンセリングできない @setTarget "" job:(game,playerid,query)-> if @target? return "已经选择了对象" @setTarget playerid pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 尝试了策反 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead tteam = t.getTeam() if t.isWerewolf() && tteam in ["Werewolf","LoneWolf"] # LowBとかヴァンパイアを襲ったら殺される @die game,"werewolf2" @addGamelog game,"counselKilled",t.type,@target return if t.isVampire() && tteam=="Vampire" @die game,"vampire2" @addGamelog game,"counselKilled",t.type,@target return if tteam!="Human" log= mode:"skill" to:t.id comment:"#{t.name} 被策反了。" splashlog game.id,game,log @addGamelog game,"counselSuccess",t.type,@target # 複合させる newpl=Player.factory null,t,null,Counseled # カウンセリングされた t.transProfile newpl t.transform game,newpl,true else @addGamelog game,"counselFailure",t.type,@target # 巫女 class Miko extends Player type:"Miko" jobname:"PI:NAME:<NAME>END_PI" midnightSort:71 sleeping:->true jobdone:->!!@flag job:(game,playerid,query)-> if @flag return "已经使用了能力" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 用神圣的力量守护了自己。" splashlog game.id,game,log @setFlag "using" null midnight:(game,midnightSort)-> # 複合させる if @flag=="using" pl = game.getPlayer @id newpl=Player.factory null,pl,null,MikoProtected # 守られた人 pl.transProfile newpl pl.transform game,newpl,true @setFlag "done" null makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super class GreedyWolf extends Werewolf type:"GreedyWolf" jobname:"贪婪的狼" sleeping:(game)->game.werewolf_target_remain<=0 # 占いは必須ではない jobdone:(game)->game.werewolf_target_remain<=0 && (@flag || game.day==1) job:(game,playerid,query)-> if query.jobtype!="GreedyWolf" # LowBの仕事 return super if @flag return "已经使用了能力" @setFlag true if game.werewolf_target_remain+game.werewolf_target.length ==0 return "今晚不能袭击" log= mode:"wolfskill" comment:"为了满足 #{@name} 的贪欲。LowB们今晚可以多袭击一个人。" splashlog game.id,game,log game.werewolf_target_remain++ game.werewolf_flag.push "GreedyWolf_#{@id}" game.splashjobinfo game.players.filter (x)=>x.id!=@id && x.isWerewolf() null makejobinfo:(game,result)-> super if game.night if @sleeping game # 襲撃は必要ない result.open = result.open?.filter (x)=>x!="_Werewolf" if !@flag && game.day>=2 result.open?.push "GreedyWolf" makeJobSelection:(game)-> if game.night && @sleeping(game) && !@jobdone(game) # 欲張る选择肢のみある return [] else return super checkJobValidity:(game,query)-> if query.jobtype=="GreedyWolf" # なしでOK! return true return super class FascinatingWolf extends Werewolf type:"FascinatingWolf" jobname:"魅惑的女狼" sleeping:(game)->super && @flag? sunset:(game)-> super if @scapegoat && !@flag? # 誘惑する hus=game.players.filter (x)->!x.dead && !x.isWerewolf() if hus.length>0 r=Math.floor Math.random()*hus.length @job game,hus[r].id,{jobtype:"FascinatingWolf"} else @setFlag "" job:(game,playerid,query)-> if query.jobtype!="FascinatingWolf" # LowBの仕事 return super if @flag return "已经使用了能力" pl=game.getPlayer playerid unless pl? return "对象玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 魅惑了 #{pl.name}。" @setFlag playerid splashlog game.id,game,log null dying:(game,found)-> # 死んだぞーーーーーーーーーーーーーー super # LWなら変えない if game.players.filter((x)->x.isWerewolf() && !x.dead).length==0 return pl=game.getPlayer @flag unless pl? # あれれーーー return if pl.dead # 既に死んでいた return unless pl.isHuman() && pl.getTeam()!="Werewolf" # 誘惑できない return newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:pl.id comment:"#{pl.name} 被狼魅惑了。" splashlog game.id,game,log makejobinfo:(game,result)-> super if game.night if @flag # もう誘惑は必要ない result.open = result.open?.filter (x)=>x!="FascinatingWolf" class SolitudeWolf extends Werewolf type:"SolitudeWolf" jobname:"孤独的狼" sleeping:(game)-> !@flag || super isListener:(game,log)-> if (log.mode in ["werewolf","wolfskill"]) && (log.to != @id) # 狼の声は听不到(自己のスキルは除く) false else super job:(game,playerid,query)-> if !@flag return "现在还不能袭击" super isAttacker:->!@dead && @flag sunset:(game)-> wolves=game.players.filter (x)->x.isWerewolf() attackers=wolves.filter (x)->!x.dead && x.isAttacker() if !@flag && attackers.length==0 # 襲えるやつ誰もいない @setFlag true log= mode:"skill" to:@id comment:"#{@name} 现在可以袭击他人了。" splashlog game.id,game,log else if @flag && attackers.length>1 # 複数いるのでやめる @setFlag false log= mode:"skill" to:@id comment:"其他的LowB还活着。#{@name} 现在不能袭击他人。" splashlog game.id,game,log super getSpeakChoice:(game)-> res=super return res.filter (x)->x!="werewolf" makejobinfo:(game,result)-> super delete result.wolves delete result.spy2s class ToughWolf extends Werewolf type:"ToughWolf" jobname:"硬汉LowB" job:(game,playerid,query)-> if query.jobtype!="ToughWolf" # LowBの仕事 return super if @flag return "已经使用了能力" res=super if res? return res @setFlag true game.werewolf_flag.push "ToughWolf_#{@id}" tp=game.getPlayer playerid unless tp? return "这个对象不存在" log= mode:"wolfskill" comment:"#{@name} 抱着舍身的觉悟袭击了 #{tp.name}。" splashlog game.id,game,log null class ThreateningWolf extends Werewolf type:"ThreateningWolf" jobname:"威吓的狼" jobdone:(game)-> if game.night super else @flag? chooseJobDay:(game)->true sunrise:(game)-> super @setTarget null job:(game,playerid,query)-> if query.jobtype!="ThreateningWolf" # LowBの仕事 return super if @flag return "已经使用了能力" if game.night return "夜晚不能使用能力" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid @setFlag true log= mode:"skill" to:@id comment:"#{@name} 威吓了 #{pl.name}。" splashlog game.id,game,log null sunset:(game)-> t=game.getPlayer @target return unless t? return if t.dead # 威嚇して能力無しにする @addGamelog game,"threaten",t.type,@target # 複合させる log= mode:"skill" to:t.id comment:"#{t.name} 受到了威吓。今晚的能力无法发动。" splashlog game.id,game,log newpl=Player.factory null,t,null,Threatened # カウンセリングされた t.transProfile newpl t.transform game,newpl,true super makejobinfo:(game,result)-> super if game.night # 夜は威嚇しない result.open = result.open?.filter (x)=>x!="ThreateningWolf" class HolyMarked extends Human type:"HolyMarked" jobname:"圣痕者" class WanderingGuard extends Player type:"WanderingGuard" jobname:"PI:NAME:<NAME>END_PI" midnightSort:80 sleeping:->@target? sunset:(game)-> @setTarget null if game.day==1 # 猎人は一日目护卫しない @setTarget "" # 誰も守らない else fl=JSON.parse(@flag ? "[]") alives=game.players.filter (x)->!x.dead if alives.every((pl)=>(pl.id in fl) || (game.rule.guardmyself!="ok" && pl.id==@id)) # もう护卫対象がいない @setTarget "" else if @scapegoat # 身代わり君の自動占い r=Math.floor Math.random()*game.players.length if @job game,game.players[r].id,{} @sunset game job:(game,playerid)-> fl=JSON.parse(@flag ? "[]") if playerid==@id && game.rule.guardmyself!="ok" return "不能守护自己" fl=JSON.parse(@flag ? "[]") if playerid in fl return "这个人已经不能守护了" @setTarget playerid # OK! pl=game.getPlayer(playerid) pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 守护了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,Guarded # 守られた人 pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true null beforebury:(game,type)-> if type=="day" # 昼になったとき if game.players.filter((x)->x.dead && x.found).length==0 # 誰も死ななかった!护卫できない pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 不能护卫 #{pl.name}。" splashlog game.id,game,log fl=JSON.parse(@flag ? "[]") fl.push pl.id @setFlag JSON.stringify fl makeJobSelection:(game)-> if game.night fl=JSON.parse(@flag ? "[]") a=super return a.filter (obj)->!(obj.value in fl) else return super class ObstructiveMad extends Madman type:"ObstructiveMad" jobname:"碍事的狂人" midnightSort:90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length @job game,alives[r].id,{} else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 妨碍了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineObstructed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true null class TroubleMaker extends Player type:"TroubleMaker" jobname:"PI:NAME:<NAME>END_PI" midnightSort:100 sleeping:->true jobdone:->!!@flag makeJobSelection:(game)-> # 夜は投票しない if game.night [] else super job:(game,playerid)-> return "已经使用了能力" if @flag @setFlag "using" log= mode:"skill" to:@id comment:"#{@name} 在村子里引发了混乱。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # ここが無効化されたら発動しないように if @flag=="using" @setFlag "using2" null sunrise:(game)-> if @flag=="using2" game.votingbox.addPunishedNumber 1 # トラブルがおきた log= mode:"system" comment:"闹事者在村子里引发了混乱。今日将会处刑 #{game.votingbox.remains} 个人。" splashlog game.id,game,log @setFlag "done" else if @flag=="using" # 不発だった @setFlag "done" deadsunrise:(game)->@sunrise game class FrankensteinsMonster extends Player type:"FrankensteinsMonster" jobname:"PI:NAME:<NAME>END_PI肯斯坦的怪物" die:(game,found)-> super if found=="punish" # 处刑で死んだらもうひとり处刑できる game.votingbox.addPunishedNumber 1 beforebury:(game)-> # 新しく死んだひとたちで母猪阵营ひとたち # 不吸收弗兰肯斯坦的怪物 founds=game.players.filter (x)->x.dead && x.found && x.getTeam()=="Human" && !x.isJobType("FrankensteinsMonster") # 吸収する thispl=this for pl in founds log= mode:"skill" to:@id comment:"#{@name} 从 #{pl.name} 的尸体里吸收了 #{pl.getJobname()} 的能力。" splashlog game.id,game,log # 同じ能力を subpl = Player.factory pl.type thispl.transProfile subpl newpl=Player.factory null, thispl,subpl,Complex # 合成する thispl.transProfile newpl # 置き換える thispl.transform game,newpl,true thispl=newpl thispl.addGamelog game,"frankeneat",pl.type,pl.id if founds.length>0 game.splashjobinfo [thispl] class BPI:NAME:<NAME>END_PIMary extends Player type:"BloodyMary" jobname:"PI:NAME:<NAME>END_PI" isReviver:->true getJobname:->if @flag then @jobname else "PI:NAME:<NAME>END_PI" getJobDisp:->@getJobname() getTypeDisp:->if @flag then @type else "Mary" sleeping:->true deadJobdone:(game)-> if @target? true else if @flag=="punish" !(game.players.some (x)->!x.dead && x.getTeam()=="Human") else if @flag=="werewolf" if game.players.filter((x)->!x.dead && x.isWerewolf()).length>1 !(game.players.some (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"]) else # 狼が残り1匹だと何もない true else true dying:(game,found,from)-> if found in ["punish","werewolf"] # 能力が… orig_jobname=@getJobname() @setFlag found if orig_jobname != @getJobname() # 変わった! @setOriginalJobname @originalJobname.replace("血腥玛丽","玛丽").replace("玛丽","血腥玛丽") super sunset:(game)-> @setTarget null deadsunset:(game)-> @sunset game job:(game,playerid)-> unless @flag in ["punish","werewolf"] return "不能使用能力" pl=game.getPlayer playerid unless pl? return "对象不存在" log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log @setTarget playerid null # 呪い殺す!!!!!!!!! deadnight:(game,midnightSort)-> pl=game.getPlayer @target unless pl? return pl.die game,"marycurse",@id # 蘇生できない revive:-> isWinner:(game,team)-> if @flag=="punish" team in ["Werewolf","LoneWolf"] else team==@team makeJobSelection:(game)-> if game.night pls=[] if @flag=="punish" # 母猪を…… pls=game.players.filter (x)->!x.dead && x.getTeam()=="Human" else if @flag=="werewolf" # LowBを…… pls=game.players.filter (x)->!x.dead && x.getTeam() in ["Werewolf","LoneWolf"] return (for pl in pls { name:pl.name value:pl.id } ) else super makejobinfo:(game,obj)-> super if @flag && !("BloodyMary" in obj.open) obj.open.push "BloodyPI:NAME:<NAME>END_PI" class King extends Player type:"King" jobname:"国王" voteafter:(game,target)-> super game.votingbox.votePower this,1 class PsychoKiller extends Madman type:"PsychoKiller" jobname:"变态杀人狂" midnightSort:110 constructor:-> super @flag="[]" touched:(game,from)-> # 殺すリストに追加する fl=try JSON.parse @flag || "[]" catch e [] fl.push from @setFlag JSON.stringify fl sunset:(game)-> @setFlag "[]" midnight:(game,midnightSort)-> fl=try JSON.parse @flag || "[]" catch e [] for id in fl pl=game.getPlayer id if pl? && !pl.dead pl.die game,"psycho",@id @setFlag "[]" deadnight:(game,midnightSort)-> @midnight game, midnightSort class SantaClaus extends Player type:"SantaClaus" jobname:"PI:NAME:<NAME>END_PI诞老人" midnightSort:100 sleeping:->@target? constructor:-> super @setFlag "[]" isWinner:(game,team)->@flag=="gone" || super sunset:(game)-> # まだ届けられる人がいるかチェック fl=JSON.parse(@flag ? "[]") if game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) @setTarget null if @scapegoat cons=game.players.filter((x)=>!x.dead && x.id!=@id && !(x.id in fl)) if cons.length>0 r=Math.floor Math.random()*cons.length @job game,cons[r].id,{} else @setTarget "" else @setTarget "" sunrise:(game)-> # 全员に配ったかチェック fl=JSON.parse(@flag ? "[]") unless game.players.some((x)=>!x.dead && x.id!=@id && !(x.id in fl)) # 村を去る @setFlag "gone" @die game,"spygone" job:(game,playerid)-> if @flag=="gone" return "已经离开了村子" fl=JSON.parse(@flag ? "[]") if playerid == @id return "不能把礼物送给自己" if playerid in fl return "这个人已经不能继续接受礼物了" pl=game.getPlayer playerid pl.touched game,@id unless pl? return "对象无效" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 赠送了礼物。" splashlog game.id,game,log fl.push playerid @setFlag JSON.stringify fl null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return if @flag=="gone" # プレゼントを送る r=Math.random() settype="" setname="" if r<0.05 # 毒だった log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了剧毒的礼物。" splashlog game.id,game,log pl.die game,"poison",@id @addGamelog game,"sendpresent","poison",pl.id return else if r<0.1 settype="HolyMarked" setname="圣痕者套装" else if r<0.15 settype="Oldman" setname="玉手箱" else if r<0.225 settype="Priest" setname="圣职者套装" else if r<0.3 settype="Miko" setname="Cosplay套装(巫女)" else if r<0.55 settype="Diviner" setname="占卜套装" else if r<0.8 settype="Guard" setname="守护套装" else settype="Psychic" setname="灵能套装" # 複合させる log= mode:"skill" to:pl.id comment:"#{pl.name} 收到了礼物 #{setname}。" splashlog game.id,game,log # 複合させる sub=Player.factory settype # 副を作る pl.transProfile sub newpl=Player.factory null,pl,sub,Complex # Complex pl.transProfile newpl pl.transform game,newpl,true @addGamelog game,"sendpresent",settype,pl.id #怪盗 class Phantom extends Player type:"Phantom" jobname:"怪盗" sleeping:->@target? sunset:(game)-> if @flag==true # もう交換済みだ @setTarget "" else @setTarget null if @scapegoat rs=@makeJobSelection game if rs.length>0 r=Math.floor Math.random()*rs.length @job game,rs[r].value,{ jobtype:@type } makeJobSelection:(game)-> if game.night res=[{ name:"放弃盗取" value:"" }] sup=super for obj in sup pl=game.getPlayer obj.value unless pl?.scapegoat res.push obj return res else super job:(game,playerid)-> @setTarget playerid if playerid=="" # 交換しない log= mode:"skill" to:@id comment:"#{@name} 没有盗取职业。" splashlog game.id,game,log return pl=game.getPlayer playerid pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 盗取了 #{pl.name} 的职业。#{pl.name} 是 #{pl.getJobDisp()}。" splashlog game.id,game,log @addGamelog game,"phantom",pl.type,playerid null sunrise:(game)-> @setFlag true pl=game.getPlayer @target unless pl? return savedobj={} pl.makejobinfo game,savedobj flagobj={} # jobinfo表示のみ抜粋 for value in Shared.game.jobinfos if savedobj[value.name]? flagobj[value.name]=savedobj[value.name] # 自己はそ的职业に変化する newpl=Player.factory pl.type @transProfile newpl @transferData newpl @transform game,newpl,false log= mode:"skill" to:@id comment:"#{@name} 变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 盗まれた側は怪盗予備軍のフラグを立てる newpl2=Player.factory null,pl,null,PhantomStolen newpl2.cmplFlag=flagobj pl.transProfile newpl2 pl.transform game,newpl2,true class BadLady extends Player type:"BadLady" jobname:"PI:NAME:<NAME>END_PI" team:"Friend" sleeping:->@flag?.set sunset:(game)-> unless @flag?.set # まだ恋人未设定 if @scapegoat @flag={ set:true } job:(game,playerid,query)-> fl=@flag ? {} if fl.set return "已经决定了对象" if playerid==@id return "请选择自己以外的对象" pl=game.getPlayer playerid unless pl? return "对象无效" pl.touched game,@id unless fl.main? # 本命を決める fl.main=playerid log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为自己的本命对象。" splashlog game.id,game,log @setFlag fl @addGamelog game,"badlady_main",pl.type,playerid return null unless fl.keep? # キープ相手を決める fl.keep=playerid fl.set=true @setFlag fl log= mode:"skill" to:@id comment:"#{@name} 选择了 #{pl.name} 作为玩弄的对象。" splashlog game.id,game,log # 2人を恋人、1人をキープに plm=game.getPlayer fl.main for pll in [plm,pl] if pll? log= mode:"skill" to:pll.id comment:"#{pll.name} 受到求爱变成了恋人。" splashlog game.id,game,log # 自己恋人 newpl=Player.factory null,this,null,Friend # 恋人だ! newpl.cmplFlag=fl.main @transProfile newpl @transform game,newpl,true # 入れ替え # 相手恋人 newpl=Player.factory null,plm,null,Friend # 恋人だ! newpl.cmplFlag=@id plm.transProfile newpl plm.transform game,newpl,true # 入れ替え # キープ newpl=Player.factory null,pl,null,KeepedLover # 恋人か? newpl.cmplFlag=@id pl.transProfile newpl pl.transform game,newpl,true # 入れ替え game.splashjobinfo [@id,plm.id,pl.id].map (id)->game.getPlayer id @addGamelog game,"badlady_keep",pl.type,playerid null makejobinfo:(game,result)-> super if !@jobdone(game) && game.night # 夜の选择肢 fl=@flag ? {} unless fl.set unless fl.main # 本命を決める result.open.push "BadLady1" else if !fl.keep # 手玉に取る result.open.push "BadLady2" # 看板娘 class DrawGirl extends Player type:"DrawGirl" jobname:"PI:NAME:<NAME>END_PI" sleeping:->true dying:(game,found)-> if found=="werewolf" # 狼に噛まれた @setFlag "bitten" else @setFlag "" super deadsunrise:(game)-> # 夜明けで死亡していた場合 if @flag=="bitten" # 噛まれて死亡した場合 game.votingbox.addPunishedNumber 1 log= mode:"system" comment:"#{@name} 是看板娘。今日将有 #{game.votingbox.remains} 人被处刑。" splashlog game.id,game,log @setFlag "" @addGamelog game,"drawgirlpower",null,null # 慎重的狼 class CautiousWolf extends Werewolf type:"CautiousWolf" jobname:"慎重的狼" makeJobSelection:(game)-> if game.night r=super return r.concat { name:"不袭击" value:"" } else return super job:(game,playerid)-> if playerid!="" super return # 不袭击場合 game.werewolf_target.push { from:@id to:"" } game.werewolf_target_remain-- log= mode:"wolfskill" comment:"以 #{@name} 为首的LowB们决定今晚不发动袭击。" splashlog game.id,game,log game.splashjobinfo game.players.filter (x)=>x.id!=playerid && x.isWerewolf() null # 烟火师 class Pyrotechnist extends Player type:"Pyrotechnist" jobname:"PI:NAME:<NAME>END_PI火师" sleeping:->true jobdone:(game)->@flag? || game.night chooseJobDay:(game)->true job:(game,playerid,query)-> if @flag? return "已经不能发动能力了" if game.night return "夜晚不能使用此能力" log= mode:"skill" to:@id comment:"#{@name} 准备释放烟火了。" splashlog game.id,game,log # 使用済 @setFlag "using" null sunset:(game)-> if @flag=="using" log= mode:"system" comment:"美丽的烟火被打上了天空。今晚不能使用能力。" splashlog game.id,game,log @setFlag "done" deadsunset:(game)-> @sunset game checkJobValidity:(game,query)-> if query.jobtype=="Pyrotechnist" # 対象选择は不要 return true return super # 面包店 class Baker extends Player type:"Baker" jobname:"面包店" sleeping:->true sunrise:(game)-> # 最初の1人が面包店ログを管理 bakers=game.players.filter (x)->x.isJobType "Baker" firstBakery=bakers[0] if firstBakery?.id==@id # わ た し だ if bakers.some((x)->!x.dead) # 生存面包店がいる if @flag=="done" @setFlag null log= mode:"system" comment:"面包店烤好了美味的面包。" splashlog game.id,game,log else if @flag!="done" # 全员死亡していてまたログを出していない log= mode:"system" comment:"今天开始没有美味的面包吃了。" splashlog game.id,game,log @setFlag "done" deadsunrise:(game)-> @sunrise game class Bomber extends Madman type:"Bomber" jobname:"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" midnightSort:81 sleeping:->true jobdone:->@flag? sunset:(game)-> @setTarget null job:(game,playerid)-> pl=game.getPlayer playerid unless pl? return "对象无效。" pl.touched game,@id @setTarget playerid @setFlag true # 爆弾を仕掛ける log= mode:"skill" to:@id comment:"#{@name} 向 #{pl.name} 送出了炸弹。" splashlog game.id,game,log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,BombTrapped pl.transProfile newpl newpl.cmplFlag=@id # 护卫元cmplFlag pl.transform game,newpl,true @addGamelog game,"bomber_set",pl.type,@target null class Blasphemy extends Player type:"Blasphemy" jobname:"PI:NAME:<NAME>END_PI" team:"Fox" midnightSort:100 sleeping:(game)->@target? || @flag constructor:-> super @setFlag null sunset:(game)-> if @flag @setTarget "" else @setTarget null if @scapegoat # 替身君 alives=game.players.filter (x)->!x.dead r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" beforebury:(game,type)-> if @flag # まだ狐を作ってないときは耐える # 狐が全员死んでいたら自殺 unless game.players.some((x)->!x.dead && x.isFox()) @die game,"foxsuicide" job:(game,playerid)-> if @flag || @target? return "已经不能发动能力了" @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 亵渎了 #{pl.name}。" splashlog game.id,game,log @addGamelog game,"blasphemy",pl.type,playerid return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # まずい対象だと自己が冒涜される if pl.type in ["Fugitive","QueenSpectator","Liar","Spy2","LoneWolf"] pl=this return if pl.dead @setFlag true # 狐凭をつける newpl=Player.factory null,pl,null,FoxMinion pl.transProfile newpl pl.transform game,newpl,true class Ushinotokimairi extends Madman type:"Ushinotokimairi" jobname:"PI:NAME:<NAME>END_PI时之女" midnightSort:90 sleeping:->true jobdone:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives=game.players.filter (x)->!x.dead if alives.length>0 r=Math.floor Math.random()*alives.length if @job game,alives[r].id,{} @setTarget "" else @setTarget "" job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid unless pl? return "这个玩家不存在" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 诅咒了 #{pl.name}。" splashlog game.id,game,log null midnight:(game,midnightSort)-> # 複合させる pl = game.getPlayer @target unless pl? return newpl=Player.factory null,pl,null,DivineCursed pl.transProfile newpl newpl.cmplFlag=@id # 邪魔元cmplFlag pl.transform game,newpl,true @addGamelog game,"ushinotokimairi_curse",pl.type,@target null divined:(game,player)-> if @target? # 能力を使用していた場合は占われると死ぬ @die game,"curse" player.addGamelog game,"cursekill",null,@id super class Patissiere extends Player type: "Patissiere" jobname: "PI:NAME:<NAME>END_PI" team:"Friend" midnightSort:100 sunset:(game)-> unless @flag? if @scapegoat # 替身君はチョコを配らない @setFlag true @setTarget "" else @setTarget null else @setTarget "" sleeping:(game)->@flag || @target? job:(game,playerid,query)-> if @target? return "已经决定了对象" if @flag return "已经不能送出巧克力" pl=game.getPlayer playerid unless pl? return "对象无效" if playerid==@id return "请选择自己以外的人" pl.touched game,@id @setTarget playerid @setFlag true log= mode: "skill" to: @id comment: "#{@name} 将 #{pl.name} 选为本命。" splashlog game.id, game, log null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 全員にチョコを配る(1人本命) alives = game.players.filter((x)->!x.dead).map((x)-> x.id) for pid in alives p = game.getPlayer pid if p.id == pl.id # 本命 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateTrue newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log else if p.id != @id # 義理 sub = Player.factory "GotChocolate" p.transProfile sub sub.sunset game newpl = Player.factory null, p, sub, GotChocolateFalse newpl.cmplFlag=@id p.transProfile newpl p.transferData newpl p.transform game, newpl, true log= mode:"skill" to: p.id comment: "#{p.name} 收到了巧克力。" splashlog game.id,game,log # 自分は本命と恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag=pl.id top.transProfile newpl top.transferData newpl top.transform game,newpl,true log= mode: "skill" to: @id comment: "#{@name} 与 #{pl.name} 结为恋人。" splashlog game.id, game, log null # 内部処理用:チョコレートもらった class GotChocolate extends Player type: "GotChocolate" jobname: "巧克力" midnightSort:100 sleeping:->true jobdone:(game)-> @flag!="unselected" job_target:0 getTypeDisp:->if @flag=="done" then null else @type makeJobSelection:(game)-> if game.night [] else super sunset:(game)-> if !@flag? # 最初は選択できない @setTarget "" @setFlag "waiting" else if @flag=="waiting" # 選択できるようになった @setFlag "unselected" job:(game,playerid)-> unless @flag == "unselected" return "无法使用能力" # 食べると本命か義理か判明する flag = false top = game.getPlayer @id unless top? # ????? return "对象无效" while top?.isComplex() if top.cmplType=="GotChocolateTrue" && top.sub==this # 本命だ t=game.getPlayer top.cmplFlag if t? log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是本命巧克力。#{@name} 与 #{t.name} 结为恋人。" splashlog game.id, game, log @setFlag "done" # 本命を消す top.uncomplex game, false # 恋人になる top = game.getPlayer @id newpl = Player.factory null, top, null, Friend newpl.cmplFlag = t.id top.transProfile newpl top.transform game,newpl,true top = game.getPlayer @id flag = true game.ss.publish.user top.id,"refresh",{id:game.id} break else if top.cmplType=="GotChocolateFalse" && top.sub==this # 義理だ @setFlag "selected:#{top.cmplFlag}" flag = true log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是义理巧克力。" splashlog game.id, game, log break top = top.main if flag == false # チョコレートをもらっていなかった log= mode:"skill" to: @id comment: "#{@name} 吃下了巧克力,什么都没有发生。" splashlog game.id, game, log null midnight:(game,midnightSort)-> re = @flag?.match /^selected:(.+)$/ if re? @setFlag "done" @uncomplex game, true # 義理チョコの効果発動 top = game.getPlayer @id r = Math.random() if r < 0.12 # 呪いのチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是被诅咒的巧克力,下一天白天不能发言。" splashlog game.id, game, log newpl = Player.factory null, top, null, Muted top.transProfile newpl top.transform game, newpl, true else if r < 0.30 # ブラックチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是黑巧克力,占卜·灵能结果将变为「LowB」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Blacked top.transProfile newpl top.transform game, newpl, true else if r < 0.45 # ホワイトチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是白巧克力,占卜·灵能结果将变为「母猪」。" splashlog game.id, game, log newpl = Player.factory null, top, null, Whited top.transProfile newpl top.transform game, newpl, true else if r < 0.50 # 毒入りチョコ log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力是毒巧克力,将被毒死。" splashlog game.id, game, log @die game, "poison", @id else if r < 0.57 # ストーカー化 topl = game.getPlayer re[1] if topl? newpl = Player.factory "Stalker" top.transProfile newpl # ストーカー先 newpl.setFlag re[1] top.transform game, newpl, true log= mode:"skill" to: @id comment: "#{@name} 凭借执念找到了巧克力的送出人,#{@name} 成为了 #{topl.name} 的跟踪狂。" splashlog game.id, game, log else if r < 0.65 # 血入りの…… log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力不知为何有铁锈的味道,占卜结果将变为「吸血鬼」。" splashlog game.id, game, log newpl = Player.factory null, top, null, VampireBlooded top.transProfile newpl top.transform game, newpl, true else if r < 0.75 # 聖職 log= mode:"skill" to: @id comment: "#{@name} 吃下的巧克力蕴含着神圣的力量,#{@name} 可以使用一次「圣职者」的力量。" splashlog game.id, game, log sub = Player.factory "Priest" top.transProfile sub newpl = Player.factory null, top, sub, Complex top.transProfile newpl top.transform game, newpl, true class MadDog extends Madman type:"MadDog" jobname:"狂犬" fortuneResult:"LowB" psychicResult:"LowB" midnightSort:100 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 袭击了 #{pl.name}。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> pl=game.getPlayer @target return unless pl? # 襲撃実行 @setFlag true # 殺害 @addGamelog game,"dogkill",pl.type,pl.id pl.die game,"dog" null class Hypnotist extends Madman type:"Hypnotist" jobname:"催眠师" midnightSort:50 jobdone:(game)->@target? || @flag sleeping:->true constructor:-> super @setFlag null sunset:(game)-> if @flag || game.day==1 @setTarget "" else @setTarget null job:(game,playerid)-> if @flag || @target? return "已经无法发动能力" @setTarget playerid pl=game.getPlayer playerid unless pl? return "对象不存在" if pl.dead return "对象已经死亡" pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 催眠了 #{pl.name}。" splashlog game.id,game,log @setFlag true null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return if pl.isWerewolf() # LowBを襲撃した場合はLowBの襲撃を無効化する game.werewolf_target = [] game.werewolf_target_remain = 0 # 催眠術を付加する @addGamelog game,"hypnosis",pl.type,pl.id newpl=Player.factory null,pl,null,UnderHypnosis pl.transProfile newpl pl.transform game,newpl,true return null class CraftyWolf extends Werewolf type:"CraftyWolf" jobname:"狡猾的狼" jobdone:(game)->super && @flag == "going" deadJobdone:(game)->@flag != "revivable" midnightSort:100 isReviver:->!@dead || (@flag in ["reviving","revivable"]) sunset:(game)-> super # 生存状態で昼になったら死んだふり能力初期化 @setFlag "" job:(game,playerid,query)-> if query.jobtype!="CraftyWolf" return super if @dead # 死亡時 if @flag != "revivable" return "不能使用能力" @setFlag "reviving" log= mode:"skill" to:@id comment:"#{@name} 取消假死了。" splashlog game.id,game,log return null else # 生存時 if @flag != "" return "已经使用过能力" # 生存フラグを残しつつ死ぬ @setFlag "going" log= mode:"skill" to:@id comment:"#{@name} 假死了。" splashlog game.id,game,log return null midnight:(game,midnightSort)-> if @flag=="going" @die game, "crafty" @addGamelog game,"craftydie" @setFlag "revivable" deadnight:(game,midnightSort)-> if @flag=="reviving" # 生存していた pl = game.getPlayer @id if pl? pl.setFlag "" pl.revive game pl.addGamelog game,"craftyrevive" else # 生存フラグが消えた @setFlag "" makejobinfo:(game,result)-> super result.open ?= [] if @dead && @flag=="revivable" # 死に戻り result.open = result.open.filter (x)->!(x in ["CraftyWolf","_Werewolf"]) result.open.push "CraftyWolf2" return result makeJobSelection:(game)-> if game.night && @dead && @flag=="revivable" # 死んだふりやめるときは選択肢がない [] else if game.night && game.werewolf_target_remain==0 # もう襲撃対象を選択しない [] else super checkJobValidity:(game,query)-> if query.jobtype in ["CraftyWolf","CraftyWolf2"] # 対象選択は不要 return true return super class Shishimai extends Player type:"Shishimai" jobname:"PI:NAME:<NAME>END_PI" team:"" sleeping:->true jobdone:(game)->@target? isWinner:(game,team)-> # 生存者(自身を除く)を全員噛んだら勝利 alives = game.players.filter (x)->!x.dead bitten = JSON.parse (@flag || "[]") flg = true for pl in alives if pl.id == @id continue unless pl.id in bitten flg = false break return flg sunset:(game)-> alives = game.players.filter (x)->!x.dead if alives.length > 0 @setTarget null if @scapegoat r = Math.floor Math.random()*alives.length @job game, alives[r].id, {} else @setTarget "" job:(game,playerid)-> pl = game.getPlayer playerid unless pl? return "这个玩家不存在。" bitten = JSON.parse (@flag || "[]") if playerid in bitten return "这个玩家已经被咀嚼过了。" log= mode:"skill" to:@id comment:"#{@name} 咀嚼了 #{pl.name}。" splashlog game.id, game, log @setTarget playerid null midnight:(game,midnightSort)-> pl = game.getPlayer @target unless pl? return # 票数が減る祝いをかける newpl = Player.factory null, pl, null, VoteGuarded pl.transProfile newpl pl.transform game, newpl, true newpl.touched game,@id # 噛んだ記録 arr = JSON.parse (@flag || "[]") arr.push newpl.id @setFlag (JSON.stringify arr) # かみかみ @addGamelog game, "shishimaibit", newpl.type, newpl.id null class Pumpkin extends Madman type: "Pumpkin" jobname: "南瓜魔" midnightSort: 90 sleeping:->@target? sunset:(game)-> super @setTarget null if @scapegoat alives = game.players.filter (x)->!x.dead if alives.length == 0 @setTarget "" else r=Math.floor Math.random()*alives.length @job game,alives[r].id ,{} job:(game,playerid)-> @setTarget playerid pl=game.getPlayer playerid return unless pl? pl.touched game,@id log= mode:"skill" to:@id comment:"#{@name} 把 #{pl.name} 变成了南瓜。" splashlog game.id,game,log @addGamelog game,"pumpkin",null,playerid null midnight:(game,midnightSort)-> t=game.getPlayer @target return unless t? return if t.dead newpl=Player.factory null, t,null, PumpkinCostumed t.transProfile newpl t.transform game,newpl,true class MadScientist extends Madman type:"MadScientist" jobname:"疯狂科学家" midnightSort:100 isReviver:->!@dead && @flag!="done" sleeping:->true jobdone:->@flag=="done" || @target? job_target: Player.JOB_T_DEAD sunset:(game)-> @setTarget (if game.day<2 || @flag=="done" then "" else null) if game.players.every((x)->!x.dead) @setTarget "" # 誰も死んでいないなら能力発動しない job:(game,playerid)-> if game.day<2 return "现在还不能发动技能" if @flag == "done" return "已经不能发动技能" pl=game.getPlayer playerid unless pl? return "这个玩家不存在" unless pl.dead return "不能选择这名玩家" @setFlag "done" @setTarget playerid log= mode:"skill" to:@id comment:"#{@name} 对 #{pl.name} 实施了复活手术。" splashlog game.id,game,log null midnight:(game,midnightSort)-> return unless @target? pl=game.getPlayer @target return unless pl? return unless pl.dead # 蘇生 @addGamelog game,"raise",true,pl.id pl.revive game pl = game.getPlayer @target return if pl.dead # 蘇生に成功したら胜利条件を変える newpl=Player.factory null,pl,null,WolfMinion # WolfMinion pl.transProfile newpl pl.transform game,newpl,true log= mode:"skill" to:newpl.id comment:"#{newpl.name} 变成了狼的仆从。" splashlog game.id,game,log class SpiritPossessed extends Player type:"SpiritPossessed" jobname:"恶灵凭依" isReviver:->!@dead # ============================ # 処理上便宜的に使用 class GameMaster extends Player type:"GameMaster" jobname:"游戏管理员" team:"" jobdone:->false sleeping:->true isWinner:(game,team)->null # 例外的に昼でも発動する可能性がある job:(game,playerid,query)-> pl=game.getPlayer playerid unless pl? return "对象无效" pl.die game,"gmpunish" game.bury("other") null isListener:(game,log)->true # 全て見える getSpeakChoice:(game)-> pls=for pl in game.players "gmreply_#{pl.id}" ["gm","gmheaven","gmaudience","gmmonologue"].concat pls getSpeakChoiceDay:(game)->@getSpeakChoice game chooseJobDay:(game)->true # 昼でも対象选择 # 帮手 class Helper extends Player type:"Helper" jobname:"PI:NAME:<NAME>END_PI" team:"" jobdone:->@flag? sleeping:->true voted:(game,votingbox)->true isWinner:(game,team)-> pl=game.getPlayer @flag return pl?.isWinner game,team # @flag: リッスン対象のid # 同じものが見える isListener:(game,log)-> pl=game.getPlayer @flag unless pl? # 自律行動帮手? return super if pl.isJobType "Helper" # 帮手の帮手の場合は听不到(無限ループ防止) return false return pl.isListener game,log getSpeakChoice:(game)-> if @flag? return ["helperwhisper_#{@flag}"] else return ["helperwhisper"] getSpeakChoiceDay:(game)->@getSpeakChoice game job:(game,playerid)-> if @flag? return "已经决定了帮助对象" pl=game.getPlayer playerid unless pl? return "帮助对象不存在" @flag=playerid log= mode:"skill" to:playerid comment:"#{@name} 成为了 #{pl.name} 的帮手。" splashlog game.id,game,log # 自己の表記を改める game.splashjobinfo [this] null makejobinfo:(game,result)-> super # ヘルプ先が分かる pl=game.getPlayer @flag if pl? helpedinfo={} pl.makejobinfo game,helpedinfo result.supporting=pl?.publicinfo() result.supportingJob=pl?.getJobDisp() for value in Shared.game.jobinfos if helpedinfo[value.name]? result[value.name]=helpedinfo[value.name] null # 开始前のやつだ!!!!!!!! class Waiting extends Player type:"Waiting" jobname:"尚未分配" team:"" sleeping:(game)->!game.rolerequestingphase || game.rolerequesttable[@id]? isListener:(game,log)-> if log.mode=="audience" true else super getSpeakChoice:(game)-> return ["prepare"] makejobinfo:(game,result)-> super # 自己で追加する result.open.push "Waiting" makeJobSelection:(game)-> if game.day==0 && game.rolerequestingphase # 开始前 result=[{ name:"放弃选择" value:"" }] for job,num of game.joblist if num result.push { name:Shared.game.getjobname job value:job } return result else super job:(game,target)-> # 希望职业 game.rolerequesttable[@id]=target if target log= mode:"skill" to:@id comment:"#{@name} 希望成为 #{Shared.game.getjobname target}。" else log= mode:"skill" to:@id comment:"#{@name} 放弃选择职业。" splashlog game.id,game,log null # Endless黑暗火锅でまだ入ってないやつ class Watching extends Player type:"Watching" jobname:"PI:NAME:<NAME>END_PI战PI:NAME:<NAME>END_PI" team:"" sleeping:(game)->true isWinner:(game,team)->true isListener:(game,log)-> if log.mode in ["audience","inlog"] # 参加前なので true else super getSpeakChoice:(game)-> return ["audience"] getSpeakChoiceDay:(game)-> return ["audience"] # 複合职业 Player.factoryで適切に生成されることを期待 # superはメイン职业 @mainにメイン @subにサブ # @cmplFlag も持っていい class Complex cmplType:"Complex" # 複合親そのものの名字 isComplex:->true getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() midnightSort: 100 #@mainのやつを呼ぶ mcall:(game,method,args...)-> if @main.isComplex() # そのまま return method.apply @main,args # 他は親が必要 top=game.participants.filter((x)=>x.id==@id)[0] if top? return method.apply top,args return null setDead:(@dead,@found)-> @main.setDead @dead,@found @sub?.setDead @dead,@found setWinner:(@winner)->@main.setWinner @winner setTarget:(@target)->@main.setTarget @target setFlag:(@flag)->@main.setFlag @flag setWill:(@will)->@main.setWill @will setOriginalType:(@originalType)->@main.setOriginalType @originalType setOriginalJobname:(@originalJobname)->@main.setOriginalJobname @originalJobname setNorevive:(@norevive)->@main.setNorevive @norevive jobdone:(game)-> @mcall(game,@main.jobdone,game) && (!@sub?.jobdone? || @sub.jobdone(game)) # ジョブの場合はサブも考慮 job:(game,playerid,query)-> # どちらの # query.jobtypeがない場合は内部処理なのでmainとして処理する? unless query? query={} unless query.jobtype? query.jobtype=@main.type if @main.isJobType(query.jobtype) && ((@main.dead && !@main.deadJobdone(game)) || (!@main.dead && !@main.jobdone(game))) @mcall game,@main.job,game,playerid,query else if @sub?.isJobType?(query.jobtype) && ((@sub.dead && !@sub.deadJobdone(game)) || (!@sub.dead && !@sub?.jobdone?(game))) @sub.job? game,playerid,query # Am I Walking Dead? isDead:-> isMainDead = @main.isDead() if isMainDead.dead && isMainDead.found # Dead! return isMainDead if @sub? isSubDead = @sub.isDead() if isSubDead.dead && isSubDead.found # Dead! return isSubDead # seems to be alive, who knows? return {dead:@dead,found:@found} isJobType:(type)-> @main.isJobType(type) || @sub?.isJobType?(type) getTeam:-> if @team then @team else @main.getTeam() #An access to @main.flag, etc. accessByJobType:(type)-> unless type throw "there must be a JOBTYPE" unless @isJobType(type) return null if @main.isJobType(type) return @main.accessByJobType(type) else unless @sub? return null return @sub.accessByJobType(type) null gatherMidnightSort:-> mids=[@midnightSort] mids=mids.concat @main.gatherMidnightSort() if @sub? mids=mids.concat @sub.gatherMidnightSort() return mids sunset:(game)-> @mcall game,@main.sunset,game @sub?.sunset? game midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort deadnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.deadnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.deadnight? game,midnightSort deadsunset:(game)-> @mcall game,@main.deadsunset,game @sub?.deadsunset? game deadsunrise:(game)-> @mcall game,@main.deadsunrise,game @sub?.deadsunrise? game sunrise:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game votestart:(game)-> @mcall game,@main.votestart,game voted:(game,votingbox)->@mcall game,@main.voted,game,votingbox dovote:(game,target)-> @mcall game,@main.dovote,game,target voteafter:(game,target)-> @mcall game,@main.voteafter,game,target @sub?.voteafter game,target modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote @mcall game, @main.modifyMyVote, game, vote makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result,@main.getJobDisp() beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type # deal with Walking Dead unless @dead isPlDead = @isDead() if isPlDead.dead && isPlDead.found @setDead isPlDead.dead,isPlDead.found divined:(game,player)-> @mcall game,@main.divined,game,player @sub?.divined? game,player getjob_target:-> if @sub? @main.getjob_target() | @sub.getjob_target() # ビットフラグ else @main.getjob_target() die:(game,found,from)-> @mcall game,@main.die,game,found,from dying:(game,found,from)-> @mcall game,@main.dying,game,found,from @sub?.dying game,found,from revive:(game)-> # まずsubを蘇生 if @sub? @sub.revive game if @sub.dead # 蘇生できない類だ return # 次にmainを蘇生 @mcall game,@main.revive,game if @main.dead # 蘇生できなかった @setDead true, @main.found else # 蘇生できた @setDead false, null makeJobSelection:(game)-> result=@mcall game,@main.makeJobSelection,game if @sub? for obj in @sub.makeJobSelection game unless result.some((x)->x.value==obj.value) result.push obj result checkJobValidity:(game,query)-> if query.jobtype=="_day" return @mcall(game,@main.checkJobValidity,game,query) if @mcall(game,@main.isJobType,query.jobtype) && !@mcall(game,@main.jobdone,game) return @mcall(game,@main.checkJobValidity,game,query) else if @sub?.isJobType?(query.jobtype) && !@sub?.jobdone?(game) return @sub.checkJobValidity game,query else return true getSpeakChoiceDay:(game)-> result=@mcall game,@main.getSpeakChoiceDay,game if @sub? for obj in @sub.getSpeakChoiceDay game unless result.some((x)->x==obj) result.push obj result getSpeakChoice:(game)-> result=@mcall game,@main.getSpeakChoice,game if @sub? for obj in @sub.getSpeakChoice game unless result.some((x)->x==obj) result.push obj result isListener:(game,log)-> @mcall(game,@main.isListener,game,log) || @sub?.isListener(game,log) isReviver:->@main.isReviver() || @sub?.isReviver() isHuman:->@main.isHuman() isWerewolf:->@main.isWerewolf() isFox:->@main.isFox() isVampire:->@main.isVampire() isWinner:(game,team)->@main.isWinner game, team #superがつかえないので注意 class Friend extends Complex # 恋人 # cmplFlag: 相方のid cmplType:"Friend" isFriend:->true team:"Friend" getJobname:->"恋人(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" beforebury:(game,type)-> @mcall game,@main.beforebury,game,type @sub?.beforebury? game,type ato=false if game.rule.friendssplit=="split" # 独立 pl=game.getPlayer @cmplFlag if pl? && pl.dead && pl.isFriend() ato=true else # みんな friends=game.players.filter (x)->x.isFriend() #恋人たち if friends.length>1 && friends.some((x)->x.dead) ato=true # 恋人が誰か死んだら自殺 if ato @die game,"friendsuicide" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"PI:NAME:<NAME>END_PI" type:"Friend" } if game.rule.friendssplit=="split" # 独立 fr=[this,game.getPlayer(@cmplFlag)].filter((x)->x?.isFriend()).map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr else # みんないっしょ result.friends=game.players.filter((x)->x.isFriend()).map (x)-> x.publicinfo() isWinner:(game,team)->@team==team && !@dead # 相手のIDは? getPartner:-> if @cmplType=="Friend" return @cmplFlag else return @main.getPartner() # 圣职者にまもられた人 class HolyProtected extends Complex # cmplFlag: 护卫元 cmplType:"HolyProtected" die:(game,found)-> # 一回耐える 死なない代わりに元に戻る log= mode:"skill" to:@id comment:"#{@name} 被神圣的力量守护了。" splashlog game.id,game,log game.getPlayer(@cmplFlag).addGamelog game,"holyGJ",found,@id @uncomplex game # カルトの信者になった人 class CultMember extends Complex cmplType:"CultMember" isCult:->true getJobname:->"教会信者(#{@main.getJobname()})" getJobDisp:->"教会信者(#{@main.getJobDisp()})" makejobinfo:(game,result)-> super # 信者の説明 result.desc?.push { name:"PI:NAME:<NAME>END_PI" type:"CultMember" } # 猎人に守られた人 class Guarded extends Complex # cmplFlag: 护卫元ID cmplType:"Guarded" die:(game,found,from)-> unless found in ["werewolf","vampire"] @mcall game,@main.die,game,found,from else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"GJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 成功守护了 #{@name}。" splashlog game.id,game,log sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunrise,game # 黙らされた人 class Muted extends Complex cmplType:"Muted" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game game.ss.publish.user @id,"refresh",{id:game.id} getSpeakChoiceDay:(game)-> ["monologue"] # 全员に喋ることができない # 狼的仆从 class WolfMinion extends Complex cmplType:"WolfMinion" team:"Werewolf" getJobname:->"狼的仆从(#{@main.getJobname()})" getJobDisp:->"狼的仆从(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"狼的仆从" type:"WolfMinion" } isWinner:(game,team)->@team==team # 酒鬼 class Drunk extends Complex cmplType:"Drunk" getJobname:->"酒鬼(#{@main.getJobname()})" getTypeDisp:->"Human" getJobDisp:->"母猪" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunset:(game)-> @mcall game,@main.sunrise,game @sub?.sunrise? game if game.day>=3 # 3日目に目が覚める log= mode:"skill" to:@id comment:"#{@name} 酒醒了。" splashlog game.id,game,log @uncomplex game game.ss.publish.user @realid,"refresh",{id:game.id} makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj isDrunk:->true getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 陷阱师守られた人 class TrapGuarded extends Complex # cmplFlag: 护卫元ID cmplType:"TrapGuarded" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 return if midnightSort != @midnightSort wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 狩人がいた!(罠も無効) wholepl = game.getPlayer @id @checkTrap game, wholepl # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag # 罠し if tr? tr.addGamelog game,"trappedGuard",null,@id gu.die game,"trap" pl.uncomplex game # 消滅 # 子の調査を継続 @checkGuard game,pl.main return true checkTrap:(game,pl)-> # TrapGuardedも消す return unless pl.isComplex() if pl.cmplType=="TrapGuarded" pl.uncomplex game @checkTrap game, pl.main else @checkTrap game, pl.main if pl.sub? @checkTrap game, pl.sub die:(game,found,from)-> unless found in ["werewolf","vampire"] # 狼以外だとしぬ @mcall game,@main.die,game,found else # 狼に噛まれた場合は耐える guard=game.getPlayer @cmplFlag if guard? guard.addGamelog game,"trapGJ",null,@id if game.rule.gjmessage log= mode:"skill" to:guard.id comment:"#{guard.name} 的陷阱成功守护了 #{@name}。" splashlog game.id,game,log # 反撃する canbedead=[] ft=game.getPlayer from if ft.isWerewolf() canbedead=game.players.filter (x)->!x.dead && x.isWerewolf() else if ft.isVampire() canbedead=game.players.filter (x)->!x.dead && x.id==from return if canbedead.length==0 r=Math.floor Math.random()*canbedead.length pl=canbedead[r] # 被害者 pl.die game,"trap" @addGamelog game,"trapkill",null,pl.id sunrise:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game # 黙らされた人 class Lycanized extends Complex cmplType:"Lycanized" fortuneResult:"LowB" sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 策士によって更生させられた人 class Counseled extends Complex cmplType:"Counseled" team:"Human" getJobname:->"更生者(#{@main.getJobname()})" getJobDisp:->"更生者(#{@main.getJobDisp()})" isWinner:(game,team)->@team==team makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result result.desc?.push { name:"更生者" type:"Counseled" } # 巫女のガードがある状态 class MikoProtected extends Complex cmplType:"MikoProtected" die:(game,found)-> # 耐える game.getPlayer(@id).addGamelog game,"mikoGJ",found sunset:(game)-> # 一日しか効かない @sub?.sunset? game @uncomplex game @mcall game,@main.sunset,game # 威嚇するLowBに威嚇された class Threatened extends Complex cmplType:"Threatened" sleeping:->true jobdone:->true isListener:(game,log)-> Human.prototype.isListener.call @,game,log sunrise:(game)-> # この昼からは戻る @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game sunset:(game)-> midnight:(game,midnightSort)-> job:(game,playerid,query)-> null dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> makejobinfo:(game,obj)-> Human.prototype.makejobinfo.call @,game,obj getSpeakChoice:(game)-> Human.prototype.getSpeakChoice.call @,game # 碍事的狂人に邪魔された(未完成) class DivineObstructed extends Complex # cmplFlag: 邪魔元ID cmplType:"DivineObstructed" sunset:(game)-> # 一日しか守られない @sub?.sunrise? game @uncomplex game @mcall game,@main.sunset,game # 占いの影響なし divineeffect:(game)-> showdivineresult:(game)-> # 结果がでなかった pl=game.getPlayer @target if pl? log= mode:"skill" to:@id comment:"#{@name} 占卜了 #{pl.name} 的身份,但是被不知道什么人妨碍了。" splashlog game.id,game,log dodivine:(game)-> # 占おうとした。邪魔成功 obstmad=game.getPlayer @cmplFlag if obstmad? obstmad.addGamelog game,"divineObstruct",null,@id class PhantomStolen extends Complex cmplType:"PhantomStolen" # cmplFlag: 保存されたアレ sunset:(game)-> # 夜になると怪盗になってしまう!!!!!!!!!!!! @sub?.sunrise? game newpl=Player.factory "Phantom" # アレがなぜか狂ってしまうので一時的に保存 saved=@originalJobname @uncomplex game pl=game.getPlayer @id pl.transProfile newpl pl.transferData newpl pl.transform game,newpl,true log= mode:"skill" to:@id comment:"#{@name} 的职业被盗走了,变成了 #{newpl.getJobDisp()}。" splashlog game.id,game,log # 夜の初期化 pl=game.getPlayer @id pl.setOriginalJobname saved pl.setFlag true # もう盗めない pl.sunset game getJobname:->"怪盗" #灵界とかでは既に怪盗化 # 胜利条件関係は母猪化(昼の間だけだし) isWerewolf:->false isFox:->false isVampire:->false #team:"Human" #女王との兼ね合いで isWinner:(game,team)-> team=="Human" die:(game,found,from)-> # 抵抗もなく死ぬし if found=="punish" Player::die.apply this,arguments else super dying:(game,found)-> makejobinfo:(game,obj)-> super for key,value of @cmplFlag obj[key]=value class KeepedLover extends Complex # 恶女に手玉にとられた(見た目は恋人) # cmplFlag: 相方のid cmplType:"KeepedLover" getJobname:->"手玉(#{@main.getJobname()})" getJobDisp:->"恋人(#{@main.getJobDisp()})" makejobinfo:(game,result)-> @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 恋人が分かる result.desc?.push { name:"PI:NAME:<NAME>END_PI人" type:"Friend" } # 恋人だと思い込む fr=[this,game.getPlayer(@cmplFlag)].map (x)-> x.publicinfo() if Array.isArray result.friends result.friends=result.friends.concat fr else result.friends=fr # 花火を見ている class WatchingFireworks extends Complex # cmplFlag: 烟火师のid cmplType:"WatchingFireworks" sleeping:->true jobdone:->true sunrise:(game)-> @sub?.sunrise? game # もう终了 @uncomplex game pl=game.getPlayer @id if pl? #pl.sunset game pl.sunrise game deadsunrise:(game)->@sunrise game makejobinfo:(game,result)-> super result.watchingfireworks=true # 炸弹魔に爆弾を仕掛けられた人 class BombTrapped extends Complex # cmplFlag: 护卫元ID cmplType:"BombTrapped" midnight:(game,midnightSort)-> if @main.isComplex() || @main.midnightSort == midnightSort @mcall game,@main.midnight,game,midnightSort if @sub?.isComplex() || @sub?.midnightSort == midnightSort @sub?.midnight? game,midnightSort # 狩人とかぶったら狩人が死んでしまう!!!!! # midnight: 狼の襲撃よりも前に行われることが保証されている処理 if midnightSort != @midnightSort then return wholepl=game.getPlayer @id # 一番表から見る result=@checkGuard game,wholepl if result # 猎人がいた!(罠も無効) @uncomplex game # bomb would explode for only once deadsunrise:(game)-> super @uncomplex game # midnight処理用 checkGuard:(game,pl)-> return false unless pl.isComplex() # Complexの場合:mainとsubを確かめる unless pl.cmplType=="Guarded" # 見つからない result=false result ||= @checkGuard game,pl.main if pl.sub? # 枝を切る result ||=@checkGuard game,pl.sub return result else # あった! # cmplFlag: 护卫元の猎人 gu=game.getPlayer pl.cmplFlag if gu? tr = game.getPlayer @cmplFlag #炸弹魔 if tr? tr.addGamelog game,"bombTrappedGuard",null,@id # 护卫元が死ぬ gu.die game,"bomb" # 自己も死ぬ @die game,"bomb" pl.uncomplex game # 罠は消滅 # 子の調査を継続 @checkGuard game,pl.main return true die:(game,found,from)-> if found=="punish" # 处刑された場合は处刑者の中から選んでしぬ # punishのときはfromがidの配列 if from? && from.length>0 pls=from.map (id)->game.getPlayer id pls=pls.filter (x)->!x.dead if pls.length>0 r=Math.floor Math.random()*pls.length pl=pls[r] if pl? pl.die game,"bomb" @addGamelog game,"bombkill",null,pl.id else if found in ["werewolf","vampire"] # 狼に噛まれた場合は襲撃者を巻き添えにする bomber=game.getPlayer @cmplFlag if bomber? bomber.addGamelog game,"bompGJ",null,@id # 反撃する wl=game.getPlayer from if wl? wl.die game,"bomb" @addGamelog game,"bombkill",null,wl.id # 自己もちゃんと死ぬ @mcall game,@main.die,game,found,from # 狐凭 class FoxMinion extends Complex cmplType:"FoxMinion" willDieWerewolf:false isHuman:->false isFox:->true isFoxVisible:->true getJobname:->"狐凭(#{@main.getJobname()})" # 占われたら死ぬ divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # 丑时之女に呪いをかけられた class DivineCursed extends Complex cmplType:"DivineCursed" sunset:(game)-> # 1日で消える @uncomplex game @mcall game,@main.sunset,game divined:(game,player)-> @mcall game,@main.divined,game,player @die game,"curse" player.addGamelog game,"cursekill",null,@id # 呪殺した # パティシエールに本命チョコをもらった class GotChocolateTrue extends Friend cmplType:"GotChocolateTrue" getJobname:->@main.getJobname() getJobDisp:->@main.getJobDisp() getPartner:-> if @cmplType=="GotChocolateTrue" return @cmplFlag else return @main.getPartner() makejobinfo:(game,result)-> # 恋人情報はでない @sub?.makejobinfo? game,result @mcall game,@main.makejobinfo,game,result # 本命ではない class GotChocolateFalse extends Complex cmplType:"GotChocolateFalse" # 黒になった class Blacked extends Complex cmplType:"Blacked" fortuneResult: "LowB" psychicResult:"LowB" # 白になった class Whited extends Complex cmplType:"Whited" fortuneResult: "母猪" psychicResult:"母猪" # 占い結果吸血鬼化 class VampireBlooded extends Complex cmplType:"VampireBlooded" fortuneResult: "吸血鬼" # 催眠術をかけられた class UnderHypnosis extends Complex cmplType:"UnderHypnosis" sunrise:(game)-> # 昼になったら戻る @uncomplex game pl=game.getPlayer @id if pl? pl.sunrise game midnight:(game,midnightSort)-> die:(game,found,from)-> Human.prototype.die.call @,game,found,from dying:(game,found,from)-> Human.prototype.dying.call @,game,found,from touched:(game,from)-> divined:(game,player)-> voteafter:(game,target)-> # 狮子舞の加護 class VoteGuarded extends Complex cmplType:"VoteGuarded" modifyMyVote:(game, vote)-> if @sub? vote = @sub.modifyMyVote game, vote vote = @mcall game, @main.modifyMyVote, game, vote # 自分への投票を1票減らす if vote.votes > 0 vote.votes-- vote # 南瓜魔の呪い class PumpkinCostumed extends Complex cmplType:"PumpkinCostumed" fortuneResult: "南瓜" # 决定者 class Decider extends Complex cmplType:"Decider" getJobname:->"#{@main.getJobname()}(决定者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePriority this,1 #優先度を1上げる null # 权力者 class Authority extends Complex cmplType:"Authority" getJobname:->"#{@main.getJobname()}(权力者)" dovote:(game,target)-> result=@mcall game,@main.dovote,game,target return result if result? game.votingbox.votePower this,1 #票をひとつ増やす null # 炼成LowBの职业 class Chemical extends Complex cmplType:"Chemical" getJobname:-> if @sub? "#{@main.getJobname()}×#{@sub.getJobname()}" else @main.getJobname() getJobDisp:-> if @sub? "#{@main.getJobDisp()}×#{@sub.getJobDisp()}" else @main.getJobDisp() sleeping:(game)->@main.sleeping(game) && (!@sub? || @sub.sleeping(game)) jobdone:(game)->@main.jobdone(game) && (!@sub? || @sub.jobdone(game)) isHuman:-> if @sub? @main.isHuman() && @sub.isHuman() else @main.isHuman() isWerewolf:-> @main.isWerewolf() || @sub?.isWerewolf() isFox:-> @main.isFox() || @sub?.isFox() isFoxVisible:-> @main.isFoxVisible() || @sub?.isFoxVisible() isVampire:-> @main.isVampire() || @sub?.isVampire() isAttacker:-> @main.isAttacker?() || @sub?.isAttacker?() humanCount:-> if @isFox() 0 else if @isWerewolf() 0 else if @isHuman() 1 else 0 werewolfCount:-> if @isFox() 0 else if @isWerewolf() if @sub? @main.werewolfCount() + @sub.werewolfCount() else @main.werewolfCount() else 0 vampireCount:-> if @isFox() 0 else if @isVampire() if @sub? @main.vampireCount() + @sub.vampireCount() else @main.vampireCount() else 0 getFortuneResult:-> fsm = @main.getFortuneResult() fss = @sub?.getFortuneResult() if "吸血鬼" in [fsm, fss] "吸血鬼" else if "LowB" in [fsm, fss] "LowB" else "母猪" getPsychicResult:-> fsm = @main.getPsychicResult() fss = @sub?.getPsychicResult() if "LowB" in [fsm, fss] "LowB" else "母猪" getTeam:-> myt = null maint = @main.getTeam() subt = @sub?.getTeam() if maint=="Cult" || subt=="Cult" myt = "Cult" else if maint=="Friend" || subt=="Friend" myt = "Friend" else if maint=="Fox" || subt=="Fox" myt = "Fox" else if maint=="Vampire" || subt=="Vampire" myt = "Vampire" else if maint=="Werewolf" || subt=="Werewolf" myt = "Werewolf" else if maint=="LoneWolf" || subt=="LoneWolf" myt = "LoneWolf" else if maint=="Human" || subt=="Human" myt = "Human" else myt = "" return myt isWinner:(game,team)-> myt = @getTeam() win = false maint = @main.getTeam() sunt = @sub?.getTeam() if maint == myt || maint == "" || maint == "Devil" win = win || @main.isWinner(game,team) if subt == myt || subt == "" || subt == "Devil" win = win || @sub.isWinner(game,team) return win die:(game, found, from)-> return if @dead if found=="werewolf" && (!@main.willDieWerewolf || (@sub? && !@sub.willDieWerewolf)) # LowBに対する襲撃耐性 return # main, subに対してdieをsimulateする(ただしdyingはdummyにする) d = Object.getOwnPropertyDescriptor(this, "dying") @dying = ()-> null # どちらかが耐えたら耐える @main.die game, found, from isdead = @dead @setDead false, null if @sub? @sub.die game, found, from isdead = isdead && @dead if d? Object.defineProperty this, "dying", d else delete @dying # XXX duplicate pl=game.getPlayer @id if isdead pl.setDead true, found pl.dying game, found, from else pl.setDead false, null touched:(game, from)-> @main.touched game, from @sub?.touched game, from makejobinfo:(game,result)-> @main.makejobinfo game,result @sub?.makejobinfo? game,result # 女王観戦者は母猪陣営×母猪陣営じゃないと見えない if result.queens? && (@main.getTeam() != "Human" || @sub?.getTeam() != "Human") delete result.queens # 陣営情報 result.myteam = @getTeam() games={} # 游戏のGC new cron.CronJob("0 0 * * * *", -> # いらないGameを消す tm=Date.now()-3600000 # 1时间前 games_length_b = 0 for id,game of games games_length_b++ for id,game of games if game.finished # 終わっているやつが消す候補 if (!game.last_time?) || (game.last_time<tm) # 十分古い console.log "delete game:"+id delete games[id] games_length_a = 0 for id,game of games games_length_a++ console.log "length of games before:"+games_length_b console.log "length of games after :"+games_length_a , null, true, "Asia/Shanghai") # 游戏を得る getGame=(id)-> # 仕事一览 jobs= Human:Human Werewolf:Werewolf Diviner:Diviner Psychic:Psychic Madman:Madman Guard:Guard Couple:Couple Fox:Fox Poisoner:Poisoner BigWolf:BigWolf TinyFox:TinyFox Bat:Bat Noble:Noble Slave:Slave Magician:Magician Spy:Spy WolfDiviner:WolfDiviner Fugitive:Fugitive Merchant:Merchant QueenSpectator:QueenSpectator MadWolf:MadWolf Neet:Neet Liar:Liar Spy2:Spy2 Copier:Copier Light:Light Fanatic:Fanatic Immoral:Immoral Devil:Devil ToughGuy:ToughGuy Cupid:Cupid Stalker:Stalker Cursed:Cursed ApprenticeSeer:ApprenticeSeer Diseased:Diseased Spellcaster:Spellcaster Lycan:Lycan Priest:Priest Prince:Prince PI:PI Sorcerer:Sorcerer Doppleganger:Doppleganger CultLeader:CultLeader Vampire:Vampire LoneWolf:LoneWolf Cat:Cat Witch:Witch Oldman:Oldman Tanner:Tanner OccultMania:OccultMania MinionSelector:MinionSelector WolfCub:WolfCub WhisperingMad:WhisperingMad Lover:Lover Thief:Thief Dog:Dog Dictator:Dictator SeersMama:SeersMama Trapper:Trapper WolfBoy:WolfBoy Hoodlum:Hoodlum QuantumPlayer:QuantumPlayer RedHood:RedHood Counselor:Counselor Miko:Miko GreedyWolf:GreedyWolf FascinatingWolf:FascinatingWolf SolitudeWolf:SolitudeWolf ToughWolf:ToughWolf ThreateningWolf:ThreateningWolf HolyMarked:HolyMarked WanderingGuard:WanderingGuard ObstructiveMad:ObstructiveMad TroubleMaker:TroubleMaker FrankensteinsMonster:FrankensteinsMonster BloodyMary:BloodyMary King:King PsychoKiller:PsychoKiller SantaClaus:SantaClaus Phantom:Phantom BadLady:BadLady DrawGirl:DrawGirl CautiousWolf:CautiousWolf Pyrotechnist:Pyrotechnist Baker:Baker Bomber:Bomber Blasphemy:Blasphemy Ushinotokimairi:Ushinotokimairi Patissiere:Patissiere GotChocolate:GotChocolate MadDog:MadDog Hypnotist:Hypnotist CraftyWolf:CraftyWolf Shishimai:Shishimai Pumpkin:Pumpkin MadScientist:MadScientist SpiritPossessed:SpiritPossessed # 特殊 GameMaster:GameMaster Helper:Helper # 开始前 Waiting:Waiting Watching:Watching complexes= Complex:Complex Friend:Friend HolyProtected:HolyProtected CultMember:CultMember Guarded:Guarded Muted:Muted WolfMinion:WolfMinion Drunk:Drunk Decider:Decider Authority:Authority TrapGuarded:TrapGuarded Lycanized:Lycanized Counseled:Counseled MikoProtected:MikoProtected Threatened:Threatened DivineObstructed:DivineObstructed PhantomStolen:PhantomStolen KeepedLover:KeepedLover WatchingFireworks:WatchingFireworks BombTrapped:BombTrapped FoxMinion:FoxMinion DivineCursed:DivineCursed GotChocolateTrue:GotChocolateTrue GotChocolateFalse:GotChocolateFalse Blacked:Blacked Whited:Whited VampireBlooded:VampireBlooded UnderHypnosis:UnderHypnosis VoteGuarded:VoteGuarded Chemical:Chemical PumpkinCostumed:PumpkinCostumed # 役職ごとの強さ jobStrength= Human:5 Werewolf:40 Diviner:25 Psychic:15 Madman:10 Guard:23 Couple:10 Fox:25 Poisoner:20 BigWolf:80 TinyFox:10 Bat:10 Noble:12 Slave:5 Magician:14 Spy:14 WolfDiviner:60 Fugitive:8 Merchant:18 QueenSpectator:20 MadWolf:40 Neet:50 Liar:8 Spy2:5 Copier:10 Light:30 Fanatic:20 Immoral:5 Devil:20 ToughGuy:11 Cupid:37 Stalker:10 Cursed:2 ApprenticeSeer:23 Diseased:16 Spellcaster:6 Lycan:5 Priest:17 Prince:17 PI:23 Sorcerer:14 Doppleganger:15 CultLeader:10 Vampire:40 LoneWolf:28 Cat:22 Witch:23 Oldman:4 Tanner:15 OccultMania:10 MinionSelector:0 WolfCub:70 WhisperingMad:20 Lover:25 Thief:0 Dog:7 Dictator:18 SeersMama:15 Trapper:13 WolfBoy:11 Hoodlum:5 QuantumPlayer:0 RedHood:16 Counselor:25 Miko:14 GreedyWolf:60 FascinatingWolf:52 SolitudeWolf:20 ToughWolf:55 ThreateningWolf:50 HolyMarked:6 WanderingGuard:10 ObstructiveMad:19 TroubleMaker:15 FrankensteinsMonster:50 BloodyMary:5 King:15 PsychoKiller:25 SantaClaus:20 Phantom:15 BadLady:30 DrawGirl:10 CautiousWolf:45 Pyrotechnist:20 Baker:16 Bomber:23 Blasphemy:10 Ushinotokimairi:19 Patissiere:10 MadDog:19 Hypnotist:17 CraftyWolf:48 Shishimai:10 Pumpkin:17 MadScientist:20 SpiritPossessed:4 module.exports.actions=(req,res,ss)-> req.use 'user.fire.wall' req.use 'session' #游戏开始処理 #成功:null gameStart:(roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return Server.game.rooms.oneRoomS roomid,(room)-> if room.error? res room.error return unless room.mode=="waiting" # すでに开始している res "游戏已经开始" return if room.players.some((x)->!x.start) res "全员尚未全部准备好" return if room.gm!=true && query.yaminabe_hidejobs!="" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"]) res "「配置公开」选项在黑暗火锅模式下,只有在有GM的房间才能使用" return # ルールオブジェクト用意 ruleobj={ number: room.players.length maxnumber:room.number blind:room.blind gm:room.gm day: parseInt(parseInt(query.day_minute)*60+parseInt(query.day_second)) night: parseInt(parseInt(query.night_minute)*60+parseInt(query.night_second)) remain: parseInt(parseInt(query.remain_minute)*60+parseInt(query.remain_second)) # (n=15)秒规则 silentrule: parseInt(query.silentrule) ? 0 } unless ruleobj.day && ruleobj.night && ruleobj.remain res "时间长度不是有效数字,或总时长为零。" return options={} # 选项ズ for opt in ["decider","authority","yaminabe_hidejobs"] options[opt]=query[opt] ? null joblist={} for job of jobs joblist[job]=0 # 一旦初期化 #frees=room.players.length # 参加者の数 # プレイヤーと其他に分類 players=[] supporters=[] for pl in room.players if pl.mode=="player" if players.filter((x)->x.realid==pl.realid).length>0 res "#{pl.name} 重复加入,游戏无法开始。" return players.push pl else supporters.push pl frees=players.length if query.scapegoat=="on" # 替身君 frees++ playersnumber=frees # 人数の確認 if frees<6 res "人数不足,不能开始。含替身君最少要有6人。" return if query.jobrule=="特殊规则.量子LowB" && frees>=20 # 多すぎてたえられない res "人数过多。量子LowB的人数应当在19人以下。" return # 炼成LowBの場合 if query.chemical=="on" # 黑暗火锅と量子LowBは無理 if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅","特殊规则.量子LowB"] res "本规则「#{query.jobrule}」无法使用炼成LowB。" return ruleinfo_str="" # 开始告知 if query.jobrule in ["特殊规则.自由配置","特殊规则.手调黑暗火锅"] # 自由のときはクエリを参考にする for job in Shared.game.jobs joblist[job]=parseInt(query[job]) || 0 # 仕事の数 # カテゴリも for type of Shared.game.categoryNames joblist["category_#{type}"]=parseInt(query["category_#{type}"]) || 0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] # カテゴリ内の人数の合計がわかる関数 countCategory=(categoryname)-> Shared.game.categories[categoryname].reduce(((prev,curr)->prev+(joblist[curr] ? 0)),0)+joblist["category_#{categoryname}"] # 黑暗火锅のときはランダムに決める pls=frees # プレイヤーの数をとっておく plsh=Math.floor pls/2 # 過半数 if query.jobrule=="特殊规则.手调黑暗火锅" # 手调黑暗火锅のときは母猪のみ黑暗火锅 frees=joblist.Human ? 0 joblist.Human=0 ruleinfo_str = Shared.game.getrulestr query.jobrule,joblist safety={ jingais:false # 人外の数を調整 teams:false # 阵营の数を調整 jobs:false # 職どうしの数を調整 strength:false # 職の強さも考慮 reverse:false # 職の強さが逆 } switch query.yaminabe_safety when "low" # 低い safety.jingais=true when "middle" safety.jingais=true safety.teams=true when "high" safety.jingais=true safety.teams=true safety.jobs=true when "super" safety.jingais=true safety.teams=true safety.jobs=true safety.strength=true when "supersuper" safety.jobs=true safety.strength=true when "reverse" safety.jingais=true safety.strength=true safety.reverse=true # 黑暗火锅のときは入れないのがある exceptions=["MinionSelector","Thief","GameMaster","Helper","QuantumPlayer","Waiting","Watching","GotChocolate"] # ユーザーが指定した入れないの excluded_exceptions=[] # チェックボックスが外れてるやつは登場しない if query.jobrule=="特殊规则.手调黑暗火锅" for job in Shared.game.jobs if query["job_use_#{job}"] != "on" # これは出してはいけない指定になっている exceptions.push job excluded_exceptions.push job # メアリーの特殊処理(セーフティ高じゃないとでない) if query.yaminabe_hidejobs=="" || !safety.jobs exceptions.push "BloodyMary" # 悪霊憑き(人気がないので出ない) if safety.jingais || safety.jobs exceptions.push "SpiritPossessed" unless query.jobrule=="特殊规则.手调黑暗火锅" && countCategory("Werewolf")>0 #人外の数 if safety.jingais # いい感じに決めてあげる wolf_number=1 fox_number=0 vampire_number=0 devil_number=0 if frees>=9 wolf_number++ if frees>=12 if Math.random()<0.6 fox_number++ else if Math.random()<0.7 devil_number++ if frees>=14 wolf_number++ if frees>=16 if Math.random()<0.5 fox_number++ else if Math.random()<0.3 vampire_number++ else devil_number++ if frees>=18 wolf_number++ if frees>=22 if Math.random()<0.2 fox_number++ else if Math.random()<0.6 vampire_number++ else if Math.random()<0.9 devil_number++ if frees>=24 wolf_number++ if frees>=30 wolf_number++ # ランダム調整 if wolf_number>1 && Math.random()<0.1 wolf_number-- else if frees>0 && playersnumber>=10 && Math.random()<0.2 wolf_number++ if fox_number>1 && Math.random()<0.15 fox_number-- else if frees>=11 && Math.random()<0.25 fox_number++ else if frees>=8 && Math.random()<0.1 fox_number++ if frees>=11 && Math.random()<0.2 vampire_number++ if frees>=11 && Math.random()<0.2 devil_number++ # セットする if joblist.category_Werewolf>0 frees+=joblist.category_Werewolf joblist.category_Werewolf=wolf_number frees -= wolf_number if joblist.Fox>0 frees+=joblist.Fox if joblist.TinyFox>0 frees+=joblist.TinyFox if joblist.Blasphemy>0 frees+=joblist.Blasphemy joblist.Fox=0 joblist.TinyFox=0 joblist.Blasphemy=0 # 除外役職を入れないように気をつける nonavs = {} for job in exceptions nonavs[job] = true # 狐を振分け for i in [0...fox_number] if frees <= 0 break r = Math.random() if r<0.55 && !nonavs.Fox joblist.Fox++ frees-- else if r<0.85 && !nonavs.TinyFox joblist.TinyFox++ frees-- else if !nonavs.Blasphemy joblist.Blasphemy++ frees-- if joblist.Vampire>0 frees+=joblist.Vampire if vampire_number <= frees joblist.Vampire = vampire_number frees -= vampire_number else joblist.Vampire = frees frees = 0 if joblist.Devil>0 frees+=joblist.Devil if devil_number <= frees joblist.Devil = devil_number frees -= devil_number else joblist.Devil = frees frees = 0 # 人外は選んだのでもう選ばれなくする exceptions=exceptions.concat Shared.game.nonhumans exceptions.push "Blasphemy" else # 調整しない joblist.category_Werewolf=1 frees-- if safety.jingais || safety.jobs if joblist.Fox==0 && joblist.TinyFox==0 exceptions.push "Immoral" # 狐がいないのに背徳は出ない nonavs = {} for job in exceptions nonavs[job] = true if safety.teams # 阵营調整もする # 恋人阵营 if frees>0 if 17>=playersnumber>=12 if Math.random()<0.15 && !nonavs.Cupid joblist.Cupid++ frees-- else if Math.random()<0.12 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.BadLady joblist.BadLady++ frees-- else if playersnumber>=8 if Math.random()<0.15 && !nonavs.Lover joblist.Lover++ frees-- else if Math.random()<0.1 && !nonavs.Cupid joblist.Cupid++ frees-- # 妖狐陣営 if frees>0 && joblist.Fox>0 if joblist.Fox==1 if playersnumber>=14 # 1人くらいは… if Math.random()<0.3 && !nonavs.Immoral joblist.Immoral++ frees-- else # サプライズ的に… if Math.random()<0.1 && !nonavs.Immoral joblist.Immoral++ frees-- exceptions.push "Immoral" # LowB阵营 if frees>0 wolf_number = countCategory "Werewolf" if wolf_number<=playersnumber/8 # 確定狂人サービス joblist.category_Madman ?= 0 joblist.category_Madman++ frees-- # 占い確定 if safety.teams || safety.jobs # 母猪阵营 if frees>0 # 占い師いてほしい if Math.random()<0.8 && !nonavs.Diviner joblist.Diviner++ frees-- else if !safety.jobs && Math.random()<0.3 && !nonavs.ApprenticeSeer joblist.ApprenticeSeer++ frees-- if safety.teams # できれば猎人も if frees>0 if joblist.Diviner>0 if Math.random()<0.5 && !nonavs.Guard joblist.Guard++ frees-- else if Math.random()<0.2 && !nonavs.Guard joblist.Guard++ frees-- ((date)-> month=date.getMonth() d=date.getDate() if month==11 && 24<=d<=25 # 12/24〜12/25はサンタがよくでる if Math.random()<0.5 && frees>0 && !nonavs.SantaClaus joblist.SantaClaus ?= 0 joblist.SantaClaus++ frees-- else # サンタは出にくい if Math.random()<0.8 exceptions.push "SantaClaus" unless month==6 && 26<=d || month==7 && d<=16 # 期間外は烟火师は出にくい if Math.random()<0.7 exceptions.push "Pyrotechnist" else # ちょっと出やすい if Math.random()<0.11 && frees>0 && !nonavs.Pyrotechnist joblist.Pyrotechnist ?= 0 joblist.Pyrotechnist++ frees-- if month==11 && 24<=d<=25 || month==1 && d==14 # 爆弾魔がでやすい if Math.random()<0.5 && frees>0 && !nonavs.Bomber joblist.Bomber ?= 0 joblist.Bomber++ frees-- if month==1 && 13<=d<=14 # パティシエールが出やすい if Math.random()<0.4 && frees>0 && !nonavs.Patissiere joblist.Patissiere ?= 0 joblist.Patissiere++ frees-- else # 出にくい if Math.random()<0.84 exceptions.push "Patissiere" if month==0 && d<=3 # 正月は巫女がでやすい if Math.random()<0.35 && frees>0 && !nonavs.Miko joblist.Miko ?= 0 joblist.Miko++ frees-- if month==3 && d==1 # 4月1日は嘘つきがでやすい if Math.random()<0.5 && !nonavs.Liar while frees>0 joblist.Liar ?= 0 joblist.Liar++ frees-- if Math.random()<0.75 break if month==11 && d==31 || month==0 && 4<=d<=7 # 獅子舞の季節 if Math.random()<0.5 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else if month==0 && 1<=d<=3 # 獅子舞の季節(真) if Math.random()<0.7 && frees>0 && !nonavs.Shishimai joblist.Shishimai ?= 0 joblist.Shishimai++ frees-- else # 狮子舞がでにくい季節 if Math.random()<0.8 exceptions.push "Shishimai" if month==9 && 30<=d<=31 # ハロウィンなので南瓜 if Math.random()<0.4 && frees>0 && !nonavs.Pumpkin joblist.Pumpkin ?= 0 joblist.Pumpkin++ frees-- else if Math.random()<0.2 exceptions.push "Pumpkin" )(new Date) possibility=Object.keys(jobs).filter (x)->!(x in exceptions) if possibility.length == 0 # 0はまずい possibility.push "Human" # 強制的に入れる関数 init=(jobname,categoryname)-> unless jobname in possibility return false if categoryname? && joblist["category_#{categoryname}"]>0 # あった joblist[jobname]++ joblist["category_#{categoryname}"]-- return true if frees>0 # あった joblist[jobname]++ frees-- return true return false # 安全性超用 trial_count=0 trial_max=if safety.strength then 40 else 1 best_list=null best_points=null if safety.reverse best_diff=-Infinity else best_diff=Infinity first_list=joblist first_frees=frees # チームのやつキャッシュ teamCache={} getTeam=(job)-> if teamCache[job]? return teamCache[job] for team of Shared.game.teams if job in Shared.game.teams[team] teamCache[job]=team return team return null while trial_count++ < trial_max joblist=copyObject first_list #wolf_teams=countCategory "Werewolf" wolf_teams=0 frees=first_frees while true category=null job=null #カテゴリ职业がまだあるか探す for type,arr of Shared.game.categories if joblist["category_#{type}"]>0 # カテゴリの中から候補をしぼる arr2 = arr.filter (x)->!(x in excluded_exceptions) if arr2.length > 0 r=Math.floor Math.random()*arr2.length job=arr2[r] category="category_#{type}" break else # これもう無理だわ joblist["category_#{type}"] = 0 unless job? # もうカテゴリがない if frees<=0 # もう空きがない break r=Math.floor Math.random()*possibility.length job=possibility[r] if safety.teams && !category? if job in Shared.game.teams.Werewolf if wolf_teams+1>=plsh # LowBが過半数を越えた(PP) continue if safety.jobs # 職どうしの兼ね合いを考慮 switch job when "Psychic","RedHood" # 1人のとき灵能は意味ない if countCategory("Werewolf")==1 # 狼1人だと灵能が意味ない continue when "Couple" # 共有者はひとりだと寂しい if joblist.Couple==0 unless init "Couple","Human" #共有者が入る隙間はない continue when "Noble" # 贵族は奴隶がほしい if joblist.Slave==0 unless init "Slave","Human" continue when "Slave" if joblist.Noble==0 unless init "Noble","Human" continue when "OccultMania" if joblist.Diviner==0 && Math.random()<0.5 # 占卜师いないと出现確率低い continue when "QueenSpectator" # 2人いたらだめ if joblist.QueenSpectator>0 || joblist.Spy2>0 || joblist.BloodyMary>0 continue if Math.random()>0.1 # 90%の確率で弾く continue # 女王观战者はガードがないと不安 if joblist.Guard==0 && joblist.Priest==0 && joblist.Trapper==0 unless Math.random()<0.4 && init "Guard","Human" unless Math.random()<0.5 && init "Priest","Human" unless init "Trapper","Human" # 护卫がいない continue when "Spy2" # 间谍IIは2人いるとかわいそうなので入れない if joblist.Spy2>0 || joblist.QueenSpectator>0 continue else if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "MadWolf" if Math.random()>0.1 # 90%の確率で弾く(レア) continue when "Lycan","SeersMama","Sorcerer","WolfBoy","ObstructirveMad" # 占い系がいないと入れない if joblist.Diviner==0 && joblist.ApprenticeSeer==0 && joblist.PI==0 continue when "LoneWolf","FascinatingWolf","ToughWolf","WolfCub" # 魅惑的女狼はほかにLowBがいないと効果発揮しない # 硬汉LowBはほかに狼いないと微妙、一匹狼は1人だけででると狂人が絶望 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue when "BigWolf" # 強いので狼2以上 if countCategory("Werewolf")-(if category? then 1 else 0)==0 continue # 灵能を出す unless Math.random()<0.15 || init "Psychic","Human" continue when "BPI:NAME:<NAME>END_PIodyMary" # 狼が2以上必要 if countCategory("Werewolf")<=1 continue # 女王とは共存できない if joblist.QueenSpectator>0 continue when "SpiritPossessed" # 2人いるとうるさい if joblist.SpiritPossessed > 0 continue joblist[job]++ # ひとつ追加 if category? joblist[category]-- else frees-- if safety.teams && (job in Shared.game.teams.Werewolf) wolf_teams++ # LowB阵营が増えた # 安全性超の場合判定が入る if safety.strength # ポイントを計算する points= Human:0 Werewolf:0 Others:0 for job of jobStrength if joblist[job]>0 switch getTeam(job) when "Human" points.Human+=jobStrength[job]*joblist[job] when "Werewolf" points.Werewolf+=jobStrength[job]*joblist[job] else points.Others+=jobStrength[job]*joblist[job] # 判定する if points.Others>points.Human || points.Others>points.Werewolf # だめだめ continue # jgs=Math.sqrt(points.Werewolf*points.Werewolf+points.Others*points.Others) jgs = points.Werewolf+points.Others diff=Math.abs(points.Human-jgs) if safety.reverse # 逆 diff+=points.Others if diff>best_diff best_list=copyObject joblist best_diff=diff best_points=points else if diff<best_diff best_list=copyObject joblist best_diff=diff best_points=points #console.log "diff:#{diff}" #console.log best_list if safety.strength && best_list? # 安全性超 joblist=best_list else if query.jobrule=="特殊规则.量子LowB" # 量子LowBのときは全员量子人类だけど职业はある func=Shared.game.getrulefunc "内部利用.量子LowB" joblist=func frees sum=0 for job of jobs if joblist[job] sum+=joblist[job] joblist.Human=frees-sum # 残りは母猪だ! list_for_rule = JSON.parse JSON.stringify joblist ruleobj.quantum_joblist=joblist # LowBの順位を決めていく i=1 while joblist.Werewolf>0 joblist["Werewolf#{i}"]=1 joblist.Werewolf-=1 i+=1 delete joblist.Werewolf # 量子LowB用 joblist={ QuantumPlayer:frees } for job of jobs unless joblist[job]? joblist[job]=0 ruleinfo_str=Shared.game.getrulestr query.jobrule,list_for_rule else if query.jobrule!="特殊规则.自由配置" # 配置に従ってアレする func=Shared.game.getrulefunc query.jobrule unless func res "不明的配置" return joblist=func frees sum=0 # 穴を埋めつつ合計数える for job of jobs unless joblist[job]? joblist[job]=0 else sum+=joblist[job] # カテゴリも for type of Shared.game.categoryNames if joblist["category_#{type}"]>0 sum-=parseInt joblist["category_#{type}"] # 残りは母猪だ! if query.chemical == "on" # 炼成LowBなので母猪が大い joblist.Human = frees * 2 - sum else joblist.Human=frees-sum ruleinfo_str=Shared.game.getrulestr query.jobrule,joblist if query.yaminabe_hidejobs!="" && query.jobrule!="特殊规则.黑暗火锅" && query.jobrule!="特殊规则.Endless黑暗火锅" # 黑暗火锅以外で配役情報を公開しないときはアレする ruleinfo_str = "" if query.chemical == "on" # ケミカルLowBの場合は表示 ruleinfo_str = "炼成LowB " + (ruleinfo_str ? "") if (joblist.WolfBoy>0 || joblist.ObstructiveMad>0 || joblist.Pumpkin>0) && query.divineresult=="immediate" query.divineresult="sunrise" log= mode:"system" comment:"由于存在能够左右占卜结果的职业,占卜结果从「立刻知道」变更为「天亮才知道」。" splashlog game.id,game,log if ruleinfo_str != "" # 表示すべき情報がない場合は表示しない log= mode:"system" comment:"配置: #{ruleinfo_str}" splashlog game.id,game,log if query.jobrule == "特殊规则.手调黑暗火锅" && excluded_exceptions.length > 0 # 除外职业の情報を表示する exclude_str = excluded_exceptions.map((job)-> Shared.game.getjobname job).join ", " log= mode:"system" comment:"除外职业:#{exclude_str}" splashlog game.id,game,log if query.yaminabe_hidejobs=="team" # 陣営のみ公開モード # 各陣営 teaminfos=[] for team,obj of Shared.game.jobinfo teamcount=0 for job,num of joblist #出现职业チェック continue if num==0 if obj[job]? # この阵营だ teamcount+=num if teamcount>0 teaminfos.push "#{obj.name}#{teamcount}" #阵营名 log= mode:"system" comment:"出场阵营信息: "+teaminfos.join(" ") splashlog game.id,game,log if query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.Endless黑暗火锅"] if query.yaminabe_hidejobs=="" # 黑暗火锅用の职业公開ログ jobinfos=[] for job,num of joblist continue if num==0 jobinfos.push "#{Shared.game.getjobname job}#{num}" log= mode:"system" comment:"出场职业: "+jobinfos.join(" ") splashlog game.id,game,log for x in ["jobrule", "decider","authority","scapegoat","will","wolfsound","couplesound","heavenview", "wolfattack","guardmyself","votemyself","deadfox","deathnote","divineresult","psychicresult","waitingnight", "safety","friendsjudge","noticebitten","voteresult","GMpsychic","wolfminion","drunk","losemode","gjmessage","rolerequest","runoff","chemical", "poisonwolf", "friendssplit", "quantumwerewolf_table","quantumwerewolf_dead","quantumwerewolf_diviner","quantumwerewolf_firstattack","yaminabe_hidejobs","yaminabe_safety"] ruleobj[x]=query[x] ? null game.setrule ruleobj # 配置リストをセット game.joblist=joblist game.startoptions=options game.startplayers=players game.startsupporters=supporters if ruleobj.rolerequest=="on" && !(query.jobrule in ["特殊规则.黑暗火锅","特殊规则.手调黑暗火锅","特殊规则.量子LowB","特殊规则.Endless黑暗火锅"]) # 希望役职制あり # とりあえず入れなくする M.rooms.update {id:roomid},{$set:{mode:"playing"}} # 职业选择中 game.rolerequestingphase=true # ここ書いてないよ! game.rolerequesttable={} res null log= mode:"system" comment:"本场游戏采取了希望役职制,请选择希望就职的职业。" splashlog game.id,game,log game.timer() ss.publish.channel "room#{roomid}","refresh",{id:roomid} else game.setplayers (result)-> unless result? # プレイヤー初期化に成功 M.rooms.update {id:roomid},{ $set:{ mode:"playing", jobrule:query.jobrule } } game.nextturn() res null ss.publish.channel "room#{roomid}","refresh",{id:roomid} else res result # 情報を開示 getlog:(roomid)-> M.games.findOne {id:roomid}, (err,doc)=> if err? console.error err callback err,null else if !doc? callback "游戏不存在",null else unless games[roomid]? games[roomid] = Game.unserialize doc,ss game = games[roomid] # ゲーム後の行動 player=game.getPlayerReal req.session.userId result= #logs:game.logs.filter (x)-> islogOK game,player,x logs:game.makelogs (doc.logs ? []), player result=makejobinfo game,player,result result.timer=if game.timerid? game.timer_remain-(Date.now()/1000-game.timer_start) # 全体 - 経過时间 else null result.timer_mode=game.timer_mode if game.day==0 # 开始前はプレイヤー情報配信しない delete result.game.players res result speak: (roomid,query)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless query? res "无效操作" return comment=query.comment unless comment res "没有简介" return player=game.getPlayerReal req.session.userId #console.log query,player log = comment:comment userid:req.session.userId name:player?.name ? req.session.user.name to:null if query.size in ["big","small"] log.size=query.size # ログを流す dosp=-> if !game.finished && game.voting # 投票犹豫时间は发言できない if player && !player.dead && !player.isJobType("GameMaster") return #まだ死んでいないプレイヤーの場合は发言できないよ! if game.day<=0 || game.finished #準備中 unless log.mode=="audience" log.mode="prepare" if player?.isJobType "GameMaster" log.mode="gm" #log.name="游戏管理员" else # 游戏している unless player? # 观战者 log.mode="audience" else if player.dead # 天国 if player.isJobType "Spy" && player.flag=="spygone" # 间谍なら会話に参加できない log.mode="monologue" log.to=player.id else if query.mode=="monologue" # 霊界の独り言 log.mode="heavenmonologue" else log.mode="heaven" else if !game.night # 昼 unless query.mode in player.getSpeakChoiceDay game return log.mode=query.mode if game.silentexpires && game.silentexpires>=Date.now() # まだ发言できない(15秒规则) return else # 夜 unless query.mode in player.getSpeakChoice game query.mode="monologue" log.mode=query.mode switch log.mode when "monologue","heavenmonologue","helperwhisper" # helperwhisper:守り先が決まっていないヘルパー log.to=player.id when "heaven" # 霊界の発言は悪霊憑きの発言になるかも if !game.night && !game.voting && !(game.silentexpires && game.silentexpires >= Date.now()) possessions = game.players.filter (x)-> !x.dead && x.isJobType "SpiritPossessed" if possessions.length > 0 # 悪魔憑き r = Math.floor (Math.random()*possessions.length) pl = possessions[r] # 悪魔憑きのプロパティ log.possess_name = pl.name log.possess_id = pl.id when "gm" log.name="GM→所有人" when "gmheaven" log.name="GM→灵界" when "gmaudience" log.name="GM→观战者" when "gmmonologue" log.name="GM自言自语" when "prepare" # ごちゃごちゃ言わない else if result=query.mode?.match /^gmreply_(.+)$/ log.mode="gmreply" pl=game.getPlayer result[1] unless pl? return log.to=pl.id log.name="GM→#{pl.name}" else if result=query.mode?.match /^helperwhisper_(.+)$/ log.mode="helperwhisper" log.to=result[1] splashlog roomid,game,log res null if player? log.name=player.name log.userid=player.id dosp() else # 房间情報から探す Server.game.rooms.oneRoomS roomid,(room)=> pl=room.players.filter((x)=>x.realid==req.session.userId)[0] if pl? log.name=pl.name else log.mode="audience" dosp() # 夜の仕事・投票 job:(roomid,query)-> game=games[roomid] unless game? res {error:"游戏不存在"} return unless req.session.userId res {error:"请登陆"} return player=game.getPlayerReal req.session.userId unless player? res {error:"没有加入游戏"} return unless player in game.participants res {error:"没有加入游戏"} return ### if player.dead && player.deadJobdone game res {error:"你已经死了"} return ### jt=player.getjob_target() sl=player.makeJobSelection game ### if !(to=game.players.filter((x)->x.id==query.target)[0]) && jt!=0 res {error:"这个对象不存在"} return if to?.dead && (!(jt & Player.JOB_T_DEAD) || !game.night) && (jt & Player.JOB_T_ALIVE) res {error:"对象已经死亡"} return ### unless player.checkJobValidity game,query res {error:"对象选择无效"} return if game.night || query.jobtype!="_day" # 昼の投票 # 夜 ### if !to?.dead && !(player.job_target & Player.JOB_T_ALIVE) && (player.job_target & Player.JOB_T_DEAD) res {error:"対象はまだ生きています"} return ### if (player.dead && player.deadJobdone(game)) || (!player.dead && player.jobdone(game)) res {error:"已经使用了能力"} return unless player.isJobType query.jobtype res {error:"职业错误"} return # 错误メッセージ if ret=player.job game,query.target,query console.log "err!",ret res {error:ret} return # 能力発動を記録 game.addGamelog { id:player.id type:query.jobtype target:query.target event:"job" } # 能力をすべて発動したかどうかチェック #res {sleeping:player.jobdone(game)} res makejobinfo game,player if game.night || game.day==0 game.checkjobs() else # 投票 ### if @votingbox.isVoteFinished player res {error:"既に投票しています"} return if query.target==player.id && game.rule.votemyself!="ok" res {error:"自己には投票できません"} return to=game.getPlayer query.target unless to? res {error:"その人には投票できません"} return ### unless player.checkJobValidity game,query res {error:"请选择对象"} return err=player.dovote game,query.target if err? res {error:err} return #player.dovote query.target # 投票が終わったかチェック game.addGamelog { id:player.id type:player.type target:query.target event:"vote" } res makejobinfo game,player game.execute() #遗言 will:(roomid,will)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return unless !game.rule || game.rule.will res "不能使用遗言" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.dead res "你已经死了" return player.setWill will res null #拒绝复活 norevive:(roomid)-> game=games[roomid] unless game? res "游戏不存在" return unless req.session.userId res "请登陆" return player=game.getPlayerReal req.session.userId unless player? res "没有加入游戏" return if player.norevive res "已经不可复活" return player.setNorevive true log= mode:"userinfo" comment:"#{player.name} 拒绝复活。" to:player.id splashlog roomid,game,log # 全员に通知 game.splashjobinfo() res null splashlog=(roomid,game,log)-> log.time=Date.now() # 時間を付加 #DBに追加 M.games.update {id:roomid},{$push:{logs:log}} flash=(log)-> # まず観戦者 aulogs = makelogsFor game, null, log for x in aulogs x.roomid = roomid game.ss.publish.channel "room#{roomid}_audience","log",x # GM #if game.gm&&!rev # game.ss.publish.channel "room#{roomid}_gamemaster","log",log # 其他 game.participants.forEach (pl)-> ls = makelogsFor game, pl, log for x in ls x.roomid = roomid game.ss.publish.user pl.realid,"log",x flash log # ある人に見せたいログ makelogsFor=(game,player,log)-> if islogOK game, player, log if log.mode=="heaven" && log.possess_name? # 両方見える感じで otherslog= mode:"half-day" comment: log.comment name: log.possess_name time: log.time size: log.size return [log, otherslog] return [log] if log.mode=="werewolf" && game.rule.wolfsound=="aloud" # 狼的远吠が能听到 otherslog= mode:"werewolf" comment:"嗷呜・・・" name:"狼的远吠" time:log.time return [otherslog] if log.mode=="couple" && game.rule.couplesound=="aloud" # 共有者の小声が聞こえる otherslog= mode:"couple" comment:"沙沙・・・" name:"共有者的低语声" time:log.time return [otherslog] if log.mode=="heaven" && log.possess_name? # 昼の霊界発言 with 悪魔憑き otherslog = mode:"day" comment: log.comment name:log.possess_name time:log.time size:log.size return [otherslog] return [] # プレイヤーにログを見せてもよいか islogOK=(game,player,log)-> # player: Player / null return true if game.finished # 终了ならtrue return true if player?.isJobType "GameMaster" unless player? # 观战者 if log.mode in ["day","system","prepare","nextturn","audience","will","gm","gmaudience","probability_table"] !log.to? # 观战者にも公開 else if log.mode=="voteresult" game.rule.voteresult!="hide" # 投票结果公開なら公開 else false # 其他は非公開 else if log.mode=="gmmonologue" # GM自言自语はGMにしか見えない false else if player.dead && game.heavenview true else if log.mode=="heaven" && log.possess_name? # 恶灵凭依についている霊界発言 false else if log.to? && log.to!=player.id # 個人宛 if player.isJobType "Helper" log.to==player.flag # ヘルプ先のも見える else false else player.isListener game,log #job情報を makejobinfo = (game,player,result={})-> result.type= if player? then player.getTypeDisp() else null # job情報表示するか actpl=player if player? if player instanceof Helper actpl=game.getPlayer player.flag unless actpl? #あれっ actpl=player is_gm = actpl?.isJobType("GameMaster") openjob_flag=game.finished || (actpl?.dead && game.heavenview) || is_gm result.openjob_flag = openjob_flag result.game=game.publicinfo({ openjob: openjob_flag gm: is_gm }) # 終了か霊界(ルール設定あり)の場合は職情報公開 result.id=game.id if player # 参加者としての(perticipantsは除く) plpl=game.getPlayer player.id player.makejobinfo game,result result.dead=player.dead result.voteopen=false result.sleeping=true # 投票が终了したかどうか(表单表示するかどうか判断) if plpl? # 参加者として if game.night || game.day==0 if player.dead result.sleeping=player.deadJobdone game else result.sleeping=player.jobdone game else # 昼 result.sleeping=true unless player.dead || game.votingbox.isVoteFinished player # 投票ボックスオープン!!! result.voteopen=true result.sleeping=false if player.chooseJobDay game # 昼でも能力発動できる人 result.sleeping &&= player.jobdone game else # それ以外(participants) result.sleeping=if game.night then player.jobdone(game) else true result.jobname=player.getJobDisp() result.winner=player.winner if game.night || game.day==0 result.speak =player.getSpeakChoice game else result.speak =player.getSpeakChoiceDay game if game.rule?.will=="die" result.will=player.will result # 配列シャッフル(破壊的) shuffle= (arr)-> ret=[] while arr.length ret.push arr.splice(Math.floor(Math.random()*arr.length),1)[0] ret # 游戏情報ツイート tweet=(roomid,message)-> Server.oauth.template roomid,message,Config.PI:PASSWORD:<PASSWORD>END_PI
[ { "context": "rbitrary-sized positive integers\n# Author: Austin Ewens (aewens)\n# Copyright: (C) Austin Ewens 2015\n", "end": 157, "score": 0.9998970031738281, "start": 145, "tag": "NAME", "value": "Austin Ewens" }, { "context": "positive integers\n# Author: Aus...
src/pasta.coffee
aewens/pastajs
0
# File: pasta.js # Version: 0.1 # Purpose: Utility for doing math to arbitrary-sized positive integers # Author: Austin Ewens (aewens) # Copyright: (C) Austin Ewens 2015 define [], () -> class Pasta constructor: (value) -> return "Not a string" unless typeof value is "string" @value = value @ int: (value) -> return if value is undefined then parseInt(@value, 10) else parseInt(value, 10) check: (foreign) -> foreign = new Pasta(foreign) unless foreign instanceof Pasta return null if foreign.value is undefined return foreign rev: (value) -> return if value is undefined then @value.split("").reverse().join("") else value.split("").reverse().join("") pad: (a, b) -> return @pad(a, "0" + b) if a.length > b.length return @pad("0" + a, b) if a.length < b.length return [a, b] if a.length is b.length unpad: (c) -> if c is undefined if @value[0] is "0" then return @unpad(@value.substr(1)) else return @value else if c[0] is "0" then return @unpad(c.substr(1)) else return c zeros: (a, zs) -> if zs is 0 then return a else @zeros(a.concat("0"), zs - 1) add: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) ab = "" + (ia + ib + c) if ab.length > 1 c = @int(ab[0]) ab = ab[1] else c = 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ sub: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) cc = false if (ia - c) < ib ia = ia + 10 cc = true ab = "" + ((ia - c) - ib) c = if cc then 1 else 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ mul: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = new Pasta("0") cc = [] for i in [0...len] ib = @int(bb[i]) continue if ib is 0 for j in [0...len] ia = @int(aa[j]) continue if ia is 0 ab = @zeros(""+(ia * ib), j) cc.push(@zeros(ab, i)) res.add(cc[c]) for c in [0...cc.length] @value = res.value @ _exp: (a, b, xs) -> if b.unpad() is "" then return xs else bb = b.sub("1") xs.push(a) @_exp(a, bb, xs) exp: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other res = new Pasta("1") xs = @_exp(a, b, []) res.mul(xs[x]) for x in [0...xs.length] @value = res.value @ return Pasta
23256
# File: pasta.js # Version: 0.1 # Purpose: Utility for doing math to arbitrary-sized positive integers # Author: <NAME> (aewens) # Copyright: (C) <NAME> 2015 define [], () -> class Pasta constructor: (value) -> return "Not a string" unless typeof value is "string" @value = value @ int: (value) -> return if value is undefined then parseInt(@value, 10) else parseInt(value, 10) check: (foreign) -> foreign = new Pasta(foreign) unless foreign instanceof Pasta return null if foreign.value is undefined return foreign rev: (value) -> return if value is undefined then @value.split("").reverse().join("") else value.split("").reverse().join("") pad: (a, b) -> return @pad(a, "0" + b) if a.length > b.length return @pad("0" + a, b) if a.length < b.length return [a, b] if a.length is b.length unpad: (c) -> if c is undefined if @value[0] is "0" then return @unpad(@value.substr(1)) else return @value else if c[0] is "0" then return @unpad(c.substr(1)) else return c zeros: (a, zs) -> if zs is 0 then return a else @zeros(a.concat("0"), zs - 1) add: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) ab = "" + (ia + ib + c) if ab.length > 1 c = @int(ab[0]) ab = ab[1] else c = 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ sub: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) cc = false if (ia - c) < ib ia = ia + 10 cc = true ab = "" + ((ia - c) - ib) c = if cc then 1 else 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ mul: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = new Pasta("0") cc = [] for i in [0...len] ib = @int(bb[i]) continue if ib is 0 for j in [0...len] ia = @int(aa[j]) continue if ia is 0 ab = @zeros(""+(ia * ib), j) cc.push(@zeros(ab, i)) res.add(cc[c]) for c in [0...cc.length] @value = res.value @ _exp: (a, b, xs) -> if b.unpad() is "" then return xs else bb = b.sub("1") xs.push(a) @_exp(a, bb, xs) exp: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other res = new Pasta("1") xs = @_exp(a, b, []) res.mul(xs[x]) for x in [0...xs.length] @value = res.value @ return Pasta
true
# File: pasta.js # Version: 0.1 # Purpose: Utility for doing math to arbitrary-sized positive integers # Author: PI:NAME:<NAME>END_PI (aewens) # Copyright: (C) PI:NAME:<NAME>END_PI 2015 define [], () -> class Pasta constructor: (value) -> return "Not a string" unless typeof value is "string" @value = value @ int: (value) -> return if value is undefined then parseInt(@value, 10) else parseInt(value, 10) check: (foreign) -> foreign = new Pasta(foreign) unless foreign instanceof Pasta return null if foreign.value is undefined return foreign rev: (value) -> return if value is undefined then @value.split("").reverse().join("") else value.split("").reverse().join("") pad: (a, b) -> return @pad(a, "0" + b) if a.length > b.length return @pad("0" + a, b) if a.length < b.length return [a, b] if a.length is b.length unpad: (c) -> if c is undefined if @value[0] is "0" then return @unpad(@value.substr(1)) else return @value else if c[0] is "0" then return @unpad(c.substr(1)) else return c zeros: (a, zs) -> if zs is 0 then return a else @zeros(a.concat("0"), zs - 1) add: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) ab = "" + (ia + ib + c) if ab.length > 1 c = @int(ab[0]) ab = ab[1] else c = 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ sub: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = "" c = 0 for i in [0...len] ia = @int(aa[i]) ib = @int(bb[i]) cc = false if (ia - c) < ib ia = ia + 10 cc = true ab = "" + ((ia - c) - ib) c = if cc then 1 else 0 res = res.concat(ab) res = res.concat(c) res = @rev(res) @value = res @ mul: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other.value pab = @pad(a, b) aa = @rev(pab[0]) bb = @rev(pab[1]) len = (aa.length + bb.length) / 2 res = new Pasta("0") cc = [] for i in [0...len] ib = @int(bb[i]) continue if ib is 0 for j in [0...len] ia = @int(aa[j]) continue if ia is 0 ab = @zeros(""+(ia * ib), j) cc.push(@zeros(ab, i)) res.add(cc[c]) for c in [0...cc.length] @value = res.value @ _exp: (a, b, xs) -> if b.unpad() is "" then return xs else bb = b.sub("1") xs.push(a) @_exp(a, bb, xs) exp: (foreign) -> other = @check(foreign) return "Invalid input: #{foreign}" if other is null a = @value b = other res = new Pasta("1") xs = @_exp(a, b, []) res.mul(xs[x]) for x in [0...xs.length] @value = res.value @ return Pasta
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993101954460144, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-fs-stat.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") got_error = false success_count = 0 fs.stat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return fs.stat ".", (err, stats) -> assert.ok stats.hasOwnProperty("blksize") assert.ok stats.hasOwnProperty("blocks") return fs.lstat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return # fstat fs.open ".", "r", `undefined`, (err, fd) -> assert.ok not err assert.ok fd fs.fstat fd, (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd assert this is global return assert this is global return # fstatSync fs.open ".", "r", `undefined`, (err, fd) -> stats = undefined try stats = fs.fstatSync(fd) catch err got_error = true if stats console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd return console.log "stating: " + __filename fs.stat __filename, (err, s) -> if err got_error = true else console.dir s success_count++ console.log "isDirectory: " + JSON.stringify(s.isDirectory()) assert.equal false, s.isDirectory() console.log "isFile: " + JSON.stringify(s.isFile()) assert.equal true, s.isFile() console.log "isSocket: " + JSON.stringify(s.isSocket()) assert.equal false, s.isSocket() console.log "isBlockDevice: " + JSON.stringify(s.isBlockDevice()) assert.equal false, s.isBlockDevice() console.log "isCharacterDevice: " + JSON.stringify(s.isCharacterDevice()) assert.equal false, s.isCharacterDevice() console.log "isFIFO: " + JSON.stringify(s.isFIFO()) assert.equal false, s.isFIFO() console.log "isSymbolicLink: " + JSON.stringify(s.isSymbolicLink()) assert.equal false, s.isSymbolicLink() assert.ok s.mtime instanceof Date return process.on "exit", -> assert.equal 5, success_count assert.equal false, got_error return
17808
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") got_error = false success_count = 0 fs.stat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return fs.stat ".", (err, stats) -> assert.ok stats.hasOwnProperty("blksize") assert.ok stats.hasOwnProperty("blocks") return fs.lstat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return # fstat fs.open ".", "r", `undefined`, (err, fd) -> assert.ok not err assert.ok fd fs.fstat fd, (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd assert this is global return assert this is global return # fstatSync fs.open ".", "r", `undefined`, (err, fd) -> stats = undefined try stats = fs.fstatSync(fd) catch err got_error = true if stats console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd return console.log "stating: " + __filename fs.stat __filename, (err, s) -> if err got_error = true else console.dir s success_count++ console.log "isDirectory: " + JSON.stringify(s.isDirectory()) assert.equal false, s.isDirectory() console.log "isFile: " + JSON.stringify(s.isFile()) assert.equal true, s.isFile() console.log "isSocket: " + JSON.stringify(s.isSocket()) assert.equal false, s.isSocket() console.log "isBlockDevice: " + JSON.stringify(s.isBlockDevice()) assert.equal false, s.isBlockDevice() console.log "isCharacterDevice: " + JSON.stringify(s.isCharacterDevice()) assert.equal false, s.isCharacterDevice() console.log "isFIFO: " + JSON.stringify(s.isFIFO()) assert.equal false, s.isFIFO() console.log "isSymbolicLink: " + JSON.stringify(s.isSymbolicLink()) assert.equal false, s.isSymbolicLink() assert.ok s.mtime instanceof Date return process.on "exit", -> assert.equal 5, success_count assert.equal false, got_error return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") fs = require("fs") got_error = false success_count = 0 fs.stat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return fs.stat ".", (err, stats) -> assert.ok stats.hasOwnProperty("blksize") assert.ok stats.hasOwnProperty("blocks") return fs.lstat ".", (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ assert this is global return # fstat fs.open ".", "r", `undefined`, (err, fd) -> assert.ok not err assert.ok fd fs.fstat fd, (err, stats) -> if err got_error = true else console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd assert this is global return assert this is global return # fstatSync fs.open ".", "r", `undefined`, (err, fd) -> stats = undefined try stats = fs.fstatSync(fd) catch err got_error = true if stats console.dir stats assert.ok stats.mtime instanceof Date success_count++ fs.close fd return console.log "stating: " + __filename fs.stat __filename, (err, s) -> if err got_error = true else console.dir s success_count++ console.log "isDirectory: " + JSON.stringify(s.isDirectory()) assert.equal false, s.isDirectory() console.log "isFile: " + JSON.stringify(s.isFile()) assert.equal true, s.isFile() console.log "isSocket: " + JSON.stringify(s.isSocket()) assert.equal false, s.isSocket() console.log "isBlockDevice: " + JSON.stringify(s.isBlockDevice()) assert.equal false, s.isBlockDevice() console.log "isCharacterDevice: " + JSON.stringify(s.isCharacterDevice()) assert.equal false, s.isCharacterDevice() console.log "isFIFO: " + JSON.stringify(s.isFIFO()) assert.equal false, s.isFIFO() console.log "isSymbolicLink: " + JSON.stringify(s.isSymbolicLink()) assert.equal false, s.isSymbolicLink() assert.ok s.mtime instanceof Date return process.on "exit", -> assert.equal 5, success_count assert.equal false, got_error return
[ { "context": "e66e209\n vpc_id: vpc-ef17be8a\n ssh_username: ubuntu\n tags:\n Name: koding-test\n - type: virtu", "end": 2321, "score": 0.9939321875572205, "start": 2315, "tag": "USERNAME", "value": "ubuntu" }, { "context": "ubuntu-14.04.2-server-amd64.iso'\n ssh_us...
client/app/lib/util/stacks/defaulttemplate.coffee
lionheart1022/koding
0
module.exports = { json: ''' { "provider": { "aws": { "access_key": "${var.aws_access_key}", "secret_key": "${var.aws_secret_key}" } }, "resource": { "aws_instance": { "example-instance": { "tags": { "Name": "${var.koding_user_username}-${var.koding_group_slug}" }, "instance_type": "t2.nano", "ami": "", "user_data": "\\necho \\\"hello world!\\\" >> /helloworld.txt\\n" } } } } ''' yaml: ''' # Here is your stack preview # You can make advanced changes like modifying your VM, # installing packages, and running shell commands. provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' resource: aws_instance: # this is the name of your VM example-instance: # select your instance_type here: eg. c3.xlarge instance_type: t2.nano # select your ami (optional) eg. ami-xxxxx (it should be based on ubuntu 14.04) ami: '' # we will tag the instance here so you can identify it when you login to your AWS console tags: Name: '${var.koding_user_username}-${var.koding_group_slug}' # on user_data section we will write bash and configure our VM user_data: |- # let's create a file on your root folder: echo "hello world!" >> /helloworld.txt # please note: all commands under user_data will be run as root. # now add your credentials and save this stack. # once vm finishes building, you can see this file by typing # ls / # # for more information please click the link below "Stack Script Docs" ''' } ### Full YAML Example provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' github: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' builders: - type: amazon-ebs access_key: '{{user `aws_access_key`}}' secret_key: '{{user `aws_secret_key`}}' ami_name: 'koding-base-latest-{{timestamp}}' ami_description: Koding Base Image instance_type: m3.medium region: ap-northeast-1 source_ami: ami-9e5cff9e subnet_id: subnet-7e66e209 vpc_id: vpc-ef17be8a ssh_username: ubuntu tags: Name: koding-test - type: virtualbox-iso disk_size: 40960 guest_os_type: Ubuntu_64 http_directory: http iso_checksum: 83aabd8dcf1e8f469f3c72fff2375195 iso_checksum_type: md5 iso_url: 'http://releases.ubuntu.com/14.04/ubuntu-14.04.2-server-amd64.iso' ssh_username: vagrant ssh_password: vagrant ssh_port: 22 ssh_wait_timeout: 10000 shutdown_command: "echo 'shutdown -P now' > /tmp/shutdown.sh; echo 'vagrant'|sudo -S sh '/tmp/shutdown.sh'" vboxmanage: - - modifyvm - '{{.Name}}' - '--memory' - '512' - - modifyvm - '{{.Name}}' - '--cpus' - '1' provisioners: - type: shell inline: - 'echo ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub' - 'echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa' - chmod 600 ~/.ssh/ - 'git clone git@github.com:${var.github_username}/${lookup(var.github_reponames, 0)}.git' - 'git clone git@github.com:${var.github_username}/${lookup(var.github_reponames, 1)}.git' resource: aws_instance: web: source_dest_check: false user_data: "\necho ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub\n&& echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa\n&& chmod 600 ~/.ssh/*\n&& git clone git@github.com:${var.github_username}/${lookup(var.github_reponames, 0)}.git \n&& git clone git@github.com:${var.github_username}/${lookup(var.github_reponames, 1)}.git \n&& cd folder \n&& make install" github_adduser: add: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' username: '${var.github_username}' source_repos: '${var.github_reponames}' twitter_post: send: accessToken: '${var.twitter_access_token}' body: 'We are excited to announce @${var.koding_user_twitter_username} joined our team!1!!1!!1' koding_post: join_team: url: 'https://api.koding.com/integration/incoming/<integration id>' body: '@channel, please welcome ${var.koding_username} to team!' gmail_create_user: email: email: '${var.koding_username}@koding.com' notificationEmail: '${var.koding_user_contact_email}' ###
156237
module.exports = { json: ''' { "provider": { "aws": { "access_key": "${var.aws_access_key}", "secret_key": "${var.aws_secret_key}" } }, "resource": { "aws_instance": { "example-instance": { "tags": { "Name": "${var.koding_user_username}-${var.koding_group_slug}" }, "instance_type": "t2.nano", "ami": "", "user_data": "\\necho \\\"hello world!\\\" >> /helloworld.txt\\n" } } } } ''' yaml: ''' # Here is your stack preview # You can make advanced changes like modifying your VM, # installing packages, and running shell commands. provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' resource: aws_instance: # this is the name of your VM example-instance: # select your instance_type here: eg. c3.xlarge instance_type: t2.nano # select your ami (optional) eg. ami-xxxxx (it should be based on ubuntu 14.04) ami: '' # we will tag the instance here so you can identify it when you login to your AWS console tags: Name: '${var.koding_user_username}-${var.koding_group_slug}' # on user_data section we will write bash and configure our VM user_data: |- # let's create a file on your root folder: echo "hello world!" >> /helloworld.txt # please note: all commands under user_data will be run as root. # now add your credentials and save this stack. # once vm finishes building, you can see this file by typing # ls / # # for more information please click the link below "Stack Script Docs" ''' } ### Full YAML Example provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' github: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' builders: - type: amazon-ebs access_key: '{{user `aws_access_key`}}' secret_key: '{{user `aws_secret_key`}}' ami_name: 'koding-base-latest-{{timestamp}}' ami_description: Koding Base Image instance_type: m3.medium region: ap-northeast-1 source_ami: ami-9e5cff9e subnet_id: subnet-7e66e209 vpc_id: vpc-ef17be8a ssh_username: ubuntu tags: Name: koding-test - type: virtualbox-iso disk_size: 40960 guest_os_type: Ubuntu_64 http_directory: http iso_checksum: 83aabd8dcf1e8f469f3c72fff2375195 iso_checksum_type: md5 iso_url: 'http://releases.ubuntu.com/14.04/ubuntu-14.04.2-server-amd64.iso' ssh_username: vagrant ssh_password: <PASSWORD> ssh_port: 22 ssh_wait_timeout: 10000 shutdown_command: "echo 'shutdown -P now' > /tmp/shutdown.sh; echo 'vagrant'|sudo -S sh '/tmp/shutdown.sh'" vboxmanage: - - modifyvm - '{{.Name}}' - '--memory' - '512' - - modifyvm - '{{.Name}}' - '--cpus' - '1' provisioners: - type: shell inline: - 'echo ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub' - 'echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa' - chmod 600 ~/.ssh/ - 'git clone <EMAIL>:${var.github_username}/${lookup(var.github_reponames, 0)}.git' - 'git clone <EMAIL>:${var.github_username}/${lookup(var.github_reponames, 1)}.git' resource: aws_instance: web: source_dest_check: false user_data: "\necho ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub\n&& echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa\n&& chmod 600 ~/.ssh/*\n&& git clone <EMAIL>:${var.github_username}/${lookup(var.github_reponames, 0)}.git \n&& git clone <EMAIL>:${var.github_username}/${lookup(var.github_reponames, 1)}.git \n&& cd folder \n&& make install" github_adduser: add: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' username: '${var.github_username}' source_repos: '${var.github_reponames}' twitter_post: send: accessToken: '${var.twitter_access_token}' body: 'We are excited to announce @${var.koding_user_twitter_username} joined our team!1!!1!!1' koding_post: join_team: url: 'https://api.koding.com/integration/incoming/<integration id>' body: '@channel, please welcome ${var.koding_username} to team!' gmail_create_user: email: email: <EMAIL>' notificationEmail: '${var.koding_user_contact_email}' ###
true
module.exports = { json: ''' { "provider": { "aws": { "access_key": "${var.aws_access_key}", "secret_key": "${var.aws_secret_key}" } }, "resource": { "aws_instance": { "example-instance": { "tags": { "Name": "${var.koding_user_username}-${var.koding_group_slug}" }, "instance_type": "t2.nano", "ami": "", "user_data": "\\necho \\\"hello world!\\\" >> /helloworld.txt\\n" } } } } ''' yaml: ''' # Here is your stack preview # You can make advanced changes like modifying your VM, # installing packages, and running shell commands. provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' resource: aws_instance: # this is the name of your VM example-instance: # select your instance_type here: eg. c3.xlarge instance_type: t2.nano # select your ami (optional) eg. ami-xxxxx (it should be based on ubuntu 14.04) ami: '' # we will tag the instance here so you can identify it when you login to your AWS console tags: Name: '${var.koding_user_username}-${var.koding_group_slug}' # on user_data section we will write bash and configure our VM user_data: |- # let's create a file on your root folder: echo "hello world!" >> /helloworld.txt # please note: all commands under user_data will be run as root. # now add your credentials and save this stack. # once vm finishes building, you can see this file by typing # ls / # # for more information please click the link below "Stack Script Docs" ''' } ### Full YAML Example provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' github: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' builders: - type: amazon-ebs access_key: '{{user `aws_access_key`}}' secret_key: '{{user `aws_secret_key`}}' ami_name: 'koding-base-latest-{{timestamp}}' ami_description: Koding Base Image instance_type: m3.medium region: ap-northeast-1 source_ami: ami-9e5cff9e subnet_id: subnet-7e66e209 vpc_id: vpc-ef17be8a ssh_username: ubuntu tags: Name: koding-test - type: virtualbox-iso disk_size: 40960 guest_os_type: Ubuntu_64 http_directory: http iso_checksum: 83aabd8dcf1e8f469f3c72fff2375195 iso_checksum_type: md5 iso_url: 'http://releases.ubuntu.com/14.04/ubuntu-14.04.2-server-amd64.iso' ssh_username: vagrant ssh_password: PI:PASSWORD:<PASSWORD>END_PI ssh_port: 22 ssh_wait_timeout: 10000 shutdown_command: "echo 'shutdown -P now' > /tmp/shutdown.sh; echo 'vagrant'|sudo -S sh '/tmp/shutdown.sh'" vboxmanage: - - modifyvm - '{{.Name}}' - '--memory' - '512' - - modifyvm - '{{.Name}}' - '--cpus' - '1' provisioners: - type: shell inline: - 'echo ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub' - 'echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa' - chmod 600 ~/.ssh/ - 'git clone PI:EMAIL:<EMAIL>END_PI:${var.github_username}/${lookup(var.github_reponames, 0)}.git' - 'git clone PI:EMAIL:<EMAIL>END_PI:${var.github_username}/${lookup(var.github_reponames, 1)}.git' resource: aws_instance: web: source_dest_check: false user_data: "\necho ${var.github_adduser.adduser.publicKey} > ~/.ssh/id_rsa.pub\n&& echo ${var.github_adduser.adduser.privateKey} > ~/.ssh/id_rsa\n&& chmod 600 ~/.ssh/*\n&& git clone PI:EMAIL:<EMAIL>END_PI:${var.github_username}/${lookup(var.github_reponames, 0)}.git \n&& git clone PI:EMAIL:<EMAIL>END_PI:${var.github_username}/${lookup(var.github_reponames, 1)}.git \n&& cd folder \n&& make install" github_adduser: add: organizationKey: '${var.github_organization_access_token}' userKey: '${var.github_user_access_token}' username: '${var.github_username}' source_repos: '${var.github_reponames}' twitter_post: send: accessToken: '${var.twitter_access_token}' body: 'We are excited to announce @${var.koding_user_twitter_username} joined our team!1!!1!!1' koding_post: join_team: url: 'https://api.koding.com/integration/incoming/<integration id>' body: '@channel, please welcome ${var.koding_username} to team!' gmail_create_user: email: email: PI:EMAIL:<EMAIL>END_PI' notificationEmail: '${var.koding_user_contact_email}' ###
[ { "context": "ands:\n# none\n#\n# Notes:\n# None\n#\n# Author:\n# Brad Clark <bdashrad@gmail.com>\n\nmodule.exports = (robot) ->", "end": 461, "score": 0.9998636245727539, "start": 451, "tag": "NAME", "value": "Brad Clark" }, { "context": "e\n#\n# Notes:\n# None\n#\n# Author:...
src/jiralinks.coffee
bdashrad/hubot-jira-links
0
# Description: # Automatically post jira links when issue numbers are seen # # Dependencies: # None # # Configuration: # HUBOT_JIRA_DOMAIN - domain when your jira instance lives (e.g. "example.atlassian.com") # HUBOT_JIRA_PROJECTS - comma separated list of project prefixes (e.g. "AB,CD,EF") # HUBOT_JIRA_INSECURE - if this is set urls will be prefixed by "http" instead of "https" # # Commands: # none # # Notes: # None # # Author: # Brad Clark <bdashrad@gmail.com> module.exports = (robot) -> if process.env.HUBOT_JIRA_INSECURE? http_proto = 'http://' else http_proto = 'https://' if process.env.HUBOT_JIRA_PROJECTS regex = /// (?:^|\s) # start of line or space (#{process.env.HUBOT_JIRA_PROJECTS.split(',').join('|')}) # list of jira project prefixes - # a hyphen (\d+) # one or more digits \b # word boundary ///i # case insensitive else regex = /// (?:^|\s) # start of line or space ([a-z]+) # one or more letters - (\d+) # one or more digits \b # word boundary ///i robot.hear regex, (res) -> # return if msg.subtype is 'bot_message' project = res.match[1].toUpperCase() id = res.match[2] issue = project + '-' + id url = http_proto + process.env.HUBOT_JIRA_DOMAIN + '/browse/' + issue res.send url
192901
# Description: # Automatically post jira links when issue numbers are seen # # Dependencies: # None # # Configuration: # HUBOT_JIRA_DOMAIN - domain when your jira instance lives (e.g. "example.atlassian.com") # HUBOT_JIRA_PROJECTS - comma separated list of project prefixes (e.g. "AB,CD,EF") # HUBOT_JIRA_INSECURE - if this is set urls will be prefixed by "http" instead of "https" # # Commands: # none # # Notes: # None # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> if process.env.HUBOT_JIRA_INSECURE? http_proto = 'http://' else http_proto = 'https://' if process.env.HUBOT_JIRA_PROJECTS regex = /// (?:^|\s) # start of line or space (#{process.env.HUBOT_JIRA_PROJECTS.split(',').join('|')}) # list of jira project prefixes - # a hyphen (\d+) # one or more digits \b # word boundary ///i # case insensitive else regex = /// (?:^|\s) # start of line or space ([a-z]+) # one or more letters - (\d+) # one or more digits \b # word boundary ///i robot.hear regex, (res) -> # return if msg.subtype is 'bot_message' project = res.match[1].toUpperCase() id = res.match[2] issue = project + '-' + id url = http_proto + process.env.HUBOT_JIRA_DOMAIN + '/browse/' + issue res.send url
true
# Description: # Automatically post jira links when issue numbers are seen # # Dependencies: # None # # Configuration: # HUBOT_JIRA_DOMAIN - domain when your jira instance lives (e.g. "example.atlassian.com") # HUBOT_JIRA_PROJECTS - comma separated list of project prefixes (e.g. "AB,CD,EF") # HUBOT_JIRA_INSECURE - if this is set urls will be prefixed by "http" instead of "https" # # Commands: # none # # Notes: # None # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> if process.env.HUBOT_JIRA_INSECURE? http_proto = 'http://' else http_proto = 'https://' if process.env.HUBOT_JIRA_PROJECTS regex = /// (?:^|\s) # start of line or space (#{process.env.HUBOT_JIRA_PROJECTS.split(',').join('|')}) # list of jira project prefixes - # a hyphen (\d+) # one or more digits \b # word boundary ///i # case insensitive else regex = /// (?:^|\s) # start of line or space ([a-z]+) # one or more letters - (\d+) # one or more digits \b # word boundary ///i robot.hear regex, (res) -> # return if msg.subtype is 'bot_message' project = res.match[1].toUpperCase() id = res.match[2] issue = project + '-' + id url = http_proto + process.env.HUBOT_JIRA_DOMAIN + '/browse/' + issue res.send url
[ { "context": " expect(jsonClone samp).toEqual { keyMap: { 0: 'aa', 1: 'ab' } }\n\n it 'does one observation', (do", "end": 537, "score": 0.5386722087860107, "start": 535, "tag": "KEY", "value": "aa" }, { "context": "(jsonClone samp).toEqual { keyMap: { 0: 'aa', 1: 'ab' } }\n\n ...
server/spec/recorder.spec.coffee
triggerrally/triggerrally.github.io
1
describe 'recorder', -> # TODO test: # key mapping # freq (record skipping) # playback recorder = require '../public/scripts/util/recorder' data1 = aa: 1 ab: 2 ac: 3 keys1 = aa: 2 ab: 1 data2 = x: 0 keys2 = x: 1 jsonClone = (obj) -> JSON.parse JSON.stringify obj describe 'StateSampler', -> it 'maps keys', -> samp = new recorder.StateSampler data1, keys1, 1 expect(samp.keyMap).toEqual { aa: '0', ab: '1' } expect(jsonClone samp).toEqual { keyMap: { 0: 'aa', 1: 'ab' } } it 'does one observation', (done) -> changeHandler = (index, data) -> expect(index).toBe 0 expect(data).toEqual { 0: '1', 1: '2' } done() samp = new recorder.StateSampler data1, keys1, 1, changeHandler samp.observe() describe 'StateRecorder', -> it 'has the right overall format', -> rec = new recorder.StateRecorder data1, keys1, 1 expect(jsonClone rec).toEqual keyMap: { 0: 'aa', 1: 'ab' } timeline: [] it 'records', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() rec.observe() obj.x = 2 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '2' } ] [ 2, { 0: '3' } ] ] it 'records with freq 2', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() obj.x = 4 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '3' } ] [ 2, { 0: '4' } ] ] describe 'StatePlayback', -> saved = do -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() jsonClone rec it 'has the expected test data', -> expect(saved).toEqual keyMap: { 0: 'x' } timeline: [ [ 0, { 0: '1' } ] [ 1, { 0: '2' } ] [ 1, { 0: '3' } ] ] it 'works', -> obj = {} play = new recorder.StatePlayback obj, saved expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 2 } play.step() expect(obj).toEqual { x: 3 } play.step() expect(obj).toEqual { x: 3 } it 'has correct timing', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() saved2 = jsonClone rec obj = {} play = new recorder.StatePlayback obj, saved2 expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 3 }
64531
describe 'recorder', -> # TODO test: # key mapping # freq (record skipping) # playback recorder = require '../public/scripts/util/recorder' data1 = aa: 1 ab: 2 ac: 3 keys1 = aa: 2 ab: 1 data2 = x: 0 keys2 = x: 1 jsonClone = (obj) -> JSON.parse JSON.stringify obj describe 'StateSampler', -> it 'maps keys', -> samp = new recorder.StateSampler data1, keys1, 1 expect(samp.keyMap).toEqual { aa: '0', ab: '1' } expect(jsonClone samp).toEqual { keyMap: { 0: '<KEY>', 1: '<KEY>' } } it 'does one observation', (done) -> changeHandler = (index, data) -> expect(index).toBe 0 expect(data).toEqual { 0: '1', 1: '2' } done() samp = new recorder.StateSampler data1, keys1, 1, changeHandler samp.observe() describe 'StateRecorder', -> it 'has the right overall format', -> rec = new recorder.StateRecorder data1, keys1, 1 expect(jsonClone rec).toEqual keyMap: { 0: '<KEY>', 1: '<KEY>' } timeline: [] it 'records', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() rec.observe() obj.x = 2 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '2' } ] [ 2, { 0: '3' } ] ] it 'records with freq 2', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() obj.x = 4 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '3' } ] [ 2, { 0: '4' } ] ] describe 'StatePlayback', -> saved = do -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() jsonClone rec it 'has the expected test data', -> expect(saved).toEqual keyMap: { 0: 'x' } timeline: [ [ 0, { 0: '1' } ] [ 1, { 0: '2' } ] [ 1, { 0: '3' } ] ] it 'works', -> obj = {} play = new recorder.StatePlayback obj, saved expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 2 } play.step() expect(obj).toEqual { x: 3 } play.step() expect(obj).toEqual { x: 3 } it 'has correct timing', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() saved2 = jsonClone rec obj = {} play = new recorder.StatePlayback obj, saved2 expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 3 }
true
describe 'recorder', -> # TODO test: # key mapping # freq (record skipping) # playback recorder = require '../public/scripts/util/recorder' data1 = aa: 1 ab: 2 ac: 3 keys1 = aa: 2 ab: 1 data2 = x: 0 keys2 = x: 1 jsonClone = (obj) -> JSON.parse JSON.stringify obj describe 'StateSampler', -> it 'maps keys', -> samp = new recorder.StateSampler data1, keys1, 1 expect(samp.keyMap).toEqual { aa: '0', ab: '1' } expect(jsonClone samp).toEqual { keyMap: { 0: 'PI:KEY:<KEY>END_PI', 1: 'PI:KEY:<KEY>END_PI' } } it 'does one observation', (done) -> changeHandler = (index, data) -> expect(index).toBe 0 expect(data).toEqual { 0: '1', 1: '2' } done() samp = new recorder.StateSampler data1, keys1, 1, changeHandler samp.observe() describe 'StateRecorder', -> it 'has the right overall format', -> rec = new recorder.StateRecorder data1, keys1, 1 expect(jsonClone rec).toEqual keyMap: { 0: 'PI:KEY:<KEY>END_PI', 1: 'PI:KEY:<KEY>END_PI' } timeline: [] it 'records', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() rec.observe() obj.x = 2 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '2' } ] [ 2, { 0: '3' } ] ] it 'records with freq 2', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() obj.x = 4 rec.observe() rec.observe() expect(jsonClone(rec).timeline).toEqual [ [ 0, { 0: '1' } ] [ 2, { 0: '3' } ] [ 2, { 0: '4' } ] ] describe 'StatePlayback', -> saved = do -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 1 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() jsonClone rec it 'has the expected test data', -> expect(saved).toEqual keyMap: { 0: 'x' } timeline: [ [ 0, { 0: '1' } ] [ 1, { 0: '2' } ] [ 1, { 0: '3' } ] ] it 'works', -> obj = {} play = new recorder.StatePlayback obj, saved expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 2 } play.step() expect(obj).toEqual { x: 3 } play.step() expect(obj).toEqual { x: 3 } it 'has correct timing', -> obj = jsonClone data2 rec = new recorder.StateRecorder obj, keys2, 2 obj.x = 1 rec.observe() obj.x = 2 rec.observe() obj.x = 3 rec.observe() saved2 = jsonClone rec obj = {} play = new recorder.StatePlayback obj, saved2 expect(obj).toEqual {} play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 1 } play.step() expect(obj).toEqual { x: 3 }
[ { "context": "business.ru/api/WcfService.svc'\n @.APP_NAME = 'Clarins'\n\n @.GEOLOCATION_TIMEOUT_ANDROID = 3000\n @.", "end": 217, "score": 0.9963892102241516, "start": 210, "tag": "NAME", "value": "Clarins" } ]
client/coffee/core/Config.coffee
HiPiH/App1
0
class Config @.VIRTICAL_DEVICE_MIN_WIDTH = 420 @.HORIZONTAL_DEVICE_MIN_WIDTH = 600 @.DEFAULT_LANGUAGE = 'ru' @.SERVER_URL = 'https://cc.orange-business.ru/api/WcfService.svc' @.APP_NAME = 'Clarins' @.GEOLOCATION_TIMEOUT_ANDROID = 3000 @.GEOLOCATION_TIMEOUT_OTHER = 3000 @.LOADING_TIME_OUT_DELAY = 20000 @.STATUS_DAY = { 'CheckIn': 0 #Производится регистрация 'CheckOut': 1, #Производится закрытие дня 'Reporting': 2, #Производится отчёт 'None': 3 #Можно только поправить } @.ORDER_TYPE = { 0: 'Standart', #Стандартный 1: 'Customer', #Клиентский 2: 'Spa', # СПА 3: 'RegionSupervisor' #Региональный представитель } @.TYPE_EMPLOYEE = { 'Employer': 0, #Простой консультант 'Supervisor': 1 #Супервизор } @.TYPE_POINT_DAY = { 'None': 0, #Отсутствие 'Done': 1, #Пройден 'Fail': 2 #Пройден, но с ошибкой }
168945
class Config @.VIRTICAL_DEVICE_MIN_WIDTH = 420 @.HORIZONTAL_DEVICE_MIN_WIDTH = 600 @.DEFAULT_LANGUAGE = 'ru' @.SERVER_URL = 'https://cc.orange-business.ru/api/WcfService.svc' @.APP_NAME = '<NAME>' @.GEOLOCATION_TIMEOUT_ANDROID = 3000 @.GEOLOCATION_TIMEOUT_OTHER = 3000 @.LOADING_TIME_OUT_DELAY = 20000 @.STATUS_DAY = { 'CheckIn': 0 #Производится регистрация 'CheckOut': 1, #Производится закрытие дня 'Reporting': 2, #Производится отчёт 'None': 3 #Можно только поправить } @.ORDER_TYPE = { 0: 'Standart', #Стандартный 1: 'Customer', #Клиентский 2: 'Spa', # СПА 3: 'RegionSupervisor' #Региональный представитель } @.TYPE_EMPLOYEE = { 'Employer': 0, #Простой консультант 'Supervisor': 1 #Супервизор } @.TYPE_POINT_DAY = { 'None': 0, #Отсутствие 'Done': 1, #Пройден 'Fail': 2 #Пройден, но с ошибкой }
true
class Config @.VIRTICAL_DEVICE_MIN_WIDTH = 420 @.HORIZONTAL_DEVICE_MIN_WIDTH = 600 @.DEFAULT_LANGUAGE = 'ru' @.SERVER_URL = 'https://cc.orange-business.ru/api/WcfService.svc' @.APP_NAME = 'PI:NAME:<NAME>END_PI' @.GEOLOCATION_TIMEOUT_ANDROID = 3000 @.GEOLOCATION_TIMEOUT_OTHER = 3000 @.LOADING_TIME_OUT_DELAY = 20000 @.STATUS_DAY = { 'CheckIn': 0 #Производится регистрация 'CheckOut': 1, #Производится закрытие дня 'Reporting': 2, #Производится отчёт 'None': 3 #Можно только поправить } @.ORDER_TYPE = { 0: 'Standart', #Стандартный 1: 'Customer', #Клиентский 2: 'Spa', # СПА 3: 'RegionSupervisor' #Региональный представитель } @.TYPE_EMPLOYEE = { 'Employer': 0, #Простой консультант 'Supervisor': 1 #Супервизор } @.TYPE_POINT_DAY = { 'None': 0, #Отсутствие 'Done': 1, #Пройден 'Fail': 2 #Пройден, но с ошибкой }
[ { "context": "haves similarly to a physical credit card.\n@author Ken Keiter <ken@kenkeiter.com>\n@updated 2013-07-25\n@website ", "end": 295, "score": 0.9998683929443359, "start": 285, "tag": "NAME", "value": "Ken Keiter" }, { "context": "ly to a physical credit card.\n@author Ken K...
javascripts/src/Skeuocard.coffee
mueslico/skeuocard
416
### "Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement @description Skeuocard is a skeuomorphic credit card input plugin, supporting progressive enhancement. It renders a credit-card input which behaves similarly to a physical credit card. @author Ken Keiter <ken@kenkeiter.com> @updated 2013-07-25 @website http://kenkeiter.com/ @exports [window.Skeuocard] ### $ = jQuery class Skeuocard @currentDate: new Date() constructor: (el, opts = {})-> @el = container: $(el), underlyingFields: {} @_inputViews = {} @_inputViewsByFace = {front: [], back: []} @_tabViews = {} @_state = {} @product = null @visibleFace = 'front' # configure default opts optDefaults = debug: false dontFocus: false acceptedCardProducts: null cardNumberPlaceholderChar: 'X' genericPlaceholder: "XXXX XXXX XXXX XXXX" typeInputSelector: '[name="cc_type"]' numberInputSelector: '[name="cc_number"]' expMonthInputSelector: '[name="cc_exp_month"]' expYearInputSelector: '[name="cc_exp_year"]' nameInputSelector: '[name="cc_name"]' cvcInputSelector: '[name="cc_cvc"]' initialValues: {} validationState: {} strings: hiddenFaceFillPrompt: "<strong>Click here</strong> to <br>fill in the other side." hiddenFaceErrorWarning: "There's a problem on the other side." hiddenFaceSwitchPrompt: "Forget something?<br> Flip the card over." @options = $.extend(optDefaults, opts) # initialize the card @_conformDOM() # conform the DOM, add our elements @_bindInputEvents() # bind input and interaction events @_importImplicitOptions() # import init options from DOM element attrs @render() # perform initial render # Debugging helper; if debug is set to true at instantiation, messages will # be printed to the console. _log: (msg...)-> if console?.log and !!@options.debug console.log("[skeuocard]", msg...) if @options.debug? # Trigger an event on a Skeuocard instance (jQuery's #trigger signature). trigger: (args...)-> @el.container.trigger(args...) # Bind an event handler on a Skeuocard instance (jQuery's #trigger signature). bind: (args...)-> @el.container.bind(args...) ### Transform the elements within the container, conforming the DOM so that it becomes styleable, and that the underlying inputs are hidden. ### _conformDOM: -> @el.container.removeClass('no-js') @el.container.addClass("skeuocard js") # remove anything that's not an underlying form field @el.container.find("> :not(input,select,textarea)").remove() @el.container.find("> input,select,textarea").hide() # Attach underlying form fields. @el.underlyingFields = type: @el.container.find(@options.typeInputSelector) number: @el.container.find(@options.numberInputSelector) expMonth: @el.container.find(@options.expMonthInputSelector) expYear: @el.container.find(@options.expYearInputSelector) name: @el.container.find(@options.nameInputSelector) cvc: @el.container.find(@options.cvcInputSelector) # construct the necessary card elements @el.front = $("<div>").attr(class: "face front") @el.back = $("<div>").attr(class: "face back") @el.cardBody = $("<div>").attr(class: "card-body") # add elements to the DOM @el.front.appendTo(@el.cardBody) @el.back.appendTo(@el.cardBody) @el.cardBody.appendTo(@el.container) # create the validation indicator (flip tab), and attach them. @_tabViews.front = new Skeuocard::FlipTabView(@, 'front', strings: @options.strings) @_tabViews.back = new Skeuocard::FlipTabView(@, 'back', strings: @options.strings) @el.front.prepend(@_tabViews.front.el) @el.back.prepend(@_tabViews.back.el) @_tabViews.front.hide() @_tabViews.back.hide() # Create new input views, attach them to the appropriate surfaces @_inputViews = number: new @SegmentedCardNumberInputView() exp: new @ExpirationInputView(currentDate: @options.currentDate) name: new @TextInputView(class: "cc-name", placeholder: "YOUR NAME") cvc: new @TextInputView(class: "cc-cvc", placeholder: "XXX", requireMaxLength: true) # style and attach the number view to the DOM @_inputViews.number.el.addClass('cc-number') @_inputViews.number.el.appendTo(@el.front) # attach name input @_inputViews.name.el.appendTo(@el.front) # style and attach the exp view to the DOM @_inputViews.exp.el.addClass('cc-exp') @_inputViews.exp.el.appendTo(@el.front) # attach cvc field to the DOM @_inputViews.cvc.el.appendTo(@el.back) return @el.container ### Import implicit initialization options from the DOM. Brings in things like the accepted card type, initial validation state, existing values, etc. ### _importImplicitOptions: -> for fieldName, fieldEl of @el.underlyingFields # import initial values, with constructor options taking precedence unless @options.initialValues[fieldName]? @options.initialValues[fieldName] = fieldEl.val() else # update underlying field value so that it is canonical. @options.initialValues[fieldName] = @options.initialValues[fieldName].toString() @_setUnderlyingValue(fieldName, @options.initialValues[fieldName]) # set a flag if any fields were initially filled if @options.initialValues[fieldName].length > 0 @_state['initiallyFilled'] = true # import initial validation state unless @options.validationState[fieldName]? @options.validationState[fieldName] = not fieldEl.hasClass('invalid') # If no explicit acceptedCardProducts were specified, determine accepted # card products using the underlying type select field. unless @options.acceptedCardProducts? @options.acceptedCardProducts = [] @el.underlyingFields.type.find('option').each (i, _el)=> el = $(_el) shortname = el.attr('data-sc-type') || el.attr('value') @options.acceptedCardProducts.push shortname # setup default values; when render is called, these will be picked up if @options.initialValues.number.length > 0 @set 'number', @options.initialValues.number if @options.initialValues.name.length > 0 @set 'name', @options.initialValues.name if @options.initialValues.cvc.length > 0 @set 'cvc', @options.initialValues.cvc if @options.initialValues.expYear.length > 0 and @options.initialValues.expMonth.length > 0 _initialExp = new Date parseInt(@options.initialValues.expYear), parseInt(@options.initialValues.expMonth) - 1, 1 @set 'exp', _initialExp @_updateValidationForFace('front') @_updateValidationForFace('back') set: (field, newValue)-> @_inputViews[field].setValue(newValue) @_inputViews[field].trigger('valueChanged', @_inputViews[field]) ### Bind interaction events to their appropriate handlers. ### _bindInputEvents: -> # bind change handlers to render @el.underlyingFields.number.bind "change", (e)=> @_inputViews.number.setValue @_getUnderlyingValue('number') @render() _expirationChange = (e)=> month = parseInt @_getUnderlyingValue('expMonth') year = parseInt @_getUnderlyingValue('expYear') @_inputViews.exp.setValue new Date(year, month - 1) @render() @el.underlyingFields.expMonth.bind "change", _expirationChange @el.underlyingFields.expYear.bind "change", _expirationChange @el.underlyingFields.name.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('name') @render() @el.underlyingFields.cvc.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('cvc') @render() # bind change events to their underlying form elements @_inputViews.number.bind "change valueChanged", (e, input)=> cardNumber = input.getValue() @_setUnderlyingValue 'number', cardNumber @_updateValidation 'number', cardNumber # update the product if needed. number = @_getUnderlyingValue('number') matchedProduct = Skeuocard::CardProduct.firstMatchingNumber(number) # check if the product is accepted if not @product?.eql(matchedProduct) @_log("Product will change:", @product, "=>", matchedProduct) if matchedProduct?.attrs.companyShortname in @options.acceptedCardProducts @trigger 'productWillChange.skeuocard', [@, @product, matchedProduct] previousProduct = @product @el.container.removeClass('unaccepted') @_renderProduct(matchedProduct) @product = matchedProduct else if matchedProduct? @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.addClass('unaccepted') @_renderProduct(null) @product = null else @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.removeClass('unaccepted') @_renderProduct(null) @product = null @trigger 'productDidChange.skeuocard', [@, previousProduct, @product] @_inputViews.exp.bind "keyup valueChanged", (e, input)=> newDate = input.getValue() @_updateValidation('exp', newDate) if newDate? @_setUnderlyingValue('expMonth', newDate.getMonth() + 1) @_setUnderlyingValue('expYear', newDate.getFullYear()) @_inputViews.name.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('name', value) @_updateValidation('name', value) @_inputViews.cvc.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('cvc', value) @_updateValidation('cvc', value) @el.container.delegate "input", "keyup keydown", @_handleFieldTab.bind(@) @_tabViews.front.el.click => @flip() @_tabViews.back.el.click => @flip() _handleFieldTab: (e)-> if e.which is 9 # tab currentFieldEl = $(e.currentTarget) _oppositeFace = if @visibleFace is 'front' then 'back' else 'front' _currentFace = if @visibleFace is 'front' then 'front' else 'back' backFieldEls = @el[_oppositeFace].find('input') frontFieldEls = @el[_currentFace].find('input') if @visibleFace is 'front' and @el.front.hasClass('filled') and backFieldEls.length > 0 and frontFieldEls.index(currentFieldEl) is frontFieldEls.length-1 and not e.shiftKey @flip() backFieldEls.first().focus() e.preventDefault() if @visibleFace is 'back' and e.shiftKey @flip() backFieldEls.last().focus() # other side, now... e.preventDefault() return true _updateValidation: (fieldName, newValue)-> return false unless @product? # Check against the current product to determine if the field is filled isFilled = @product[fieldName].isFilled(newValue) # If an initial value was supplied and marked as invalid, ensure that it # has been changed to a new value. needsFix = @options.validationState[fieldName]? is false isFixed = @options.initialValues[fieldName]? and newValue isnt @options.initialValues[fieldName] # Check validity of value, asserting fixes have occurred if necessary. isValid = @product[fieldName].isValid(newValue) and ((needsFix and isFixed) or true) # Determine if state changed fillStateChanged = @_state["#{fieldName}Filled"] isnt isFilled validationStateChanged = @_state["#{fieldName}Valid"] isnt isValid # If the fill state has changed, trigger events, and make styling changes. if fillStateChanged @trigger "fieldFillStateWillChange.skeuocard", [@, fieldName, isFilled] @_inputViews[fieldName].el.toggleClass 'filled', isFilled @_state["#{fieldName}Filled"] = isFilled @trigger "fieldFillStateDidChange.skeuocard", [@, fieldName, isFilled] # If the valid state has changed, trigger events, and make styling changes. if validationStateChanged @trigger "fieldValidationStateWillChange.skeuocard", [@, fieldName, isValid] @_inputViews[fieldName].el.toggleClass 'valid', isValid @_inputViews[fieldName].el.toggleClass 'invalid', not isValid @_state["#{fieldName}Valid"] = isValid @trigger "fieldValidationStateDidChange.skeuocard", [@, fieldName, isValid] @_updateValidationForFace(@visibleFace) _updateValidationForFace: (face)-> fieldsFilled = (iv.el.hasClass('filled') for iv in @_inputViewsByFace[face]).every(Boolean) fieldsValid = (iv.el.hasClass('valid') for iv in @_inputViewsByFace[face]).every(Boolean) isFilled = (fieldsFilled and @product?) or (@_state['initiallyFilled'] or false) isValid = fieldsValid and @product? fillStateChanged = @_state["#{face}Filled"] isnt isFilled validationStateChanged = @_state["#{face}Valid"] isnt isValid if fillStateChanged @trigger "faceFillStateWillChange.skeuocard", [@, face, isFilled] @el[face].toggleClass 'filled', isFilled @_state["#{face}Filled"] = isFilled @trigger "faceFillStateDidChange.skeuocard", [@, face, isFilled] if validationStateChanged @trigger "faceValidationStateWillChange.skeuocard", [@, face, isValid] @el[face].toggleClass 'valid', isValid @el[face].toggleClass 'invalid', not isValid @_state["#{face}Valid"] = isValid @trigger "faceValidationStateDidChange.skeuocard", [@, face, isValid] ### Assert rendering changes necessary for the current product. Passing a null value instead of a product will revert the card to a generic state. ### _renderProduct: (product)-> @_log("[_renderProduct]", "Rendering product:", product) # remove existing product and issuer classes (destyling product) @el.container.removeClass (index, css)=> (css.match(/\b(product|issuer)-\S+/g) || []).join(' ') # add classes necessary to identify new product if product?.attrs.companyShortname? @el.container.addClass("product-#{product.attrs.companyShortname}") if product?.attrs.issuerShortname? @el.container.addClass("issuer-#{product.attrs.issuerShortname}") # update the underlying card type field @_setUnderlyingValue('type', product?.attrs.companyShortname || null) # reconfigure the number input groupings @_inputViews.number.setGroupings(product?.attrs.cardNumberGrouping || [@options.genericPlaceholder.length], @options.dontFocus) delete @options.dontFocus if product? # reconfigure the expiration input groupings @_inputViews.exp.reconfigure pattern: product?.attrs.expirationFormat || "MM/YY" # reconfigure the CVC @_inputViews.cvc.attr maxlength: product.attrs.cvcLength placeholder: new Array(product.attrs.cvcLength + 1).join(@options.cardNumberPlaceholderChar) # set visibility and re-layout fields @_inputViewsByFace = {front: [], back: []} focused = $('input:focus') # allow restoration of focus upon re-attachment for fieldName, destFace of product.attrs.layout @_log("Moving", fieldName, "to", destFace) viewEl = @_inputViews[fieldName].el.detach() viewEl.appendTo(@el[destFace]) @_inputViewsByFace[destFace].push @_inputViews[fieldName] @_inputViews[fieldName].show() # Restore focus. Use setTimeout to resolve IE10 issue. setTimeout => if (fieldEl = focused.first())? fieldLength = fieldEl[0].maxLength fieldEl.focus() fieldEl[0].setSelectionRange(fieldLength, fieldLength) , 10 else for fieldName, view of @_inputViews view.hide() if fieldName isnt 'number' return product _renderValidation: -> # update the validation state of all fields for fieldName, fieldView of @_inputViews @_updateValidation(fieldName, fieldView.getValue()) # Update the card's visual representation to reflect internal state. render: -> @_renderProduct(@product) @_renderValidation() # @_flipToInvalidSide() # Flip the card over. flip: -> targetFace = if @visibleFace is 'front' then 'back' else 'front' @trigger('faceWillBecomeVisible.skeuocard', [@, targetFace]) @visibleFace = targetFace @el.cardBody.toggleClass('flip') surfaceName = if @visibleFace is 'front' then 'front' else 'back' @el[surfaceName].find('.cc-field').not('.filled').find('input').first().focus() @trigger('faceDidBecomeVisible.skeuocard', [@, targetFace]) # Set a value in the underlying form. _setUnderlyingValue: (field, newValue)-> fieldEl = @el.underlyingFields[field] _newValue = (newValue || "").toString() throw "Set underlying value of unknown field: #{field}." unless fieldEl? @trigger('change.skeuocard', [@]) unless fieldEl.is('select') @el.underlyingFields[field].val(_newValue) else remapAttrKey = "data-sc-" + field.toLowerCase() fieldEl.find('option').each (i, _el)=> optionEl = $(_el) if _newValue is (optionEl.attr(remapAttrKey) || optionEl.attr('value')) @el.underlyingFields[field].val optionEl.attr('value') # Get a value from the underlying form. _getUnderlyingValue: (field)-> @el.underlyingFields[field]?.val() isValid: -> not @el.front.hasClass('invalid') and not @el.back.hasClass('invalid') # Export the object. window.Skeuocard = Skeuocard
64527
### "Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement @description Skeuocard is a skeuomorphic credit card input plugin, supporting progressive enhancement. It renders a credit-card input which behaves similarly to a physical credit card. @author <NAME> <<EMAIL>> @updated 2013-07-25 @website http://kenkeiter.com/ @exports [window.Skeuocard] ### $ = jQuery class Skeuocard @currentDate: new Date() constructor: (el, opts = {})-> @el = container: $(el), underlyingFields: {} @_inputViews = {} @_inputViewsByFace = {front: [], back: []} @_tabViews = {} @_state = {} @product = null @visibleFace = 'front' # configure default opts optDefaults = debug: false dontFocus: false acceptedCardProducts: null cardNumberPlaceholderChar: 'X' genericPlaceholder: "XXXX XXXX XXXX XXXX" typeInputSelector: '[name="cc_type"]' numberInputSelector: '[name="cc_number"]' expMonthInputSelector: '[name="cc_exp_month"]' expYearInputSelector: '[name="cc_exp_year"]' nameInputSelector: '[name="cc_name"]' cvcInputSelector: '[name="cc_cvc"]' initialValues: {} validationState: {} strings: hiddenFaceFillPrompt: "<strong>Click here</strong> to <br>fill in the other side." hiddenFaceErrorWarning: "There's a problem on the other side." hiddenFaceSwitchPrompt: "Forget something?<br> Flip the card over." @options = $.extend(optDefaults, opts) # initialize the card @_conformDOM() # conform the DOM, add our elements @_bindInputEvents() # bind input and interaction events @_importImplicitOptions() # import init options from DOM element attrs @render() # perform initial render # Debugging helper; if debug is set to true at instantiation, messages will # be printed to the console. _log: (msg...)-> if console?.log and !!@options.debug console.log("[skeuocard]", msg...) if @options.debug? # Trigger an event on a Skeuocard instance (jQuery's #trigger signature). trigger: (args...)-> @el.container.trigger(args...) # Bind an event handler on a Skeuocard instance (jQuery's #trigger signature). bind: (args...)-> @el.container.bind(args...) ### Transform the elements within the container, conforming the DOM so that it becomes styleable, and that the underlying inputs are hidden. ### _conformDOM: -> @el.container.removeClass('no-js') @el.container.addClass("skeuocard js") # remove anything that's not an underlying form field @el.container.find("> :not(input,select,textarea)").remove() @el.container.find("> input,select,textarea").hide() # Attach underlying form fields. @el.underlyingFields = type: @el.container.find(@options.typeInputSelector) number: @el.container.find(@options.numberInputSelector) expMonth: @el.container.find(@options.expMonthInputSelector) expYear: @el.container.find(@options.expYearInputSelector) name: @el.container.find(@options.nameInputSelector) cvc: @el.container.find(@options.cvcInputSelector) # construct the necessary card elements @el.front = $("<div>").attr(class: "face front") @el.back = $("<div>").attr(class: "face back") @el.cardBody = $("<div>").attr(class: "card-body") # add elements to the DOM @el.front.appendTo(@el.cardBody) @el.back.appendTo(@el.cardBody) @el.cardBody.appendTo(@el.container) # create the validation indicator (flip tab), and attach them. @_tabViews.front = new Skeuocard::FlipTabView(@, 'front', strings: @options.strings) @_tabViews.back = new Skeuocard::FlipTabView(@, 'back', strings: @options.strings) @el.front.prepend(@_tabViews.front.el) @el.back.prepend(@_tabViews.back.el) @_tabViews.front.hide() @_tabViews.back.hide() # Create new input views, attach them to the appropriate surfaces @_inputViews = number: new @SegmentedCardNumberInputView() exp: new @ExpirationInputView(currentDate: @options.currentDate) name: new @TextInputView(class: "cc-name", placeholder: "YOUR NAME") cvc: new @TextInputView(class: "cc-cvc", placeholder: "XXX", requireMaxLength: true) # style and attach the number view to the DOM @_inputViews.number.el.addClass('cc-number') @_inputViews.number.el.appendTo(@el.front) # attach name input @_inputViews.name.el.appendTo(@el.front) # style and attach the exp view to the DOM @_inputViews.exp.el.addClass('cc-exp') @_inputViews.exp.el.appendTo(@el.front) # attach cvc field to the DOM @_inputViews.cvc.el.appendTo(@el.back) return @el.container ### Import implicit initialization options from the DOM. Brings in things like the accepted card type, initial validation state, existing values, etc. ### _importImplicitOptions: -> for fieldName, fieldEl of @el.underlyingFields # import initial values, with constructor options taking precedence unless @options.initialValues[fieldName]? @options.initialValues[fieldName] = fieldEl.val() else # update underlying field value so that it is canonical. @options.initialValues[fieldName] = @options.initialValues[fieldName].toString() @_setUnderlyingValue(fieldName, @options.initialValues[fieldName]) # set a flag if any fields were initially filled if @options.initialValues[fieldName].length > 0 @_state['initiallyFilled'] = true # import initial validation state unless @options.validationState[fieldName]? @options.validationState[fieldName] = not fieldEl.hasClass('invalid') # If no explicit acceptedCardProducts were specified, determine accepted # card products using the underlying type select field. unless @options.acceptedCardProducts? @options.acceptedCardProducts = [] @el.underlyingFields.type.find('option').each (i, _el)=> el = $(_el) shortname = el.attr('data-sc-type') || el.attr('value') @options.acceptedCardProducts.push shortname # setup default values; when render is called, these will be picked up if @options.initialValues.number.length > 0 @set 'number', @options.initialValues.number if @options.initialValues.name.length > 0 @set 'name', @options.initialValues.name if @options.initialValues.cvc.length > 0 @set 'cvc', @options.initialValues.cvc if @options.initialValues.expYear.length > 0 and @options.initialValues.expMonth.length > 0 _initialExp = new Date parseInt(@options.initialValues.expYear), parseInt(@options.initialValues.expMonth) - 1, 1 @set 'exp', _initialExp @_updateValidationForFace('front') @_updateValidationForFace('back') set: (field, newValue)-> @_inputViews[field].setValue(newValue) @_inputViews[field].trigger('valueChanged', @_inputViews[field]) ### Bind interaction events to their appropriate handlers. ### _bindInputEvents: -> # bind change handlers to render @el.underlyingFields.number.bind "change", (e)=> @_inputViews.number.setValue @_getUnderlyingValue('number') @render() _expirationChange = (e)=> month = parseInt @_getUnderlyingValue('expMonth') year = parseInt @_getUnderlyingValue('expYear') @_inputViews.exp.setValue new Date(year, month - 1) @render() @el.underlyingFields.expMonth.bind "change", _expirationChange @el.underlyingFields.expYear.bind "change", _expirationChange @el.underlyingFields.name.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('name') @render() @el.underlyingFields.cvc.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('cvc') @render() # bind change events to their underlying form elements @_inputViews.number.bind "change valueChanged", (e, input)=> cardNumber = input.getValue() @_setUnderlyingValue 'number', cardNumber @_updateValidation 'number', cardNumber # update the product if needed. number = @_getUnderlyingValue('number') matchedProduct = Skeuocard::CardProduct.firstMatchingNumber(number) # check if the product is accepted if not @product?.eql(matchedProduct) @_log("Product will change:", @product, "=>", matchedProduct) if matchedProduct?.attrs.companyShortname in @options.acceptedCardProducts @trigger 'productWillChange.skeuocard', [@, @product, matchedProduct] previousProduct = @product @el.container.removeClass('unaccepted') @_renderProduct(matchedProduct) @product = matchedProduct else if matchedProduct? @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.addClass('unaccepted') @_renderProduct(null) @product = null else @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.removeClass('unaccepted') @_renderProduct(null) @product = null @trigger 'productDidChange.skeuocard', [@, previousProduct, @product] @_inputViews.exp.bind "keyup valueChanged", (e, input)=> newDate = input.getValue() @_updateValidation('exp', newDate) if newDate? @_setUnderlyingValue('expMonth', newDate.getMonth() + 1) @_setUnderlyingValue('expYear', newDate.getFullYear()) @_inputViews.name.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('name', value) @_updateValidation('name', value) @_inputViews.cvc.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('cvc', value) @_updateValidation('cvc', value) @el.container.delegate "input", "keyup keydown", @_handleFieldTab.bind(@) @_tabViews.front.el.click => @flip() @_tabViews.back.el.click => @flip() _handleFieldTab: (e)-> if e.which is 9 # tab currentFieldEl = $(e.currentTarget) _oppositeFace = if @visibleFace is 'front' then 'back' else 'front' _currentFace = if @visibleFace is 'front' then 'front' else 'back' backFieldEls = @el[_oppositeFace].find('input') frontFieldEls = @el[_currentFace].find('input') if @visibleFace is 'front' and @el.front.hasClass('filled') and backFieldEls.length > 0 and frontFieldEls.index(currentFieldEl) is frontFieldEls.length-1 and not e.shiftKey @flip() backFieldEls.first().focus() e.preventDefault() if @visibleFace is 'back' and e.shiftKey @flip() backFieldEls.last().focus() # other side, now... e.preventDefault() return true _updateValidation: (fieldName, newValue)-> return false unless @product? # Check against the current product to determine if the field is filled isFilled = @product[fieldName].isFilled(newValue) # If an initial value was supplied and marked as invalid, ensure that it # has been changed to a new value. needsFix = @options.validationState[fieldName]? is false isFixed = @options.initialValues[fieldName]? and newValue isnt @options.initialValues[fieldName] # Check validity of value, asserting fixes have occurred if necessary. isValid = @product[fieldName].isValid(newValue) and ((needsFix and isFixed) or true) # Determine if state changed fillStateChanged = @_state["#{fieldName}Filled"] isnt isFilled validationStateChanged = @_state["#{fieldName}Valid"] isnt isValid # If the fill state has changed, trigger events, and make styling changes. if fillStateChanged @trigger "fieldFillStateWillChange.skeuocard", [@, fieldName, isFilled] @_inputViews[fieldName].el.toggleClass 'filled', isFilled @_state["#{fieldName}Filled"] = isFilled @trigger "fieldFillStateDidChange.skeuocard", [@, fieldName, isFilled] # If the valid state has changed, trigger events, and make styling changes. if validationStateChanged @trigger "fieldValidationStateWillChange.skeuocard", [@, fieldName, isValid] @_inputViews[fieldName].el.toggleClass 'valid', isValid @_inputViews[fieldName].el.toggleClass 'invalid', not isValid @_state["#{fieldName}Valid"] = isValid @trigger "fieldValidationStateDidChange.skeuocard", [@, fieldName, isValid] @_updateValidationForFace(@visibleFace) _updateValidationForFace: (face)-> fieldsFilled = (iv.el.hasClass('filled') for iv in @_inputViewsByFace[face]).every(Boolean) fieldsValid = (iv.el.hasClass('valid') for iv in @_inputViewsByFace[face]).every(Boolean) isFilled = (fieldsFilled and @product?) or (@_state['initiallyFilled'] or false) isValid = fieldsValid and @product? fillStateChanged = @_state["#{face}Filled"] isnt isFilled validationStateChanged = @_state["#{face}Valid"] isnt isValid if fillStateChanged @trigger "faceFillStateWillChange.skeuocard", [@, face, isFilled] @el[face].toggleClass 'filled', isFilled @_state["#{face}Filled"] = isFilled @trigger "faceFillStateDidChange.skeuocard", [@, face, isFilled] if validationStateChanged @trigger "faceValidationStateWillChange.skeuocard", [@, face, isValid] @el[face].toggleClass 'valid', isValid @el[face].toggleClass 'invalid', not isValid @_state["#{face}Valid"] = isValid @trigger "faceValidationStateDidChange.skeuocard", [@, face, isValid] ### Assert rendering changes necessary for the current product. Passing a null value instead of a product will revert the card to a generic state. ### _renderProduct: (product)-> @_log("[_renderProduct]", "Rendering product:", product) # remove existing product and issuer classes (destyling product) @el.container.removeClass (index, css)=> (css.match(/\b(product|issuer)-\S+/g) || []).join(' ') # add classes necessary to identify new product if product?.attrs.companyShortname? @el.container.addClass("product-#{product.attrs.companyShortname}") if product?.attrs.issuerShortname? @el.container.addClass("issuer-#{product.attrs.issuerShortname}") # update the underlying card type field @_setUnderlyingValue('type', product?.attrs.companyShortname || null) # reconfigure the number input groupings @_inputViews.number.setGroupings(product?.attrs.cardNumberGrouping || [@options.genericPlaceholder.length], @options.dontFocus) delete @options.dontFocus if product? # reconfigure the expiration input groupings @_inputViews.exp.reconfigure pattern: product?.attrs.expirationFormat || "MM/YY" # reconfigure the CVC @_inputViews.cvc.attr maxlength: product.attrs.cvcLength placeholder: new Array(product.attrs.cvcLength + 1).join(@options.cardNumberPlaceholderChar) # set visibility and re-layout fields @_inputViewsByFace = {front: [], back: []} focused = $('input:focus') # allow restoration of focus upon re-attachment for fieldName, destFace of product.attrs.layout @_log("Moving", fieldName, "to", destFace) viewEl = @_inputViews[fieldName].el.detach() viewEl.appendTo(@el[destFace]) @_inputViewsByFace[destFace].push @_inputViews[fieldName] @_inputViews[fieldName].show() # Restore focus. Use setTimeout to resolve IE10 issue. setTimeout => if (fieldEl = focused.first())? fieldLength = fieldEl[0].maxLength fieldEl.focus() fieldEl[0].setSelectionRange(fieldLength, fieldLength) , 10 else for fieldName, view of @_inputViews view.hide() if fieldName isnt 'number' return product _renderValidation: -> # update the validation state of all fields for fieldName, fieldView of @_inputViews @_updateValidation(fieldName, fieldView.getValue()) # Update the card's visual representation to reflect internal state. render: -> @_renderProduct(@product) @_renderValidation() # @_flipToInvalidSide() # Flip the card over. flip: -> targetFace = if @visibleFace is 'front' then 'back' else 'front' @trigger('faceWillBecomeVisible.skeuocard', [@, targetFace]) @visibleFace = targetFace @el.cardBody.toggleClass('flip') surfaceName = if @visibleFace is 'front' then 'front' else 'back' @el[surfaceName].find('.cc-field').not('.filled').find('input').first().focus() @trigger('faceDidBecomeVisible.skeuocard', [@, targetFace]) # Set a value in the underlying form. _setUnderlyingValue: (field, newValue)-> fieldEl = @el.underlyingFields[field] _newValue = (newValue || "").toString() throw "Set underlying value of unknown field: #{field}." unless fieldEl? @trigger('change.skeuocard', [@]) unless fieldEl.is('select') @el.underlyingFields[field].val(_newValue) else remapAttrKey = "data-sc-" + field.toLowerCase() fieldEl.find('option').each (i, _el)=> optionEl = $(_el) if _newValue is (optionEl.attr(remapAttrKey) || optionEl.attr('value')) @el.underlyingFields[field].val optionEl.attr('value') # Get a value from the underlying form. _getUnderlyingValue: (field)-> @el.underlyingFields[field]?.val() isValid: -> not @el.front.hasClass('invalid') and not @el.back.hasClass('invalid') # Export the object. window.Skeuocard = Skeuocard
true
### "Skeuocard" -- A Skeuomorphic Credit-Card Input Enhancement @description Skeuocard is a skeuomorphic credit card input plugin, supporting progressive enhancement. It renders a credit-card input which behaves similarly to a physical credit card. @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @updated 2013-07-25 @website http://kenkeiter.com/ @exports [window.Skeuocard] ### $ = jQuery class Skeuocard @currentDate: new Date() constructor: (el, opts = {})-> @el = container: $(el), underlyingFields: {} @_inputViews = {} @_inputViewsByFace = {front: [], back: []} @_tabViews = {} @_state = {} @product = null @visibleFace = 'front' # configure default opts optDefaults = debug: false dontFocus: false acceptedCardProducts: null cardNumberPlaceholderChar: 'X' genericPlaceholder: "XXXX XXXX XXXX XXXX" typeInputSelector: '[name="cc_type"]' numberInputSelector: '[name="cc_number"]' expMonthInputSelector: '[name="cc_exp_month"]' expYearInputSelector: '[name="cc_exp_year"]' nameInputSelector: '[name="cc_name"]' cvcInputSelector: '[name="cc_cvc"]' initialValues: {} validationState: {} strings: hiddenFaceFillPrompt: "<strong>Click here</strong> to <br>fill in the other side." hiddenFaceErrorWarning: "There's a problem on the other side." hiddenFaceSwitchPrompt: "Forget something?<br> Flip the card over." @options = $.extend(optDefaults, opts) # initialize the card @_conformDOM() # conform the DOM, add our elements @_bindInputEvents() # bind input and interaction events @_importImplicitOptions() # import init options from DOM element attrs @render() # perform initial render # Debugging helper; if debug is set to true at instantiation, messages will # be printed to the console. _log: (msg...)-> if console?.log and !!@options.debug console.log("[skeuocard]", msg...) if @options.debug? # Trigger an event on a Skeuocard instance (jQuery's #trigger signature). trigger: (args...)-> @el.container.trigger(args...) # Bind an event handler on a Skeuocard instance (jQuery's #trigger signature). bind: (args...)-> @el.container.bind(args...) ### Transform the elements within the container, conforming the DOM so that it becomes styleable, and that the underlying inputs are hidden. ### _conformDOM: -> @el.container.removeClass('no-js') @el.container.addClass("skeuocard js") # remove anything that's not an underlying form field @el.container.find("> :not(input,select,textarea)").remove() @el.container.find("> input,select,textarea").hide() # Attach underlying form fields. @el.underlyingFields = type: @el.container.find(@options.typeInputSelector) number: @el.container.find(@options.numberInputSelector) expMonth: @el.container.find(@options.expMonthInputSelector) expYear: @el.container.find(@options.expYearInputSelector) name: @el.container.find(@options.nameInputSelector) cvc: @el.container.find(@options.cvcInputSelector) # construct the necessary card elements @el.front = $("<div>").attr(class: "face front") @el.back = $("<div>").attr(class: "face back") @el.cardBody = $("<div>").attr(class: "card-body") # add elements to the DOM @el.front.appendTo(@el.cardBody) @el.back.appendTo(@el.cardBody) @el.cardBody.appendTo(@el.container) # create the validation indicator (flip tab), and attach them. @_tabViews.front = new Skeuocard::FlipTabView(@, 'front', strings: @options.strings) @_tabViews.back = new Skeuocard::FlipTabView(@, 'back', strings: @options.strings) @el.front.prepend(@_tabViews.front.el) @el.back.prepend(@_tabViews.back.el) @_tabViews.front.hide() @_tabViews.back.hide() # Create new input views, attach them to the appropriate surfaces @_inputViews = number: new @SegmentedCardNumberInputView() exp: new @ExpirationInputView(currentDate: @options.currentDate) name: new @TextInputView(class: "cc-name", placeholder: "YOUR NAME") cvc: new @TextInputView(class: "cc-cvc", placeholder: "XXX", requireMaxLength: true) # style and attach the number view to the DOM @_inputViews.number.el.addClass('cc-number') @_inputViews.number.el.appendTo(@el.front) # attach name input @_inputViews.name.el.appendTo(@el.front) # style and attach the exp view to the DOM @_inputViews.exp.el.addClass('cc-exp') @_inputViews.exp.el.appendTo(@el.front) # attach cvc field to the DOM @_inputViews.cvc.el.appendTo(@el.back) return @el.container ### Import implicit initialization options from the DOM. Brings in things like the accepted card type, initial validation state, existing values, etc. ### _importImplicitOptions: -> for fieldName, fieldEl of @el.underlyingFields # import initial values, with constructor options taking precedence unless @options.initialValues[fieldName]? @options.initialValues[fieldName] = fieldEl.val() else # update underlying field value so that it is canonical. @options.initialValues[fieldName] = @options.initialValues[fieldName].toString() @_setUnderlyingValue(fieldName, @options.initialValues[fieldName]) # set a flag if any fields were initially filled if @options.initialValues[fieldName].length > 0 @_state['initiallyFilled'] = true # import initial validation state unless @options.validationState[fieldName]? @options.validationState[fieldName] = not fieldEl.hasClass('invalid') # If no explicit acceptedCardProducts were specified, determine accepted # card products using the underlying type select field. unless @options.acceptedCardProducts? @options.acceptedCardProducts = [] @el.underlyingFields.type.find('option').each (i, _el)=> el = $(_el) shortname = el.attr('data-sc-type') || el.attr('value') @options.acceptedCardProducts.push shortname # setup default values; when render is called, these will be picked up if @options.initialValues.number.length > 0 @set 'number', @options.initialValues.number if @options.initialValues.name.length > 0 @set 'name', @options.initialValues.name if @options.initialValues.cvc.length > 0 @set 'cvc', @options.initialValues.cvc if @options.initialValues.expYear.length > 0 and @options.initialValues.expMonth.length > 0 _initialExp = new Date parseInt(@options.initialValues.expYear), parseInt(@options.initialValues.expMonth) - 1, 1 @set 'exp', _initialExp @_updateValidationForFace('front') @_updateValidationForFace('back') set: (field, newValue)-> @_inputViews[field].setValue(newValue) @_inputViews[field].trigger('valueChanged', @_inputViews[field]) ### Bind interaction events to their appropriate handlers. ### _bindInputEvents: -> # bind change handlers to render @el.underlyingFields.number.bind "change", (e)=> @_inputViews.number.setValue @_getUnderlyingValue('number') @render() _expirationChange = (e)=> month = parseInt @_getUnderlyingValue('expMonth') year = parseInt @_getUnderlyingValue('expYear') @_inputViews.exp.setValue new Date(year, month - 1) @render() @el.underlyingFields.expMonth.bind "change", _expirationChange @el.underlyingFields.expYear.bind "change", _expirationChange @el.underlyingFields.name.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('name') @render() @el.underlyingFields.cvc.bind "change", (e)=> @_inputViews.exp.setValue @_getUnderlyingValue('cvc') @render() # bind change events to their underlying form elements @_inputViews.number.bind "change valueChanged", (e, input)=> cardNumber = input.getValue() @_setUnderlyingValue 'number', cardNumber @_updateValidation 'number', cardNumber # update the product if needed. number = @_getUnderlyingValue('number') matchedProduct = Skeuocard::CardProduct.firstMatchingNumber(number) # check if the product is accepted if not @product?.eql(matchedProduct) @_log("Product will change:", @product, "=>", matchedProduct) if matchedProduct?.attrs.companyShortname in @options.acceptedCardProducts @trigger 'productWillChange.skeuocard', [@, @product, matchedProduct] previousProduct = @product @el.container.removeClass('unaccepted') @_renderProduct(matchedProduct) @product = matchedProduct else if matchedProduct? @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.addClass('unaccepted') @_renderProduct(null) @product = null else @trigger 'productWillChange.skeuocard', [@, @product, null] @el.container.removeClass('unaccepted') @_renderProduct(null) @product = null @trigger 'productDidChange.skeuocard', [@, previousProduct, @product] @_inputViews.exp.bind "keyup valueChanged", (e, input)=> newDate = input.getValue() @_updateValidation('exp', newDate) if newDate? @_setUnderlyingValue('expMonth', newDate.getMonth() + 1) @_setUnderlyingValue('expYear', newDate.getFullYear()) @_inputViews.name.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('name', value) @_updateValidation('name', value) @_inputViews.cvc.bind "keyup valueChanged", (e, input)=> value = input.getValue() @_setUnderlyingValue('cvc', value) @_updateValidation('cvc', value) @el.container.delegate "input", "keyup keydown", @_handleFieldTab.bind(@) @_tabViews.front.el.click => @flip() @_tabViews.back.el.click => @flip() _handleFieldTab: (e)-> if e.which is 9 # tab currentFieldEl = $(e.currentTarget) _oppositeFace = if @visibleFace is 'front' then 'back' else 'front' _currentFace = if @visibleFace is 'front' then 'front' else 'back' backFieldEls = @el[_oppositeFace].find('input') frontFieldEls = @el[_currentFace].find('input') if @visibleFace is 'front' and @el.front.hasClass('filled') and backFieldEls.length > 0 and frontFieldEls.index(currentFieldEl) is frontFieldEls.length-1 and not e.shiftKey @flip() backFieldEls.first().focus() e.preventDefault() if @visibleFace is 'back' and e.shiftKey @flip() backFieldEls.last().focus() # other side, now... e.preventDefault() return true _updateValidation: (fieldName, newValue)-> return false unless @product? # Check against the current product to determine if the field is filled isFilled = @product[fieldName].isFilled(newValue) # If an initial value was supplied and marked as invalid, ensure that it # has been changed to a new value. needsFix = @options.validationState[fieldName]? is false isFixed = @options.initialValues[fieldName]? and newValue isnt @options.initialValues[fieldName] # Check validity of value, asserting fixes have occurred if necessary. isValid = @product[fieldName].isValid(newValue) and ((needsFix and isFixed) or true) # Determine if state changed fillStateChanged = @_state["#{fieldName}Filled"] isnt isFilled validationStateChanged = @_state["#{fieldName}Valid"] isnt isValid # If the fill state has changed, trigger events, and make styling changes. if fillStateChanged @trigger "fieldFillStateWillChange.skeuocard", [@, fieldName, isFilled] @_inputViews[fieldName].el.toggleClass 'filled', isFilled @_state["#{fieldName}Filled"] = isFilled @trigger "fieldFillStateDidChange.skeuocard", [@, fieldName, isFilled] # If the valid state has changed, trigger events, and make styling changes. if validationStateChanged @trigger "fieldValidationStateWillChange.skeuocard", [@, fieldName, isValid] @_inputViews[fieldName].el.toggleClass 'valid', isValid @_inputViews[fieldName].el.toggleClass 'invalid', not isValid @_state["#{fieldName}Valid"] = isValid @trigger "fieldValidationStateDidChange.skeuocard", [@, fieldName, isValid] @_updateValidationForFace(@visibleFace) _updateValidationForFace: (face)-> fieldsFilled = (iv.el.hasClass('filled') for iv in @_inputViewsByFace[face]).every(Boolean) fieldsValid = (iv.el.hasClass('valid') for iv in @_inputViewsByFace[face]).every(Boolean) isFilled = (fieldsFilled and @product?) or (@_state['initiallyFilled'] or false) isValid = fieldsValid and @product? fillStateChanged = @_state["#{face}Filled"] isnt isFilled validationStateChanged = @_state["#{face}Valid"] isnt isValid if fillStateChanged @trigger "faceFillStateWillChange.skeuocard", [@, face, isFilled] @el[face].toggleClass 'filled', isFilled @_state["#{face}Filled"] = isFilled @trigger "faceFillStateDidChange.skeuocard", [@, face, isFilled] if validationStateChanged @trigger "faceValidationStateWillChange.skeuocard", [@, face, isValid] @el[face].toggleClass 'valid', isValid @el[face].toggleClass 'invalid', not isValid @_state["#{face}Valid"] = isValid @trigger "faceValidationStateDidChange.skeuocard", [@, face, isValid] ### Assert rendering changes necessary for the current product. Passing a null value instead of a product will revert the card to a generic state. ### _renderProduct: (product)-> @_log("[_renderProduct]", "Rendering product:", product) # remove existing product and issuer classes (destyling product) @el.container.removeClass (index, css)=> (css.match(/\b(product|issuer)-\S+/g) || []).join(' ') # add classes necessary to identify new product if product?.attrs.companyShortname? @el.container.addClass("product-#{product.attrs.companyShortname}") if product?.attrs.issuerShortname? @el.container.addClass("issuer-#{product.attrs.issuerShortname}") # update the underlying card type field @_setUnderlyingValue('type', product?.attrs.companyShortname || null) # reconfigure the number input groupings @_inputViews.number.setGroupings(product?.attrs.cardNumberGrouping || [@options.genericPlaceholder.length], @options.dontFocus) delete @options.dontFocus if product? # reconfigure the expiration input groupings @_inputViews.exp.reconfigure pattern: product?.attrs.expirationFormat || "MM/YY" # reconfigure the CVC @_inputViews.cvc.attr maxlength: product.attrs.cvcLength placeholder: new Array(product.attrs.cvcLength + 1).join(@options.cardNumberPlaceholderChar) # set visibility and re-layout fields @_inputViewsByFace = {front: [], back: []} focused = $('input:focus') # allow restoration of focus upon re-attachment for fieldName, destFace of product.attrs.layout @_log("Moving", fieldName, "to", destFace) viewEl = @_inputViews[fieldName].el.detach() viewEl.appendTo(@el[destFace]) @_inputViewsByFace[destFace].push @_inputViews[fieldName] @_inputViews[fieldName].show() # Restore focus. Use setTimeout to resolve IE10 issue. setTimeout => if (fieldEl = focused.first())? fieldLength = fieldEl[0].maxLength fieldEl.focus() fieldEl[0].setSelectionRange(fieldLength, fieldLength) , 10 else for fieldName, view of @_inputViews view.hide() if fieldName isnt 'number' return product _renderValidation: -> # update the validation state of all fields for fieldName, fieldView of @_inputViews @_updateValidation(fieldName, fieldView.getValue()) # Update the card's visual representation to reflect internal state. render: -> @_renderProduct(@product) @_renderValidation() # @_flipToInvalidSide() # Flip the card over. flip: -> targetFace = if @visibleFace is 'front' then 'back' else 'front' @trigger('faceWillBecomeVisible.skeuocard', [@, targetFace]) @visibleFace = targetFace @el.cardBody.toggleClass('flip') surfaceName = if @visibleFace is 'front' then 'front' else 'back' @el[surfaceName].find('.cc-field').not('.filled').find('input').first().focus() @trigger('faceDidBecomeVisible.skeuocard', [@, targetFace]) # Set a value in the underlying form. _setUnderlyingValue: (field, newValue)-> fieldEl = @el.underlyingFields[field] _newValue = (newValue || "").toString() throw "Set underlying value of unknown field: #{field}." unless fieldEl? @trigger('change.skeuocard', [@]) unless fieldEl.is('select') @el.underlyingFields[field].val(_newValue) else remapAttrKey = "data-sc-" + field.toLowerCase() fieldEl.find('option').each (i, _el)=> optionEl = $(_el) if _newValue is (optionEl.attr(remapAttrKey) || optionEl.attr('value')) @el.underlyingFields[field].val optionEl.attr('value') # Get a value from the underlying form. _getUnderlyingValue: (field)-> @el.underlyingFields[field]?.val() isValid: -> not @el.front.hasClass('invalid') and not @el.back.hasClass('invalid') # Export the object. window.Skeuocard = Skeuocard
[ { "context": " Commands:\n# hubot deploy to production - Deploy Ralph to production.\n\napps = [\n 'argos',\n 'levelup-or", "end": 100, "score": 0.7660766839981079, "start": 95, "tag": "NAME", "value": "Ralph" } ]
scripts/deploy.coffee
TheLevelUp/hubot-ralph
4
# Description: # Causes heart attacks. # # Commands: # hubot deploy to production - Deploy Ralph to production. apps = [ 'argos', 'levelup-order-ahead-production', 'levelup-production', 'order-ahead-network-production', 'plutus-production' ] emojis = [ ':+1:', ':dance:', ':party_poop:', ':party_try_not_to_cry:', ':partydumpster:', ':shush:', ':spinner:' ] module.exports = (robot) -> robot.respond /deploy\s+to\s+prod(?:uction)?/i, (msg) -> reply = "ok, deploying myself to #{msg.random(apps)} #{msg.random(emojis)}" msg.send reply
101850
# Description: # Causes heart attacks. # # Commands: # hubot deploy to production - Deploy <NAME> to production. apps = [ 'argos', 'levelup-order-ahead-production', 'levelup-production', 'order-ahead-network-production', 'plutus-production' ] emojis = [ ':+1:', ':dance:', ':party_poop:', ':party_try_not_to_cry:', ':partydumpster:', ':shush:', ':spinner:' ] module.exports = (robot) -> robot.respond /deploy\s+to\s+prod(?:uction)?/i, (msg) -> reply = "ok, deploying myself to #{msg.random(apps)} #{msg.random(emojis)}" msg.send reply
true
# Description: # Causes heart attacks. # # Commands: # hubot deploy to production - Deploy PI:NAME:<NAME>END_PI to production. apps = [ 'argos', 'levelup-order-ahead-production', 'levelup-production', 'order-ahead-network-production', 'plutus-production' ] emojis = [ ':+1:', ':dance:', ':party_poop:', ':party_try_not_to_cry:', ':partydumpster:', ':shush:', ':spinner:' ] module.exports = (robot) -> robot.respond /deploy\s+to\s+prod(?:uction)?/i, (msg) -> reply = "ok, deploying myself to #{msg.random(apps)} #{msg.random(emojis)}" msg.send reply
[ { "context": " expand tags', ->\n tags = [\n { name: \"first\" },\n { name: \"second\" },\n ]\n\n ex", "end": 337, "score": 0.6835723519325256, "start": 332, "tag": "NAME", "value": "first" }, { "context": "s = [\n { name: \"first\" },\n { n...
test/filter/tag_expand-spec.coffee
PriviPK/privipk-webapp
47
define ['angular', 'angularMocks', 'baobab.filter'], (angular) -> describe 'tag_expand filter', -> tag_expand = null beforeEach -> angular.mock.module("baobab.filter") angular.mock.inject ($filter) -> tag_expand = $filter("tag_expand") it 'should expand tags', -> tags = [ { name: "first" }, { name: "second" }, ] expect(tag_expand(tags)).toEqual("first second ")
220980
define ['angular', 'angularMocks', 'baobab.filter'], (angular) -> describe 'tag_expand filter', -> tag_expand = null beforeEach -> angular.mock.module("baobab.filter") angular.mock.inject ($filter) -> tag_expand = $filter("tag_expand") it 'should expand tags', -> tags = [ { name: "<NAME>" }, { name: "<NAME>" }, ] expect(tag_expand(tags)).toEqual("first second ")
true
define ['angular', 'angularMocks', 'baobab.filter'], (angular) -> describe 'tag_expand filter', -> tag_expand = null beforeEach -> angular.mock.module("baobab.filter") angular.mock.inject ($filter) -> tag_expand = $filter("tag_expand") it 'should expand tags', -> tags = [ { name: "PI:NAME:<NAME>END_PI" }, { name: "PI:NAME:<NAME>END_PI" }, ] expect(tag_expand(tags)).toEqual("first second ")
[ { "context": "ed\"\n state:\n firstPage: 1\n sortKey: \"surname\"\n pageSize: 20\n\n parse: (response) -> \n ", "end": 3886, "score": 0.8457931280136108, "start": 3879, "tag": "NAME", "value": "surname" }, { "context": "mns: [\n {\n ...
src/app.coffee
digihum/hispanicliverpool
0
require [ "jquery" "underscore" "backbone" "bootstrap" "backbone.paginator" "backbone-relational" ], ($, _, Backbone, Bootstrap, PageableCollection) -> htmlEncode = (value) -> $("<div/>").text(value).html() $.fn.serializeObject = -> o = {} a = @serializeArray() $.each a, -> if o[@name] isnt `undefined` o[@name] = [o[@name]] unless o[@name].push o[@name].push @value or "" else o[@name] = @value or "" return o $.ajaxPrefilter (options, originalOptions, jqXHR) -> if options.url.split(":")[0] != "http" options.url = "http://researchdb.warwick.ac.uk/liverpool/api" + options.url return app = @ #sets a top level this Address = Backbone.RelationalModel.extend() Addresses = Backbone.Collection.extend( model: Address ) Occupation = Backbone.RelationalModel.extend() Occupations = Backbone.Collection.extend url: "/occupations" model: Occupation Relationship = Backbone.RelationalModel.extend() Relationships = Backbone.Collection.extend( url: -> "/relationships/" + @models[0].id model: Relationship ) FlatPerson = Backbone.Model.extend() Person = Backbone.RelationalModel.extend( urlRoot: "/people" relations: [ type: Backbone.HasMany key: 'relationships' relatedModel: Relationship collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'occupations' relatedModel: Occupation collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'addresses' relatedModel: Address collectionType: Addresses reverseRelation: key: 'person', includeInJSON: 'id' ] parse: (response) -> # use some render helpers to add to the model some text to format fuzzy date types response.birthdate = @fuzzyDateMaker response.birthtype, response.birthdate1, response.birthdate2 response.deathdate = @fuzzyDateMaker response.deathtype, response.deathdate1, response.deathdate2 response.gender = @genderMaker response.sex _.each response.addresses, (address) -> query = [] query.push address.address.split(",")[1].trim() + " " + address.address.split(",")[0].trim() #street #address.district != "" && query.push address.district currently causes failed lookup query.push "Liverpool" address.region != "" && query.push address.region address.country != "" && query.push address.country address.query = query.join ", " response fuzzyDateMaker: (type, date1, date2) -> #takes the HL way of representing fuzzy dates, and returns a formatted string. switch type when "exactly" return date1 when "between" return "between " + ((if isset(date1) then date1 else "unknown")) + " and " + ((if isset(date2) then date2 else "unknown")) when "unknown", null return "unknown" genderMaker: (sex) -> switch sex when "m" return "Male" when "f" return "Female" when "","unknown", null return "Unknown" ) People = Backbone.Collection.extend( url: "/people" model: FlatPerson parse: (response) -> response ) PeopleSearch = Backbone.Collection.extend( url: -> console.log options #doesn't seem to be used. "/peoplesearch?" + options.querystring model: FlatPerson parse: (response) -> response ) Backbone.PageableCollection = PageableCollection PaginatedPeople = Backbone.PageableCollection.extend( model: FlatPerson url: "/peoplepaginated" state: firstPage: 1 sortKey: "surname" pageSize: 20 parse: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) response.data parseRecords: (response) -> response.data parseState: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) @state ) Place = Backbone.RelationalModel.extend( idAttribute: 'place' ) Places = Backbone.Collection.extend( model: Place parse: (response)-> console.log @, response, "parsing place" response ) Country = Backbone.RelationalModel.extend( relations: [ type: Backbone.HasMany key: 'places' relatedModel: Place reverseRelation: key: 'country' ] parse: (response) -> response ) Countries = Backbone.Collection.extend( url: "/countriesfull" model: Country ) PeopleListView = Backbone.View.extend( el: "#page" initialize: -> @listenTo(app.paginatedPeople,"sync",@render) @$el.html $("#view-loading").html() breadcrumb: (collection)-> breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "",title: "Page " + collection.state.currentPage.toString() + " of " + collection.state.lastPage }] ) $("#breadcrumb").html breadcrumb_template render: () -> that = @ @breadcrumb(paginatedPeople); @$el.empty() if !paginatedPeople @$el.html $("#view-loading").html() else if paginatedPeople require [ "backgrid" "backgrid-paginator" ], (Backgrid, BackgridPaginator) -> myCell = Backgrid.Cell.extend className: "results col-sm-1" viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" peopleGrid = new Backgrid.Grid( className: "table table-striped table-condensed" row: ClickableRow columns: [ { name: "surname" label: "Surname" cell: "string" sortable: true editable: false } { name: "forenames" label: "Forename(s)" cell: forenamesCell sortable: true editable: false } { name: "sex" label: "Gender" cell: genderCell sortable: true editable: false } { cell: myCell } ] collection: paginatedPeople ) $paginatorExample = $("#page") $paginatorExample.append peopleGrid.render().el paginator = new Backgrid.Extension.Paginator collection: paginatedPeople $paginatorExample.append paginator.render().el paginator.listenTo(paginatedPeople,"reset", () -> router.navigate "list/page/" + @collection.state.currentPage.toString(), trigger: false that.breadcrumb(@collection) return ) return @$el.show() else @$el.show() return ) SearchFormView = Backbone.View.extend( el: "#page" render: (options) -> that = this templated = _.template($("#breadcrumb-template").html(), breadcrumbs: [ title: "Search" url: "/search" ] ) $("#breadcrumb").html templated require ["text!../templates/search.html.tpl"], (template) -> that.$el.html _.template(template) return @countries = new Countries() @countries.fetch dataType: "jsonp" success: (countries) -> $(countries.models).each (index, country) -> $("select[name=birthCountry]").append $("<option></option>").attr("value", country.get("country")).text(country.get("country")) return return occupations = new Occupations() occupations.fetch dataType: "jsonp" success: (occupations) -> $(occupations.models).each (index, occupation) -> $("#occupation-category").append $("<option></option>").attr("value", occupation.get("category")).attr("data-id",occupation.get("id")).text(occupation.get("category")) return return return events: "click div[id^=search-] label.btn": "visualDateUpdate" "change input[id$=-start], input[id$=-end]": "valueDateUpdate" "click label[id$=-include]": "dateSelectorUpdate" "submit #search-form": "searchResults" "change select[name=birthCountry]": "placesUpdate" searchResults: (e) -> e.preventDefault() peopleSearchResultsView = new PeopleSearchResultsView() queryString = $(e.currentTarget).serialize() @$el.html $("#view-loading").html() router.navigate "search/results?" + queryString, trigger: true peopleSearchResultsView.search queryString false dateSelectorUpdate: (event) -> #reset $("#birth-start, #birth-and, #death-start, #death-and").hide() $("input[name^=date-type]:checked").each -> @.checked = false; $("label.disabled").removeClass("disabled") return true visualDateUpdate: (event) -> optionHit = $(event.currentTarget)[0].firstElementChild set = $("input[name='birth-death']:checked").val() #this returns birth or death unset = $("input[name='birth-death']:not(:checked)").val() #this returns birth or death switch optionHit.value when "exactly" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "before" $("#" + set + "-start, #" + set + "-and").hide() $("#" + set + "-end").show() when "after" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "between" $("#" + set + "-end, #" + set + "-and, #" + set + "-start").show() else @valueDateUpdate event return valueDateUpdate: (event) -> set = event.currentTarget.id.split("-")[0] optionSelected = parseInt(event.currentTarget.id.split("-")[2]) if event.type is "click" optionSelected = parseInt($("input[name=" + set + "type]:checked").val()) if event.type is "change" switch optionSelected when "excatly" #precice $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val $("#" + set + "-start").val() when "before" #before $("#" + set + "-start").val "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" when "after" #after $("#" + set + "-end").val "9999" $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" when "between" #between console.log "evaluating: ", $("#" + set + "-start").val(), $("#" + set + "-end").val() $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" else return placesUpdate: (event) -> that = @ @country = @countries.findWhere country: $(event.currentTarget).children("option:selected")[0].value switch @country.get("places").models.length when 1 $("select[name=birthPlace]") .empty() .attr("disabled",true) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) when 0 $("select[name=birthPlace]") .empty() .attr("disabled",true) else $("select[name=birthPlace]") .empty() .attr("disabled",false) .append $("<option></option>").attr("value", "").text("-- " + @country.get("places").models.length + " places within " + @country.get("country") + " --" ) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) initialize: -> _.bindAll(@,'render','placesLookup') @model.bind('change:places', @placesLookup) ) PeopleSearchResultsView = Backbone.View.extend( el: "#page", initialize: -> @$el.html $("#view-loading").html() @peopleResults = new PeopleSearch @createBackGrid() createBackGrid: -> that = @ require ["backgrid"], (Backgrid) -> myCell = Backgrid.Cell.extend viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" that.peopleGrid = new Backgrid.Grid( className: "table table-condensed table-striped" row: ClickableRow columns: [ { name: "surname" label: "Surname" cell: "string" sortable: true editable: false } { name: "forenames" label: "Forename(s)" cell: "string" sortable: true editable: false } { name: "sex" label: "Gender" className: "gender" cell: "string" sortable: true editable: false } { className: "button" cell: myCell editable: false } ], collection: that.peopleResults ) search: (queryString) -> that = @ $.when @peopleResults.fetch dataType: "jsonp" url: "/peoplesearch?" + queryString .done -> that.render() render: -> that = @ breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [url: "#search",title: "People Search"] ) breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "#search",title: "People Search"},{url: "",title:"Showing search results (" + that.peopleResults.length + ")"}] ) $("#breadcrumb").html breadcrumb_template @$el.empty() @$el.append @peopleGrid.render().el ) PersonSingleView = Backbone.View.extend( el: "#page", initialize: -> @listenTo @model, 'change', @.render @model.fetch dataType: "jsonp" render: (options) -> that = @ require ["text!../templates/view.html.tpl"], (template) -> that.$el.html _.template(template) return # render the person partial require ["text!../templates/view_details.html.tpl"], (template) -> $("#person-details").html _.template(template, person: that.model ) return # now we have a name, add this to the breadcrumb template = _.template($("#breadcrumb-template").html(), breadcrumbs: [ url: "#view/" + @model.get("id") title: @model.get("forenames") + " " + @model.get("surname") ] ) $("#breadcrumb").html template if @model.get("relationships").models.length > 0 require ["text!../templates/view_relationships.html.tpl"], (template) -> $("#relationships").empty().html _.template template, relationships: that.model.get("relationships").models if @model.get("occupations").models.length > 0 require ["text!../templates/view_occupation.html.tpl"], (template) -> $("#bibliographical-details .loading").remove(); $("#bibliographical-details").append _.template template, occupations: that.model.get("occupations").models if @model.get("addresses").models.length > 0 require ["text!../templates/view_address.html.tpl"], (template) -> $("#bibliographical-details").append _.template template, addresses: that.model.get("addresses").models that.mapView = new MapView(); that.mapView.render(); _.each that.model.get("addresses").models, (address) -> if address.get("latitude") && address.get("longitude") #use an existing geocode that.mapView.addMarker(address.get("latitude"),address.get("longitude")) else #create a new geocode geocode = new GeoCode id: address.get("query") geocode.fetchFind dataType: "jsonp" that.listenTo geocode, 'change', that.addMarker addMarker: (geocode)-> #popupContent = "Source: " + address.get("recordtype") + "(" + address.get("recorddate") + ")<br/> " + address.get("query") @mapView.addMarker(geocode.get("latitude"),geocode.get("longitude"), geocode.get("id") ) ) MapView = Backbone.View.extend el: "#address-map" initialize: -> require ["leaflet"], -> @.map = L.map "address-map" .setView [0, 0], 10 render: (options) -> that = @ require ["leaflet"], -> L.tileLayer 'http://{s}.tiles.mapbox.com/v3/steveranford.icifhpgl/{z}/{x}/{y}.png', attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>' maxZoom: 18 .addTo @.map $(that.el).hide() addMarker: (lat,long,popupContent) -> that = @ require ["leaflet"], -> location = L.latLng lat,long L.marker location .addTo(@.map) .bindPopup(popupContent).openPopup(); @.map.setView [lat, long], 15 $(that.el).show() GeoCode = Backbone.Model.extend( urlRoot: "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/" parse: (response) -> geocode = {} if response.locations.length > 0 geocode.longitude = response.locations[0].feature.geometry.x || '' geocode.latitude = response.locations[0].feature.geometry.y || '' geocode fetchFind: (options) -> options = options || {}; if options.url == undefined options.url = @urlRoot + "find?f=pjson&text=" + @id; return Backbone.Model.prototype.fetch.call this, options ) Router = Backbone.Router.extend(routes: "": "home" "view/:id": "viewPerson" new: "editPerson" "list/page/:page": "listPage" list: "home" search: "searchForm" "search/results?:querystring": "viewPersonResults" #not tested, in place to permit direct access "search/results": "searchForm" ) router = new Router #because peopleListView is special, we need to have this outside of the init router, otherwise it doesn't work when we call a subpage directly etc. router.on "route:home", -> app.paginatedPeople = new PaginatedPeople() #needs to create a paginated people peopleListView = new PeopleListView() app.paginatedPeople.getFirstPage dataType: "jsonp" return router.on "route:listPage", (page) -> app.paginatedPeople = new PaginatedPeople() #assumes that this is only called when a new request peopleListView = new PeopleListView() app.paginatedPeople.getPage parseInt(page), dataType: "jsonp" return router.on "route:searchForm", -> searchFormView = new SearchFormView() searchFormView.render() return router.on "route:viewPerson", (id) -> if person = Person.findModel {id: id} else person = new Person id: id personSingleView = new PersonSingleView({model: person}) return router.on "route:viewPersonResults", (querystring) -> peopleSearchResultsView = new PeopleSearchResultsView() peopleSearchResultsView.search querystring return Backbone.history.start() return
201316
require [ "jquery" "underscore" "backbone" "bootstrap" "backbone.paginator" "backbone-relational" ], ($, _, Backbone, Bootstrap, PageableCollection) -> htmlEncode = (value) -> $("<div/>").text(value).html() $.fn.serializeObject = -> o = {} a = @serializeArray() $.each a, -> if o[@name] isnt `undefined` o[@name] = [o[@name]] unless o[@name].push o[@name].push @value or "" else o[@name] = @value or "" return o $.ajaxPrefilter (options, originalOptions, jqXHR) -> if options.url.split(":")[0] != "http" options.url = "http://researchdb.warwick.ac.uk/liverpool/api" + options.url return app = @ #sets a top level this Address = Backbone.RelationalModel.extend() Addresses = Backbone.Collection.extend( model: Address ) Occupation = Backbone.RelationalModel.extend() Occupations = Backbone.Collection.extend url: "/occupations" model: Occupation Relationship = Backbone.RelationalModel.extend() Relationships = Backbone.Collection.extend( url: -> "/relationships/" + @models[0].id model: Relationship ) FlatPerson = Backbone.Model.extend() Person = Backbone.RelationalModel.extend( urlRoot: "/people" relations: [ type: Backbone.HasMany key: 'relationships' relatedModel: Relationship collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'occupations' relatedModel: Occupation collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'addresses' relatedModel: Address collectionType: Addresses reverseRelation: key: 'person', includeInJSON: 'id' ] parse: (response) -> # use some render helpers to add to the model some text to format fuzzy date types response.birthdate = @fuzzyDateMaker response.birthtype, response.birthdate1, response.birthdate2 response.deathdate = @fuzzyDateMaker response.deathtype, response.deathdate1, response.deathdate2 response.gender = @genderMaker response.sex _.each response.addresses, (address) -> query = [] query.push address.address.split(",")[1].trim() + " " + address.address.split(",")[0].trim() #street #address.district != "" && query.push address.district currently causes failed lookup query.push "Liverpool" address.region != "" && query.push address.region address.country != "" && query.push address.country address.query = query.join ", " response fuzzyDateMaker: (type, date1, date2) -> #takes the HL way of representing fuzzy dates, and returns a formatted string. switch type when "exactly" return date1 when "between" return "between " + ((if isset(date1) then date1 else "unknown")) + " and " + ((if isset(date2) then date2 else "unknown")) when "unknown", null return "unknown" genderMaker: (sex) -> switch sex when "m" return "Male" when "f" return "Female" when "","unknown", null return "Unknown" ) People = Backbone.Collection.extend( url: "/people" model: FlatPerson parse: (response) -> response ) PeopleSearch = Backbone.Collection.extend( url: -> console.log options #doesn't seem to be used. "/peoplesearch?" + options.querystring model: FlatPerson parse: (response) -> response ) Backbone.PageableCollection = PageableCollection PaginatedPeople = Backbone.PageableCollection.extend( model: FlatPerson url: "/peoplepaginated" state: firstPage: 1 sortKey: "<NAME>" pageSize: 20 parse: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) response.data parseRecords: (response) -> response.data parseState: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) @state ) Place = Backbone.RelationalModel.extend( idAttribute: 'place' ) Places = Backbone.Collection.extend( model: Place parse: (response)-> console.log @, response, "parsing place" response ) Country = Backbone.RelationalModel.extend( relations: [ type: Backbone.HasMany key: 'places' relatedModel: Place reverseRelation: key: 'country' ] parse: (response) -> response ) Countries = Backbone.Collection.extend( url: "/countriesfull" model: Country ) PeopleListView = Backbone.View.extend( el: "#page" initialize: -> @listenTo(app.paginatedPeople,"sync",@render) @$el.html $("#view-loading").html() breadcrumb: (collection)-> breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "",title: "Page " + collection.state.currentPage.toString() + " of " + collection.state.lastPage }] ) $("#breadcrumb").html breadcrumb_template render: () -> that = @ @breadcrumb(paginatedPeople); @$el.empty() if !paginatedPeople @$el.html $("#view-loading").html() else if paginatedPeople require [ "backgrid" "backgrid-paginator" ], (Backgrid, BackgridPaginator) -> myCell = Backgrid.Cell.extend className: "results col-sm-1" viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" peopleGrid = new Backgrid.Grid( className: "table table-striped table-condensed" row: ClickableRow columns: [ { name: "<NAME>" label: "Surname" cell: "string" sortable: true editable: false } { name: "<NAME>" label: "Forename(s)" cell: forenamesCell sortable: true editable: false } { name: "sex" label: "Gender" cell: genderCell sortable: true editable: false } { cell: myCell } ] collection: paginatedPeople ) $paginatorExample = $("#page") $paginatorExample.append peopleGrid.render().el paginator = new Backgrid.Extension.Paginator collection: paginatedPeople $paginatorExample.append paginator.render().el paginator.listenTo(paginatedPeople,"reset", () -> router.navigate "list/page/" + @collection.state.currentPage.toString(), trigger: false that.breadcrumb(@collection) return ) return @$el.show() else @$el.show() return ) SearchFormView = Backbone.View.extend( el: "#page" render: (options) -> that = this templated = _.template($("#breadcrumb-template").html(), breadcrumbs: [ title: "Search" url: "/search" ] ) $("#breadcrumb").html templated require ["text!../templates/search.html.tpl"], (template) -> that.$el.html _.template(template) return @countries = new Countries() @countries.fetch dataType: "jsonp" success: (countries) -> $(countries.models).each (index, country) -> $("select[name=birthCountry]").append $("<option></option>").attr("value", country.get("country")).text(country.get("country")) return return occupations = new Occupations() occupations.fetch dataType: "jsonp" success: (occupations) -> $(occupations.models).each (index, occupation) -> $("#occupation-category").append $("<option></option>").attr("value", occupation.get("category")).attr("data-id",occupation.get("id")).text(occupation.get("category")) return return return events: "click div[id^=search-] label.btn": "visualDateUpdate" "change input[id$=-start], input[id$=-end]": "valueDateUpdate" "click label[id$=-include]": "dateSelectorUpdate" "submit #search-form": "searchResults" "change select[name=birthCountry]": "placesUpdate" searchResults: (e) -> e.preventDefault() peopleSearchResultsView = new PeopleSearchResultsView() queryString = $(e.currentTarget).serialize() @$el.html $("#view-loading").html() router.navigate "search/results?" + queryString, trigger: true peopleSearchResultsView.search queryString false dateSelectorUpdate: (event) -> #reset $("#birth-start, #birth-and, #death-start, #death-and").hide() $("input[name^=date-type]:checked").each -> @.checked = false; $("label.disabled").removeClass("disabled") return true visualDateUpdate: (event) -> optionHit = $(event.currentTarget)[0].firstElementChild set = $("input[name='birth-death']:checked").val() #this returns birth or death unset = $("input[name='birth-death']:not(:checked)").val() #this returns birth or death switch optionHit.value when "exactly" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "before" $("#" + set + "-start, #" + set + "-and").hide() $("#" + set + "-end").show() when "after" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "between" $("#" + set + "-end, #" + set + "-and, #" + set + "-start").show() else @valueDateUpdate event return valueDateUpdate: (event) -> set = event.currentTarget.id.split("-")[0] optionSelected = parseInt(event.currentTarget.id.split("-")[2]) if event.type is "click" optionSelected = parseInt($("input[name=" + set + "type]:checked").val()) if event.type is "change" switch optionSelected when "excatly" #precice $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val $("#" + set + "-start").val() when "before" #before $("#" + set + "-start").val "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" when "after" #after $("#" + set + "-end").val "9999" $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" when "between" #between console.log "evaluating: ", $("#" + set + "-start").val(), $("#" + set + "-end").val() $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" else return placesUpdate: (event) -> that = @ @country = @countries.findWhere country: $(event.currentTarget).children("option:selected")[0].value switch @country.get("places").models.length when 1 $("select[name=birthPlace]") .empty() .attr("disabled",true) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) when 0 $("select[name=birthPlace]") .empty() .attr("disabled",true) else $("select[name=birthPlace]") .empty() .attr("disabled",false) .append $("<option></option>").attr("value", "").text("-- " + @country.get("places").models.length + " places within " + @country.get("country") + " --" ) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) initialize: -> _.bindAll(@,'render','placesLookup') @model.bind('change:places', @placesLookup) ) PeopleSearchResultsView = Backbone.View.extend( el: "#page", initialize: -> @$el.html $("#view-loading").html() @peopleResults = new PeopleSearch @createBackGrid() createBackGrid: -> that = @ require ["backgrid"], (Backgrid) -> myCell = Backgrid.Cell.extend viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" that.peopleGrid = new Backgrid.Grid( className: "table table-condensed table-striped" row: ClickableRow columns: [ { name: "<NAME>" label: "Surname" cell: "string" sortable: true editable: false } { name: "forenames" label: "Forename(s)" cell: "string" sortable: true editable: false } { name: "sex" label: "Gender" className: "gender" cell: "string" sortable: true editable: false } { className: "button" cell: myCell editable: false } ], collection: that.peopleResults ) search: (queryString) -> that = @ $.when @peopleResults.fetch dataType: "jsonp" url: "/peoplesearch?" + queryString .done -> that.render() render: -> that = @ breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [url: "#search",title: "People Search"] ) breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "#search",title: "People Search"},{url: "",title:"Showing search results (" + that.peopleResults.length + ")"}] ) $("#breadcrumb").html breadcrumb_template @$el.empty() @$el.append @peopleGrid.render().el ) PersonSingleView = Backbone.View.extend( el: "#page", initialize: -> @listenTo @model, 'change', @.render @model.fetch dataType: "jsonp" render: (options) -> that = @ require ["text!../templates/view.html.tpl"], (template) -> that.$el.html _.template(template) return # render the person partial require ["text!../templates/view_details.html.tpl"], (template) -> $("#person-details").html _.template(template, person: that.model ) return # now we have a name, add this to the breadcrumb template = _.template($("#breadcrumb-template").html(), breadcrumbs: [ url: "#view/" + @model.get("id") title: @model.get("forenames") + " " + @model.get("surname") ] ) $("#breadcrumb").html template if @model.get("relationships").models.length > 0 require ["text!../templates/view_relationships.html.tpl"], (template) -> $("#relationships").empty().html _.template template, relationships: that.model.get("relationships").models if @model.get("occupations").models.length > 0 require ["text!../templates/view_occupation.html.tpl"], (template) -> $("#bibliographical-details .loading").remove(); $("#bibliographical-details").append _.template template, occupations: that.model.get("occupations").models if @model.get("addresses").models.length > 0 require ["text!../templates/view_address.html.tpl"], (template) -> $("#bibliographical-details").append _.template template, addresses: that.model.get("addresses").models that.mapView = new MapView(); that.mapView.render(); _.each that.model.get("addresses").models, (address) -> if address.get("latitude") && address.get("longitude") #use an existing geocode that.mapView.addMarker(address.get("latitude"),address.get("longitude")) else #create a new geocode geocode = new GeoCode id: address.get("query") geocode.fetchFind dataType: "jsonp" that.listenTo geocode, 'change', that.addMarker addMarker: (geocode)-> #popupContent = "Source: " + address.get("recordtype") + "(" + address.get("recorddate") + ")<br/> " + address.get("query") @mapView.addMarker(geocode.get("latitude"),geocode.get("longitude"), geocode.get("id") ) ) MapView = Backbone.View.extend el: "#address-map" initialize: -> require ["leaflet"], -> @.map = L.map "address-map" .setView [0, 0], 10 render: (options) -> that = @ require ["leaflet"], -> L.tileLayer 'http://{s}.tiles.mapbox.com/v3/steveranford.icifhpgl/{z}/{x}/{y}.png', attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>' maxZoom: 18 .addTo @.map $(that.el).hide() addMarker: (lat,long,popupContent) -> that = @ require ["leaflet"], -> location = L.latLng lat,long L.marker location .addTo(@.map) .bindPopup(popupContent).openPopup(); @.map.setView [lat, long], 15 $(that.el).show() GeoCode = Backbone.Model.extend( urlRoot: "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/" parse: (response) -> geocode = {} if response.locations.length > 0 geocode.longitude = response.locations[0].feature.geometry.x || '' geocode.latitude = response.locations[0].feature.geometry.y || '' geocode fetchFind: (options) -> options = options || {}; if options.url == undefined options.url = @urlRoot + "find?f=pjson&text=" + @id; return Backbone.Model.prototype.fetch.call this, options ) Router = Backbone.Router.extend(routes: "": "home" "view/:id": "viewPerson" new: "editPerson" "list/page/:page": "listPage" list: "home" search: "searchForm" "search/results?:querystring": "viewPersonResults" #not tested, in place to permit direct access "search/results": "searchForm" ) router = new Router #because peopleListView is special, we need to have this outside of the init router, otherwise it doesn't work when we call a subpage directly etc. router.on "route:home", -> app.paginatedPeople = new PaginatedPeople() #needs to create a paginated people peopleListView = new PeopleListView() app.paginatedPeople.getFirstPage dataType: "jsonp" return router.on "route:listPage", (page) -> app.paginatedPeople = new PaginatedPeople() #assumes that this is only called when a new request peopleListView = new PeopleListView() app.paginatedPeople.getPage parseInt(page), dataType: "jsonp" return router.on "route:searchForm", -> searchFormView = new SearchFormView() searchFormView.render() return router.on "route:viewPerson", (id) -> if person = Person.findModel {id: id} else person = new Person id: id personSingleView = new PersonSingleView({model: person}) return router.on "route:viewPersonResults", (querystring) -> peopleSearchResultsView = new PeopleSearchResultsView() peopleSearchResultsView.search querystring return Backbone.history.start() return
true
require [ "jquery" "underscore" "backbone" "bootstrap" "backbone.paginator" "backbone-relational" ], ($, _, Backbone, Bootstrap, PageableCollection) -> htmlEncode = (value) -> $("<div/>").text(value).html() $.fn.serializeObject = -> o = {} a = @serializeArray() $.each a, -> if o[@name] isnt `undefined` o[@name] = [o[@name]] unless o[@name].push o[@name].push @value or "" else o[@name] = @value or "" return o $.ajaxPrefilter (options, originalOptions, jqXHR) -> if options.url.split(":")[0] != "http" options.url = "http://researchdb.warwick.ac.uk/liverpool/api" + options.url return app = @ #sets a top level this Address = Backbone.RelationalModel.extend() Addresses = Backbone.Collection.extend( model: Address ) Occupation = Backbone.RelationalModel.extend() Occupations = Backbone.Collection.extend url: "/occupations" model: Occupation Relationship = Backbone.RelationalModel.extend() Relationships = Backbone.Collection.extend( url: -> "/relationships/" + @models[0].id model: Relationship ) FlatPerson = Backbone.Model.extend() Person = Backbone.RelationalModel.extend( urlRoot: "/people" relations: [ type: Backbone.HasMany key: 'relationships' relatedModel: Relationship collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'occupations' relatedModel: Occupation collectionType: Occupations reverseRelation: key: 'person', includeInJSON: 'id' , type: Backbone.HasMany key: 'addresses' relatedModel: Address collectionType: Addresses reverseRelation: key: 'person', includeInJSON: 'id' ] parse: (response) -> # use some render helpers to add to the model some text to format fuzzy date types response.birthdate = @fuzzyDateMaker response.birthtype, response.birthdate1, response.birthdate2 response.deathdate = @fuzzyDateMaker response.deathtype, response.deathdate1, response.deathdate2 response.gender = @genderMaker response.sex _.each response.addresses, (address) -> query = [] query.push address.address.split(",")[1].trim() + " " + address.address.split(",")[0].trim() #street #address.district != "" && query.push address.district currently causes failed lookup query.push "Liverpool" address.region != "" && query.push address.region address.country != "" && query.push address.country address.query = query.join ", " response fuzzyDateMaker: (type, date1, date2) -> #takes the HL way of representing fuzzy dates, and returns a formatted string. switch type when "exactly" return date1 when "between" return "between " + ((if isset(date1) then date1 else "unknown")) + " and " + ((if isset(date2) then date2 else "unknown")) when "unknown", null return "unknown" genderMaker: (sex) -> switch sex when "m" return "Male" when "f" return "Female" when "","unknown", null return "Unknown" ) People = Backbone.Collection.extend( url: "/people" model: FlatPerson parse: (response) -> response ) PeopleSearch = Backbone.Collection.extend( url: -> console.log options #doesn't seem to be used. "/peoplesearch?" + options.querystring model: FlatPerson parse: (response) -> response ) Backbone.PageableCollection = PageableCollection PaginatedPeople = Backbone.PageableCollection.extend( model: FlatPerson url: "/peoplepaginated" state: firstPage: 1 sortKey: "PI:NAME:<NAME>END_PI" pageSize: 20 parse: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) response.data parseRecords: (response) -> response.data parseState: (response) -> @state.totalRecords = parseInt(response.total) @state.lastPage = Math.ceil(response.total / @state.pageSize) @state ) Place = Backbone.RelationalModel.extend( idAttribute: 'place' ) Places = Backbone.Collection.extend( model: Place parse: (response)-> console.log @, response, "parsing place" response ) Country = Backbone.RelationalModel.extend( relations: [ type: Backbone.HasMany key: 'places' relatedModel: Place reverseRelation: key: 'country' ] parse: (response) -> response ) Countries = Backbone.Collection.extend( url: "/countriesfull" model: Country ) PeopleListView = Backbone.View.extend( el: "#page" initialize: -> @listenTo(app.paginatedPeople,"sync",@render) @$el.html $("#view-loading").html() breadcrumb: (collection)-> breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "",title: "Page " + collection.state.currentPage.toString() + " of " + collection.state.lastPage }] ) $("#breadcrumb").html breadcrumb_template render: () -> that = @ @breadcrumb(paginatedPeople); @$el.empty() if !paginatedPeople @$el.html $("#view-loading").html() else if paginatedPeople require [ "backgrid" "backgrid-paginator" ], (Backgrid, BackgridPaginator) -> myCell = Backgrid.Cell.extend className: "results col-sm-1" viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" peopleGrid = new Backgrid.Grid( className: "table table-striped table-condensed" row: ClickableRow columns: [ { name: "PI:NAME:<NAME>END_PI" label: "Surname" cell: "string" sortable: true editable: false } { name: "PI:NAME:<NAME>END_PI" label: "Forename(s)" cell: forenamesCell sortable: true editable: false } { name: "sex" label: "Gender" cell: genderCell sortable: true editable: false } { cell: myCell } ] collection: paginatedPeople ) $paginatorExample = $("#page") $paginatorExample.append peopleGrid.render().el paginator = new Backgrid.Extension.Paginator collection: paginatedPeople $paginatorExample.append paginator.render().el paginator.listenTo(paginatedPeople,"reset", () -> router.navigate "list/page/" + @collection.state.currentPage.toString(), trigger: false that.breadcrumb(@collection) return ) return @$el.show() else @$el.show() return ) SearchFormView = Backbone.View.extend( el: "#page" render: (options) -> that = this templated = _.template($("#breadcrumb-template").html(), breadcrumbs: [ title: "Search" url: "/search" ] ) $("#breadcrumb").html templated require ["text!../templates/search.html.tpl"], (template) -> that.$el.html _.template(template) return @countries = new Countries() @countries.fetch dataType: "jsonp" success: (countries) -> $(countries.models).each (index, country) -> $("select[name=birthCountry]").append $("<option></option>").attr("value", country.get("country")).text(country.get("country")) return return occupations = new Occupations() occupations.fetch dataType: "jsonp" success: (occupations) -> $(occupations.models).each (index, occupation) -> $("#occupation-category").append $("<option></option>").attr("value", occupation.get("category")).attr("data-id",occupation.get("id")).text(occupation.get("category")) return return return events: "click div[id^=search-] label.btn": "visualDateUpdate" "change input[id$=-start], input[id$=-end]": "valueDateUpdate" "click label[id$=-include]": "dateSelectorUpdate" "submit #search-form": "searchResults" "change select[name=birthCountry]": "placesUpdate" searchResults: (e) -> e.preventDefault() peopleSearchResultsView = new PeopleSearchResultsView() queryString = $(e.currentTarget).serialize() @$el.html $("#view-loading").html() router.navigate "search/results?" + queryString, trigger: true peopleSearchResultsView.search queryString false dateSelectorUpdate: (event) -> #reset $("#birth-start, #birth-and, #death-start, #death-and").hide() $("input[name^=date-type]:checked").each -> @.checked = false; $("label.disabled").removeClass("disabled") return true visualDateUpdate: (event) -> optionHit = $(event.currentTarget)[0].firstElementChild set = $("input[name='birth-death']:checked").val() #this returns birth or death unset = $("input[name='birth-death']:not(:checked)").val() #this returns birth or death switch optionHit.value when "exactly" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "before" $("#" + set + "-start, #" + set + "-and").hide() $("#" + set + "-end").show() when "after" $("#" + set + "-end, #" + set + "-and").hide() $("#" + set + "-start").show() when "between" $("#" + set + "-end, #" + set + "-and, #" + set + "-start").show() else @valueDateUpdate event return valueDateUpdate: (event) -> set = event.currentTarget.id.split("-")[0] optionSelected = parseInt(event.currentTarget.id.split("-")[2]) if event.type is "click" optionSelected = parseInt($("input[name=" + set + "type]:checked").val()) if event.type is "change" switch optionSelected when "excatly" #precice $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val $("#" + set + "-start").val() when "before" #before $("#" + set + "-start").val "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" when "after" #after $("#" + set + "-end").val "9999" $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" when "between" #between console.log "evaluating: ", $("#" + set + "-start").val(), $("#" + set + "-end").val() $("#" + set + "-start").val "" if $("#" + set + "-start").val() is "0000" $("#" + set + "-end").val "" if $("#" + set + "-end").val() is "9999" else return placesUpdate: (event) -> that = @ @country = @countries.findWhere country: $(event.currentTarget).children("option:selected")[0].value switch @country.get("places").models.length when 1 $("select[name=birthPlace]") .empty() .attr("disabled",true) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) when 0 $("select[name=birthPlace]") .empty() .attr("disabled",true) else $("select[name=birthPlace]") .empty() .attr("disabled",false) .append $("<option></option>").attr("value", "").text("-- " + @country.get("places").models.length + " places within " + @country.get("country") + " --" ) $.each(@country.get("places").models (index, place) -> $("select[name=birthPlace]").append $("<option></option>").attr("value", place.get("place")).text(place.get("place")) ) initialize: -> _.bindAll(@,'render','placesLookup') @model.bind('change:places', @placesLookup) ) PeopleSearchResultsView = Backbone.View.extend( el: "#page", initialize: -> @$el.html $("#view-loading").html() @peopleResults = new PeopleSearch @createBackGrid() createBackGrid: -> that = @ require ["backgrid"], (Backgrid) -> myCell = Backgrid.Cell.extend viewingPerson: (e) -> e.preventDefault(); return router.navigate "view/" + this.model.get("id"), trigger: true render: -> @$el.html("<button class='btn btn-primary btn-xs'>Records</button>") return @ events: "click": "viewingPerson" ClickableRow = Backgrid.Row.extend events: "click": "rowClicked" rowClicked: -> return router.navigate "view/" + this.model.get("id"), { trigger: true } genderCell = Backgrid.Cell.extend className: "gender-cell col-sm-5" forenamesCell = Backgrid.Cell.extend className: "forenames-cell col-sm-3" surnameCell = Backgrid.Cell.extend className: "surname-cell col-sm-3" that.peopleGrid = new Backgrid.Grid( className: "table table-condensed table-striped" row: ClickableRow columns: [ { name: "PI:NAME:<NAME>END_PI" label: "Surname" cell: "string" sortable: true editable: false } { name: "forenames" label: "Forename(s)" cell: "string" sortable: true editable: false } { name: "sex" label: "Gender" className: "gender" cell: "string" sortable: true editable: false } { className: "button" cell: myCell editable: false } ], collection: that.peopleResults ) search: (queryString) -> that = @ $.when @peopleResults.fetch dataType: "jsonp" url: "/peoplesearch?" + queryString .done -> that.render() render: -> that = @ breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [url: "#search",title: "People Search"] ) breadcrumb_template = _.template($("#breadcrumb-template").html(), breadcrumbs: [{url: "#search",title: "People Search"},{url: "",title:"Showing search results (" + that.peopleResults.length + ")"}] ) $("#breadcrumb").html breadcrumb_template @$el.empty() @$el.append @peopleGrid.render().el ) PersonSingleView = Backbone.View.extend( el: "#page", initialize: -> @listenTo @model, 'change', @.render @model.fetch dataType: "jsonp" render: (options) -> that = @ require ["text!../templates/view.html.tpl"], (template) -> that.$el.html _.template(template) return # render the person partial require ["text!../templates/view_details.html.tpl"], (template) -> $("#person-details").html _.template(template, person: that.model ) return # now we have a name, add this to the breadcrumb template = _.template($("#breadcrumb-template").html(), breadcrumbs: [ url: "#view/" + @model.get("id") title: @model.get("forenames") + " " + @model.get("surname") ] ) $("#breadcrumb").html template if @model.get("relationships").models.length > 0 require ["text!../templates/view_relationships.html.tpl"], (template) -> $("#relationships").empty().html _.template template, relationships: that.model.get("relationships").models if @model.get("occupations").models.length > 0 require ["text!../templates/view_occupation.html.tpl"], (template) -> $("#bibliographical-details .loading").remove(); $("#bibliographical-details").append _.template template, occupations: that.model.get("occupations").models if @model.get("addresses").models.length > 0 require ["text!../templates/view_address.html.tpl"], (template) -> $("#bibliographical-details").append _.template template, addresses: that.model.get("addresses").models that.mapView = new MapView(); that.mapView.render(); _.each that.model.get("addresses").models, (address) -> if address.get("latitude") && address.get("longitude") #use an existing geocode that.mapView.addMarker(address.get("latitude"),address.get("longitude")) else #create a new geocode geocode = new GeoCode id: address.get("query") geocode.fetchFind dataType: "jsonp" that.listenTo geocode, 'change', that.addMarker addMarker: (geocode)-> #popupContent = "Source: " + address.get("recordtype") + "(" + address.get("recorddate") + ")<br/> " + address.get("query") @mapView.addMarker(geocode.get("latitude"),geocode.get("longitude"), geocode.get("id") ) ) MapView = Backbone.View.extend el: "#address-map" initialize: -> require ["leaflet"], -> @.map = L.map "address-map" .setView [0, 0], 10 render: (options) -> that = @ require ["leaflet"], -> L.tileLayer 'http://{s}.tiles.mapbox.com/v3/steveranford.icifhpgl/{z}/{x}/{y}.png', attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>' maxZoom: 18 .addTo @.map $(that.el).hide() addMarker: (lat,long,popupContent) -> that = @ require ["leaflet"], -> location = L.latLng lat,long L.marker location .addTo(@.map) .bindPopup(popupContent).openPopup(); @.map.setView [lat, long], 15 $(that.el).show() GeoCode = Backbone.Model.extend( urlRoot: "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/" parse: (response) -> geocode = {} if response.locations.length > 0 geocode.longitude = response.locations[0].feature.geometry.x || '' geocode.latitude = response.locations[0].feature.geometry.y || '' geocode fetchFind: (options) -> options = options || {}; if options.url == undefined options.url = @urlRoot + "find?f=pjson&text=" + @id; return Backbone.Model.prototype.fetch.call this, options ) Router = Backbone.Router.extend(routes: "": "home" "view/:id": "viewPerson" new: "editPerson" "list/page/:page": "listPage" list: "home" search: "searchForm" "search/results?:querystring": "viewPersonResults" #not tested, in place to permit direct access "search/results": "searchForm" ) router = new Router #because peopleListView is special, we need to have this outside of the init router, otherwise it doesn't work when we call a subpage directly etc. router.on "route:home", -> app.paginatedPeople = new PaginatedPeople() #needs to create a paginated people peopleListView = new PeopleListView() app.paginatedPeople.getFirstPage dataType: "jsonp" return router.on "route:listPage", (page) -> app.paginatedPeople = new PaginatedPeople() #assumes that this is only called when a new request peopleListView = new PeopleListView() app.paginatedPeople.getPage parseInt(page), dataType: "jsonp" return router.on "route:searchForm", -> searchFormView = new SearchFormView() searchFormView.render() return router.on "route:viewPerson", (id) -> if person = Person.findModel {id: id} else person = new Person id: id personSingleView = new PersonSingleView({model: person}) return router.on "route:viewPersonResults", (querystring) -> peopleSearchResultsView = new PeopleSearchResultsView() peopleSearchResultsView.search querystring return Backbone.history.start() return
[ { "context": "motePlayer()\n 'starter AI': -> computerPlayer 'monte-carlo', 500\n 'smart AI': -> computerPlayer 'minimax'", "end": 1950, "score": 0.8450912237167358, "start": 1939, "tag": "NAME", "value": "monte-carlo" }, { "context": "te-carlo', 500\n 'smart AI': -> compute...
app/src/index.coffee
jordao76/ultimate-tic-tac-toe
5
# coffeelint: disable=max_line_length $ = jQuery {X, O, decode} = require 'aye-aye/lib/games/bin-tic-tac-toe' {UltimateTicTacToe} = require 'aye-aye/lib/games/ultimate-tic-tac-toe' {showSpinner, hideSpinner} = require './spinner' require './highlight' {RTC} = require './web-rtc' $ -> game = null lastAction = null playable = -> className = if game.nextPlayer is X then 'x-playable-tile' else 'o-playable-tile' for [i, j] in game.possibleActions() $ "##{i}\\,#{j}" .addClass className className unplayable = -> $ '.tile' .removeClass 'x-playable-tile' .removeClass 'o-playable-tile' .removeClass 'human-playable-tile' .off 'click' markWins = -> for i in [0...9] wonBy = null for j in game.winOn i wonBy = game.at i, j wonClass = if wonBy is X then 'x-won-tile' else 'o-won-tile' ($ "##{i}\\,#{j}").addClass wonClass if wonBy? wonClass = if wonBy is X then 'x-won-board' else 'o-won-board' ($ '#' + i).addClass wonClass checkGameOver = -> return no unless game.isTerminal() endText = switch when game.isWin(X) then 'X Wins!' when game.isWin(O) then 'O Wins!' else 'Draw!' $ '#end-text' .text endText $ '#modal-game-over' .modal('show') yes playerText = -> (decode game.nextPlayer).toLowerCase() playAction = (action) -> [i, j] = action hideSpinner() $ "##{i}\\,#{j}" .text playerText() .highlight() game = game.play action lastAction = action next() # player :: { # setup : (done: ->) -> # teardown : -> # play : -> # } playerX = null playerO = null next = -> unplayable() markWins() player = if game.nextPlayer is X then playerX else playerO player.play() players = human: -> humanPlayer() peer: -> remotePlayer() 'starter AI': -> computerPlayer 'monte-carlo', 500 'smart AI': -> computerPlayer 'minimax', 3 createPlayerX = -> playerName = ($ '#btn-player-x').text() players[playerName]() createPlayerO = -> playerName = ($ '#btn-player-o').text() players[playerName]() swapPlayers = -> $x = $ '#btn-player-x' $o = $ '#btn-player-o' tmp = $x.text() $x.text $o.text() $o.text tmp $ '.player' .on 'click', -> $player = $ this playerFor = $player.data 'player-for' $btn = $ "#btn-player-#{playerFor}" playerName = $player.text() currentPlayerName = $btn.text() if currentPlayerName isnt playerName $btn.text playerName setup() humanPlayer = -> int = (s) -> parseInt s, 10 parseAction = (text) -> match = text.match /(\d),(\d)/ [(int match[1]), (int match[2])] setup: (done) -> done() play: -> return if checkGameOver() playableClassName = playable() $ ".#{playableClassName}" .addClass 'human-playable-tile' .on 'click', -> $tile = $ this action = parseAction $tile.get(0).id playAction action computerPlayer = (agentName = 'minimax', depth = 3) -> worker = new Worker 'src/ai-worker.min.js' setup: (done) -> worker.onmessage = (e) -> playAction e.data.action worker.postMessage command: 'setup', args: {agentName, depth} done() play: -> return if checkGameOver() playable() showSpinner() worker.postMessage command: 'play', args: {lastAction} teardown: -> worker.terminate() $.fn.enable = (v = yes) -> ($ this).prop 'disabled', not v RTC.greet() RTC.ondatachannelopen = -> [xPlayer, oPlayer] = if RTC.isHost then ['human', 'peer'] else ['peer', 'human'] $ '#btn-player-x' .text xPlayer .enable no $ '#btn-player-o' .text oPlayer .enable no setup() RTC.ondisconnected = -> $ '#btn-player-x' .text 'human' .enable() $ '#btn-player-o' .text 'smart AI' .enable() setup() remotePlayer = -> sendNew = -> RTC.send "new" ($ '#btn-new-game').on 'click', sendNew RTC.onmessage = (data) -> if data is "new" then newGame() else playAction data setup: (done) -> done() play: -> unless checkGameOver() playable() showSpinner() RTC.send lastAction if lastAction? teardown: -> ($ '#btn-new-game').off 'click', sendNew setup = -> teardown() game = new UltimateTicTacToe game.lastPlayedPosition = null # start with the full board open lastAction = null [playerX, playerO] = [createPlayerX(), createPlayerO()] playerX.setup -> playerO.setup -> next() teardown = -> playerX?.teardown?() playerO?.teardown?() hideSpinner() $ '.tic-tac-toe' .removeClass 'x-won-board' .removeClass 'o-won-board' $ '.tile' .removeClass 'x-won-tile' .removeClass 'o-won-tile' .text '' newGame = -> swapPlayers() setup() $ '#btn-new-game' .on 'click', newGame setup()
216223
# coffeelint: disable=max_line_length $ = jQuery {X, O, decode} = require 'aye-aye/lib/games/bin-tic-tac-toe' {UltimateTicTacToe} = require 'aye-aye/lib/games/ultimate-tic-tac-toe' {showSpinner, hideSpinner} = require './spinner' require './highlight' {RTC} = require './web-rtc' $ -> game = null lastAction = null playable = -> className = if game.nextPlayer is X then 'x-playable-tile' else 'o-playable-tile' for [i, j] in game.possibleActions() $ "##{i}\\,#{j}" .addClass className className unplayable = -> $ '.tile' .removeClass 'x-playable-tile' .removeClass 'o-playable-tile' .removeClass 'human-playable-tile' .off 'click' markWins = -> for i in [0...9] wonBy = null for j in game.winOn i wonBy = game.at i, j wonClass = if wonBy is X then 'x-won-tile' else 'o-won-tile' ($ "##{i}\\,#{j}").addClass wonClass if wonBy? wonClass = if wonBy is X then 'x-won-board' else 'o-won-board' ($ '#' + i).addClass wonClass checkGameOver = -> return no unless game.isTerminal() endText = switch when game.isWin(X) then 'X Wins!' when game.isWin(O) then 'O Wins!' else 'Draw!' $ '#end-text' .text endText $ '#modal-game-over' .modal('show') yes playerText = -> (decode game.nextPlayer).toLowerCase() playAction = (action) -> [i, j] = action hideSpinner() $ "##{i}\\,#{j}" .text playerText() .highlight() game = game.play action lastAction = action next() # player :: { # setup : (done: ->) -> # teardown : -> # play : -> # } playerX = null playerO = null next = -> unplayable() markWins() player = if game.nextPlayer is X then playerX else playerO player.play() players = human: -> humanPlayer() peer: -> remotePlayer() 'starter AI': -> computerPlayer '<NAME>', 500 'smart AI': -> computerPlayer 'minimax', 3 createPlayerX = -> playerName = ($ '#btn-player-x').text() players[playerName]() createPlayerO = -> playerName = ($ '#btn-player-o').text() players[playerName]() swapPlayers = -> $x = $ '#btn-player-x' $o = $ '#btn-player-o' tmp = $x.text() $x.text $o.text() $o.text tmp $ '.player' .on 'click', -> $player = $ this playerFor = $player.data 'player-for' $btn = $ "#btn-player-#{playerFor}" playerName = $player.text() currentPlayerName = $btn.text() if currentPlayerName isnt playerName $btn.text playerName setup() humanPlayer = -> int = (s) -> parseInt s, 10 parseAction = (text) -> match = text.match /(\d),(\d)/ [(int match[1]), (int match[2])] setup: (done) -> done() play: -> return if checkGameOver() playableClassName = playable() $ ".#{playableClassName}" .addClass 'human-playable-tile' .on 'click', -> $tile = $ this action = parseAction $tile.get(0).id playAction action computerPlayer = (agentName = 'minimax', depth = 3) -> worker = new Worker 'src/ai-worker.min.js' setup: (done) -> worker.onmessage = (e) -> playAction e.data.action worker.postMessage command: 'setup', args: {agentName, depth} done() play: -> return if checkGameOver() playable() showSpinner() worker.postMessage command: 'play', args: {lastAction} teardown: -> worker.terminate() $.fn.enable = (v = yes) -> ($ this).prop 'disabled', not v RTC.greet() RTC.ondatachannelopen = -> [xPlayer, oPlayer] = if RTC.isHost then ['human', 'peer'] else ['peer', 'human'] $ '#btn-player-x' .text xPlayer .enable no $ '#btn-player-o' .text oPlayer .enable no setup() RTC.ondisconnected = -> $ '#btn-player-x' .text 'human' .enable() $ '#btn-player-o' .text 'smart AI' .enable() setup() remotePlayer = -> sendNew = -> RTC.send "new" ($ '#btn-new-game').on 'click', sendNew RTC.onmessage = (data) -> if data is "new" then newGame() else playAction data setup: (done) -> done() play: -> unless checkGameOver() playable() showSpinner() RTC.send lastAction if lastAction? teardown: -> ($ '#btn-new-game').off 'click', sendNew setup = -> teardown() game = new UltimateTicTacToe game.lastPlayedPosition = null # start with the full board open lastAction = null [playerX, playerO] = [createPlayerX(), createPlayerO()] playerX.setup -> playerO.setup -> next() teardown = -> playerX?.teardown?() playerO?.teardown?() hideSpinner() $ '.tic-tac-toe' .removeClass 'x-won-board' .removeClass 'o-won-board' $ '.tile' .removeClass 'x-won-tile' .removeClass 'o-won-tile' .text '' newGame = -> swapPlayers() setup() $ '#btn-new-game' .on 'click', newGame setup()
true
# coffeelint: disable=max_line_length $ = jQuery {X, O, decode} = require 'aye-aye/lib/games/bin-tic-tac-toe' {UltimateTicTacToe} = require 'aye-aye/lib/games/ultimate-tic-tac-toe' {showSpinner, hideSpinner} = require './spinner' require './highlight' {RTC} = require './web-rtc' $ -> game = null lastAction = null playable = -> className = if game.nextPlayer is X then 'x-playable-tile' else 'o-playable-tile' for [i, j] in game.possibleActions() $ "##{i}\\,#{j}" .addClass className className unplayable = -> $ '.tile' .removeClass 'x-playable-tile' .removeClass 'o-playable-tile' .removeClass 'human-playable-tile' .off 'click' markWins = -> for i in [0...9] wonBy = null for j in game.winOn i wonBy = game.at i, j wonClass = if wonBy is X then 'x-won-tile' else 'o-won-tile' ($ "##{i}\\,#{j}").addClass wonClass if wonBy? wonClass = if wonBy is X then 'x-won-board' else 'o-won-board' ($ '#' + i).addClass wonClass checkGameOver = -> return no unless game.isTerminal() endText = switch when game.isWin(X) then 'X Wins!' when game.isWin(O) then 'O Wins!' else 'Draw!' $ '#end-text' .text endText $ '#modal-game-over' .modal('show') yes playerText = -> (decode game.nextPlayer).toLowerCase() playAction = (action) -> [i, j] = action hideSpinner() $ "##{i}\\,#{j}" .text playerText() .highlight() game = game.play action lastAction = action next() # player :: { # setup : (done: ->) -> # teardown : -> # play : -> # } playerX = null playerO = null next = -> unplayable() markWins() player = if game.nextPlayer is X then playerX else playerO player.play() players = human: -> humanPlayer() peer: -> remotePlayer() 'starter AI': -> computerPlayer 'PI:NAME:<NAME>END_PI', 500 'smart AI': -> computerPlayer 'minimax', 3 createPlayerX = -> playerName = ($ '#btn-player-x').text() players[playerName]() createPlayerO = -> playerName = ($ '#btn-player-o').text() players[playerName]() swapPlayers = -> $x = $ '#btn-player-x' $o = $ '#btn-player-o' tmp = $x.text() $x.text $o.text() $o.text tmp $ '.player' .on 'click', -> $player = $ this playerFor = $player.data 'player-for' $btn = $ "#btn-player-#{playerFor}" playerName = $player.text() currentPlayerName = $btn.text() if currentPlayerName isnt playerName $btn.text playerName setup() humanPlayer = -> int = (s) -> parseInt s, 10 parseAction = (text) -> match = text.match /(\d),(\d)/ [(int match[1]), (int match[2])] setup: (done) -> done() play: -> return if checkGameOver() playableClassName = playable() $ ".#{playableClassName}" .addClass 'human-playable-tile' .on 'click', -> $tile = $ this action = parseAction $tile.get(0).id playAction action computerPlayer = (agentName = 'minimax', depth = 3) -> worker = new Worker 'src/ai-worker.min.js' setup: (done) -> worker.onmessage = (e) -> playAction e.data.action worker.postMessage command: 'setup', args: {agentName, depth} done() play: -> return if checkGameOver() playable() showSpinner() worker.postMessage command: 'play', args: {lastAction} teardown: -> worker.terminate() $.fn.enable = (v = yes) -> ($ this).prop 'disabled', not v RTC.greet() RTC.ondatachannelopen = -> [xPlayer, oPlayer] = if RTC.isHost then ['human', 'peer'] else ['peer', 'human'] $ '#btn-player-x' .text xPlayer .enable no $ '#btn-player-o' .text oPlayer .enable no setup() RTC.ondisconnected = -> $ '#btn-player-x' .text 'human' .enable() $ '#btn-player-o' .text 'smart AI' .enable() setup() remotePlayer = -> sendNew = -> RTC.send "new" ($ '#btn-new-game').on 'click', sendNew RTC.onmessage = (data) -> if data is "new" then newGame() else playAction data setup: (done) -> done() play: -> unless checkGameOver() playable() showSpinner() RTC.send lastAction if lastAction? teardown: -> ($ '#btn-new-game').off 'click', sendNew setup = -> teardown() game = new UltimateTicTacToe game.lastPlayedPosition = null # start with the full board open lastAction = null [playerX, playerO] = [createPlayerX(), createPlayerO()] playerX.setup -> playerO.setup -> next() teardown = -> playerX?.teardown?() playerO?.teardown?() hideSpinner() $ '.tic-tac-toe' .removeClass 'x-won-board' .removeClass 'o-won-board' $ '.tile' .removeClass 'x-won-tile' .removeClass 'o-won-tile' .text '' newGame = -> swapPlayers() setup() $ '#btn-new-game' .on 'click', newGame setup()
[ { "context": "kids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: ", "end": 32, "score": 0.9998598694801331, "start": 29, "tag": "NAME", "value": "Max" }, { "context": " name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\...
packages/coffee/test/fixtures/bar.coffee
jbucaran/fly
729
kids = brother: name: "Max" age: 11 sister: name: "Ida" age: 9
160147
kids = brother: name: "<NAME>" age: 11 sister: name: "<NAME>" age: 9
true
kids = brother: name: "PI:NAME:<NAME>END_PI" age: 11 sister: name: "PI:NAME:<NAME>END_PI" age: 9
[ { "context": "s.dynamicDampingFactor = 0.9\n\n controls.keys = [ 65, 83, 68 ]\n\n curves = new WorkerFlyingCurves visibilityDi", "end": 9771, "score": 0.9732385873794556, "start": 9761, "tag": "KEY", "value": "65, 83, 68" }, { "context": "|0\n y = Math.round(Math.sin(u1)*r) |0\n...
3d/singlerot3d.coffee
dmishin/singlerot-smooth
18
{parseFieldDescriptionlLanguage} = require "../fdl_parser" {parseUri} = require "../parseuri" container = undefined stats = undefined camera = undefined scene = undefined renderer = undefined controls = undefined curves = undefined stepsPerMs = 10 / 1000 visibilityDistance = 10000 #Parameter of the splitted processing of tube packs: minimal time between adding separte groups of tubes. # When time is big, tubes are added by big portions, which is fast, but animation becomes jerky. # When too slow, tubes could lag. minTimePerTube = 1000/30 #100 parts/second palette = [0xfe8f0f, 0xf7325e, 0x7dc410, 0xfef8cf, 0x0264ed] requestStop = false class WorkerFlyingCurves constructor: (startZ=4000, endZ=-4000) -> @worker = new Worker "./tubing_worker_app.js" @worker.addEventListener "message", (e)=>@_onMsg(e) @worker.addEventListener "error", (e)-> console.log JSON.stringify e @scale = scale = 30 @group = new THREE.Object3D @chunks = [] @zMin = endZ / scale @zMax = startZ / scale @lastChunkZ = 0 @group.scale.set scale, scale, scale @ready = false @taskId2dummyChunks = {} @nextTaskId = 0 #All these parameters are applied, when initializing worker. # (loadPattern) #number of steps in one mesh chunk @chunkSize = 500 #generate tube section every nth step (1 - every step) @skipSteps = 1 #size of the toroidal board, must be even! @boardSize = 100 #interpolation order. 1 ... 3. 1 - linear interp, 3 - smooth interp @lanczosOrder = 3 #how many mesh steps are there between 2 generation. integer, 1 ... 4 @interpSteps = 1 #Low-pass filter, removed oscillations with period bigger than this. # integer, 1 ... 100. 1 - no filtering. @smoothingPeriod = 4 #"speed of light". z-axis length of one generation @timeScale = 0.1 #Radius of a single rube @tubeRadius = 0.1 #NUmber of sides in the tube (2...10) @tubeSides = 3 #continue initialization after loading _finishInitialize: (nCells, fldWidth, fldHeight, chunkLen)-> #Colors array must be set by the previous calls if @colors.length isnt nCells @colors = (palette[i%palette.length] for i in [0...nCells] by 1) @materials = for color in @colors new THREE.MeshBasicMaterial color: color @group.position.set -0.5*fldWidth*@scale, -0.5*fldHeight*@scale, 0 @group.updateMatrix() @ready = true @chunkLen = chunkLen console.log "Initializatoin finished" #Calculate geometric size (width, height) of the cross-section of the field. getCrossSectionSize: -> s = @boardSize * @scale [s,s] _onMsg: (e)-> cmd = e.data.cmd unless cmd? console.log "Bad message received! #{JSON.stringify e.data}" return switch cmd when "init" @_finishInitialize e.data.nCells, e.data.fldWidth, e.data.fldHeight, e.data.chunkLen when "chunk" @_receiveChunk e.data.blueprint, e.data.taskId else console.log "Unknown responce #{e.cmd}" #returns: tuple [chunk, taskId] # chunk is an empty object # taskId is ID of the sent task requestChunk: -> taskId = @nextTaskId @nextTaskId = (taskId + 1) % 65536 #just because. @worker.postMessage cmd: "chunk" taskId: taskId dummy = new THREE.Object3D @taskId2dummyChunks[taskId] = dummy return dummy _receiveChunk: (blueprint, taskId)-> chunk = @taskId2dummyChunks[taskId] #discard unexpected chunks return unless chunk? delete @taskId2dummyChunks[taskId] i = 0 #We must process all tubes in 75% of the chunk flyby time chunkFlybyTime = @chunkLen / stepsPerMs #How many pieces to split blueprint to completionTime = Math.min(1000, chunkFlybyTime * 0.75) nPieces = completionTime/minTimePerTube | 0 nPieces = Math.min(nPieces, blueprint.length) tubesPerPart = Math.ceil(blueprint.length / nPieces) | 0 nPieces = Math.ceil(blueprint.length / tubesPerPart) | 0 processingDelay = completionTime / nPieces timeStart = Date.now() processPart = => if i + tubesPerPart < blueprint.length setTimeout processPart, processingDelay for j in [0...Math.min(blueprint.length-i, tubesPerPart)] by 1 tubeBp = blueprint[i] tubeGeom = @createTube tubeBp tube = new THREE.Mesh tubeGeom, @materials[i] chunk.add tube i+=1 #if i < blueprint.length-1 # setTimeout processPart, processingDelay #else # dt = Date.now() - timeStart # console.log "Expected completion time: #{completionTime}, actual: #{dt}" processPart() #console.log "Received chunk!" return createTube: (blueprint)-> tube = new THREE.BufferGeometry() tube.addAttribute 'position', new THREE.BufferAttribute(blueprint.v, 3) tube.addAttribute 'index', new THREE.BufferAttribute(blueprint.idx, 1) tube.computeBoundingSphere() #do we need it? return tube #remove all tubes, return to the initial state. reset: -> #we don't expect any more chunks @taskId2dummyChunks = {} @lastChunkZ = 0 for chunk in @chunks @group.remove chunk return loadFDL: (fdlText) -> parsed = parseFieldDescriptionlLanguage fdlText, palette @loadPattern parsed.pattern, parsed.colors loadPattern: (pattern, colors) -> @reset() @colors = colors @worker.postMessage cmd: "init" pattern: pattern chunkSize: @chunkSize skipSteps: @skipSteps #1 size: @boardSize #100 lanczosOrder: @lanczosOrder interpSteps: @interpSteps smoothingPeriod: @smoothingPeriod timeScale: @timeScale #0.1 tubeRadius: @tubeRadius #0.1 tubeSides: @tubeSides # _finishInitialize invoked on responce step: (dz) -> unless @ready #console.log "Worker not ready yet..." return i = 0 while i < @chunks.length chunk = @chunks[i] chunk.position.setZ chunk.position.z-dz if chunk.position.z < @zMin #console.log "Discarding chunk #{i}" @chunks.splice i, 1 @group.remove chunk else i += 1 @lastChunkZ -= dz if @lastChunkZ < @zMax #console.log "last chunk is at #{@lastChunkZ}, Requesting new chunk..." #Posts request to the worker and quickly returns dummy chunk = @requestChunk() @lastChunkZ += @chunkLen chunk.position.setZ @lastChunkZ @chunks.push chunk @group.add chunk return createIsochronePlane: (z=0, textureScale=8, visible=false) -> #calculate plane dimensions [w, h] = @getCrossSectionSize() w2 = w*0.5 h2 = h*0.5 vs = new Float32Array [ -w2, h2,0, -w2,-h2,0, w2, h2,0, -w2,-h2,0, w2,-h2,0, w2, h2,0 ] tw=th=@boardSize / textureScale uvs = new Float32Array [ 0,th, 0,0, tw,th, 0,0, tw,0, tw,th ] plane = new THREE.BufferGeometry() plane.addAttribute 'position', new THREE.BufferAttribute(vs, 3) plane.addAttribute "uv", new THREE.BufferAttribute(uvs, 2) plane.computeBoundingSphere() #do we need it? texture = THREE.ImageUtils.loadTexture( "../images/isoplane.png" ) texture.wrapS = THREE.RepeatWrapping texture.wrapT = THREE.RepeatWrapping material = new THREE.MeshBasicMaterial map: texture side: THREE.DoubleSide opacity: 0.5 transparent: true planeMesh = new THREE.Mesh plane, material planeMesh.position.setZ z planeMesh.visible = visible @isochrone = planeMesh #Load parameters from URI arguments loadUriParameters: (keys)-> loadIntParam = (fieldName, keyName, isValid)=> if keyName of keys val = parseInt keys[keyName], 10 if val isnt val alert "Value incorrect #{val}" return if isValid and not isValid(val) alert "Parameter #{keyName} is incorrect" return this[fieldName] = val #console.log "Loading paramter #{fieldName}, #{val}" return loadIntParam "chunkSize", "chunkSize", (s)->(s>=10 and s<100000) loadIntParam "skipSteps", "skipSteps", (s)->(s>=1 and s<10000) loadIntParam "boardSize", "boardSize", (s)->(s>0 and (s%2 is 0)) loadIntParam "lanczosOrder", "lanczosOrder", (s)->(s>=0 and s < 10) loadIntParam "interpSteps", "interpSteps", (s)->(s>=1 and s <100) loadIntParam "smoothingPeriod", "smoothingPeriod", (s)->(s>=1 and s <10000) loadIntParam "tubeSides", "tubeSides", (s)->(s>=2 and s <10) if "timeScale" of keys v = parseFloat keys["timeScale"] @timeScale = v if (v is v) and v > 0 if "tubeRadius" of keys v = parseFloat keys["tubeRadius"] @tubeRadius = v if (v is v) and v > 0 return init = -> keys = parseUri(window.location).queryKey container = document.getElementById("container") if keys.visibility? vd = parseFloat keys.visibility if vd > 0 and vd < 1e5 visibilityDistance=vd # camera = new THREE.PerspectiveCamera(27, window.innerWidth / window.innerHeight, 1, visibilityDistance * 1.1) camera.position.set 300, 0, -1550 scene = new THREE.Scene() scene.fog = new THREE.Fog 0x000505, visibilityDistance*0.85, visibilityDistance scene.add new THREE.AmbientLight 0x444444 controls = new THREE.TrackballControls camera controls.rotateSpeed = 1.0 controls.zoomSpeed = 3.2 controls.panSpeed = 0.8 controls.noZoom = false controls.noPan = false controls.staticMoving = true controls.dynamicDampingFactor = 0.9 controls.keys = [ 65, 83, 68 ] curves = new WorkerFlyingCurves visibilityDistance, -0.5*visibilityDistance #apply additional parameters curves.loadUriParameters keys loadRandomPattern Math.min(20, Math.round(curves.boardSize*0.4)) scene.add curves.group scene.add curves.createIsochronePlane 1000 # renderer = new THREE.WebGLRenderer(antialias: keys.antialias is "true") renderer.setSize window.innerWidth, window.innerHeight renderer.gammaInput = true renderer.gammaOutput = true container.appendChild renderer.domElement # if Stats? stats = new Stats() stats.domElement.style.position = "absolute" stats.domElement.style.bottom = "0px" container.appendChild stats.domElement # window.addEventListener "resize", onWindowResize, false return onWindowResize = -> camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize window.innerWidth, window.innerHeight controls.handleResize() return showPatternsWindow = -> controls.enabled = false patterns = document.getElementById "patterns-window" patterns.style.display = "" #reset "none" and apply setting from css hidePatternsWindow = -> controls.enabled = true patterns = document.getElementById "patterns-window" patterns.style.display = "none"#override CSS and hide. loadRandomPattern = (size) -> curves.loadPattern makeRandomPattern(size)... makeRandomPattern = (size) -> cells = {} pattern = [] colors = [] xyRange = Math.sqrt(size) while pattern.length isnt size #Generate normally distributed cells, using box-muller transform. #I just want to implement it. u1 = Math.random()*Math.PI u2 = Math.random() r = Math.sqrt(-Math.log(u2))*xyRange if r>100 or r isnt r then continue x = Math.round(Math.cos(u1)*r) |0 y = Math.round(Math.sin(u1)*r) |0 key = "#{x}$#{y}" if key of cells then continue cells[key] = true pattern.push [x,y] colors.push palette[pattern.length % palette.length] return [pattern, colors] loadCustomPattern = -> try curves.loadFDL document.getElementById("custom-rle").value true catch e alert ""+e false bindEvents = -> E = (eid)->document.getElementById eid setSpeed = (speed) -> (e) -> stepsPerMs = speed * 1e-3 E("btn-speed-0").addEventListener "click", setSpeed 0 E("btn-speed-1").addEventListener "click", setSpeed 10 E("btn-speed-2").addEventListener "click", setSpeed 30 E("btn-speed-3").addEventListener "click", setSpeed 100 E("btn-speed-4").addEventListener "click", setSpeed 300 E("btn-show-patterns").addEventListener "click", showPatternsWindow E("patterns-window").addEventListener "click", (e)-> if (e.target || e.srcElement).id is "patterns-window" hidePatternsWindow() E("btn-close-patterns").addEventListener "click", hidePatternsWindow E("btn-load-custom").addEventListener "click", (e)-> if loadCustomPattern() then hidePatternsWindow() E("select-pattern").addEventListener "change", (e)-> if (rle=E("select-pattern").value) curves.loadFDL rle E("custom-rle").value = rle hidePatternsWindow() E("btn-make-random").addEventListener "click", (e)-> loadRandomPattern parseInt(E("random-pattern-size").value, 10) hidePatternsWindow() E("show-isoplane").addEventListener "change", (e)-> curves.isochrone.visible = E("show-isoplane").checked initLibrary = -> if window.defaultLibrary? select = document.getElementById "select-pattern" for fdl in window.defaultLibrary parsed = parseFieldDescriptionlLanguage fdl, palette select.options[select.options.length] = new Option parsed.name, fdl return prevTime = null animate = -> if requestStop requestStop = false prevTime = null return requestAnimationFrame animate render() controls.update() stats?.update() time = Date.now() if prevTime isnt null dt = Math.min(time-prevTime, 100) #if FPS falls below 10, slow down simulation instead. curves.step stepsPerMs * dt prevTime = time return render = -> renderer.render scene, camera Detector.addGetWebGLMessage() unless Detector.webgl bindEvents() init() initLibrary() animate()
103884
{parseFieldDescriptionlLanguage} = require "../fdl_parser" {parseUri} = require "../parseuri" container = undefined stats = undefined camera = undefined scene = undefined renderer = undefined controls = undefined curves = undefined stepsPerMs = 10 / 1000 visibilityDistance = 10000 #Parameter of the splitted processing of tube packs: minimal time between adding separte groups of tubes. # When time is big, tubes are added by big portions, which is fast, but animation becomes jerky. # When too slow, tubes could lag. minTimePerTube = 1000/30 #100 parts/second palette = [0xfe8f0f, 0xf7325e, 0x7dc410, 0xfef8cf, 0x0264ed] requestStop = false class WorkerFlyingCurves constructor: (startZ=4000, endZ=-4000) -> @worker = new Worker "./tubing_worker_app.js" @worker.addEventListener "message", (e)=>@_onMsg(e) @worker.addEventListener "error", (e)-> console.log JSON.stringify e @scale = scale = 30 @group = new THREE.Object3D @chunks = [] @zMin = endZ / scale @zMax = startZ / scale @lastChunkZ = 0 @group.scale.set scale, scale, scale @ready = false @taskId2dummyChunks = {} @nextTaskId = 0 #All these parameters are applied, when initializing worker. # (loadPattern) #number of steps in one mesh chunk @chunkSize = 500 #generate tube section every nth step (1 - every step) @skipSteps = 1 #size of the toroidal board, must be even! @boardSize = 100 #interpolation order. 1 ... 3. 1 - linear interp, 3 - smooth interp @lanczosOrder = 3 #how many mesh steps are there between 2 generation. integer, 1 ... 4 @interpSteps = 1 #Low-pass filter, removed oscillations with period bigger than this. # integer, 1 ... 100. 1 - no filtering. @smoothingPeriod = 4 #"speed of light". z-axis length of one generation @timeScale = 0.1 #Radius of a single rube @tubeRadius = 0.1 #NUmber of sides in the tube (2...10) @tubeSides = 3 #continue initialization after loading _finishInitialize: (nCells, fldWidth, fldHeight, chunkLen)-> #Colors array must be set by the previous calls if @colors.length isnt nCells @colors = (palette[i%palette.length] for i in [0...nCells] by 1) @materials = for color in @colors new THREE.MeshBasicMaterial color: color @group.position.set -0.5*fldWidth*@scale, -0.5*fldHeight*@scale, 0 @group.updateMatrix() @ready = true @chunkLen = chunkLen console.log "Initializatoin finished" #Calculate geometric size (width, height) of the cross-section of the field. getCrossSectionSize: -> s = @boardSize * @scale [s,s] _onMsg: (e)-> cmd = e.data.cmd unless cmd? console.log "Bad message received! #{JSON.stringify e.data}" return switch cmd when "init" @_finishInitialize e.data.nCells, e.data.fldWidth, e.data.fldHeight, e.data.chunkLen when "chunk" @_receiveChunk e.data.blueprint, e.data.taskId else console.log "Unknown responce #{e.cmd}" #returns: tuple [chunk, taskId] # chunk is an empty object # taskId is ID of the sent task requestChunk: -> taskId = @nextTaskId @nextTaskId = (taskId + 1) % 65536 #just because. @worker.postMessage cmd: "chunk" taskId: taskId dummy = new THREE.Object3D @taskId2dummyChunks[taskId] = dummy return dummy _receiveChunk: (blueprint, taskId)-> chunk = @taskId2dummyChunks[taskId] #discard unexpected chunks return unless chunk? delete @taskId2dummyChunks[taskId] i = 0 #We must process all tubes in 75% of the chunk flyby time chunkFlybyTime = @chunkLen / stepsPerMs #How many pieces to split blueprint to completionTime = Math.min(1000, chunkFlybyTime * 0.75) nPieces = completionTime/minTimePerTube | 0 nPieces = Math.min(nPieces, blueprint.length) tubesPerPart = Math.ceil(blueprint.length / nPieces) | 0 nPieces = Math.ceil(blueprint.length / tubesPerPart) | 0 processingDelay = completionTime / nPieces timeStart = Date.now() processPart = => if i + tubesPerPart < blueprint.length setTimeout processPart, processingDelay for j in [0...Math.min(blueprint.length-i, tubesPerPart)] by 1 tubeBp = blueprint[i] tubeGeom = @createTube tubeBp tube = new THREE.Mesh tubeGeom, @materials[i] chunk.add tube i+=1 #if i < blueprint.length-1 # setTimeout processPart, processingDelay #else # dt = Date.now() - timeStart # console.log "Expected completion time: #{completionTime}, actual: #{dt}" processPart() #console.log "Received chunk!" return createTube: (blueprint)-> tube = new THREE.BufferGeometry() tube.addAttribute 'position', new THREE.BufferAttribute(blueprint.v, 3) tube.addAttribute 'index', new THREE.BufferAttribute(blueprint.idx, 1) tube.computeBoundingSphere() #do we need it? return tube #remove all tubes, return to the initial state. reset: -> #we don't expect any more chunks @taskId2dummyChunks = {} @lastChunkZ = 0 for chunk in @chunks @group.remove chunk return loadFDL: (fdlText) -> parsed = parseFieldDescriptionlLanguage fdlText, palette @loadPattern parsed.pattern, parsed.colors loadPattern: (pattern, colors) -> @reset() @colors = colors @worker.postMessage cmd: "init" pattern: pattern chunkSize: @chunkSize skipSteps: @skipSteps #1 size: @boardSize #100 lanczosOrder: @lanczosOrder interpSteps: @interpSteps smoothingPeriod: @smoothingPeriod timeScale: @timeScale #0.1 tubeRadius: @tubeRadius #0.1 tubeSides: @tubeSides # _finishInitialize invoked on responce step: (dz) -> unless @ready #console.log "Worker not ready yet..." return i = 0 while i < @chunks.length chunk = @chunks[i] chunk.position.setZ chunk.position.z-dz if chunk.position.z < @zMin #console.log "Discarding chunk #{i}" @chunks.splice i, 1 @group.remove chunk else i += 1 @lastChunkZ -= dz if @lastChunkZ < @zMax #console.log "last chunk is at #{@lastChunkZ}, Requesting new chunk..." #Posts request to the worker and quickly returns dummy chunk = @requestChunk() @lastChunkZ += @chunkLen chunk.position.setZ @lastChunkZ @chunks.push chunk @group.add chunk return createIsochronePlane: (z=0, textureScale=8, visible=false) -> #calculate plane dimensions [w, h] = @getCrossSectionSize() w2 = w*0.5 h2 = h*0.5 vs = new Float32Array [ -w2, h2,0, -w2,-h2,0, w2, h2,0, -w2,-h2,0, w2,-h2,0, w2, h2,0 ] tw=th=@boardSize / textureScale uvs = new Float32Array [ 0,th, 0,0, tw,th, 0,0, tw,0, tw,th ] plane = new THREE.BufferGeometry() plane.addAttribute 'position', new THREE.BufferAttribute(vs, 3) plane.addAttribute "uv", new THREE.BufferAttribute(uvs, 2) plane.computeBoundingSphere() #do we need it? texture = THREE.ImageUtils.loadTexture( "../images/isoplane.png" ) texture.wrapS = THREE.RepeatWrapping texture.wrapT = THREE.RepeatWrapping material = new THREE.MeshBasicMaterial map: texture side: THREE.DoubleSide opacity: 0.5 transparent: true planeMesh = new THREE.Mesh plane, material planeMesh.position.setZ z planeMesh.visible = visible @isochrone = planeMesh #Load parameters from URI arguments loadUriParameters: (keys)-> loadIntParam = (fieldName, keyName, isValid)=> if keyName of keys val = parseInt keys[keyName], 10 if val isnt val alert "Value incorrect #{val}" return if isValid and not isValid(val) alert "Parameter #{keyName} is incorrect" return this[fieldName] = val #console.log "Loading paramter #{fieldName}, #{val}" return loadIntParam "chunkSize", "chunkSize", (s)->(s>=10 and s<100000) loadIntParam "skipSteps", "skipSteps", (s)->(s>=1 and s<10000) loadIntParam "boardSize", "boardSize", (s)->(s>0 and (s%2 is 0)) loadIntParam "lanczosOrder", "lanczosOrder", (s)->(s>=0 and s < 10) loadIntParam "interpSteps", "interpSteps", (s)->(s>=1 and s <100) loadIntParam "smoothingPeriod", "smoothingPeriod", (s)->(s>=1 and s <10000) loadIntParam "tubeSides", "tubeSides", (s)->(s>=2 and s <10) if "timeScale" of keys v = parseFloat keys["timeScale"] @timeScale = v if (v is v) and v > 0 if "tubeRadius" of keys v = parseFloat keys["tubeRadius"] @tubeRadius = v if (v is v) and v > 0 return init = -> keys = parseUri(window.location).queryKey container = document.getElementById("container") if keys.visibility? vd = parseFloat keys.visibility if vd > 0 and vd < 1e5 visibilityDistance=vd # camera = new THREE.PerspectiveCamera(27, window.innerWidth / window.innerHeight, 1, visibilityDistance * 1.1) camera.position.set 300, 0, -1550 scene = new THREE.Scene() scene.fog = new THREE.Fog 0x000505, visibilityDistance*0.85, visibilityDistance scene.add new THREE.AmbientLight 0x444444 controls = new THREE.TrackballControls camera controls.rotateSpeed = 1.0 controls.zoomSpeed = 3.2 controls.panSpeed = 0.8 controls.noZoom = false controls.noPan = false controls.staticMoving = true controls.dynamicDampingFactor = 0.9 controls.keys = [ <KEY> ] curves = new WorkerFlyingCurves visibilityDistance, -0.5*visibilityDistance #apply additional parameters curves.loadUriParameters keys loadRandomPattern Math.min(20, Math.round(curves.boardSize*0.4)) scene.add curves.group scene.add curves.createIsochronePlane 1000 # renderer = new THREE.WebGLRenderer(antialias: keys.antialias is "true") renderer.setSize window.innerWidth, window.innerHeight renderer.gammaInput = true renderer.gammaOutput = true container.appendChild renderer.domElement # if Stats? stats = new Stats() stats.domElement.style.position = "absolute" stats.domElement.style.bottom = "0px" container.appendChild stats.domElement # window.addEventListener "resize", onWindowResize, false return onWindowResize = -> camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize window.innerWidth, window.innerHeight controls.handleResize() return showPatternsWindow = -> controls.enabled = false patterns = document.getElementById "patterns-window" patterns.style.display = "" #reset "none" and apply setting from css hidePatternsWindow = -> controls.enabled = true patterns = document.getElementById "patterns-window" patterns.style.display = "none"#override CSS and hide. loadRandomPattern = (size) -> curves.loadPattern makeRandomPattern(size)... makeRandomPattern = (size) -> cells = {} pattern = [] colors = [] xyRange = Math.sqrt(size) while pattern.length isnt size #Generate normally distributed cells, using box-muller transform. #I just want to implement it. u1 = Math.random()*Math.PI u2 = Math.random() r = Math.sqrt(-Math.log(u2))*xyRange if r>100 or r isnt r then continue x = Math.round(Math.cos(u1)*r) |0 y = Math.round(Math.sin(u1)*r) |0 key = <KEY> if key of cells then continue cells[key] = true pattern.push [x,y] colors.push palette[pattern.length % palette.length] return [pattern, colors] loadCustomPattern = -> try curves.loadFDL document.getElementById("custom-rle").value true catch e alert ""+e false bindEvents = -> E = (eid)->document.getElementById eid setSpeed = (speed) -> (e) -> stepsPerMs = speed * 1e-3 E("btn-speed-0").addEventListener "click", setSpeed 0 E("btn-speed-1").addEventListener "click", setSpeed 10 E("btn-speed-2").addEventListener "click", setSpeed 30 E("btn-speed-3").addEventListener "click", setSpeed 100 E("btn-speed-4").addEventListener "click", setSpeed 300 E("btn-show-patterns").addEventListener "click", showPatternsWindow E("patterns-window").addEventListener "click", (e)-> if (e.target || e.srcElement).id is "patterns-window" hidePatternsWindow() E("btn-close-patterns").addEventListener "click", hidePatternsWindow E("btn-load-custom").addEventListener "click", (e)-> if loadCustomPattern() then hidePatternsWindow() E("select-pattern").addEventListener "change", (e)-> if (rle=E("select-pattern").value) curves.loadFDL rle E("custom-rle").value = rle hidePatternsWindow() E("btn-make-random").addEventListener "click", (e)-> loadRandomPattern parseInt(E("random-pattern-size").value, 10) hidePatternsWindow() E("show-isoplane").addEventListener "change", (e)-> curves.isochrone.visible = E("show-isoplane").checked initLibrary = -> if window.defaultLibrary? select = document.getElementById "select-pattern" for fdl in window.defaultLibrary parsed = parseFieldDescriptionlLanguage fdl, palette select.options[select.options.length] = new Option parsed.name, fdl return prevTime = null animate = -> if requestStop requestStop = false prevTime = null return requestAnimationFrame animate render() controls.update() stats?.update() time = Date.now() if prevTime isnt null dt = Math.min(time-prevTime, 100) #if FPS falls below 10, slow down simulation instead. curves.step stepsPerMs * dt prevTime = time return render = -> renderer.render scene, camera Detector.addGetWebGLMessage() unless Detector.webgl bindEvents() init() initLibrary() animate()
true
{parseFieldDescriptionlLanguage} = require "../fdl_parser" {parseUri} = require "../parseuri" container = undefined stats = undefined camera = undefined scene = undefined renderer = undefined controls = undefined curves = undefined stepsPerMs = 10 / 1000 visibilityDistance = 10000 #Parameter of the splitted processing of tube packs: minimal time between adding separte groups of tubes. # When time is big, tubes are added by big portions, which is fast, but animation becomes jerky. # When too slow, tubes could lag. minTimePerTube = 1000/30 #100 parts/second palette = [0xfe8f0f, 0xf7325e, 0x7dc410, 0xfef8cf, 0x0264ed] requestStop = false class WorkerFlyingCurves constructor: (startZ=4000, endZ=-4000) -> @worker = new Worker "./tubing_worker_app.js" @worker.addEventListener "message", (e)=>@_onMsg(e) @worker.addEventListener "error", (e)-> console.log JSON.stringify e @scale = scale = 30 @group = new THREE.Object3D @chunks = [] @zMin = endZ / scale @zMax = startZ / scale @lastChunkZ = 0 @group.scale.set scale, scale, scale @ready = false @taskId2dummyChunks = {} @nextTaskId = 0 #All these parameters are applied, when initializing worker. # (loadPattern) #number of steps in one mesh chunk @chunkSize = 500 #generate tube section every nth step (1 - every step) @skipSteps = 1 #size of the toroidal board, must be even! @boardSize = 100 #interpolation order. 1 ... 3. 1 - linear interp, 3 - smooth interp @lanczosOrder = 3 #how many mesh steps are there between 2 generation. integer, 1 ... 4 @interpSteps = 1 #Low-pass filter, removed oscillations with period bigger than this. # integer, 1 ... 100. 1 - no filtering. @smoothingPeriod = 4 #"speed of light". z-axis length of one generation @timeScale = 0.1 #Radius of a single rube @tubeRadius = 0.1 #NUmber of sides in the tube (2...10) @tubeSides = 3 #continue initialization after loading _finishInitialize: (nCells, fldWidth, fldHeight, chunkLen)-> #Colors array must be set by the previous calls if @colors.length isnt nCells @colors = (palette[i%palette.length] for i in [0...nCells] by 1) @materials = for color in @colors new THREE.MeshBasicMaterial color: color @group.position.set -0.5*fldWidth*@scale, -0.5*fldHeight*@scale, 0 @group.updateMatrix() @ready = true @chunkLen = chunkLen console.log "Initializatoin finished" #Calculate geometric size (width, height) of the cross-section of the field. getCrossSectionSize: -> s = @boardSize * @scale [s,s] _onMsg: (e)-> cmd = e.data.cmd unless cmd? console.log "Bad message received! #{JSON.stringify e.data}" return switch cmd when "init" @_finishInitialize e.data.nCells, e.data.fldWidth, e.data.fldHeight, e.data.chunkLen when "chunk" @_receiveChunk e.data.blueprint, e.data.taskId else console.log "Unknown responce #{e.cmd}" #returns: tuple [chunk, taskId] # chunk is an empty object # taskId is ID of the sent task requestChunk: -> taskId = @nextTaskId @nextTaskId = (taskId + 1) % 65536 #just because. @worker.postMessage cmd: "chunk" taskId: taskId dummy = new THREE.Object3D @taskId2dummyChunks[taskId] = dummy return dummy _receiveChunk: (blueprint, taskId)-> chunk = @taskId2dummyChunks[taskId] #discard unexpected chunks return unless chunk? delete @taskId2dummyChunks[taskId] i = 0 #We must process all tubes in 75% of the chunk flyby time chunkFlybyTime = @chunkLen / stepsPerMs #How many pieces to split blueprint to completionTime = Math.min(1000, chunkFlybyTime * 0.75) nPieces = completionTime/minTimePerTube | 0 nPieces = Math.min(nPieces, blueprint.length) tubesPerPart = Math.ceil(blueprint.length / nPieces) | 0 nPieces = Math.ceil(blueprint.length / tubesPerPart) | 0 processingDelay = completionTime / nPieces timeStart = Date.now() processPart = => if i + tubesPerPart < blueprint.length setTimeout processPart, processingDelay for j in [0...Math.min(blueprint.length-i, tubesPerPart)] by 1 tubeBp = blueprint[i] tubeGeom = @createTube tubeBp tube = new THREE.Mesh tubeGeom, @materials[i] chunk.add tube i+=1 #if i < blueprint.length-1 # setTimeout processPart, processingDelay #else # dt = Date.now() - timeStart # console.log "Expected completion time: #{completionTime}, actual: #{dt}" processPart() #console.log "Received chunk!" return createTube: (blueprint)-> tube = new THREE.BufferGeometry() tube.addAttribute 'position', new THREE.BufferAttribute(blueprint.v, 3) tube.addAttribute 'index', new THREE.BufferAttribute(blueprint.idx, 1) tube.computeBoundingSphere() #do we need it? return tube #remove all tubes, return to the initial state. reset: -> #we don't expect any more chunks @taskId2dummyChunks = {} @lastChunkZ = 0 for chunk in @chunks @group.remove chunk return loadFDL: (fdlText) -> parsed = parseFieldDescriptionlLanguage fdlText, palette @loadPattern parsed.pattern, parsed.colors loadPattern: (pattern, colors) -> @reset() @colors = colors @worker.postMessage cmd: "init" pattern: pattern chunkSize: @chunkSize skipSteps: @skipSteps #1 size: @boardSize #100 lanczosOrder: @lanczosOrder interpSteps: @interpSteps smoothingPeriod: @smoothingPeriod timeScale: @timeScale #0.1 tubeRadius: @tubeRadius #0.1 tubeSides: @tubeSides # _finishInitialize invoked on responce step: (dz) -> unless @ready #console.log "Worker not ready yet..." return i = 0 while i < @chunks.length chunk = @chunks[i] chunk.position.setZ chunk.position.z-dz if chunk.position.z < @zMin #console.log "Discarding chunk #{i}" @chunks.splice i, 1 @group.remove chunk else i += 1 @lastChunkZ -= dz if @lastChunkZ < @zMax #console.log "last chunk is at #{@lastChunkZ}, Requesting new chunk..." #Posts request to the worker and quickly returns dummy chunk = @requestChunk() @lastChunkZ += @chunkLen chunk.position.setZ @lastChunkZ @chunks.push chunk @group.add chunk return createIsochronePlane: (z=0, textureScale=8, visible=false) -> #calculate plane dimensions [w, h] = @getCrossSectionSize() w2 = w*0.5 h2 = h*0.5 vs = new Float32Array [ -w2, h2,0, -w2,-h2,0, w2, h2,0, -w2,-h2,0, w2,-h2,0, w2, h2,0 ] tw=th=@boardSize / textureScale uvs = new Float32Array [ 0,th, 0,0, tw,th, 0,0, tw,0, tw,th ] plane = new THREE.BufferGeometry() plane.addAttribute 'position', new THREE.BufferAttribute(vs, 3) plane.addAttribute "uv", new THREE.BufferAttribute(uvs, 2) plane.computeBoundingSphere() #do we need it? texture = THREE.ImageUtils.loadTexture( "../images/isoplane.png" ) texture.wrapS = THREE.RepeatWrapping texture.wrapT = THREE.RepeatWrapping material = new THREE.MeshBasicMaterial map: texture side: THREE.DoubleSide opacity: 0.5 transparent: true planeMesh = new THREE.Mesh plane, material planeMesh.position.setZ z planeMesh.visible = visible @isochrone = planeMesh #Load parameters from URI arguments loadUriParameters: (keys)-> loadIntParam = (fieldName, keyName, isValid)=> if keyName of keys val = parseInt keys[keyName], 10 if val isnt val alert "Value incorrect #{val}" return if isValid and not isValid(val) alert "Parameter #{keyName} is incorrect" return this[fieldName] = val #console.log "Loading paramter #{fieldName}, #{val}" return loadIntParam "chunkSize", "chunkSize", (s)->(s>=10 and s<100000) loadIntParam "skipSteps", "skipSteps", (s)->(s>=1 and s<10000) loadIntParam "boardSize", "boardSize", (s)->(s>0 and (s%2 is 0)) loadIntParam "lanczosOrder", "lanczosOrder", (s)->(s>=0 and s < 10) loadIntParam "interpSteps", "interpSteps", (s)->(s>=1 and s <100) loadIntParam "smoothingPeriod", "smoothingPeriod", (s)->(s>=1 and s <10000) loadIntParam "tubeSides", "tubeSides", (s)->(s>=2 and s <10) if "timeScale" of keys v = parseFloat keys["timeScale"] @timeScale = v if (v is v) and v > 0 if "tubeRadius" of keys v = parseFloat keys["tubeRadius"] @tubeRadius = v if (v is v) and v > 0 return init = -> keys = parseUri(window.location).queryKey container = document.getElementById("container") if keys.visibility? vd = parseFloat keys.visibility if vd > 0 and vd < 1e5 visibilityDistance=vd # camera = new THREE.PerspectiveCamera(27, window.innerWidth / window.innerHeight, 1, visibilityDistance * 1.1) camera.position.set 300, 0, -1550 scene = new THREE.Scene() scene.fog = new THREE.Fog 0x000505, visibilityDistance*0.85, visibilityDistance scene.add new THREE.AmbientLight 0x444444 controls = new THREE.TrackballControls camera controls.rotateSpeed = 1.0 controls.zoomSpeed = 3.2 controls.panSpeed = 0.8 controls.noZoom = false controls.noPan = false controls.staticMoving = true controls.dynamicDampingFactor = 0.9 controls.keys = [ PI:KEY:<KEY>END_PI ] curves = new WorkerFlyingCurves visibilityDistance, -0.5*visibilityDistance #apply additional parameters curves.loadUriParameters keys loadRandomPattern Math.min(20, Math.round(curves.boardSize*0.4)) scene.add curves.group scene.add curves.createIsochronePlane 1000 # renderer = new THREE.WebGLRenderer(antialias: keys.antialias is "true") renderer.setSize window.innerWidth, window.innerHeight renderer.gammaInput = true renderer.gammaOutput = true container.appendChild renderer.domElement # if Stats? stats = new Stats() stats.domElement.style.position = "absolute" stats.domElement.style.bottom = "0px" container.appendChild stats.domElement # window.addEventListener "resize", onWindowResize, false return onWindowResize = -> camera.aspect = window.innerWidth / window.innerHeight camera.updateProjectionMatrix() renderer.setSize window.innerWidth, window.innerHeight controls.handleResize() return showPatternsWindow = -> controls.enabled = false patterns = document.getElementById "patterns-window" patterns.style.display = "" #reset "none" and apply setting from css hidePatternsWindow = -> controls.enabled = true patterns = document.getElementById "patterns-window" patterns.style.display = "none"#override CSS and hide. loadRandomPattern = (size) -> curves.loadPattern makeRandomPattern(size)... makeRandomPattern = (size) -> cells = {} pattern = [] colors = [] xyRange = Math.sqrt(size) while pattern.length isnt size #Generate normally distributed cells, using box-muller transform. #I just want to implement it. u1 = Math.random()*Math.PI u2 = Math.random() r = Math.sqrt(-Math.log(u2))*xyRange if r>100 or r isnt r then continue x = Math.round(Math.cos(u1)*r) |0 y = Math.round(Math.sin(u1)*r) |0 key = PI:KEY:<KEY>END_PI if key of cells then continue cells[key] = true pattern.push [x,y] colors.push palette[pattern.length % palette.length] return [pattern, colors] loadCustomPattern = -> try curves.loadFDL document.getElementById("custom-rle").value true catch e alert ""+e false bindEvents = -> E = (eid)->document.getElementById eid setSpeed = (speed) -> (e) -> stepsPerMs = speed * 1e-3 E("btn-speed-0").addEventListener "click", setSpeed 0 E("btn-speed-1").addEventListener "click", setSpeed 10 E("btn-speed-2").addEventListener "click", setSpeed 30 E("btn-speed-3").addEventListener "click", setSpeed 100 E("btn-speed-4").addEventListener "click", setSpeed 300 E("btn-show-patterns").addEventListener "click", showPatternsWindow E("patterns-window").addEventListener "click", (e)-> if (e.target || e.srcElement).id is "patterns-window" hidePatternsWindow() E("btn-close-patterns").addEventListener "click", hidePatternsWindow E("btn-load-custom").addEventListener "click", (e)-> if loadCustomPattern() then hidePatternsWindow() E("select-pattern").addEventListener "change", (e)-> if (rle=E("select-pattern").value) curves.loadFDL rle E("custom-rle").value = rle hidePatternsWindow() E("btn-make-random").addEventListener "click", (e)-> loadRandomPattern parseInt(E("random-pattern-size").value, 10) hidePatternsWindow() E("show-isoplane").addEventListener "change", (e)-> curves.isochrone.visible = E("show-isoplane").checked initLibrary = -> if window.defaultLibrary? select = document.getElementById "select-pattern" for fdl in window.defaultLibrary parsed = parseFieldDescriptionlLanguage fdl, palette select.options[select.options.length] = new Option parsed.name, fdl return prevTime = null animate = -> if requestStop requestStop = false prevTime = null return requestAnimationFrame animate render() controls.update() stats?.update() time = Date.now() if prevTime isnt null dt = Math.min(time-prevTime, 100) #if FPS falls below 10, slow down simulation instead. curves.step stepsPerMs * dt prevTime = time return render = -> renderer.render scene, camera Detector.addGetWebGLMessage() unless Detector.webgl bindEvents() init() initLibrary() animate()
[ { "context": "bject: 'Hey {{name}}'\n body: 'h1= name'\n name: 'kieron'", "end": 159, "score": 0.999800980091095, "start": 153, "tag": "NAME", "value": "kieron" } ]
src/test/test.coffee
ndxbxrme/ndx-email
0
'use strict' ndx = settings: {} require('../index.js') ndx ndx.email.send to: '' from: '' subject: 'Hey {{name}}' body: 'h1= name' name: 'kieron'
163340
'use strict' ndx = settings: {} require('../index.js') ndx ndx.email.send to: '' from: '' subject: 'Hey {{name}}' body: 'h1= name' name: '<NAME>'
true
'use strict' ndx = settings: {} require('../index.js') ndx ndx.email.send to: '' from: '' subject: 'Hey {{name}}' body: 'h1= name' name: 'PI:NAME:<NAME>END_PI'
[ { "context": "g 'Caught error in longjohn. Please report this to matt.insler@gmail.com.'\n lines.push(frames.map(exports.format_stack_fr", "end": 1605, "score": 0.9998778104782104, "start": 1584, "tag": "EMAIL", "value": "matt.insler@gmail.com" } ]
lib/longjohn.coffee
john-aws/longjohn
546
{EventEmitter} = require 'events' if EventEmitter.prototype.on?['longjohn'] return module.exports = EventEmitter.prototype.on['longjohn'] source_map = require 'source-map-support' source_map.install() filename = __filename current_trace_error = null in_prepare = 0 exports.empty_frame = '---------------------------------------------' exports.async_trace_limit = 10 format_location = (frame) -> return 'native' if frame.isNative() return 'eval at ' + frame.getEvalOrigin() if frame.isEval() file = frame.getFileName() file = frame.getFileName() || '<anonymous>' line = frame.getLineNumber() column = frame.getColumnNumber() column = if column? then ':' + column else '' line = if line? then ':' + line else '' file + line + column format_method = (frame) -> function_name = frame.getFunctionName() unless frame.isToplevel() or frame.isConstructor() method = frame.getMethodName() type = frame.getTypeName() return "#{type}.#{method ? '<anonymous>'}" unless function_name? return "#{type}.#{function_name}" if method is function_name "#{type}.#{function_name} [as #{method}]" return "new #{function_name ? '<anonymous>'}" if frame.isConstructor() return function_name if function_name? null exports.format_stack_frame = (frame) -> return exports.empty_frame if frame.getFileName() is exports.empty_frame return ' at ' + source_map.wrapCallSite(frame) exports.format_stack = (err, frames) -> lines = [] try lines.push(err.toString()) catch e console.log 'Caught error in longjohn. Please report this to matt.insler@gmail.com.' lines.push(frames.map(exports.format_stack_frame)...) lines.join('\n') create_callsite = (location) -> Object.create { getFileName: -> location getLineNumber: -> null getFunctionName: -> null getTypeName: -> null getMethodName: -> null getColumnNumber: -> null isNative: -> null } prepareStackTrace = (error, structured_stack_trace) -> ++in_prepare unless error.__cached_trace__? Object.defineProperty(error, '__cached_trace__', { writable: true, enumerable: false, configurable: true, value: structured_stack_trace.filter (f) -> f.getFileName() isnt filename }); if !error.__previous__? and in_prepare is 1 Object.defineProperty(error, '__previous__', { writable: true, enumerable: false, configurable: true, value: current_trace_error }); if error.__previous__? previous_stack =prepareStackTrace(error.__previous__, error.__previous__.__stack__) if previous_stack?.length > 0 error.__cached_trace__.push(create_callsite(exports.empty_frame)) error.__cached_trace__.push(previous_stack...) --in_prepare return error.__cached_trace__ if in_prepare > 0 exports.format_stack(error, error.__cached_trace__) limit_frames = (stack) -> return if exports.async_trace_limit <= 0 count = exports.async_trace_limit - 1 previous = stack while previous? and count > 1 previous = previous.__previous__ --count delete previous.__previous__ if previous? ERROR_ID = 1 wrap_callback = (callback, location) -> orig = Error.prepareStackTrace Error.prepareStackTrace = (x, stack) -> stack trace_error = new Error() Error.captureStackTrace(trace_error, arguments.callee) trace_error.__stack__ = trace_error.stack; Error.prepareStackTrace = orig trace_error.id = ERROR_ID++ if trace_error.stack[1] trace_error.location = "#{trace_error.stack[1].getFunctionName()} (#{trace_error.stack[1].getFileName()}:#{trace_error.stack[1].getLineNumber()})"; else trace_error.location = 'bad call_stack_location' trace_error.__location__ = location trace_error.__previous__ = current_trace_error trace_error.__trace_count__ = if current_trace_error? then current_trace_error.__trace_count__ + 1 else 1 limit_frames(trace_error) new_callback = -> current_trace_error = trace_error # Clear trace_error variable from the closure, so it can potentially be garbage collected. trace_error = null try callback.apply(this, arguments) catch e # Ensure we're formatting the Error in longjohn e.stack throw e finally current_trace_error = null new_callback.listener = callback new_callback _on = EventEmitter.prototype.on _addListener = EventEmitter.prototype.addListener _listeners = EventEmitter.prototype.listeners EventEmitter.prototype.addListener = (event, callback) -> args = Array::slice.call(arguments) args[1] = wrap_callback(callback, 'EventEmitter.addListener') _addListener.apply(this, args) EventEmitter.prototype.on = (event, callback) -> args = Array::slice.call(arguments) # Coming from EventEmitter.prototype.once if callback.listener wrap = wrap_callback(callback.listener, 'EventEmitter.once'); g = () -> this.removeListener(event, g) if !fired fired = true wrap.apply(this, arguments) g.listener = callback.listener; else g = wrap_callback(callback, 'EventEmitter.on') args[1] = g; _on.apply(this, args) EventEmitter.prototype.listeners = (event) -> listeners = _listeners.call(this, event) unwrapped = [] for l in listeners if l.listener unwrapped.push l.listener else unwrapped.push l return unwrapped Object.defineProperty(EventEmitter.prototype.on, 'longjohn', { writable: true, enumerable: false, configurable: true, value: this }); _nextTick = process.nextTick process.nextTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextTick') _nextTick.apply(this, args) __nextDomainTick = process._nextDomainTick process._nextDomainTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextDomainTick') __nextDomainTick.apply(this, args) _setTimeout = global.setTimeout _setInterval = global.setInterval global.setTimeout = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setTimeout') _setTimeout.apply(this, args) global.setInterval = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setInterval') _setInterval.apply(this, args) if global.setImmediate? _setImmediate = global.setImmediate global.setImmediate = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setImmediate') _setImmediate.apply(this, args) Error.prepareStackTrace = prepareStackTrace if process.env.NODE_ENV == 'production' console.warn ''' NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime. It generally should not be used in production applications. '''
23744
{EventEmitter} = require 'events' if EventEmitter.prototype.on?['longjohn'] return module.exports = EventEmitter.prototype.on['longjohn'] source_map = require 'source-map-support' source_map.install() filename = __filename current_trace_error = null in_prepare = 0 exports.empty_frame = '---------------------------------------------' exports.async_trace_limit = 10 format_location = (frame) -> return 'native' if frame.isNative() return 'eval at ' + frame.getEvalOrigin() if frame.isEval() file = frame.getFileName() file = frame.getFileName() || '<anonymous>' line = frame.getLineNumber() column = frame.getColumnNumber() column = if column? then ':' + column else '' line = if line? then ':' + line else '' file + line + column format_method = (frame) -> function_name = frame.getFunctionName() unless frame.isToplevel() or frame.isConstructor() method = frame.getMethodName() type = frame.getTypeName() return "#{type}.#{method ? '<anonymous>'}" unless function_name? return "#{type}.#{function_name}" if method is function_name "#{type}.#{function_name} [as #{method}]" return "new #{function_name ? '<anonymous>'}" if frame.isConstructor() return function_name if function_name? null exports.format_stack_frame = (frame) -> return exports.empty_frame if frame.getFileName() is exports.empty_frame return ' at ' + source_map.wrapCallSite(frame) exports.format_stack = (err, frames) -> lines = [] try lines.push(err.toString()) catch e console.log 'Caught error in longjohn. Please report this to <EMAIL>.' lines.push(frames.map(exports.format_stack_frame)...) lines.join('\n') create_callsite = (location) -> Object.create { getFileName: -> location getLineNumber: -> null getFunctionName: -> null getTypeName: -> null getMethodName: -> null getColumnNumber: -> null isNative: -> null } prepareStackTrace = (error, structured_stack_trace) -> ++in_prepare unless error.__cached_trace__? Object.defineProperty(error, '__cached_trace__', { writable: true, enumerable: false, configurable: true, value: structured_stack_trace.filter (f) -> f.getFileName() isnt filename }); if !error.__previous__? and in_prepare is 1 Object.defineProperty(error, '__previous__', { writable: true, enumerable: false, configurable: true, value: current_trace_error }); if error.__previous__? previous_stack =prepareStackTrace(error.__previous__, error.__previous__.__stack__) if previous_stack?.length > 0 error.__cached_trace__.push(create_callsite(exports.empty_frame)) error.__cached_trace__.push(previous_stack...) --in_prepare return error.__cached_trace__ if in_prepare > 0 exports.format_stack(error, error.__cached_trace__) limit_frames = (stack) -> return if exports.async_trace_limit <= 0 count = exports.async_trace_limit - 1 previous = stack while previous? and count > 1 previous = previous.__previous__ --count delete previous.__previous__ if previous? ERROR_ID = 1 wrap_callback = (callback, location) -> orig = Error.prepareStackTrace Error.prepareStackTrace = (x, stack) -> stack trace_error = new Error() Error.captureStackTrace(trace_error, arguments.callee) trace_error.__stack__ = trace_error.stack; Error.prepareStackTrace = orig trace_error.id = ERROR_ID++ if trace_error.stack[1] trace_error.location = "#{trace_error.stack[1].getFunctionName()} (#{trace_error.stack[1].getFileName()}:#{trace_error.stack[1].getLineNumber()})"; else trace_error.location = 'bad call_stack_location' trace_error.__location__ = location trace_error.__previous__ = current_trace_error trace_error.__trace_count__ = if current_trace_error? then current_trace_error.__trace_count__ + 1 else 1 limit_frames(trace_error) new_callback = -> current_trace_error = trace_error # Clear trace_error variable from the closure, so it can potentially be garbage collected. trace_error = null try callback.apply(this, arguments) catch e # Ensure we're formatting the Error in longjohn e.stack throw e finally current_trace_error = null new_callback.listener = callback new_callback _on = EventEmitter.prototype.on _addListener = EventEmitter.prototype.addListener _listeners = EventEmitter.prototype.listeners EventEmitter.prototype.addListener = (event, callback) -> args = Array::slice.call(arguments) args[1] = wrap_callback(callback, 'EventEmitter.addListener') _addListener.apply(this, args) EventEmitter.prototype.on = (event, callback) -> args = Array::slice.call(arguments) # Coming from EventEmitter.prototype.once if callback.listener wrap = wrap_callback(callback.listener, 'EventEmitter.once'); g = () -> this.removeListener(event, g) if !fired fired = true wrap.apply(this, arguments) g.listener = callback.listener; else g = wrap_callback(callback, 'EventEmitter.on') args[1] = g; _on.apply(this, args) EventEmitter.prototype.listeners = (event) -> listeners = _listeners.call(this, event) unwrapped = [] for l in listeners if l.listener unwrapped.push l.listener else unwrapped.push l return unwrapped Object.defineProperty(EventEmitter.prototype.on, 'longjohn', { writable: true, enumerable: false, configurable: true, value: this }); _nextTick = process.nextTick process.nextTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextTick') _nextTick.apply(this, args) __nextDomainTick = process._nextDomainTick process._nextDomainTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextDomainTick') __nextDomainTick.apply(this, args) _setTimeout = global.setTimeout _setInterval = global.setInterval global.setTimeout = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setTimeout') _setTimeout.apply(this, args) global.setInterval = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setInterval') _setInterval.apply(this, args) if global.setImmediate? _setImmediate = global.setImmediate global.setImmediate = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setImmediate') _setImmediate.apply(this, args) Error.prepareStackTrace = prepareStackTrace if process.env.NODE_ENV == 'production' console.warn ''' NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime. It generally should not be used in production applications. '''
true
{EventEmitter} = require 'events' if EventEmitter.prototype.on?['longjohn'] return module.exports = EventEmitter.prototype.on['longjohn'] source_map = require 'source-map-support' source_map.install() filename = __filename current_trace_error = null in_prepare = 0 exports.empty_frame = '---------------------------------------------' exports.async_trace_limit = 10 format_location = (frame) -> return 'native' if frame.isNative() return 'eval at ' + frame.getEvalOrigin() if frame.isEval() file = frame.getFileName() file = frame.getFileName() || '<anonymous>' line = frame.getLineNumber() column = frame.getColumnNumber() column = if column? then ':' + column else '' line = if line? then ':' + line else '' file + line + column format_method = (frame) -> function_name = frame.getFunctionName() unless frame.isToplevel() or frame.isConstructor() method = frame.getMethodName() type = frame.getTypeName() return "#{type}.#{method ? '<anonymous>'}" unless function_name? return "#{type}.#{function_name}" if method is function_name "#{type}.#{function_name} [as #{method}]" return "new #{function_name ? '<anonymous>'}" if frame.isConstructor() return function_name if function_name? null exports.format_stack_frame = (frame) -> return exports.empty_frame if frame.getFileName() is exports.empty_frame return ' at ' + source_map.wrapCallSite(frame) exports.format_stack = (err, frames) -> lines = [] try lines.push(err.toString()) catch e console.log 'Caught error in longjohn. Please report this to PI:EMAIL:<EMAIL>END_PI.' lines.push(frames.map(exports.format_stack_frame)...) lines.join('\n') create_callsite = (location) -> Object.create { getFileName: -> location getLineNumber: -> null getFunctionName: -> null getTypeName: -> null getMethodName: -> null getColumnNumber: -> null isNative: -> null } prepareStackTrace = (error, structured_stack_trace) -> ++in_prepare unless error.__cached_trace__? Object.defineProperty(error, '__cached_trace__', { writable: true, enumerable: false, configurable: true, value: structured_stack_trace.filter (f) -> f.getFileName() isnt filename }); if !error.__previous__? and in_prepare is 1 Object.defineProperty(error, '__previous__', { writable: true, enumerable: false, configurable: true, value: current_trace_error }); if error.__previous__? previous_stack =prepareStackTrace(error.__previous__, error.__previous__.__stack__) if previous_stack?.length > 0 error.__cached_trace__.push(create_callsite(exports.empty_frame)) error.__cached_trace__.push(previous_stack...) --in_prepare return error.__cached_trace__ if in_prepare > 0 exports.format_stack(error, error.__cached_trace__) limit_frames = (stack) -> return if exports.async_trace_limit <= 0 count = exports.async_trace_limit - 1 previous = stack while previous? and count > 1 previous = previous.__previous__ --count delete previous.__previous__ if previous? ERROR_ID = 1 wrap_callback = (callback, location) -> orig = Error.prepareStackTrace Error.prepareStackTrace = (x, stack) -> stack trace_error = new Error() Error.captureStackTrace(trace_error, arguments.callee) trace_error.__stack__ = trace_error.stack; Error.prepareStackTrace = orig trace_error.id = ERROR_ID++ if trace_error.stack[1] trace_error.location = "#{trace_error.stack[1].getFunctionName()} (#{trace_error.stack[1].getFileName()}:#{trace_error.stack[1].getLineNumber()})"; else trace_error.location = 'bad call_stack_location' trace_error.__location__ = location trace_error.__previous__ = current_trace_error trace_error.__trace_count__ = if current_trace_error? then current_trace_error.__trace_count__ + 1 else 1 limit_frames(trace_error) new_callback = -> current_trace_error = trace_error # Clear trace_error variable from the closure, so it can potentially be garbage collected. trace_error = null try callback.apply(this, arguments) catch e # Ensure we're formatting the Error in longjohn e.stack throw e finally current_trace_error = null new_callback.listener = callback new_callback _on = EventEmitter.prototype.on _addListener = EventEmitter.prototype.addListener _listeners = EventEmitter.prototype.listeners EventEmitter.prototype.addListener = (event, callback) -> args = Array::slice.call(arguments) args[1] = wrap_callback(callback, 'EventEmitter.addListener') _addListener.apply(this, args) EventEmitter.prototype.on = (event, callback) -> args = Array::slice.call(arguments) # Coming from EventEmitter.prototype.once if callback.listener wrap = wrap_callback(callback.listener, 'EventEmitter.once'); g = () -> this.removeListener(event, g) if !fired fired = true wrap.apply(this, arguments) g.listener = callback.listener; else g = wrap_callback(callback, 'EventEmitter.on') args[1] = g; _on.apply(this, args) EventEmitter.prototype.listeners = (event) -> listeners = _listeners.call(this, event) unwrapped = [] for l in listeners if l.listener unwrapped.push l.listener else unwrapped.push l return unwrapped Object.defineProperty(EventEmitter.prototype.on, 'longjohn', { writable: true, enumerable: false, configurable: true, value: this }); _nextTick = process.nextTick process.nextTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextTick') _nextTick.apply(this, args) __nextDomainTick = process._nextDomainTick process._nextDomainTick = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'process.nextDomainTick') __nextDomainTick.apply(this, args) _setTimeout = global.setTimeout _setInterval = global.setInterval global.setTimeout = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setTimeout') _setTimeout.apply(this, args) global.setInterval = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setInterval') _setInterval.apply(this, args) if global.setImmediate? _setImmediate = global.setImmediate global.setImmediate = (callback) -> args = Array::slice.call(arguments) args[0] = wrap_callback(callback, 'global.setImmediate') _setImmediate.apply(this, args) Error.prepareStackTrace = prepareStackTrace if process.env.NODE_ENV == 'production' console.warn ''' NOTICE: Longjohn is known to cause CPU usage due to its extensive data collection during runtime. It generally should not be used in production applications. '''
[ { "context": "name: 'uhn'}\n else\n {username: $scope.username, password: $scope.password}\n $scope.clearMes", "end": 689, "score": 0.832491397857666, "start": 681, "tag": "USERNAME", "value": "username" }, { "context": "else\n {username: $scope.username, pass...
src/main/client/authentication/authentication-controller.coffee
morungos/turalt-openmentor
0
angular .module 'openmentor.authentication' .controller 'LoginController', Array '$scope', '$state', 'authenticationService', ($scope, $state, authenticationService) -> $scope.prompt = null console.log "State params", $state.params if $state.params.prompt != 'default' $scope.prompt = $state.params.prompt if $state.params.challenge == 'default' $state.go 'home' return else $scope.challenge = $state.params.challenge $scope.clearMessage = () -> $scope.message = "" $scope.ok = (data) -> data = if $scope.challenge == 'oidc' {redirect: true, client_name: 'uhn'} else {username: $scope.username, password: $scope.password} $scope.clearMessage() console.log "Starting login process", data authenticationService.login $scope, data $scope.cancel = () -> $scope.clearMessage() $scope.$emit "event:loginCancelled" $scope.$on 'event:loginDenied', (evt, data, status) -> if status == 403 $scope.message = "Sorry, couldn't verify this username and password" else $scope.message = data.message .controller 'AuthenticationController', Array '$scope', '$state', ($scope, $state) -> $scope.challenge = undefined $scope.username = undefined $scope.password = undefined $scope.shown = false $scope.message = "" $scope.$on 'event:loginRequired', (event, values) -> challenge = values.challenge prompt = values.prompt match = /(\w+)/.exec challenge $state.go 'login', {challenge: match[1].toLowerCase(), prompt: prompt} $scope.$on 'event:loginDenied', (evt, data) -> $scope.message = data.message if ! $scope.shown $scope.$emit 'event:loginRequired'
24581
angular .module 'openmentor.authentication' .controller 'LoginController', Array '$scope', '$state', 'authenticationService', ($scope, $state, authenticationService) -> $scope.prompt = null console.log "State params", $state.params if $state.params.prompt != 'default' $scope.prompt = $state.params.prompt if $state.params.challenge == 'default' $state.go 'home' return else $scope.challenge = $state.params.challenge $scope.clearMessage = () -> $scope.message = "" $scope.ok = (data) -> data = if $scope.challenge == 'oidc' {redirect: true, client_name: 'uhn'} else {username: $scope.username, password: <PASSWORD>} $scope.clearMessage() console.log "Starting login process", data authenticationService.login $scope, data $scope.cancel = () -> $scope.clearMessage() $scope.$emit "event:loginCancelled" $scope.$on 'event:loginDenied', (evt, data, status) -> if status == 403 $scope.message = "Sorry, couldn't verify this username and password" else $scope.message = data.message .controller 'AuthenticationController', Array '$scope', '$state', ($scope, $state) -> $scope.challenge = undefined $scope.username = undefined $scope.password = <PASSWORD> $scope.shown = false $scope.message = "" $scope.$on 'event:loginRequired', (event, values) -> challenge = values.challenge prompt = values.prompt match = /(\w+)/.exec challenge $state.go 'login', {challenge: match[1].toLowerCase(), prompt: prompt} $scope.$on 'event:loginDenied', (evt, data) -> $scope.message = data.message if ! $scope.shown $scope.$emit 'event:loginRequired'
true
angular .module 'openmentor.authentication' .controller 'LoginController', Array '$scope', '$state', 'authenticationService', ($scope, $state, authenticationService) -> $scope.prompt = null console.log "State params", $state.params if $state.params.prompt != 'default' $scope.prompt = $state.params.prompt if $state.params.challenge == 'default' $state.go 'home' return else $scope.challenge = $state.params.challenge $scope.clearMessage = () -> $scope.message = "" $scope.ok = (data) -> data = if $scope.challenge == 'oidc' {redirect: true, client_name: 'uhn'} else {username: $scope.username, password: PI:PASSWORD:<PASSWORD>END_PI} $scope.clearMessage() console.log "Starting login process", data authenticationService.login $scope, data $scope.cancel = () -> $scope.clearMessage() $scope.$emit "event:loginCancelled" $scope.$on 'event:loginDenied', (evt, data, status) -> if status == 403 $scope.message = "Sorry, couldn't verify this username and password" else $scope.message = data.message .controller 'AuthenticationController', Array '$scope', '$state', ($scope, $state) -> $scope.challenge = undefined $scope.username = undefined $scope.password = PI:PASSWORD:<PASSWORD>END_PI $scope.shown = false $scope.message = "" $scope.$on 'event:loginRequired', (event, values) -> challenge = values.challenge prompt = values.prompt match = /(\w+)/.exec challenge $state.go 'login', {challenge: match[1].toLowerCase(), prompt: prompt} $scope.$on 'event:loginDenied', (evt, data) -> $scope.message = data.message if ! $scope.shown $scope.$emit 'event:loginRequired'