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": "s.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAZOysega_DA0M9e-vElE11GsW8o65AF3g&v=3.exp&signed_in=true&callback=googleMapsLoaded'", "end": 1297, "score": 0.9995893836021423, "start": 1258, "tag": "KEY", "value": "AIzaSyAZOysega_DA0M9e-vElE11GsW8o65AF3g" } ]
app/assets/javascripts/ajeh_admin/master.js.coffee
pixelcabin/wscs_admin
0
window.ajaxBusy = false $(document).on 'keyup', (e) -> return unless e.ctrlKey and e.keyCode == 70 e.preventDefault() $('body').toggleClass('fullpage') $(document).on 'click', '[data-action]', (e) -> nodeName = e.target.nodeName return if nodeName is 'BUTTON' or nodeName is 'A' destination = $(this).data('action') if Turbolinks? Turbolinks.visit(destination) else window.location = destination ready = -> FastClick.attach(document.body) if window.devicePixelRatio and devicePixelRatio >= 2 testElem = document.createElement('div') testElem.style.border = '.5px solid transparent' document.body.appendChild(testElem) if testElem.offsetHeight is 1 document.querySelector('html').classList.add('support-css-hairlines') document.body.removeChild(testElem) # window.googleMapsLoaded = -> # window.googleMapsDidLoad = true # $(document).trigger('google-maps-loaded') # window.onGoogleMapsLoad = (fn) -> # if window.googleMapsDidLoad # fn.call() # else # $(document).on('google-maps-loaded', fn) # unless window.googleMapsDidLoad # $script = $ '<script>', # type: 'text/javascript' # src: 'https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyAZOysega_DA0M9e-vElE11GsW8o65AF3g&v=3.exp&signed_in=true&callback=googleMapsLoaded' # $script.appendTo('body') pageScripts.load() $(document).on 'cocoon:after-insert', (e, added) -> $(added).find('textarea').expanding() $(document).on 'mouseover', 'a.remove_fields', -> $(this).parents('.nested-fields').addClass('remove') $(document).on 'mouseout', 'a.remove_fields', -> $(this).parents('.nested-fields').removeClass('remove') $('textarea[data-wysiwyg]').each -> $textarea = $(this) wysiwygConfig = $textarea.data('wysiwyg-config') $textarea.redactor(wysiwygConfig) $('table[data-sortable]').each -> $table = $(this) url = $table.data('sortable') $table.find('tbody').sortable axis: 'y' items: 'tr' handle: '.handle' helper: (e, tr) -> $originals = tr.children() $helper = tr.clone() $helper.children().each (index) -> $(this).width($originals.eq(index).outerWidth()) $helper forcePlaceholderSize: true update: -> array = {} for tr, i in $table.find('tr') id = $(tr).data('id') array[id] = i+1 $.ajax url: url type: 'POST' data: _method: 'PATCH' records: array # layoutPageHeader = -> # widths = [] # $('#page-header a').each (el, i) -> widths.push $(this).outerWidth() # largestWidth = widths.sort()[widths.length-1] # # $('#page-header').css(padding: "0 #{largestWidth}px") # $('#page-header').css(paddingRight: "0 #{largestWidth}px") # $(window).on 'resize', layoutPageHeader # layoutPageHeader() jqPageOverlay = $('<div id="page-overlay">') jqPageOverlay.appendTo('#page') # if $('#page-header a:contains(Cancel)').length # $('#header').hide() # $('#page-header').addClass('full-width') # if Modernizr.touch # jqPageOverlay.on 'touchstart', (e) -> # e.preventDefault() # e.stopPropagation() # $('#header').on 'click', -> # $('body').toggleClass('nav-open') # jqPageOverlay.on 'touchend', -> # $('body').removeClass('nav-open') # else # headerTimeout = null # $('#header').on # mouseenter: -> # clearTimeout(headerTimeout) # $('body').addClass('nav-open') # mouseleave: -> # headerTimeout = ajeh._.delay 300, -> $('body').removeClass('nav-open') # initDataActions() # $('[data-remote]').on 'ajax:success', -> # initDataActions() $('input[type="text"], textarea').each -> $this = $(this) return if $this.attr('placeholder')? id = $this.attr('id') $label = $("label[for='#{id}']") if $label.length and $label.text() isnt '' $this.attr('placeholder', $label.text()) else $this.attr('placeholder', '…') # $('input, textarea').attr('placeholder', '…') $('.field').on focusin: -> $(this).addClass('focussed') focusout: -> $(this).removeClass('focussed') # $('.field > label').each -> $(this).text("#{$(this).text()}:") $('main > footer a.form-submit').on 'click', (e) -> e.preventDefault() return if ajaxBusy $('form:not(.button_to)').submit() $('.flash').velocity p: translateY: [ '0%', '-100%' ] o: duration: 500 delay: 300, easing: [ 500, 20 ] removeFlash = (flash) -> $(flash).velocity p: translateY: [ '-100%', '0%' ] o: duration: 500 easing: [ 500, 20 ] complete: -> $(this).remove() if this? $('.flash').on 'click', -> removeFlash(this) ajeh._.delay 5000, -> removeFlash('.flash') # Form label widths # ajeh._.delay 50, -> # $('form').each -> # $form = $(this) # widths = $form.find('.field > label').map(-> $(this).width() # ).get().sort((a, b) -> # b - a # ) # # $form.css maxWidth: 700 # # $form.css(maxWidth: 700 + widths[0] + 20) # # $form.css maxWidth: 700 + (widths[0])*2 + 30 # # $form.css paddingRight: "+=#{widths[0]}" # $form.find('.field > label').css width: widths[0] # $form.find('legend span').css marginLeft: widths[0] + 20 # # $form.find('.actions').css marginLeft: widths[0] + 20 # # $('.destroy_form').find('div').css maxWidth: 700 + (widths[0])*2 # # $('.destroy_form').find('div').css maxWidth: 700 # # jqHeader = $('#header') # # jqHeader.data('open', true).on 'click', -> # # if jqHeader.data('open') # # jqHeader.transition(width: 80) # # jqHeader.find('nav').transition(x: '-100%') # # $('#page').transition left: 80, -> jqHeader.data('open', false) # # else # # jqHeader.transition(width: 280) # # jqHeader.find('nav').transition(x: 0) # # $('#page').transition left: 280, -> jqHeader.data('open', true) $(':input[size]').autoGrowInput() $('.rome-datetime').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') romeInstance = rome romeInput, initialValue: $input.val() timeInterval: 60 * 15 timeFormat: 'h:mma' weekStart: 1 $input.data('rome', romeInstance) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.rome-date').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') inputRomeOptions = $input.data('rome') || {} romeOptions = $.extend inputRomeOptions, initialValue: $input.val() time: false weekStart: 1 rome(romeInput, romeOptions) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.date input').pickadate firstDay: 1 weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] format: 'dddd, d mmmm yyyy' formatSubmit: 'yyyy-mm-dd' $('.time input').pickatime() $('input[type="radio"]:checked').parent().addClass('checked') $('input[type="radio"]').on 'click', -> jqRadioButton = $(this) jqRadioButton.parent().addClass('checked').siblings().removeClass('checked') # File uploads $(':file.ajeh-uploader-simple').each -> jqInput = $(this) jqFilePreview = jqInput.parent().find('.file-preview') jqInput.on 'change', (e) -> # Destroy existing file preview jqFilePreview.empty() # Create file preview jqPreview = $('<img>', width: 220).hide().appendTo(jqFilePreview) jqHiddenInput = $('<input>', type: 'hidden', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqPreview.attr('src', fileUpload.previewSrc()).show() $('.ajeh-image-crop-upload').each -> jqThis = $(this) modelName = jqThis.parents('form').data('model') jqInput = jqThis.find(':file') jqFilePreview = jqThis.find('.file-preview') jqFilePreviewImage = jqFilePreview.find('img') jqCropInput = $("##{modelName}_cover_crop") savedCrop = jqFilePreviewImage.data('crop') if jqFilePreviewImage.length jCropApi = null jCropOptions = boxWidth: 640 setSelect: [savedCrop.x, savedCrop.y, savedCrop.x2, savedCrop.y2] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) jqFilePreviewImage.Jcrop jCropOptions, -> jCropApi = this jqInput.on 'change', (e) -> # Destroy existing jCrop instance jCropApi.destroy() if jCropApi # Create file preview jqInput.nextAll('input').remove() jqHiddenInput = $('<input>', type: 'text', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) jqFilePreview.empty() jqFilePreviewImage = $('<img>') jqFilePreviewImage.appendTo(jqFilePreview) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqFilePreviewImage.attr('src', fileUpload.previewSrc()).Jcrop boxWidth: 640 setSelect: [0,0,10000,10000] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) # window.editor = new Don.Editor(selector: '.don') $('[data-don]').each -> new don.Editor(this) $(document).ajaxStart -> ajaxBusy = true $('a.form-submit').addClass('disabled') # $('#busy-indicator').addClass('visible') $(document).ajaxComplete -> ajaxBusy = false $('a.form-submit').removeClass('disabled') # $('#busy-indicator').removeClass('visible') # Auto-expanding textareas # $('textarea:not(.wysiwyg)').expanding().on 'keydown', (e) -> # e.preventDefault() if e.originalEvent.keyCode is 13 $('.controls-text-area textarea:visible').addClass('-expanding').expanding() # Toggle form fields $('[data-toggle-name]').each -> jqField = $(this) fieldName = jqField.data('toggle-name') fieldVal = jqField.data('toggle-val') jqToggleField = $("[name='#{fieldName}'") jqToggleField.on 'change', -> if $(this).val() is fieldVal then jqField.show() else jqField.hide() if jqToggleField.filter(':checked').val() is fieldVal then jqField.show() else jqField.hide() if window.Turbolinks? $(document).on 'turbolinks:load', ready else $ -> ready() # $(document).on 'page:load', -> # ajeh._.delay 1, -> $('#page').scrollTop(0) # $(document).on 'page:before-change', -> $('#busy-indicator').css(opacity: 1, width: '30%') # $(document).on 'page:fetch', -> $('#busy-indicator').css(width: '60%') # $(document).on 'page:receive', -> $('#busy-indicator').css(width: '90%') # $(document).on 'page:load', -> $('#busy-indicator').css(width: '100%')
219300
window.ajaxBusy = false $(document).on 'keyup', (e) -> return unless e.ctrlKey and e.keyCode == 70 e.preventDefault() $('body').toggleClass('fullpage') $(document).on 'click', '[data-action]', (e) -> nodeName = e.target.nodeName return if nodeName is 'BUTTON' or nodeName is 'A' destination = $(this).data('action') if Turbolinks? Turbolinks.visit(destination) else window.location = destination ready = -> FastClick.attach(document.body) if window.devicePixelRatio and devicePixelRatio >= 2 testElem = document.createElement('div') testElem.style.border = '.5px solid transparent' document.body.appendChild(testElem) if testElem.offsetHeight is 1 document.querySelector('html').classList.add('support-css-hairlines') document.body.removeChild(testElem) # window.googleMapsLoaded = -> # window.googleMapsDidLoad = true # $(document).trigger('google-maps-loaded') # window.onGoogleMapsLoad = (fn) -> # if window.googleMapsDidLoad # fn.call() # else # $(document).on('google-maps-loaded', fn) # unless window.googleMapsDidLoad # $script = $ '<script>', # type: 'text/javascript' # src: 'https://maps.googleapis.com/maps/api/js?libraries=places&key=<KEY>&v=3.exp&signed_in=true&callback=googleMapsLoaded' # $script.appendTo('body') pageScripts.load() $(document).on 'cocoon:after-insert', (e, added) -> $(added).find('textarea').expanding() $(document).on 'mouseover', 'a.remove_fields', -> $(this).parents('.nested-fields').addClass('remove') $(document).on 'mouseout', 'a.remove_fields', -> $(this).parents('.nested-fields').removeClass('remove') $('textarea[data-wysiwyg]').each -> $textarea = $(this) wysiwygConfig = $textarea.data('wysiwyg-config') $textarea.redactor(wysiwygConfig) $('table[data-sortable]').each -> $table = $(this) url = $table.data('sortable') $table.find('tbody').sortable axis: 'y' items: 'tr' handle: '.handle' helper: (e, tr) -> $originals = tr.children() $helper = tr.clone() $helper.children().each (index) -> $(this).width($originals.eq(index).outerWidth()) $helper forcePlaceholderSize: true update: -> array = {} for tr, i in $table.find('tr') id = $(tr).data('id') array[id] = i+1 $.ajax url: url type: 'POST' data: _method: 'PATCH' records: array # layoutPageHeader = -> # widths = [] # $('#page-header a').each (el, i) -> widths.push $(this).outerWidth() # largestWidth = widths.sort()[widths.length-1] # # $('#page-header').css(padding: "0 #{largestWidth}px") # $('#page-header').css(paddingRight: "0 #{largestWidth}px") # $(window).on 'resize', layoutPageHeader # layoutPageHeader() jqPageOverlay = $('<div id="page-overlay">') jqPageOverlay.appendTo('#page') # if $('#page-header a:contains(Cancel)').length # $('#header').hide() # $('#page-header').addClass('full-width') # if Modernizr.touch # jqPageOverlay.on 'touchstart', (e) -> # e.preventDefault() # e.stopPropagation() # $('#header').on 'click', -> # $('body').toggleClass('nav-open') # jqPageOverlay.on 'touchend', -> # $('body').removeClass('nav-open') # else # headerTimeout = null # $('#header').on # mouseenter: -> # clearTimeout(headerTimeout) # $('body').addClass('nav-open') # mouseleave: -> # headerTimeout = ajeh._.delay 300, -> $('body').removeClass('nav-open') # initDataActions() # $('[data-remote]').on 'ajax:success', -> # initDataActions() $('input[type="text"], textarea').each -> $this = $(this) return if $this.attr('placeholder')? id = $this.attr('id') $label = $("label[for='#{id}']") if $label.length and $label.text() isnt '' $this.attr('placeholder', $label.text()) else $this.attr('placeholder', '…') # $('input, textarea').attr('placeholder', '…') $('.field').on focusin: -> $(this).addClass('focussed') focusout: -> $(this).removeClass('focussed') # $('.field > label').each -> $(this).text("#{$(this).text()}:") $('main > footer a.form-submit').on 'click', (e) -> e.preventDefault() return if ajaxBusy $('form:not(.button_to)').submit() $('.flash').velocity p: translateY: [ '0%', '-100%' ] o: duration: 500 delay: 300, easing: [ 500, 20 ] removeFlash = (flash) -> $(flash).velocity p: translateY: [ '-100%', '0%' ] o: duration: 500 easing: [ 500, 20 ] complete: -> $(this).remove() if this? $('.flash').on 'click', -> removeFlash(this) ajeh._.delay 5000, -> removeFlash('.flash') # Form label widths # ajeh._.delay 50, -> # $('form').each -> # $form = $(this) # widths = $form.find('.field > label').map(-> $(this).width() # ).get().sort((a, b) -> # b - a # ) # # $form.css maxWidth: 700 # # $form.css(maxWidth: 700 + widths[0] + 20) # # $form.css maxWidth: 700 + (widths[0])*2 + 30 # # $form.css paddingRight: "+=#{widths[0]}" # $form.find('.field > label').css width: widths[0] # $form.find('legend span').css marginLeft: widths[0] + 20 # # $form.find('.actions').css marginLeft: widths[0] + 20 # # $('.destroy_form').find('div').css maxWidth: 700 + (widths[0])*2 # # $('.destroy_form').find('div').css maxWidth: 700 # # jqHeader = $('#header') # # jqHeader.data('open', true).on 'click', -> # # if jqHeader.data('open') # # jqHeader.transition(width: 80) # # jqHeader.find('nav').transition(x: '-100%') # # $('#page').transition left: 80, -> jqHeader.data('open', false) # # else # # jqHeader.transition(width: 280) # # jqHeader.find('nav').transition(x: 0) # # $('#page').transition left: 280, -> jqHeader.data('open', true) $(':input[size]').autoGrowInput() $('.rome-datetime').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') romeInstance = rome romeInput, initialValue: $input.val() timeInterval: 60 * 15 timeFormat: 'h:mma' weekStart: 1 $input.data('rome', romeInstance) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.rome-date').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') inputRomeOptions = $input.data('rome') || {} romeOptions = $.extend inputRomeOptions, initialValue: $input.val() time: false weekStart: 1 rome(romeInput, romeOptions) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.date input').pickadate firstDay: 1 weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] format: 'dddd, d mmmm yyyy' formatSubmit: 'yyyy-mm-dd' $('.time input').pickatime() $('input[type="radio"]:checked').parent().addClass('checked') $('input[type="radio"]').on 'click', -> jqRadioButton = $(this) jqRadioButton.parent().addClass('checked').siblings().removeClass('checked') # File uploads $(':file.ajeh-uploader-simple').each -> jqInput = $(this) jqFilePreview = jqInput.parent().find('.file-preview') jqInput.on 'change', (e) -> # Destroy existing file preview jqFilePreview.empty() # Create file preview jqPreview = $('<img>', width: 220).hide().appendTo(jqFilePreview) jqHiddenInput = $('<input>', type: 'hidden', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqPreview.attr('src', fileUpload.previewSrc()).show() $('.ajeh-image-crop-upload').each -> jqThis = $(this) modelName = jqThis.parents('form').data('model') jqInput = jqThis.find(':file') jqFilePreview = jqThis.find('.file-preview') jqFilePreviewImage = jqFilePreview.find('img') jqCropInput = $("##{modelName}_cover_crop") savedCrop = jqFilePreviewImage.data('crop') if jqFilePreviewImage.length jCropApi = null jCropOptions = boxWidth: 640 setSelect: [savedCrop.x, savedCrop.y, savedCrop.x2, savedCrop.y2] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) jqFilePreviewImage.Jcrop jCropOptions, -> jCropApi = this jqInput.on 'change', (e) -> # Destroy existing jCrop instance jCropApi.destroy() if jCropApi # Create file preview jqInput.nextAll('input').remove() jqHiddenInput = $('<input>', type: 'text', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) jqFilePreview.empty() jqFilePreviewImage = $('<img>') jqFilePreviewImage.appendTo(jqFilePreview) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqFilePreviewImage.attr('src', fileUpload.previewSrc()).Jcrop boxWidth: 640 setSelect: [0,0,10000,10000] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) # window.editor = new Don.Editor(selector: '.don') $('[data-don]').each -> new don.Editor(this) $(document).ajaxStart -> ajaxBusy = true $('a.form-submit').addClass('disabled') # $('#busy-indicator').addClass('visible') $(document).ajaxComplete -> ajaxBusy = false $('a.form-submit').removeClass('disabled') # $('#busy-indicator').removeClass('visible') # Auto-expanding textareas # $('textarea:not(.wysiwyg)').expanding().on 'keydown', (e) -> # e.preventDefault() if e.originalEvent.keyCode is 13 $('.controls-text-area textarea:visible').addClass('-expanding').expanding() # Toggle form fields $('[data-toggle-name]').each -> jqField = $(this) fieldName = jqField.data('toggle-name') fieldVal = jqField.data('toggle-val') jqToggleField = $("[name='#{fieldName}'") jqToggleField.on 'change', -> if $(this).val() is fieldVal then jqField.show() else jqField.hide() if jqToggleField.filter(':checked').val() is fieldVal then jqField.show() else jqField.hide() if window.Turbolinks? $(document).on 'turbolinks:load', ready else $ -> ready() # $(document).on 'page:load', -> # ajeh._.delay 1, -> $('#page').scrollTop(0) # $(document).on 'page:before-change', -> $('#busy-indicator').css(opacity: 1, width: '30%') # $(document).on 'page:fetch', -> $('#busy-indicator').css(width: '60%') # $(document).on 'page:receive', -> $('#busy-indicator').css(width: '90%') # $(document).on 'page:load', -> $('#busy-indicator').css(width: '100%')
true
window.ajaxBusy = false $(document).on 'keyup', (e) -> return unless e.ctrlKey and e.keyCode == 70 e.preventDefault() $('body').toggleClass('fullpage') $(document).on 'click', '[data-action]', (e) -> nodeName = e.target.nodeName return if nodeName is 'BUTTON' or nodeName is 'A' destination = $(this).data('action') if Turbolinks? Turbolinks.visit(destination) else window.location = destination ready = -> FastClick.attach(document.body) if window.devicePixelRatio and devicePixelRatio >= 2 testElem = document.createElement('div') testElem.style.border = '.5px solid transparent' document.body.appendChild(testElem) if testElem.offsetHeight is 1 document.querySelector('html').classList.add('support-css-hairlines') document.body.removeChild(testElem) # window.googleMapsLoaded = -> # window.googleMapsDidLoad = true # $(document).trigger('google-maps-loaded') # window.onGoogleMapsLoad = (fn) -> # if window.googleMapsDidLoad # fn.call() # else # $(document).on('google-maps-loaded', fn) # unless window.googleMapsDidLoad # $script = $ '<script>', # type: 'text/javascript' # src: 'https://maps.googleapis.com/maps/api/js?libraries=places&key=PI:KEY:<KEY>END_PI&v=3.exp&signed_in=true&callback=googleMapsLoaded' # $script.appendTo('body') pageScripts.load() $(document).on 'cocoon:after-insert', (e, added) -> $(added).find('textarea').expanding() $(document).on 'mouseover', 'a.remove_fields', -> $(this).parents('.nested-fields').addClass('remove') $(document).on 'mouseout', 'a.remove_fields', -> $(this).parents('.nested-fields').removeClass('remove') $('textarea[data-wysiwyg]').each -> $textarea = $(this) wysiwygConfig = $textarea.data('wysiwyg-config') $textarea.redactor(wysiwygConfig) $('table[data-sortable]').each -> $table = $(this) url = $table.data('sortable') $table.find('tbody').sortable axis: 'y' items: 'tr' handle: '.handle' helper: (e, tr) -> $originals = tr.children() $helper = tr.clone() $helper.children().each (index) -> $(this).width($originals.eq(index).outerWidth()) $helper forcePlaceholderSize: true update: -> array = {} for tr, i in $table.find('tr') id = $(tr).data('id') array[id] = i+1 $.ajax url: url type: 'POST' data: _method: 'PATCH' records: array # layoutPageHeader = -> # widths = [] # $('#page-header a').each (el, i) -> widths.push $(this).outerWidth() # largestWidth = widths.sort()[widths.length-1] # # $('#page-header').css(padding: "0 #{largestWidth}px") # $('#page-header').css(paddingRight: "0 #{largestWidth}px") # $(window).on 'resize', layoutPageHeader # layoutPageHeader() jqPageOverlay = $('<div id="page-overlay">') jqPageOverlay.appendTo('#page') # if $('#page-header a:contains(Cancel)').length # $('#header').hide() # $('#page-header').addClass('full-width') # if Modernizr.touch # jqPageOverlay.on 'touchstart', (e) -> # e.preventDefault() # e.stopPropagation() # $('#header').on 'click', -> # $('body').toggleClass('nav-open') # jqPageOverlay.on 'touchend', -> # $('body').removeClass('nav-open') # else # headerTimeout = null # $('#header').on # mouseenter: -> # clearTimeout(headerTimeout) # $('body').addClass('nav-open') # mouseleave: -> # headerTimeout = ajeh._.delay 300, -> $('body').removeClass('nav-open') # initDataActions() # $('[data-remote]').on 'ajax:success', -> # initDataActions() $('input[type="text"], textarea').each -> $this = $(this) return if $this.attr('placeholder')? id = $this.attr('id') $label = $("label[for='#{id}']") if $label.length and $label.text() isnt '' $this.attr('placeholder', $label.text()) else $this.attr('placeholder', '…') # $('input, textarea').attr('placeholder', '…') $('.field').on focusin: -> $(this).addClass('focussed') focusout: -> $(this).removeClass('focussed') # $('.field > label').each -> $(this).text("#{$(this).text()}:") $('main > footer a.form-submit').on 'click', (e) -> e.preventDefault() return if ajaxBusy $('form:not(.button_to)').submit() $('.flash').velocity p: translateY: [ '0%', '-100%' ] o: duration: 500 delay: 300, easing: [ 500, 20 ] removeFlash = (flash) -> $(flash).velocity p: translateY: [ '-100%', '0%' ] o: duration: 500 easing: [ 500, 20 ] complete: -> $(this).remove() if this? $('.flash').on 'click', -> removeFlash(this) ajeh._.delay 5000, -> removeFlash('.flash') # Form label widths # ajeh._.delay 50, -> # $('form').each -> # $form = $(this) # widths = $form.find('.field > label').map(-> $(this).width() # ).get().sort((a, b) -> # b - a # ) # # $form.css maxWidth: 700 # # $form.css(maxWidth: 700 + widths[0] + 20) # # $form.css maxWidth: 700 + (widths[0])*2 + 30 # # $form.css paddingRight: "+=#{widths[0]}" # $form.find('.field > label').css width: widths[0] # $form.find('legend span').css marginLeft: widths[0] + 20 # # $form.find('.actions').css marginLeft: widths[0] + 20 # # $('.destroy_form').find('div').css maxWidth: 700 + (widths[0])*2 # # $('.destroy_form').find('div').css maxWidth: 700 # # jqHeader = $('#header') # # jqHeader.data('open', true).on 'click', -> # # if jqHeader.data('open') # # jqHeader.transition(width: 80) # # jqHeader.find('nav').transition(x: '-100%') # # $('#page').transition left: 80, -> jqHeader.data('open', false) # # else # # jqHeader.transition(width: 280) # # jqHeader.find('nav').transition(x: 0) # # $('#page').transition left: 280, -> jqHeader.data('open', true) $(':input[size]').autoGrowInput() $('.rome-datetime').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') romeInstance = rome romeInput, initialValue: $input.val() timeInterval: 60 * 15 timeFormat: 'h:mma' weekStart: 1 $input.data('rome', romeInstance) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.rome-date').each -> romeInput = document.createElement('div') $field = $(this) $field.find('.controls').prepend(romeInput) $input = $field.find(':input:first') inputRomeOptions = $input.data('rome') || {} romeOptions = $.extend inputRomeOptions, initialValue: $input.val() time: false weekStart: 1 rome(romeInput, romeOptions) rome(romeInput).on 'data', (value) -> $input.val(value) $input.val rome(romeInput).getDateString() $('.date input').pickadate firstDay: 1 weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] format: 'dddd, d mmmm yyyy' formatSubmit: 'yyyy-mm-dd' $('.time input').pickatime() $('input[type="radio"]:checked').parent().addClass('checked') $('input[type="radio"]').on 'click', -> jqRadioButton = $(this) jqRadioButton.parent().addClass('checked').siblings().removeClass('checked') # File uploads $(':file.ajeh-uploader-simple').each -> jqInput = $(this) jqFilePreview = jqInput.parent().find('.file-preview') jqInput.on 'change', (e) -> # Destroy existing file preview jqFilePreview.empty() # Create file preview jqPreview = $('<img>', width: 220).hide().appendTo(jqFilePreview) jqHiddenInput = $('<input>', type: 'hidden', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqPreview.attr('src', fileUpload.previewSrc()).show() $('.ajeh-image-crop-upload').each -> jqThis = $(this) modelName = jqThis.parents('form').data('model') jqInput = jqThis.find(':file') jqFilePreview = jqThis.find('.file-preview') jqFilePreviewImage = jqFilePreview.find('img') jqCropInput = $("##{modelName}_cover_crop") savedCrop = jqFilePreviewImage.data('crop') if jqFilePreviewImage.length jCropApi = null jCropOptions = boxWidth: 640 setSelect: [savedCrop.x, savedCrop.y, savedCrop.x2, savedCrop.y2] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) jqFilePreviewImage.Jcrop jCropOptions, -> jCropApi = this jqInput.on 'change', (e) -> # Destroy existing jCrop instance jCropApi.destroy() if jCropApi # Create file preview jqInput.nextAll('input').remove() jqHiddenInput = $('<input>', type: 'text', name: jqInput.attr('name')) jqHiddenInput.insertAfter(jqInput) jqFilePreview.empty() jqFilePreviewImage = $('<img>') jqFilePreviewImage.appendTo(jqFilePreview) # Create the file upload file = this.files[0] fileUpload = new FileUpload file, done: (key) -> url = ajeh.FileUploads.url_for("#{key}.jpg") jqHiddenInput.val(key) jqFilePreviewImage.attr('src', fileUpload.previewSrc()).Jcrop boxWidth: 640 setSelect: [0,0,10000,10000] aspectRatio: 2 onSelect: (c) -> jqCropInput.val JSON.stringify(c) # window.editor = new Don.Editor(selector: '.don') $('[data-don]').each -> new don.Editor(this) $(document).ajaxStart -> ajaxBusy = true $('a.form-submit').addClass('disabled') # $('#busy-indicator').addClass('visible') $(document).ajaxComplete -> ajaxBusy = false $('a.form-submit').removeClass('disabled') # $('#busy-indicator').removeClass('visible') # Auto-expanding textareas # $('textarea:not(.wysiwyg)').expanding().on 'keydown', (e) -> # e.preventDefault() if e.originalEvent.keyCode is 13 $('.controls-text-area textarea:visible').addClass('-expanding').expanding() # Toggle form fields $('[data-toggle-name]').each -> jqField = $(this) fieldName = jqField.data('toggle-name') fieldVal = jqField.data('toggle-val') jqToggleField = $("[name='#{fieldName}'") jqToggleField.on 'change', -> if $(this).val() is fieldVal then jqField.show() else jqField.hide() if jqToggleField.filter(':checked').val() is fieldVal then jqField.show() else jqField.hide() if window.Turbolinks? $(document).on 'turbolinks:load', ready else $ -> ready() # $(document).on 'page:load', -> # ajeh._.delay 1, -> $('#page').scrollTop(0) # $(document).on 'page:before-change', -> $('#busy-indicator').css(opacity: 1, width: '30%') # $(document).on 'page:fetch', -> $('#busy-indicator').css(width: '60%') # $(document).on 'page:receive', -> $('#busy-indicator').css(width: '90%') # $(document).on 'page:load', -> $('#busy-indicator').css(width: '100%')
[ { "context": "_isCombModule\n driven_list.push({key:lhs.getElId(),checkPoint:false,inst:lhs,driven:rhsInfo.dr", "end": 15559, "score": 0.5992090702056885, "start": 15556, "tag": "KEY", "value": "get" }, { "context": "mbModule\n driven_list.push({key:lhs.getElId(),checkPoint:false,inst:lhs,driven:rhsInfo.driven", "end": 15563, "score": 0.5615247488021851, "start": 15561, "tag": "KEY", "value": "Id" }, { "context": "\n else\n driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsIn", "end": 15677, "score": 0.5842199921607971, "start": 15674, "tag": "KEY", "value": "get" }, { "context": " else\n driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.d", "end": 15681, "score": 0.5150622129440308, "start": 15679, "tag": "KEY", "value": "Id" }, { "context": "__isCombModule\n driven_list.push({key:lhs.getElId(),checkPoint:false,inst:lhs,driven:rhsInfo.driven", "end": 16130, "score": 0.730714738368988, "start": 16123, "tag": "KEY", "value": "getElId" }, { "context": ")\n else\n driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.d", "end": 16248, "score": 0.7612828016281128, "start": 16241, "tag": "KEY", "value": "getElId" }, { "context": "'input'\n item = _.find(driven_list,{key:pin.getId()})\n if not item?\n if port.isCloc", "end": 20042, "score": 0.856890082359314, "start": 20037, "tag": "KEY", "value": "getId" }, { "context": "aultClock};\"\n driven_list.push({key:pin.getElId(),checkPoint:false,inst:pin,driven:[defaultClk.ge", "end": 20229, "score": 0.8354145884513855, "start": 20222, "tag": "KEY", "value": "getElId" }, { "context": "aultReset};\"\n driven_list.push({key:pin.getElId(),checkPoint:false,inst:pin,driven:[defaultRst.ge", "end": 20458, "score": 0.8462862372398376, "start": 20451, "tag": "KEY", "value": "getElId" } ]
src/chdl_base.coffee
wujun51227/coffee-hdl
14
_ = require 'lodash' log = require 'fancy-log' colors = require 'colors' fs = require 'fs' Expr = require('chdl_expr') Reg = require('chdl_reg') Vec = require('chdl_vec') Wire = require('chdl_wire') Port = require('chdl_port') Channel = require('chdl_channel') Module = require('chdl_module') Vnumber = require('chdl_number') Verilog = require('verilog') {table} = require 'table' global = require('chdl_global') {stringifyTree} = require "stringify-tree" {getValue,packEl,simBuffer,printBuffer,dumpBuffer,toSignal,toFlatten,syncType} = require('chdl_utils') {cdcAnalysis,buildClkTree}= require 'chdl_cdc' moduleIndex=0 moduleCache={} globalModuleCache={} config={ #autoClock: false tree: false noAlwaysComb: false lint: false } arr=[ 'abcdefghijklmnopqrstuvwxyz'... 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'... ] dict=[arr...] obscure_map={} do => dict.sort(()=> return 0.5 - Math.random() ) for i,index in arr obscure_map[i]=dict[index] blur=(s)=> if global.getObfuscate() out=[] for i in [s...] if obscure_map[i]? out.push obscure_map[i] else out.push i return out.join('') else if global.getPrefix() prefix = global.getPrefix() return prefix+'__'+s else return s getCellList= (inst)-> p = Object.getPrototypeOf(inst) list=({name:k,inst:v} for k,v of p when typeof(v)=='object' and v instanceof Module) for i in inst.__cells list.push(i) unless _.find(list,(n)-> n.inst.__id==i.inst.__id) return _.sortBy(list,['name']) cell_build = (inst) => inst._elaboration() for i in getCellList(inst) i.inst._link(i.name) #log 'Link cell',i.name i.inst._setParentNode(inst) cell_build(i.inst) inst._postElaboration() get_module_build_name= (inst)-> baseName=inst.constructor.name suffix='' if getCellList(inst).length>0 or inst.__uniq moduleIndex+=1 suffix='__'+moduleIndex s='' return baseName+s+suffix lineComment=(lineno)-> " /* #{lineno} */ " sharpToDot = (s)-> s.replace(/#/g,'.') rhsExpand=(expandItem)-> if expandItem?.__type == 'expr' cntExpr() return { code: sharpToDot(expandItem.e.str)+expandItem.append w: expandItem.e.wstr driven: _.clone(expandItem.e.driven) } else if _.isArray(expandItem) str='' w='' driven=[] cntCond(expandItem.length) for item,index in expandItem anno= do-> if item.lineno>=0 "#{lineComment(item.lineno)}" else "" v= rhsExpand(item.value) if not v? log("Error:assign expr is undefined #{anno}".red) throw new Error("assign expr is undefined #{anno}") if index==0 str="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else if item.cond? str+="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else str+="#{v.code}#{anno}" if index==0 w=v.w else w=w+'|'+v.w driven.push(_.clone(v.driven)...) return { code:str w: w driven: driven } checkAssignWidth=(lhs,rhsInfo,lineno)-> return if config.lint==false return if getLint('widthCheckLevel')==0 return if rhsInfo.w.match(/^"/) try rhsWidth=Number(Verilog.parser.parse(rhsInfo.w)) lhsWidth=lhs.getWidth() #console.log rhsInfo.code,rhsInfo.w,rhsWidth,lhs.getWidth() if getLint('widthCheckLevel')==1 if lhsWidth<rhsWidth log "Error: width overflow at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red else if getLint('widthCheckLevel')==2 if lhsWidth!=rhsWidth log "Error: width mismatch at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red catch e console.log 'Parse error:',lineno,lhs.hier,instEnv.get()._getModuleName() console.log e statementGen=(buffer,statement,cond_stack=[],sig_driven_list=[])-> stateType=statement[0] if stateType=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else if lhs.constructor?.name is 'VecMember' lhsName=lhs.refName() else throw new Error("Unknown lhs type") space=" ".repeat(cond_stack.length+1) conds= if cond_stack.length>0 then _.last(cond_stack) else [] if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null at #{lineno}".red) buffer.add space+"#{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null".red) buffer.add space+"#{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else if stateType=='end' buffer.add " end" else if stateType=='cond_end' space=" ".repeat(cond_stack.length) buffer.add space+"end" else if stateType=='verilog' buffer.add statement[1] else if stateType=='while' cond=statement[1] lineno=statement[2] if lineno? and lineno>=0 buffer.add " while(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add " while(#{toSignal cond.str}) begin" else if stateType=='if' cond=statement[1] cond_driven = [] if cond_stack.length>0 cond_driven.push(_.last(cond_stack)...) cond_driven.push(_.clone(cond.driven)) cond_stack.push(cond_driven) space=" ".repeat(cond_stack.length) lineno=statement[2] cntCond(1) if lineno? and lineno>=0 buffer.add space+"if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"if(#{toSignal cond.str}) begin" else if stateType=='elseif' cntCond(1) cond=statement[1] cond_driven = _.last(cond_stack) dList=_.last(cond_driven) dList.push(cond.driven...) space=" ".repeat(cond_stack.length) lineno=statement[2] if lineno? and lineno>=0 buffer.add space+"else if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"else if(#{toSignal cond.str}) begin" else if stateType=='else' cntCond(1) lineno=statement[1] space=" ".repeat(cond_stack.length) if lineno? and lineno>=0 buffer.add space+"else begin #{lineComment(lineno)}" else buffer.add space+"else begin" else if stateType=='flow_delay' if _.isNumber(statement[2]) and statement[2]!=null buffer.add " ##{statement[2]}" else if stateType=='flow_posedge' buffer.add " @(posedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_negedge' buffer.add " @(negedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_wait' buffer.add " wait(#{statement[2].e.str});" else if stateType=='flow_event' buffer.add " -> #{statement[2]};" else if stateType=='flow_trigger' buffer.add " @(#{statement[2]});" else if stateType=='flow_polling' item = statement[3] buffer.add " #{item.active} = 1;" buffer.add " while(#{item.active}) begin" buffer.add " @(posedge #{statement[2]});" buffer.add " if(#{item.expr.e.str}) begin" buffer.add " #{item.active} = 0;" buffer.add " end;" buffer.add " end;" else if stateType=='array_init' array_el=statement[1] file_type=statement[2][0] file_path=statement[2][1] oomr=statement[2][2] if oomr array_path=array_el.oomrName() else array_path=array_el.getName() if file_type=='hex' buffer.add " $readmemh(#{file_path},#{array_path});" else throw new Error("arrays init format #{file_type} undefined".red) else if stateType=='endif' cond_stack.pop() else throw new Error("can not find type #{stateType}") buildSim= (buildName,inst)=> #console.log(JSON.stringify(inst._dumpWire(),null,' ')) #console.log(JSON.stringify(inst._dumpPort(),null,' ')) #console.log(JSON.stringify(inst._dumpReg(),null,' ')) #console.log(JSON.stringify(inst._dumpVar(),null,' ')) #console.log(JSON.stringify(inst._dumpCell(),null,' ')) simBuffer.setName(buildName,inst) simBuffer.add 'const '+buildName+' = { }' simBuffer.add _.map(toFlatten(inst.__ports), (i)=> "_.set(#{buildName},'#{i[0]}',rxGen(#{i[1].getWidth()}))" ).join("\n") simBuffer.flush() ### simPackage={ name : buildName port : inst._dumpPort() reg : inst._dumpReg() wire : inst._dumpWire() var : inst._dumpVar() event : inst._dumpEvent() cell : inst._dumpCell() } ### code_gen= (inst,allInst,first=false)=> if first inst._setProperty({uniq_name:false}) buildName = inst._getBuildName() if first and (!inst._isCompany()) and global.getTopName()? buildName = global.getTopName() if inst.__uniq moduleIndex += 1 buildName = buildName+'__'+moduleIndex if first==false if not global.getUntouchModules().includes(inst.constructor.name) buildName=blur(buildName) inst._overrideModuleName(buildName) log ('Build cell '+inst._getPath()+' ( '+buildName+' )').green if moduleCache[buildName]? return else if inst._isBlackBox() log 'Warning:',inst._getPath(),'is blackbox' return else moduleCache[buildName]=true sig_driven_tree={inst:inst,list:[],children:[]} for i in getCellList(inst) inst_sig_driven=code_gen(i.inst,allInst) sig_driven_tree.children.push(inst_sig_driven) driven_list=sig_driven_tree.list if inst.dump? dumpBuffer.setName(buildName,null) dumpBuffer.add JSON.stringify(inst.dump(),null,2) dumpBuffer.flush() #fs.writeFileSync(buildName+'.dump.json',JSON.stringify(inst.dump(),null,2),'utf8') instEnv.register(inst) allInst.push(inst) if allInst? channelWireList=[] for [name,channel] in toFlatten(inst.__channels) code=channel.verilogDeclare() channelWireList.push(code) if code!='' for [name,item] in toFlatten(inst.__channels) if item.probeChannel==null if item.wireMap? _.set(inst,name,item.wireMap) else _.set(inst,name,item.portMap) inst.build() if global.getSim() log(("Build sim "+buildName).green) buildSim(buildName,inst) printBuffer.setName(buildName,inst) printBuffer.add '`ifndef UDLY' printBuffer.add '`define UDLY 1' printBuffer.add '`endif' if global.getIfdefProtect() printBuffer.add '`ifndef _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add '`define _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add 'module '+buildName+'(' printBuffer.add _.map(toFlatten(inst.__ports), (i)=> " "+i[1].getName() ).join(",\n") printBuffer.add ');' printBuffer.blank('//parameter declare') for i in inst.__moduleParameter printBuffer.add i.verilogDeclare(false) printBuffer.blank('//port declare') _.map(toFlatten(inst.__ports), (i)=> printBuffer.add i[1].portDeclare()+";" ) printBuffer.blank('//channel declare') for i in channelWireList printBuffer.add(i) printBuffer.blank('//wire declare') for [name,wire] in toFlatten(inst.__wires) if wire.constructor.name=='Wire' printBuffer.add wire.verilogDeclare() for [name,wire] in toFlatten(inst.__local_wires) if wire.constructor.name=='Wire' and wire.local printBuffer.add wire.verilogDeclare() printBuffer.blank('//port wire declare') for [name,port] in toFlatten(inst.__ports) unless port.isReg printBuffer.add port.verilogDeclare() printBuffer.blank('//register declare') for [name,reg] in toFlatten(inst.__local_vecs) printBuffer.add reg.verilogDeclare() printBuffer.blank() printBuffer.blank('//register init and update') for [name,reg] in toFlatten(inst.__regs) when reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__regs) when not reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__local_regs) if reg.local printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() printBuffer.blank('//assign logic') if inst.__wireAssignList.length>0 for statement in inst.__wireAssignList if statement[0]=='reg' name=statement[2] lineno=statement[3] if lineno? and lineno>=0 printBuffer.add "reg #{name}#{lineComment(lineno)};" else printBuffer.add "reg #{name};" else if statement[0]=='array_set' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays set to #{lhsName} condition is null".red) rhs=statement[2][1] rhsInfo=rhsExpand(rhs) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("arrays set to #{lhsName} value is null".red) clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{lhsName} <= #{rhsInfo.code};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='array_get' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays get to #{lhsName} condition is null".red) target=statement[2][1] targetName=target.refName() clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{targetName} <= #{lhsName};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else throw new Error('Unknown lhs type') if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.getElId(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null at #{lineno}".red) printBuffer.add "assign #{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.getElId(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null".red) printBuffer.add "assign #{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) printBuffer.blank('//event declare') unless _.isEmpty(inst.__trigMap) for name in Object.keys(inst.__trigMap) printBuffer.add "event #{name};" printBuffer.blank('//initial statement') if inst.__initialList.length>0 for seqList in inst.__initialList when seqList.length>0 printBuffer.add "initial begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//forever statement') if inst.__foreverList.length>0 for seqList in inst.__foreverList when seqList.length>0 printBuffer.add "always begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//register update logic') if inst.__alwaysList.length>0 for [assignList,lineno] in inst.__alwaysList when assignList? and assignList.length>0 if lineno? and lineno>=0 if config.noAlwaysComb printBuffer.add 'always @* begin'+"#{lineComment(lineno)}" else printBuffer.add 'always_comb begin'+"#{lineComment(lineno)}" else if config.noAlwaysComb printBuffer.add 'always @* begin' else printBuffer.add 'always_comb begin' updateEls=[] for statement in assignList stateType=statement[0] if stateType=='assign' updateEls.push statement[1] for i in _.uniqBy(updateEls,(n)=>n.hier) if i.constructor?.name is 'Reg' printBuffer.add " #{global.getPrefix()}_"+i.getName()+'='+getValue(i.getPending())+';' else if (i.constructor?.name is 'Wire') or (i.constructor?.name is 'Port') printBuffer.add ' '+i.getName()+'='+getValue(i.getPending())+';' if assignList cond_stack=[] for statement in assignList statementGen(printBuffer,statement,cond_stack,driven_list) printBuffer.add 'end' printBuffer.blank() printBuffer.blank('//cell instance') for i in getCellList(inst) paramDeclare=getVerilogParameter(i.inst) printBuffer.add i.inst._getModuleName()+paramDeclare+blur(i.name)+'(' if (not i.inst.__isCombModule) if i.inst.__defaultClock clockPort=i.inst.__ports[i.inst.__defaultClock] if (!clockPort.isBinded()) clockPort.setBindSignal(inst.__defaultClock) if i.inst.__defaultReset resetPort=i.inst.__ports[i.inst.__defaultReset] if (!resetPort.isBinded()) resetPort.setBindSignal(inst.__defaultReset) [pinConn,pinAssigns]=i.inst._pinConnect(inst) printBuffer.add pinConn.join(",\n") printBuffer.add ');' printBuffer.blank() if pinAssigns.length>0 pinAssignList=[] for pinAssign in pinAssigns hit= _.find(inst.__pinAssign,{to:pinAssign.to}) if hit? pinAssignList.push({ from: pinAssign.from to: hit.from }) else pinAssignList.push(pinAssign) _.map(pinAssignList,(n)-> printBuffer.add "assign #{n.to} = #{n.from};" ) printBuffer.blank() if !inst.__isCombModule defaultClk = _.get(inst.__ports,inst._clock()) defaultRst = _.get(inst.__ports,inst._reset()) for {pin,port} in i.inst.__pinPortPair when port.getType()=='input' item = _.find(driven_list,{key:pin.getId()}) if not item? if port.isClock printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultClock};" driven_list.push({key:pin.getElId(),checkPoint:false,inst:pin,driven:[defaultClk.getId()],conds:[]}) if port.isReset printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultReset};" driven_list.push({key:pin.getElId(),checkPoint:false,inst:pin,driven:[defaultRst.getId()],conds:[]}) printBuffer.blank() printBuffer.blank('//Verilog Segment') for plainLines in inst.__verilogSegments lines=plainLines.split(/\n/) for line in lines printBuffer.add line printBuffer.blank() printBuffer.add 'endmodule' if global.getIfdefProtect() printBuffer.add '`endif' printBuffer.blank() printBuffer.flush() return sig_driven_tree getVerilogParameter=(inst)-> if inst.__instParameter==null return ' ' else list=[] for i in inst.__instParameter list.push(".#{i.key}(#{i.value})") return " #(\n "+list.join(",\n ")+"\n) " module.exports.buildCompanyModule=(companyModule,params...)-> inst=new companyModule(params...) inst._setCompany() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] module.exports.buildGlobalModule=(globalModule,params...)-> inst=new globalModule(params...) inst._setGlobal() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] toVerilog=(inst)-> cell_build(inst) instList=[] inst_sig_driven=code_gen(inst,instList,true) if global.isCdcCheck() clkGroup=buildClkTree(inst_sig_driven) cdcResult=cdcAnalysis(inst_sig_driven,clkGroup) reportFile=global.getCdcReportFile() if reportFile? outFile=global.getOutDir()+'/'+reportFile fs.writeFileSync(outFile,JSON.stringify(cdcResult,null,' '),'utf8') if config.tree console.log(stringifyTree({name:inst._getModuleName(),inst:inst}, ((t) -> t.name+' ('+t.inst._getModuleName()+')'), ((t) -> getCellList(t.inst)))) if global.getInfo() list= [['register name','width']] list.push(['-------------','-----']) dffBitSum=0 for [name,reg] in toFlatten(inst.__regs) list.push([toSignal(name),reg.getWidth()]) dffBitSum+=reg.getWidth() for [name,reg] in toFlatten(inst.__local_regs) list.push([reg.refName(),reg.getWidth()]) dffBitSum+=reg.getWidth() if list.length>2 list.push(['-------------','-----']) list.push(['TotalBits',dffBitSum]) console.log(table(list,{singleLine:true,columnDefault: {width:30}})) if global.getInfo() condCnt=0 transferCnt=0 tableList=[] tableList.push(['Module','Condition','Transfer']) for i in instList condCnt+=i.__lint._cnt.cond transferCnt+=i.__lint._cnt.transfer tableList.push([i._getModuleName(),i.__lint._cnt.cond,i.__lint._cnt.transfer]) tableList.push(['----------','-----','-----']) tableList.push(['Summary',condCnt,transferCnt]) console.log(table(tableList,{singleLine:true,columnDefault: {width:30}})) return inst input=(width=1)->packEl('port',Port.in(width)) output=(width=1)->packEl('port',Port.out(width)) bind= (name)-> Port.bind(name) channel= (path=null)-> Channel.create(path) instEnv= do -> inst=null return { register: (i)-> inst=i infer: ()-> inst.__assignWidth get: -> inst } cntCond=(num)-> if global.getInfo() instEnv.get().__lint._cnt.cond+=num cntExpr= -> if global.getInfo() instEnv.get().__lint._cnt.transfer+=1 getLint= (key)-> if instEnv.get().__lint[key]? return instEnv.get().__lint[key] else return null module.exports.hex = Vnumber.hex module.exports.dec = Vnumber.dec module.exports.oct = Vnumber.oct module.exports.bin = Vnumber.bin module.exports.Module = Module module.exports.Expr = Expr module.exports.toVerilog = toVerilog module.exports.input = input module.exports.output = output module.exports.bind = bind module.exports.channel = channel module.exports.infer = instEnv.infer module.exports.configBase =(cfg)-> config=Object.assign(config,cfg) module.exports.resetBase = -> moduleCache={} globalModuleCache={} moduleIndex=0
132574
_ = require 'lodash' log = require 'fancy-log' colors = require 'colors' fs = require 'fs' Expr = require('chdl_expr') Reg = require('chdl_reg') Vec = require('chdl_vec') Wire = require('chdl_wire') Port = require('chdl_port') Channel = require('chdl_channel') Module = require('chdl_module') Vnumber = require('chdl_number') Verilog = require('verilog') {table} = require 'table' global = require('chdl_global') {stringifyTree} = require "stringify-tree" {getValue,packEl,simBuffer,printBuffer,dumpBuffer,toSignal,toFlatten,syncType} = require('chdl_utils') {cdcAnalysis,buildClkTree}= require 'chdl_cdc' moduleIndex=0 moduleCache={} globalModuleCache={} config={ #autoClock: false tree: false noAlwaysComb: false lint: false } arr=[ 'abcdefghijklmnopqrstuvwxyz'... 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'... ] dict=[arr...] obscure_map={} do => dict.sort(()=> return 0.5 - Math.random() ) for i,index in arr obscure_map[i]=dict[index] blur=(s)=> if global.getObfuscate() out=[] for i in [s...] if obscure_map[i]? out.push obscure_map[i] else out.push i return out.join('') else if global.getPrefix() prefix = global.getPrefix() return prefix+'__'+s else return s getCellList= (inst)-> p = Object.getPrototypeOf(inst) list=({name:k,inst:v} for k,v of p when typeof(v)=='object' and v instanceof Module) for i in inst.__cells list.push(i) unless _.find(list,(n)-> n.inst.__id==i.inst.__id) return _.sortBy(list,['name']) cell_build = (inst) => inst._elaboration() for i in getCellList(inst) i.inst._link(i.name) #log 'Link cell',i.name i.inst._setParentNode(inst) cell_build(i.inst) inst._postElaboration() get_module_build_name= (inst)-> baseName=inst.constructor.name suffix='' if getCellList(inst).length>0 or inst.__uniq moduleIndex+=1 suffix='__'+moduleIndex s='' return baseName+s+suffix lineComment=(lineno)-> " /* #{lineno} */ " sharpToDot = (s)-> s.replace(/#/g,'.') rhsExpand=(expandItem)-> if expandItem?.__type == 'expr' cntExpr() return { code: sharpToDot(expandItem.e.str)+expandItem.append w: expandItem.e.wstr driven: _.clone(expandItem.e.driven) } else if _.isArray(expandItem) str='' w='' driven=[] cntCond(expandItem.length) for item,index in expandItem anno= do-> if item.lineno>=0 "#{lineComment(item.lineno)}" else "" v= rhsExpand(item.value) if not v? log("Error:assign expr is undefined #{anno}".red) throw new Error("assign expr is undefined #{anno}") if index==0 str="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else if item.cond? str+="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else str+="#{v.code}#{anno}" if index==0 w=v.w else w=w+'|'+v.w driven.push(_.clone(v.driven)...) return { code:str w: w driven: driven } checkAssignWidth=(lhs,rhsInfo,lineno)-> return if config.lint==false return if getLint('widthCheckLevel')==0 return if rhsInfo.w.match(/^"/) try rhsWidth=Number(Verilog.parser.parse(rhsInfo.w)) lhsWidth=lhs.getWidth() #console.log rhsInfo.code,rhsInfo.w,rhsWidth,lhs.getWidth() if getLint('widthCheckLevel')==1 if lhsWidth<rhsWidth log "Error: width overflow at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red else if getLint('widthCheckLevel')==2 if lhsWidth!=rhsWidth log "Error: width mismatch at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red catch e console.log 'Parse error:',lineno,lhs.hier,instEnv.get()._getModuleName() console.log e statementGen=(buffer,statement,cond_stack=[],sig_driven_list=[])-> stateType=statement[0] if stateType=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else if lhs.constructor?.name is 'VecMember' lhsName=lhs.refName() else throw new Error("Unknown lhs type") space=" ".repeat(cond_stack.length+1) conds= if cond_stack.length>0 then _.last(cond_stack) else [] if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null at #{lineno}".red) buffer.add space+"#{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null".red) buffer.add space+"#{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else if stateType=='end' buffer.add " end" else if stateType=='cond_end' space=" ".repeat(cond_stack.length) buffer.add space+"end" else if stateType=='verilog' buffer.add statement[1] else if stateType=='while' cond=statement[1] lineno=statement[2] if lineno? and lineno>=0 buffer.add " while(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add " while(#{toSignal cond.str}) begin" else if stateType=='if' cond=statement[1] cond_driven = [] if cond_stack.length>0 cond_driven.push(_.last(cond_stack)...) cond_driven.push(_.clone(cond.driven)) cond_stack.push(cond_driven) space=" ".repeat(cond_stack.length) lineno=statement[2] cntCond(1) if lineno? and lineno>=0 buffer.add space+"if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"if(#{toSignal cond.str}) begin" else if stateType=='elseif' cntCond(1) cond=statement[1] cond_driven = _.last(cond_stack) dList=_.last(cond_driven) dList.push(cond.driven...) space=" ".repeat(cond_stack.length) lineno=statement[2] if lineno? and lineno>=0 buffer.add space+"else if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"else if(#{toSignal cond.str}) begin" else if stateType=='else' cntCond(1) lineno=statement[1] space=" ".repeat(cond_stack.length) if lineno? and lineno>=0 buffer.add space+"else begin #{lineComment(lineno)}" else buffer.add space+"else begin" else if stateType=='flow_delay' if _.isNumber(statement[2]) and statement[2]!=null buffer.add " ##{statement[2]}" else if stateType=='flow_posedge' buffer.add " @(posedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_negedge' buffer.add " @(negedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_wait' buffer.add " wait(#{statement[2].e.str});" else if stateType=='flow_event' buffer.add " -> #{statement[2]};" else if stateType=='flow_trigger' buffer.add " @(#{statement[2]});" else if stateType=='flow_polling' item = statement[3] buffer.add " #{item.active} = 1;" buffer.add " while(#{item.active}) begin" buffer.add " @(posedge #{statement[2]});" buffer.add " if(#{item.expr.e.str}) begin" buffer.add " #{item.active} = 0;" buffer.add " end;" buffer.add " end;" else if stateType=='array_init' array_el=statement[1] file_type=statement[2][0] file_path=statement[2][1] oomr=statement[2][2] if oomr array_path=array_el.oomrName() else array_path=array_el.getName() if file_type=='hex' buffer.add " $readmemh(#{file_path},#{array_path});" else throw new Error("arrays init format #{file_type} undefined".red) else if stateType=='endif' cond_stack.pop() else throw new Error("can not find type #{stateType}") buildSim= (buildName,inst)=> #console.log(JSON.stringify(inst._dumpWire(),null,' ')) #console.log(JSON.stringify(inst._dumpPort(),null,' ')) #console.log(JSON.stringify(inst._dumpReg(),null,' ')) #console.log(JSON.stringify(inst._dumpVar(),null,' ')) #console.log(JSON.stringify(inst._dumpCell(),null,' ')) simBuffer.setName(buildName,inst) simBuffer.add 'const '+buildName+' = { }' simBuffer.add _.map(toFlatten(inst.__ports), (i)=> "_.set(#{buildName},'#{i[0]}',rxGen(#{i[1].getWidth()}))" ).join("\n") simBuffer.flush() ### simPackage={ name : buildName port : inst._dumpPort() reg : inst._dumpReg() wire : inst._dumpWire() var : inst._dumpVar() event : inst._dumpEvent() cell : inst._dumpCell() } ### code_gen= (inst,allInst,first=false)=> if first inst._setProperty({uniq_name:false}) buildName = inst._getBuildName() if first and (!inst._isCompany()) and global.getTopName()? buildName = global.getTopName() if inst.__uniq moduleIndex += 1 buildName = buildName+'__'+moduleIndex if first==false if not global.getUntouchModules().includes(inst.constructor.name) buildName=blur(buildName) inst._overrideModuleName(buildName) log ('Build cell '+inst._getPath()+' ( '+buildName+' )').green if moduleCache[buildName]? return else if inst._isBlackBox() log 'Warning:',inst._getPath(),'is blackbox' return else moduleCache[buildName]=true sig_driven_tree={inst:inst,list:[],children:[]} for i in getCellList(inst) inst_sig_driven=code_gen(i.inst,allInst) sig_driven_tree.children.push(inst_sig_driven) driven_list=sig_driven_tree.list if inst.dump? dumpBuffer.setName(buildName,null) dumpBuffer.add JSON.stringify(inst.dump(),null,2) dumpBuffer.flush() #fs.writeFileSync(buildName+'.dump.json',JSON.stringify(inst.dump(),null,2),'utf8') instEnv.register(inst) allInst.push(inst) if allInst? channelWireList=[] for [name,channel] in toFlatten(inst.__channels) code=channel.verilogDeclare() channelWireList.push(code) if code!='' for [name,item] in toFlatten(inst.__channels) if item.probeChannel==null if item.wireMap? _.set(inst,name,item.wireMap) else _.set(inst,name,item.portMap) inst.build() if global.getSim() log(("Build sim "+buildName).green) buildSim(buildName,inst) printBuffer.setName(buildName,inst) printBuffer.add '`ifndef UDLY' printBuffer.add '`define UDLY 1' printBuffer.add '`endif' if global.getIfdefProtect() printBuffer.add '`ifndef _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add '`define _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add 'module '+buildName+'(' printBuffer.add _.map(toFlatten(inst.__ports), (i)=> " "+i[1].getName() ).join(",\n") printBuffer.add ');' printBuffer.blank('//parameter declare') for i in inst.__moduleParameter printBuffer.add i.verilogDeclare(false) printBuffer.blank('//port declare') _.map(toFlatten(inst.__ports), (i)=> printBuffer.add i[1].portDeclare()+";" ) printBuffer.blank('//channel declare') for i in channelWireList printBuffer.add(i) printBuffer.blank('//wire declare') for [name,wire] in toFlatten(inst.__wires) if wire.constructor.name=='Wire' printBuffer.add wire.verilogDeclare() for [name,wire] in toFlatten(inst.__local_wires) if wire.constructor.name=='Wire' and wire.local printBuffer.add wire.verilogDeclare() printBuffer.blank('//port wire declare') for [name,port] in toFlatten(inst.__ports) unless port.isReg printBuffer.add port.verilogDeclare() printBuffer.blank('//register declare') for [name,reg] in toFlatten(inst.__local_vecs) printBuffer.add reg.verilogDeclare() printBuffer.blank() printBuffer.blank('//register init and update') for [name,reg] in toFlatten(inst.__regs) when reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__regs) when not reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__local_regs) if reg.local printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() printBuffer.blank('//assign logic') if inst.__wireAssignList.length>0 for statement in inst.__wireAssignList if statement[0]=='reg' name=statement[2] lineno=statement[3] if lineno? and lineno>=0 printBuffer.add "reg #{name}#{lineComment(lineno)};" else printBuffer.add "reg #{name};" else if statement[0]=='array_set' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays set to #{lhsName} condition is null".red) rhs=statement[2][1] rhsInfo=rhsExpand(rhs) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("arrays set to #{lhsName} value is null".red) clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{lhsName} <= #{rhsInfo.code};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='array_get' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays get to #{lhsName} condition is null".red) target=statement[2][1] targetName=target.refName() clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{targetName} <= #{lhsName};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else throw new Error('Unknown lhs type') if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.<KEY>El<KEY>(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.<KEY>El<KEY>(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null at #{lineno}".red) printBuffer.add "assign #{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.<KEY>(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.<KEY>(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null".red) printBuffer.add "assign #{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) printBuffer.blank('//event declare') unless _.isEmpty(inst.__trigMap) for name in Object.keys(inst.__trigMap) printBuffer.add "event #{name};" printBuffer.blank('//initial statement') if inst.__initialList.length>0 for seqList in inst.__initialList when seqList.length>0 printBuffer.add "initial begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//forever statement') if inst.__foreverList.length>0 for seqList in inst.__foreverList when seqList.length>0 printBuffer.add "always begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//register update logic') if inst.__alwaysList.length>0 for [assignList,lineno] in inst.__alwaysList when assignList? and assignList.length>0 if lineno? and lineno>=0 if config.noAlwaysComb printBuffer.add 'always @* begin'+"#{lineComment(lineno)}" else printBuffer.add 'always_comb begin'+"#{lineComment(lineno)}" else if config.noAlwaysComb printBuffer.add 'always @* begin' else printBuffer.add 'always_comb begin' updateEls=[] for statement in assignList stateType=statement[0] if stateType=='assign' updateEls.push statement[1] for i in _.uniqBy(updateEls,(n)=>n.hier) if i.constructor?.name is 'Reg' printBuffer.add " #{global.getPrefix()}_"+i.getName()+'='+getValue(i.getPending())+';' else if (i.constructor?.name is 'Wire') or (i.constructor?.name is 'Port') printBuffer.add ' '+i.getName()+'='+getValue(i.getPending())+';' if assignList cond_stack=[] for statement in assignList statementGen(printBuffer,statement,cond_stack,driven_list) printBuffer.add 'end' printBuffer.blank() printBuffer.blank('//cell instance') for i in getCellList(inst) paramDeclare=getVerilogParameter(i.inst) printBuffer.add i.inst._getModuleName()+paramDeclare+blur(i.name)+'(' if (not i.inst.__isCombModule) if i.inst.__defaultClock clockPort=i.inst.__ports[i.inst.__defaultClock] if (!clockPort.isBinded()) clockPort.setBindSignal(inst.__defaultClock) if i.inst.__defaultReset resetPort=i.inst.__ports[i.inst.__defaultReset] if (!resetPort.isBinded()) resetPort.setBindSignal(inst.__defaultReset) [pinConn,pinAssigns]=i.inst._pinConnect(inst) printBuffer.add pinConn.join(",\n") printBuffer.add ');' printBuffer.blank() if pinAssigns.length>0 pinAssignList=[] for pinAssign in pinAssigns hit= _.find(inst.__pinAssign,{to:pinAssign.to}) if hit? pinAssignList.push({ from: pinAssign.from to: hit.from }) else pinAssignList.push(pinAssign) _.map(pinAssignList,(n)-> printBuffer.add "assign #{n.to} = #{n.from};" ) printBuffer.blank() if !inst.__isCombModule defaultClk = _.get(inst.__ports,inst._clock()) defaultRst = _.get(inst.__ports,inst._reset()) for {pin,port} in i.inst.__pinPortPair when port.getType()=='input' item = _.find(driven_list,{key:pin.<KEY>()}) if not item? if port.isClock printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultClock};" driven_list.push({key:pin.<KEY>(),checkPoint:false,inst:pin,driven:[defaultClk.getId()],conds:[]}) if port.isReset printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultReset};" driven_list.push({key:pin.<KEY>(),checkPoint:false,inst:pin,driven:[defaultRst.getId()],conds:[]}) printBuffer.blank() printBuffer.blank('//Verilog Segment') for plainLines in inst.__verilogSegments lines=plainLines.split(/\n/) for line in lines printBuffer.add line printBuffer.blank() printBuffer.add 'endmodule' if global.getIfdefProtect() printBuffer.add '`endif' printBuffer.blank() printBuffer.flush() return sig_driven_tree getVerilogParameter=(inst)-> if inst.__instParameter==null return ' ' else list=[] for i in inst.__instParameter list.push(".#{i.key}(#{i.value})") return " #(\n "+list.join(",\n ")+"\n) " module.exports.buildCompanyModule=(companyModule,params...)-> inst=new companyModule(params...) inst._setCompany() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] module.exports.buildGlobalModule=(globalModule,params...)-> inst=new globalModule(params...) inst._setGlobal() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] toVerilog=(inst)-> cell_build(inst) instList=[] inst_sig_driven=code_gen(inst,instList,true) if global.isCdcCheck() clkGroup=buildClkTree(inst_sig_driven) cdcResult=cdcAnalysis(inst_sig_driven,clkGroup) reportFile=global.getCdcReportFile() if reportFile? outFile=global.getOutDir()+'/'+reportFile fs.writeFileSync(outFile,JSON.stringify(cdcResult,null,' '),'utf8') if config.tree console.log(stringifyTree({name:inst._getModuleName(),inst:inst}, ((t) -> t.name+' ('+t.inst._getModuleName()+')'), ((t) -> getCellList(t.inst)))) if global.getInfo() list= [['register name','width']] list.push(['-------------','-----']) dffBitSum=0 for [name,reg] in toFlatten(inst.__regs) list.push([toSignal(name),reg.getWidth()]) dffBitSum+=reg.getWidth() for [name,reg] in toFlatten(inst.__local_regs) list.push([reg.refName(),reg.getWidth()]) dffBitSum+=reg.getWidth() if list.length>2 list.push(['-------------','-----']) list.push(['TotalBits',dffBitSum]) console.log(table(list,{singleLine:true,columnDefault: {width:30}})) if global.getInfo() condCnt=0 transferCnt=0 tableList=[] tableList.push(['Module','Condition','Transfer']) for i in instList condCnt+=i.__lint._cnt.cond transferCnt+=i.__lint._cnt.transfer tableList.push([i._getModuleName(),i.__lint._cnt.cond,i.__lint._cnt.transfer]) tableList.push(['----------','-----','-----']) tableList.push(['Summary',condCnt,transferCnt]) console.log(table(tableList,{singleLine:true,columnDefault: {width:30}})) return inst input=(width=1)->packEl('port',Port.in(width)) output=(width=1)->packEl('port',Port.out(width)) bind= (name)-> Port.bind(name) channel= (path=null)-> Channel.create(path) instEnv= do -> inst=null return { register: (i)-> inst=i infer: ()-> inst.__assignWidth get: -> inst } cntCond=(num)-> if global.getInfo() instEnv.get().__lint._cnt.cond+=num cntExpr= -> if global.getInfo() instEnv.get().__lint._cnt.transfer+=1 getLint= (key)-> if instEnv.get().__lint[key]? return instEnv.get().__lint[key] else return null module.exports.hex = Vnumber.hex module.exports.dec = Vnumber.dec module.exports.oct = Vnumber.oct module.exports.bin = Vnumber.bin module.exports.Module = Module module.exports.Expr = Expr module.exports.toVerilog = toVerilog module.exports.input = input module.exports.output = output module.exports.bind = bind module.exports.channel = channel module.exports.infer = instEnv.infer module.exports.configBase =(cfg)-> config=Object.assign(config,cfg) module.exports.resetBase = -> moduleCache={} globalModuleCache={} moduleIndex=0
true
_ = require 'lodash' log = require 'fancy-log' colors = require 'colors' fs = require 'fs' Expr = require('chdl_expr') Reg = require('chdl_reg') Vec = require('chdl_vec') Wire = require('chdl_wire') Port = require('chdl_port') Channel = require('chdl_channel') Module = require('chdl_module') Vnumber = require('chdl_number') Verilog = require('verilog') {table} = require 'table' global = require('chdl_global') {stringifyTree} = require "stringify-tree" {getValue,packEl,simBuffer,printBuffer,dumpBuffer,toSignal,toFlatten,syncType} = require('chdl_utils') {cdcAnalysis,buildClkTree}= require 'chdl_cdc' moduleIndex=0 moduleCache={} globalModuleCache={} config={ #autoClock: false tree: false noAlwaysComb: false lint: false } arr=[ 'abcdefghijklmnopqrstuvwxyz'... 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'... ] dict=[arr...] obscure_map={} do => dict.sort(()=> return 0.5 - Math.random() ) for i,index in arr obscure_map[i]=dict[index] blur=(s)=> if global.getObfuscate() out=[] for i in [s...] if obscure_map[i]? out.push obscure_map[i] else out.push i return out.join('') else if global.getPrefix() prefix = global.getPrefix() return prefix+'__'+s else return s getCellList= (inst)-> p = Object.getPrototypeOf(inst) list=({name:k,inst:v} for k,v of p when typeof(v)=='object' and v instanceof Module) for i in inst.__cells list.push(i) unless _.find(list,(n)-> n.inst.__id==i.inst.__id) return _.sortBy(list,['name']) cell_build = (inst) => inst._elaboration() for i in getCellList(inst) i.inst._link(i.name) #log 'Link cell',i.name i.inst._setParentNode(inst) cell_build(i.inst) inst._postElaboration() get_module_build_name= (inst)-> baseName=inst.constructor.name suffix='' if getCellList(inst).length>0 or inst.__uniq moduleIndex+=1 suffix='__'+moduleIndex s='' return baseName+s+suffix lineComment=(lineno)-> " /* #{lineno} */ " sharpToDot = (s)-> s.replace(/#/g,'.') rhsExpand=(expandItem)-> if expandItem?.__type == 'expr' cntExpr() return { code: sharpToDot(expandItem.e.str)+expandItem.append w: expandItem.e.wstr driven: _.clone(expandItem.e.driven) } else if _.isArray(expandItem) str='' w='' driven=[] cntCond(expandItem.length) for item,index in expandItem anno= do-> if item.lineno>=0 "#{lineComment(item.lineno)}" else "" v= rhsExpand(item.value) if not v? log("Error:assign expr is undefined #{anno}".red) throw new Error("assign expr is undefined #{anno}") if index==0 str="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else if item.cond? str+="(#{item.cond.str}#{anno})?(#{v.code}):" dList=_.clone(item.cond.driven) driven.push(dList...) else str+="#{v.code}#{anno}" if index==0 w=v.w else w=w+'|'+v.w driven.push(_.clone(v.driven)...) return { code:str w: w driven: driven } checkAssignWidth=(lhs,rhsInfo,lineno)-> return if config.lint==false return if getLint('widthCheckLevel')==0 return if rhsInfo.w.match(/^"/) try rhsWidth=Number(Verilog.parser.parse(rhsInfo.w)) lhsWidth=lhs.getWidth() #console.log rhsInfo.code,rhsInfo.w,rhsWidth,lhs.getWidth() if getLint('widthCheckLevel')==1 if lhsWidth<rhsWidth log "Error: width overflow at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red else if getLint('widthCheckLevel')==2 if lhsWidth!=rhsWidth log "Error: width mismatch at line #{lineno} assign #{rhsWidth} to #{lhs.hier} #{lhs.getWidth()}".red catch e console.log 'Parse error:',lineno,lhs.hier,instEnv.get()._getModuleName() console.log e statementGen=(buffer,statement,cond_stack=[],sig_driven_list=[])-> stateType=statement[0] if stateType=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else if lhs.constructor?.name is 'VecMember' lhsName=lhs.refName() else throw new Error("Unknown lhs type") space=" ".repeat(cond_stack.length+1) conds= if cond_stack.length>0 then _.last(cond_stack) else [] if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null at #{lineno}".red) buffer.add space+"#{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) sig_driven_list.push({key:lhs.getElId(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:conds}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} code is null".red) buffer.add space+"#{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else if stateType=='end' buffer.add " end" else if stateType=='cond_end' space=" ".repeat(cond_stack.length) buffer.add space+"end" else if stateType=='verilog' buffer.add statement[1] else if stateType=='while' cond=statement[1] lineno=statement[2] if lineno? and lineno>=0 buffer.add " while(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add " while(#{toSignal cond.str}) begin" else if stateType=='if' cond=statement[1] cond_driven = [] if cond_stack.length>0 cond_driven.push(_.last(cond_stack)...) cond_driven.push(_.clone(cond.driven)) cond_stack.push(cond_driven) space=" ".repeat(cond_stack.length) lineno=statement[2] cntCond(1) if lineno? and lineno>=0 buffer.add space+"if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"if(#{toSignal cond.str}) begin" else if stateType=='elseif' cntCond(1) cond=statement[1] cond_driven = _.last(cond_stack) dList=_.last(cond_driven) dList.push(cond.driven...) space=" ".repeat(cond_stack.length) lineno=statement[2] if lineno? and lineno>=0 buffer.add space+"else if(#{toSignal cond.str}) begin #{lineComment(lineno)}" else buffer.add space+"else if(#{toSignal cond.str}) begin" else if stateType=='else' cntCond(1) lineno=statement[1] space=" ".repeat(cond_stack.length) if lineno? and lineno>=0 buffer.add space+"else begin #{lineComment(lineno)}" else buffer.add space+"else begin" else if stateType=='flow_delay' if _.isNumber(statement[2]) and statement[2]!=null buffer.add " ##{statement[2]}" else if stateType=='flow_posedge' buffer.add " @(posedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_negedge' buffer.add " @(negedge #{statement[2]});" if statement[3]? buffer.add " ##{statement[3]};" else if stateType=='flow_wait' buffer.add " wait(#{statement[2].e.str});" else if stateType=='flow_event' buffer.add " -> #{statement[2]};" else if stateType=='flow_trigger' buffer.add " @(#{statement[2]});" else if stateType=='flow_polling' item = statement[3] buffer.add " #{item.active} = 1;" buffer.add " while(#{item.active}) begin" buffer.add " @(posedge #{statement[2]});" buffer.add " if(#{item.expr.e.str}) begin" buffer.add " #{item.active} = 0;" buffer.add " end;" buffer.add " end;" else if stateType=='array_init' array_el=statement[1] file_type=statement[2][0] file_path=statement[2][1] oomr=statement[2][2] if oomr array_path=array_el.oomrName() else array_path=array_el.getName() if file_type=='hex' buffer.add " $readmemh(#{file_path},#{array_path});" else throw new Error("arrays init format #{file_type} undefined".red) else if stateType=='endif' cond_stack.pop() else throw new Error("can not find type #{stateType}") buildSim= (buildName,inst)=> #console.log(JSON.stringify(inst._dumpWire(),null,' ')) #console.log(JSON.stringify(inst._dumpPort(),null,' ')) #console.log(JSON.stringify(inst._dumpReg(),null,' ')) #console.log(JSON.stringify(inst._dumpVar(),null,' ')) #console.log(JSON.stringify(inst._dumpCell(),null,' ')) simBuffer.setName(buildName,inst) simBuffer.add 'const '+buildName+' = { }' simBuffer.add _.map(toFlatten(inst.__ports), (i)=> "_.set(#{buildName},'#{i[0]}',rxGen(#{i[1].getWidth()}))" ).join("\n") simBuffer.flush() ### simPackage={ name : buildName port : inst._dumpPort() reg : inst._dumpReg() wire : inst._dumpWire() var : inst._dumpVar() event : inst._dumpEvent() cell : inst._dumpCell() } ### code_gen= (inst,allInst,first=false)=> if first inst._setProperty({uniq_name:false}) buildName = inst._getBuildName() if first and (!inst._isCompany()) and global.getTopName()? buildName = global.getTopName() if inst.__uniq moduleIndex += 1 buildName = buildName+'__'+moduleIndex if first==false if not global.getUntouchModules().includes(inst.constructor.name) buildName=blur(buildName) inst._overrideModuleName(buildName) log ('Build cell '+inst._getPath()+' ( '+buildName+' )').green if moduleCache[buildName]? return else if inst._isBlackBox() log 'Warning:',inst._getPath(),'is blackbox' return else moduleCache[buildName]=true sig_driven_tree={inst:inst,list:[],children:[]} for i in getCellList(inst) inst_sig_driven=code_gen(i.inst,allInst) sig_driven_tree.children.push(inst_sig_driven) driven_list=sig_driven_tree.list if inst.dump? dumpBuffer.setName(buildName,null) dumpBuffer.add JSON.stringify(inst.dump(),null,2) dumpBuffer.flush() #fs.writeFileSync(buildName+'.dump.json',JSON.stringify(inst.dump(),null,2),'utf8') instEnv.register(inst) allInst.push(inst) if allInst? channelWireList=[] for [name,channel] in toFlatten(inst.__channels) code=channel.verilogDeclare() channelWireList.push(code) if code!='' for [name,item] in toFlatten(inst.__channels) if item.probeChannel==null if item.wireMap? _.set(inst,name,item.wireMap) else _.set(inst,name,item.portMap) inst.build() if global.getSim() log(("Build sim "+buildName).green) buildSim(buildName,inst) printBuffer.setName(buildName,inst) printBuffer.add '`ifndef UDLY' printBuffer.add '`define UDLY 1' printBuffer.add '`endif' if global.getIfdefProtect() printBuffer.add '`ifndef _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add '`define _CHDL_'+buildName.toUpperCase()+'_' printBuffer.add 'module '+buildName+'(' printBuffer.add _.map(toFlatten(inst.__ports), (i)=> " "+i[1].getName() ).join(",\n") printBuffer.add ');' printBuffer.blank('//parameter declare') for i in inst.__moduleParameter printBuffer.add i.verilogDeclare(false) printBuffer.blank('//port declare') _.map(toFlatten(inst.__ports), (i)=> printBuffer.add i[1].portDeclare()+";" ) printBuffer.blank('//channel declare') for i in channelWireList printBuffer.add(i) printBuffer.blank('//wire declare') for [name,wire] in toFlatten(inst.__wires) if wire.constructor.name=='Wire' printBuffer.add wire.verilogDeclare() for [name,wire] in toFlatten(inst.__local_wires) if wire.constructor.name=='Wire' and wire.local printBuffer.add wire.verilogDeclare() printBuffer.blank('//port wire declare') for [name,port] in toFlatten(inst.__ports) unless port.isReg printBuffer.add port.verilogDeclare() printBuffer.blank('//register declare') for [name,reg] in toFlatten(inst.__local_vecs) printBuffer.add reg.verilogDeclare() printBuffer.blank() printBuffer.blank('//register init and update') for [name,reg] in toFlatten(inst.__regs) when reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__regs) when not reg.isVirtual() printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() for [name,reg] in toFlatten(inst.__local_regs) if reg.local printBuffer.add reg.verilogDeclare() printBuffer.add reg.verilogUpdate() printBuffer.blank() printBuffer.blank('//assign logic') if inst.__wireAssignList.length>0 for statement in inst.__wireAssignList if statement[0]=='reg' name=statement[2] lineno=statement[3] if lineno? and lineno>=0 printBuffer.add "reg #{name}#{lineComment(lineno)};" else printBuffer.add "reg #{name};" else if statement[0]=='array_set' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays set to #{lhsName} condition is null".red) rhs=statement[2][1] rhsInfo=rhsExpand(rhs) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("arrays set to #{lhsName} value is null".red) clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{lhsName} <= #{rhsInfo.code};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='array_get' lhs=statement[1] lhsName=lhs.refName() cond=statement[2][0] condInfo=rhsExpand(cond) if _.isNil(condInfo) or _.isNil(condInfo.code) throw new Error("arrays get to #{lhsName} condition is null".red) target=statement[2][1] targetName=target.refName() clock=statement[2][2] printBuffer.add "always @(posedge #{clock}) begin"+"#{lineComment(lineno)}" printBuffer.add " if(#{condInfo.code}) begin" printBuffer.add " #{targetName} <= #{lhsName};" printBuffer.add " end" printBuffer.add "end" else if statement[0]=='assign' lhs=statement[1] rhs=statement[2] lineno=statement[3] lhsName='' checkPoint=false if lhs.constructor?.name is 'Reg' lhsName=lhs.getDwire().refName() checkPoint=true else if lhs.constructor?.name is 'Wire' lhsName=lhs.refName() if lhs.getSync()? checkPoint=true else if lhs.constructor?.name is 'Port' lhsName=lhs.refName() if lhs.getType()=='output' checkPoint=true if lhs.isReg lhsName=lhs.shadowReg.getDwire().refName() else throw new Error('Unknown lhs type') if lineno? and lineno>=0 rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.PI:KEY:<KEY>END_PIElPI:KEY:<KEY>END_PI(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.PI:KEY:<KEY>END_PIElPI:KEY:<KEY>END_PI(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null at #{lineno}".red) printBuffer.add "assign #{toSignal lhsName}#{lineComment(lineno)}= #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) else rhsInfo=rhsExpand(rhs) if inst.__isCombModule driven_list.push({key:lhs.PI:KEY:<KEY>END_PI(),checkPoint:false,inst:lhs,driven:rhsInfo.driven,conds:[]}) else driven_list.push({key:lhs.PI:KEY:<KEY>END_PI(),checkPoint:checkPoint,inst:lhs,driven:rhsInfo.driven,conds:[]}) if _.isNil(rhsInfo) or _.isNil(rhsInfo.code) throw new Error("assign to #{lhsName} is null".red) printBuffer.add "assign #{toSignal lhsName} = #{rhsInfo.code};" checkAssignWidth(lhs,rhsInfo,lineno) printBuffer.blank('//event declare') unless _.isEmpty(inst.__trigMap) for name in Object.keys(inst.__trigMap) printBuffer.add "event #{name};" printBuffer.blank('//initial statement') if inst.__initialList.length>0 for seqList in inst.__initialList when seqList.length>0 printBuffer.add "initial begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//forever statement') if inst.__foreverList.length>0 for seqList in inst.__foreverList when seqList.length>0 printBuffer.add "always begin" for seq in seqList initSegmentList = seq cond_stack=[] for statement in initSegmentList statementGen(printBuffer,statement,cond_stack) printBuffer.add "end" printBuffer.blank() printBuffer.blank('//register update logic') if inst.__alwaysList.length>0 for [assignList,lineno] in inst.__alwaysList when assignList? and assignList.length>0 if lineno? and lineno>=0 if config.noAlwaysComb printBuffer.add 'always @* begin'+"#{lineComment(lineno)}" else printBuffer.add 'always_comb begin'+"#{lineComment(lineno)}" else if config.noAlwaysComb printBuffer.add 'always @* begin' else printBuffer.add 'always_comb begin' updateEls=[] for statement in assignList stateType=statement[0] if stateType=='assign' updateEls.push statement[1] for i in _.uniqBy(updateEls,(n)=>n.hier) if i.constructor?.name is 'Reg' printBuffer.add " #{global.getPrefix()}_"+i.getName()+'='+getValue(i.getPending())+';' else if (i.constructor?.name is 'Wire') or (i.constructor?.name is 'Port') printBuffer.add ' '+i.getName()+'='+getValue(i.getPending())+';' if assignList cond_stack=[] for statement in assignList statementGen(printBuffer,statement,cond_stack,driven_list) printBuffer.add 'end' printBuffer.blank() printBuffer.blank('//cell instance') for i in getCellList(inst) paramDeclare=getVerilogParameter(i.inst) printBuffer.add i.inst._getModuleName()+paramDeclare+blur(i.name)+'(' if (not i.inst.__isCombModule) if i.inst.__defaultClock clockPort=i.inst.__ports[i.inst.__defaultClock] if (!clockPort.isBinded()) clockPort.setBindSignal(inst.__defaultClock) if i.inst.__defaultReset resetPort=i.inst.__ports[i.inst.__defaultReset] if (!resetPort.isBinded()) resetPort.setBindSignal(inst.__defaultReset) [pinConn,pinAssigns]=i.inst._pinConnect(inst) printBuffer.add pinConn.join(",\n") printBuffer.add ');' printBuffer.blank() if pinAssigns.length>0 pinAssignList=[] for pinAssign in pinAssigns hit= _.find(inst.__pinAssign,{to:pinAssign.to}) if hit? pinAssignList.push({ from: pinAssign.from to: hit.from }) else pinAssignList.push(pinAssign) _.map(pinAssignList,(n)-> printBuffer.add "assign #{n.to} = #{n.from};" ) printBuffer.blank() if !inst.__isCombModule defaultClk = _.get(inst.__ports,inst._clock()) defaultRst = _.get(inst.__ports,inst._reset()) for {pin,port} in i.inst.__pinPortPair when port.getType()=='input' item = _.find(driven_list,{key:pin.PI:KEY:<KEY>END_PI()}) if not item? if port.isClock printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultClock};" driven_list.push({key:pin.PI:KEY:<KEY>END_PI(),checkPoint:false,inst:pin,driven:[defaultClk.getId()],conds:[]}) if port.isReset printBuffer.add "assign #{toSignal(pin.getName())} = #{inst.__defaultReset};" driven_list.push({key:pin.PI:KEY:<KEY>END_PI(),checkPoint:false,inst:pin,driven:[defaultRst.getId()],conds:[]}) printBuffer.blank() printBuffer.blank('//Verilog Segment') for plainLines in inst.__verilogSegments lines=plainLines.split(/\n/) for line in lines printBuffer.add line printBuffer.blank() printBuffer.add 'endmodule' if global.getIfdefProtect() printBuffer.add '`endif' printBuffer.blank() printBuffer.flush() return sig_driven_tree getVerilogParameter=(inst)-> if inst.__instParameter==null return ' ' else list=[] for i in inst.__instParameter list.push(".#{i.key}(#{i.value})") return " #(\n "+list.join(",\n ")+"\n) " module.exports.buildCompanyModule=(companyModule,params...)-> inst=new companyModule(params...) inst._setCompany() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] module.exports.buildGlobalModule=(globalModule,params...)-> inst=new globalModule(params...) inst._setGlobal() name=inst._getModuleName() ? inst.constructor.name if not globalModuleCache[name]? globalModuleCache[name]=inst toVerilog(inst) return globalModuleCache[name] toVerilog=(inst)-> cell_build(inst) instList=[] inst_sig_driven=code_gen(inst,instList,true) if global.isCdcCheck() clkGroup=buildClkTree(inst_sig_driven) cdcResult=cdcAnalysis(inst_sig_driven,clkGroup) reportFile=global.getCdcReportFile() if reportFile? outFile=global.getOutDir()+'/'+reportFile fs.writeFileSync(outFile,JSON.stringify(cdcResult,null,' '),'utf8') if config.tree console.log(stringifyTree({name:inst._getModuleName(),inst:inst}, ((t) -> t.name+' ('+t.inst._getModuleName()+')'), ((t) -> getCellList(t.inst)))) if global.getInfo() list= [['register name','width']] list.push(['-------------','-----']) dffBitSum=0 for [name,reg] in toFlatten(inst.__regs) list.push([toSignal(name),reg.getWidth()]) dffBitSum+=reg.getWidth() for [name,reg] in toFlatten(inst.__local_regs) list.push([reg.refName(),reg.getWidth()]) dffBitSum+=reg.getWidth() if list.length>2 list.push(['-------------','-----']) list.push(['TotalBits',dffBitSum]) console.log(table(list,{singleLine:true,columnDefault: {width:30}})) if global.getInfo() condCnt=0 transferCnt=0 tableList=[] tableList.push(['Module','Condition','Transfer']) for i in instList condCnt+=i.__lint._cnt.cond transferCnt+=i.__lint._cnt.transfer tableList.push([i._getModuleName(),i.__lint._cnt.cond,i.__lint._cnt.transfer]) tableList.push(['----------','-----','-----']) tableList.push(['Summary',condCnt,transferCnt]) console.log(table(tableList,{singleLine:true,columnDefault: {width:30}})) return inst input=(width=1)->packEl('port',Port.in(width)) output=(width=1)->packEl('port',Port.out(width)) bind= (name)-> Port.bind(name) channel= (path=null)-> Channel.create(path) instEnv= do -> inst=null return { register: (i)-> inst=i infer: ()-> inst.__assignWidth get: -> inst } cntCond=(num)-> if global.getInfo() instEnv.get().__lint._cnt.cond+=num cntExpr= -> if global.getInfo() instEnv.get().__lint._cnt.transfer+=1 getLint= (key)-> if instEnv.get().__lint[key]? return instEnv.get().__lint[key] else return null module.exports.hex = Vnumber.hex module.exports.dec = Vnumber.dec module.exports.oct = Vnumber.oct module.exports.bin = Vnumber.bin module.exports.Module = Module module.exports.Expr = Expr module.exports.toVerilog = toVerilog module.exports.input = input module.exports.output = output module.exports.bind = bind module.exports.channel = channel module.exports.infer = instEnv.infer module.exports.configBase =(cfg)-> config=Object.assign(config,cfg) module.exports.resetBase = -> moduleCache={} globalModuleCache={} moduleIndex=0
[ { "context": "e folder of the document\n// Copyright (c) 2013\n// Fabian \"fabiantheblind\" Morón Zirfas\n// Permission is he", "end": 71, "score": 0.999826192855835, "start": 65, "tag": "NAME", "value": "Fabian" }, { "context": "of the document\n// Copyright (c) 2013\n// Fabian \"fabiantheblind\" Morón Zirfas\n// Permission is hereby granted, fr", "end": 87, "score": 0.9993168115615845, "start": 73, "tag": "USERNAME", "value": "fabiantheblind" }, { "context": "\n// Copyright (c) 2013\n// Fabian \"fabiantheblind\" Morón Zirfas\n// Permission is hereby granted, free of charge, ", "end": 101, "score": 0.9998207092285156, "start": 89, "tag": "NAME", "value": "Morón Zirfas" } ]
_dev/coffee/Open-Active-Document-Folder.coffee
fabianmoronzirfas/mpo-id-tools
2
### //opens the folder of the document // Copyright (c) 2013 // Fabian "fabiantheblind" Morón Zirfas // 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 CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### doc = null # this will be the document try doc = app.activeDocument #get the acitve document catch e # oh oh no active doc alert "You have no document open!\n" +e; return try folder = Folder(doc.filePath) # // get the folder folder.execute() # //open it catch e alert "This doc was never saved!" #never been saved
192509
### //opens the folder of the document // Copyright (c) 2013 // <NAME> "fabiantheblind" <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 CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### doc = null # this will be the document try doc = app.activeDocument #get the acitve document catch e # oh oh no active doc alert "You have no document open!\n" +e; return try folder = Folder(doc.filePath) # // get the folder folder.execute() # //open it catch e alert "This doc was never saved!" #never been saved
true
### //opens the folder of the document // Copyright (c) 2013 // PI:NAME:<NAME>END_PI "fabiantheblind" 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 CONNECTIO // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // see also http://www.opensource.org/licenses/mit-license.php ### doc = null # this will be the document try doc = app.activeDocument #get the acitve document catch e # oh oh no active doc alert "You have no document open!\n" +e; return try folder = Folder(doc.filePath) # // get the folder folder.execute() # //open it catch e alert "This doc was never saved!" #never been saved
[ { "context": "= password.agent(pwa.cache)\n\n pwa.setPassword('hello')\n assert.equal pwa.cache.get(), 'hello'\n a", "end": 195, "score": 0.9960940480232239, "start": 190, "tag": "PASSWORD", "value": "hello" }, { "context": "ert.equal err, null\n assert.equal(password, 'hello')\n pwa.reset() unless err\n assert.equal", "end": 387, "score": 0.9978846907615662, "start": 382, "tag": "PASSWORD", "value": "hello" }, { "context": "err, password) ->\n assert.equal(password, 'hello') \n}\n", "end": 589, "score": 0.9977114200592041, "start": 584, "tag": "PASSWORD", "value": "hello" } ]
test/password.coffee
dvidelabs/poly.shell
1
assert = require('assert') password = require('..').password module.exports = { 'password agent': -> pwa = password.agent() pwa2 = password.agent(pwa.cache) pwa.setPassword('hello') assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa.getPassword (err, password) -> assert.equal err, null assert.equal(password, 'hello') pwa.reset() unless err assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa2.getPassword (err, password) -> assert.equal(password, 'hello') }
56196
assert = require('assert') password = require('..').password module.exports = { 'password agent': -> pwa = password.agent() pwa2 = password.agent(pwa.cache) pwa.setPassword('<PASSWORD>') assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa.getPassword (err, password) -> assert.equal err, null assert.equal(password, '<PASSWORD>') pwa.reset() unless err assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa2.getPassword (err, password) -> assert.equal(password, '<PASSWORD>') }
true
assert = require('assert') password = require('..').password module.exports = { 'password agent': -> pwa = password.agent() pwa2 = password.agent(pwa.cache) pwa.setPassword('PI:PASSWORD:<PASSWORD>END_PI') assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa.getPassword (err, password) -> assert.equal err, null assert.equal(password, 'PI:PASSWORD:<PASSWORD>END_PI') pwa.reset() unless err assert.equal pwa.cache.get(), 'hello' assert.equal pwa2.cache.get(), 'hello' pwa2.getPassword (err, password) -> assert.equal(password, 'PI:PASSWORD:<PASSWORD>END_PI') }
[ { "context": "cle}\n \\\\\\\\title{${1:title}}\n \\\\\\\\author{Yudai NAKATA}\n \\\\\\\\date{\\\\\\\\today}\n %\n \\\\\\\\begi", "end": 461, "score": 0.9927010536193848, "start": 449, "tag": "NAME", "value": "Yudai NAKATA" } ]
.atom/snippets.cson
yudai-nkt/dotfiles
0
# LaTeX ".text.tex.latex": "jpn doc w/ uplatex": "prefix": "jsarticle" "body": """ \\\\documentclass[dvipdfmx,uplatex]{jsarticle} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "eng doc w/ pdflatex": "prefix": "article" "body": """ \\\\documentclass[a4paper]{article} \\\\title{${1:title}} \\\\author{Yudai NAKATA} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "jpn doc w/ lualatex": "prefix": "ltjsarticle" "body": """ \\\\documentclass{ltjsarticle} \\\\usepackage{luatexja} \\\\usepackage[pass={no-math}]{luatexja-fontspec} \\\\setmainfont{Times} \\\\setsansfont{Helvetica Neue} \\\\setmainjfont{Hiragino Mincho ProN} \\\\setsansjfont{Hiragino Kaku Gothic ProN} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ # # LaTeX Beamer ".text.tex.latex.beamer": "frame": "prefix": "frame" "body": """ \\\\begin{frame}{${1:frame title}} $2 \\\\end{frame} """ "multi-columns": "prefix": "columns" "body": """ \\\\begin{columns}[t,onlytextwidth] \\\\begin{column}{${1:column width}\\\\textwidth} $2 \\\\end{column} \\\\begin{column}{${3:column width}\\\\textwidth} $4 \\\\end{column} \\\\end{columns} """ # BibTeX ".text.bibtex": "article": "prefix": "article" "body": """ @article{ ${1:citation label}, author = "$2", title = "$3", journal = "$4", year = $5 } """ "book": "prefix": "book" "body": """ @book{ ${1:citation label}, author = "$2", title = "$3", publisher = "$4", year = $5 } """ # GitHub Markdown ".source.gfm": "centering": "prefix": "center" "body": "<p class=\"center\">\n $1\n</p>" "flush right": "prefix": "right" "body": "<p class=\"right\">\n $1\n</p>" "display code": "prefix": "code" "body": "```$2\n$1\n```"
76277
# LaTeX ".text.tex.latex": "jpn doc w/ uplatex": "prefix": "jsarticle" "body": """ \\\\documentclass[dvipdfmx,uplatex]{jsarticle} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "eng doc w/ pdflatex": "prefix": "article" "body": """ \\\\documentclass[a4paper]{article} \\\\title{${1:title}} \\\\author{<NAME>} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "jpn doc w/ lualatex": "prefix": "ltjsarticle" "body": """ \\\\documentclass{ltjsarticle} \\\\usepackage{luatexja} \\\\usepackage[pass={no-math}]{luatexja-fontspec} \\\\setmainfont{Times} \\\\setsansfont{Helvetica Neue} \\\\setmainjfont{Hiragino Mincho ProN} \\\\setsansjfont{Hiragino Kaku Gothic ProN} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ # # LaTeX Beamer ".text.tex.latex.beamer": "frame": "prefix": "frame" "body": """ \\\\begin{frame}{${1:frame title}} $2 \\\\end{frame} """ "multi-columns": "prefix": "columns" "body": """ \\\\begin{columns}[t,onlytextwidth] \\\\begin{column}{${1:column width}\\\\textwidth} $2 \\\\end{column} \\\\begin{column}{${3:column width}\\\\textwidth} $4 \\\\end{column} \\\\end{columns} """ # BibTeX ".text.bibtex": "article": "prefix": "article" "body": """ @article{ ${1:citation label}, author = "$2", title = "$3", journal = "$4", year = $5 } """ "book": "prefix": "book" "body": """ @book{ ${1:citation label}, author = "$2", title = "$3", publisher = "$4", year = $5 } """ # GitHub Markdown ".source.gfm": "centering": "prefix": "center" "body": "<p class=\"center\">\n $1\n</p>" "flush right": "prefix": "right" "body": "<p class=\"right\">\n $1\n</p>" "display code": "prefix": "code" "body": "```$2\n$1\n```"
true
# LaTeX ".text.tex.latex": "jpn doc w/ uplatex": "prefix": "jsarticle" "body": """ \\\\documentclass[dvipdfmx,uplatex]{jsarticle} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "eng doc w/ pdflatex": "prefix": "article" "body": """ \\\\documentclass[a4paper]{article} \\\\title{${1:title}} \\\\author{PI:NAME:<NAME>END_PI} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ "jpn doc w/ lualatex": "prefix": "ltjsarticle" "body": """ \\\\documentclass{ltjsarticle} \\\\usepackage{luatexja} \\\\usepackage[pass={no-math}]{luatexja-fontspec} \\\\setmainfont{Times} \\\\setsansfont{Helvetica Neue} \\\\setmainjfont{Hiragino Mincho ProN} \\\\setsansjfont{Hiragino Kaku Gothic ProN} \\\\title{${1:タイトル}} \\\\author{中田雄大} \\\\date{\\\\today} % \\\\begin{document} $2 \\\\end{document} """ # # LaTeX Beamer ".text.tex.latex.beamer": "frame": "prefix": "frame" "body": """ \\\\begin{frame}{${1:frame title}} $2 \\\\end{frame} """ "multi-columns": "prefix": "columns" "body": """ \\\\begin{columns}[t,onlytextwidth] \\\\begin{column}{${1:column width}\\\\textwidth} $2 \\\\end{column} \\\\begin{column}{${3:column width}\\\\textwidth} $4 \\\\end{column} \\\\end{columns} """ # BibTeX ".text.bibtex": "article": "prefix": "article" "body": """ @article{ ${1:citation label}, author = "$2", title = "$3", journal = "$4", year = $5 } """ "book": "prefix": "book" "body": """ @book{ ${1:citation label}, author = "$2", title = "$3", publisher = "$4", year = $5 } """ # GitHub Markdown ".source.gfm": "centering": "prefix": "center" "body": "<p class=\"center\">\n $1\n</p>" "flush right": "prefix": "right" "body": "<p class=\"right\">\n $1\n</p>" "display code": "prefix": "code" "body": "```$2\n$1\n```"
[ { "context": "# Copyright (c) 2014 Anthony Bau (dab1998@gmail.com)\n# MIT License\n#\n# Minimalisti", "end": 32, "score": 0.9998823404312134, "start": 21, "tag": "NAME", "value": "Anthony Bau" }, { "context": "# Copyright (c) 2014 Anthony Bau (dab1998@gmail.com)\n# MIT License\n#\n# Minimalistic HTML5 canvas wrap", "end": 51, "score": 0.9999208450317383, "start": 34, "tag": "EMAIL", "value": "dab1998@gmail.com" } ]
src/draw.coffee
sanyaade-teachings/spresensedroplet
3
# Copyright (c) 2014 Anthony Bau (dab1998@gmail.com) # MIT License # # Minimalistic HTML5 canvas wrapper. Mainly used as conveneince tools in Droplet. ## Private (convenience) functions BEVEL_SIZE = 1.5 EPSILON = 0.00001 helper = require './helper.coffee' SVG_STANDARD = helper.SVG_STANDARD # ## _area ## # Signed area of the triangle formed by vectors [ab] and [ac] _area = (a, b, c) -> (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y) # ## _intersects ## # Test the intersection of two line segments _intersects = (a, b, c, d) -> ((_area(a, b, c) > 0) != (_area(a, b, d) > 0)) and ((_area(c, d, a) > 0) != (_area(c, d, b) > 0)) _bisector = (a, b, c, magnitude = 1) -> if a.equals(b) or b.equals(c) return null sample = a.from(b).normalize() diagonal = sample.plus( sampleB = c.from(b).normalize() ) if diagonal.almostEquals ZERO return null else if sample.almostEquals sampleB return null diagonal = diagonal.normalize() scalar = magnitude / Math.sqrt((1 - diagonal.dot(sample) ** 2)) diagonal.x *= scalar diagonal.y *= scalar if _area(a, b, c) < 0 diagonal.x *= -1 diagonal.y *= -1 return diagonal max = (a, b) -> `(a > b ? a : b)` min = (a, b) -> `(b > a ? a : b)` toRGB = (hex) -> # Convert to 6-char hex if not already there if hex.length is 4 hex = (c + c for c in hex).join('')[1..] # Extract integers from hex r = parseInt hex[1..2], 16 g = parseInt hex[3..4], 16 b = parseInt hex[5..6], 16 return [r, g, b] zeroPad = (str, len) -> if str.length < len ('0' for [str.length...len]).join('') + str else str twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2 toHex = (rgb) -> return '#' + (twoDigitHex(k) for k in rgb).join '' memoizedAvgColor = {} avgColor = (a, factor, b) -> c = (a + ',' + factor + ',' + b) if c of memoizedAvgColor return memoizedAvgColor[c] a = toRGB a b = toRGB b newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a) return memoizedAvgColor[c] = toHex newRGB exports.Draw = class Draw ## Public functions constructor: (@ctx) -> canvas = document.createElement('canvas') @measureCtx = canvas.getContext '2d' @fontSize = 15 @fontFamily = 'Courier New, monospace' @fontAscent = -2 @fontBaseline = 10 @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @ctx.style.fontFamily = @fontFamily @ctx.style.fontSize = @fontSize self = this # ## Point ## # A point knows its x and y coordinate, and can do some vector operations. @Point = Point # ## Size ## # A Size knows its width and height. @Size = Size # ## Rectangle ## # A Rectangle knows its upper-left corner, width, and height, # and can do rectangular overlap, polygonal intersection, # and rectangle or point union (point union is called "swallow"). @Rectangle = Rectangle @NoRectangle = NoRectangle @ElementWrapper = ElementWrapper @Group = Group @Path = Path @Text = Text elementWrapper: (element) -> new ElementWrapper @, element group: (style) -> new Group @, style path: (points, bevel, style) -> new Path @, points, bevel, style text: (point, value, color) -> new Text @, point, value, color refreshFontCapital: -> metrics = helper.fontMetrics(@fontFamily, @fontSize) @fontAscent = metrics.prettytop @fontBaseline = metrics.baseline setGlobalFontSize: (size) -> @fontSize = size @ctx.style.fontSize = size @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() setGlobalFontFamily: (family) -> @fontFamily = family @ctx.style.fontFamily = family @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() getGlobalFontSize: -> @fontSize exports.Point = class Point constructor: (@x, @y) -> clone: -> new Point @x, @y magnitude: -> Math.sqrt @x * @x + @y * @y times: (scalar) -> new Point @x * scalar, @y * scalar normalize: -> @times 1 / @magnitude() translate: (vector) -> @x += vector.x; @y += vector.y add: (x, y) -> @x += x; @y += y dot: (other) -> @x * other.x + @y * other.y plus: ({x, y}) -> new Point @x + x, @y + y toMagnitude: (mag) -> r = mag / @magnitude() return new Point @x * r, @y * r copy: (point) -> @x = point.x; @y = point.y return @ from: (point) -> new Point @x - point.x, @y - point.y clear: -> @x = @y = 0 equals: (point) -> point.x is @x and point.y is @y almostEquals: (point) -> Math.abs(point.x - @x) < EPSILON and Math.abs(point.y - @y) < EPSILON ZERO = new Point 0, 0 exports.Size = class Size constructor: (@width, @height) -> equals: (size) -> @width is size.width and @height is size.height @copy: (size) -> new Size(size.width, size.height) exports.Rectangle = class Rectangle constructor: (@x, @y, @width, @height) -> contains: (point) -> @x? and @y? and not ((point.x < @x) or (point.x > @x + @width) or (point.y < @y) or (point.y > @y + @height)) equals: (other) -> unless other instanceof Rectangle return false return @x is other.x and @y is other.y and @width is other.width and @height is other.height copy: (rect) -> @x = rect.x; @y = rect.y @width = rect.width; @height = rect.height return @ clone: -> rect = new Rectangle(0, 0, 0, 0) rect.copy this return rect clear: -> @width = @height = 0; @x = @y = null bottom: -> @y + @height right: -> @x + @width unite: (rectangle) -> unless @x? and @y? then @copy rectangle else unless rectangle.x? and rectangle.y? then return else @width = max(@right(), rectangle.right()) - (@x = min @x, rectangle.x) @height = max(@bottom(), rectangle.bottom()) - (@y = min @y, rectangle.y) swallow: (point) -> unless @x? and @y? then @copy new Rectangle point.x, point.y, 0, 0 else @width = max(@right(), point.x) - (@x = min @x, point.x) @height = max(@bottom(), point.y) - (@y = min @y, point.y) overlap: (rectangle) -> @x? and @y? and not ((rectangle.right()) < @x or (rectangle.bottom() < @y) or (rectangle.x > @right()) or (rectangle.y > @bottom())) translate: (vector) -> @x += vector.x; @y += vector.y upperLeftCorner: -> new Point @x, @y toPath: -> path = new Path() path.push new Point(point[0], point[1]) for point in [ [@x, @y] [@x, @bottom()] [@right(), @bottom()] [@right(), @y] ] return path # ## NoRectangle ## # NoRectangle is an alternate constructor for Rectangle which starts # the rectangle as nothing (without even a location). It can gain location and size # via unite() and swallow(). exports.NoRectangle = class NoRectangle extends Rectangle constructor: -> super(null, null, 0, 0) # ## ElementWrapper ### exports.ElementWrapper = class ElementWrapper constructor: (@draw, @element) -> if @element? @element.style.display = 'none' @active = false @parent = @element?.parentElement ? @draw.ctx manifest: -> unless @element? @element = @makeElement() @getParentElement().appendChild @element unless @active @element.style.display = 'none' else unless @element.parentElement? @getParentElement().appendChild @element deactivate: -> if @active @active = false @element?.style?.display = 'none' activate: -> @manifest() unless @active @active = true @element?.style?.display = '' focus: -> @activate() @getParentElement().appendChild @element getParentElement: -> if @parent instanceof ElementWrapper @parent.manifest() return @parent.element else return @parent setParent: (parent) -> @parent = parent if @element? parent = @getParentElement() unless parent is @element.parentElement parent.appendChild @element destroy: -> if @element? if @element.parentElement? @element.parentElement.removeChild @element exports.Group = class Group extends ElementWrapper constructor: (@draw, @style) -> super(@draw) if @style? @_lastTransform = @style.transform makeElement: -> return document.createElementNS SVG_STANDARD, 'g' activate: -> super() if @style? and @style.transform? @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform update: -> return unless @element? if @style? and @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform # ## Path ## # This is called Path, but is forced to be closed so is actually a polygon. # It can do fast translation and rectangular intersection. exports.Path = class Path extends ElementWrapper constructor: (@draw, @_points = [], @bevel = false, @style) -> @_cachedTranslation = new Point 0, 0 @_cacheFlag = true @_bounds = new NoRectangle() @_clearCache() @style = helper.extend { 'strokeColor': 'none' 'lineWidth': 1 'fillColor': 'none' 'dotted': '' }, @style super(@draw) _clearCache: -> if @_cacheFlag # If we have no points, return the empty rectangle # as our bounding box if @_points.length is 0 @_bounds = new NoRectangle() @_lightBevelPath = @_darkBevelPath = '' # Otherwise, find our bounding box based # on our points. else # Bounds minX = minY = Infinity maxX = maxY = 0 for point in @_points minX = min minX, point.x maxX = max maxX, point.x minY = min minY, point.y maxY = max maxY, point.y @_bounds.x = minX; @_bounds.y = minY @_bounds.width = maxX - minX; @_bounds.height = maxY - minY # Light bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x > @_points[i].x and point.y <= @_points[i].y) or (point.y < @_points[i].y and point.x >= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x > @_points[@_points.length - 1].x or @_points[0].y < @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_lightBevelPath = subpaths.join(' ') # Dark bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x < @_points[i].x and point.y >= @_points[i].y) or (point.y > @_points[i].y and point.x <= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x < @_points[@_points.length - 1].x or @_points[0].y > @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_darkBevelPath = subpaths.join(' ') @_cacheFlag = false _setPoints_raw: (points) -> @_points = points @_cacheFlag = true @_updateFlag = true setMarkStyle: (style) -> if style? and style.color isnt @markColor? @markColor = style.color @_markFlag = true else if @markColor? @markColor = null @_markFlag = true setPoints: (points) -> if points.length isnt @_points.length @_setPoints_raw points return for el, i in points unless @_points[i].equals(el) @_setPoints_raw points return return push: (point) -> @_points.push point @_cacheFlag = true @_updateFlag = true unshift: (point) -> @_points.unshift point @_cacheFlag = true @_updateFlag = true reverse: -> @_points.reverse() return this # ### Point containment ### # Accomplished with ray-casting contains: (point) -> @_clearCache() if @_points.length is 0 then return false unless @_bounds.contains point then return false # "Ray" to the left dest = new Point @_bounds.x - 10, point.y # Count intersections count = 0 last = @_points[@_points.length - 1] for end in @_points if _intersects(last, end, point, dest) then count += 1 last = end return count % 2 is 1 equals: (other) -> unless other instanceof Path return false if other._points.length isnt @_points.length return false for el, i in other._points unless @_points[i].equals(el) return false return true # ### Rectangular intersection ### # Succeeds if any edges intersect or either shape is # entirely within the other. intersects: (rectangle) -> @_clearCache() if @_points.length is 0 then return false if not rectangle.overlap @_bounds then return false else # Try each pair of edges for intersections last = @_points[@_points.length - 1] rectSides = [ new Point rectangle.x, rectangle.y new Point rectangle.right(), rectangle.y new Point rectangle.right(), rectangle.bottom() new Point rectangle.x, rectangle.bottom() ] for end in @_points lastSide = rectSides[rectSides.length - 1] for side in rectSides if _intersects(last, end, lastSide, side) then return true lastSide = side last = end # Intersections failed; see if we contain the rectangle. # Note that if we contain the rectangle we must contain all of its vertices, # so it suffices to test one vertex. if @contains rectSides[0] then return true # We don't contain the rectangle; see if it contains us. if rectangle.contains @_points[0] then return true # No luck return false bounds: -> @_clearCache(); @_bounds translate: (vector) -> @_cachedTranslation.translate vector @_cacheFlag = true getCommandString: -> if @_points.length is 0 return '' pathCommands = [] pathCommands.push "M#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" for point in @_points pathCommands.push "L#{Math.round(point.x)} #{Math.round(point.y)}" pathCommands.push "L#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" pathCommands.push "Z" return pathCommands.join ' ' getInsetCoordinate: (i, length) -> j = i; prev = @_points[i] while prev.equals(@_points[i]) and j > i - @_points.length j-- prev = @_points[j %% @_points.length] k = i; next = @_points[i] while next.equals(@_points[i]) and k < i + @_points.length k++ next = @_points[k %% @_points.length] vector = _bisector prev, @_points[i], next, length return null unless vector? point = @_points[i].plus vector return point getLightBevelPath: -> @_clearCache(); @_lightBevelPath getDarkBevelPath: -> @_clearCache() return @_darkBevelPath # TODO unhackify makeElement: -> @_clearCache() pathElement = document.createElementNS SVG_STANDARD, 'path' if @style.fillColor? pathElement.setAttribute 'fill', @style.fillColor @__lastFillColor = @style.fillColor @__lastStrokeColor = @style.strokeColor @__lastLineWidth = @style.lineWidth @__lastDotted = @style.dotted @__lastCssClass = @style.cssClass @__lastTransform = @style.transform pathString = @getCommandString() if pathString.length > 0 pathElement.setAttribute 'd', pathString if @bevel @backgroundPathElement = pathElement @backgroundPathElement.setAttribute 'class', 'droplet-background-path' pathElement = document.createElementNS SVG_STANDARD, 'g' @lightPathElement = document.createElementNS SVG_STANDARD, 'path' @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' if pathString.length > 0 @lightPathElement.setAttribute 'd', @getLightBevelPath() @lightPathElement.setAttribute 'class', 'droplet-light-bevel-path' @darkPathElement = document.createElementNS SVG_STANDARD, 'path' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' if pathString.length > 0 @darkPathElement.setAttribute 'd', @getDarkBevelPath() @darkPathElement.setAttribute 'class', 'droplet-dark-bevel-path' pathElement.appendChild @backgroundPathElement pathElement.appendChild @lightPathElement pathElement.appendChild @darkPathElement else pathElement.setAttribute 'stroke', @style.strokeColor pathElement.setAttribute 'stroke-width', @style.lineWidth if (@style.dotted?.length ? 0) > 0 pathElement.setAttribute 'stroke-dasharray', @style.dotted if @style.cssClass? pathElement.setAttribute 'class', @style.cssClass if @style.transform? pathElement.setAttribute 'transform', @style.transform return pathElement update: -> return unless @element? if @style.fillColor isnt @__lastFillColor @__lastFillColor = @style.fillColor if @bevel @backgroundPathElement.setAttribute 'fill', @style.fillColor @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' else @element.setAttribute 'fill', @style.fillColor if not @bevel and @style.strokeColor isnt @__lastStrokeColor @__lastStrokeColor = @style.strokeColor @element.setAttribute 'stroke', @style.strokeColor if not @bevel and @style.dotted isnt @__lastDotted @__lastDotted = @style.dotted @element.setAttribute 'stroke-dasharray', @style.dotted if not @bevel and @style.lineWidth isnt @__lastLineWidth @__lastLineWidth = @style.lineWidth @element.setAttribute 'stroke-width', @style.lineWidth if @style.cssClass? and @style.cssClass isnt @_lastCssClass @_lastCssClass = @style.cssClass @element.setAttribute 'class', @style.cssClass if @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform if @_markFlag if @markColor? if @bevel @backgroundPathElement.setAttribute 'stroke', @markColor @backgroundPathElement.setAttribute 'stroke-width', '2' @lightPathElement.setAttribute 'visibility', 'hidden' @darkPathElement.setAttribute 'visibility', 'hidden' else @element.setAttribute 'stroke', @markColor @element.setAttribute 'stroke-width', '2' else if @bevel @backgroundPathElement.setAttribute 'stroke', 'none' @lightPathElement.setAttribute 'visibility', 'visible' @darkPathElement.setAttribute 'visibility', 'visible' else @element.setAttribute 'stroke', @style.strokeColor @element.setAttribute 'line-width', @style.lineWidth if @_updateFlag @_updateFlag = false pathString = @getCommandString() if pathString.length > 0 if @bevel @backgroundPathElement.setAttribute 'd', pathString @lightPathElement.setAttribute 'd', @getLightBevelPath() @darkPathElement.setAttribute 'd', @getDarkBevelPath() else @element.setAttribute 'd', pathString clone: -> clone = new Path(@_points.slice(0), @bevel, { lineWidth: @style.lineWidth fillColor: @style.fillColor strokeColor: @style.strokeColor dotted: @style.dotted cssClass: @style.cssClass }) clone._clearCache() clone.update() return clone # ## Text ## # A Text element. Mainly this exists for computing bounding boxes, which is # accomplished via ctx.measureText(). exports.Text = class Text extends ElementWrapper constructor: (@draw, @point, @value, @fill = '#000') -> @__lastValue = @__boundsValue = @value @__lastPoint = @point.clone() @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize super(@draw) clone: -> new Text @point, @value equals: (other) -> other? and @point.equals(other.point) and @value is other.value _clearCache: -> if @value is @__boundsValue return else @__boundsValue = @value @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize bounds: -> @_clearCache(); @_bounds contains: (point) -> @_bounds.contains point setPosition: (point) -> @translate point.from @point makeElement: -> element = document.createElementNS SVG_STANDARD, 'text' element.setAttribute 'fill', @fill # We use the alphabetic baseline and add the distance # to base ourselves to avoid a chrome bug where text zooming # doesn't work for non-alphabetic baselines element.setAttribute 'x', @point.x element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 element.setAttribute 'dominant-baseline', 'alphabetic' text = document.createTextNode @value.replace(/ /g, '\u00A0') # Preserve whitespace element.appendChild text return element update: -> return unless @element? unless @point.equals(@__lastPoint) @__lastPoint = @point.clone() @element.setAttribute 'x', @point.x @element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 unless @value is @__lastValue @__lastValue = @value @element.removeChild(@element.lastChild) text = document.createTextNode @value.replace(/ /g, '\u00A0') @element.appendChild text exports._collinear = _collinear = (a, b, c) -> first = b.from(a).normalize() second = c.from(b).normalize() return first.almostEquals(second) or first.almostEquals(second.times(-1))
119687
# Copyright (c) 2014 <NAME> (<EMAIL>) # MIT License # # Minimalistic HTML5 canvas wrapper. Mainly used as conveneince tools in Droplet. ## Private (convenience) functions BEVEL_SIZE = 1.5 EPSILON = 0.00001 helper = require './helper.coffee' SVG_STANDARD = helper.SVG_STANDARD # ## _area ## # Signed area of the triangle formed by vectors [ab] and [ac] _area = (a, b, c) -> (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y) # ## _intersects ## # Test the intersection of two line segments _intersects = (a, b, c, d) -> ((_area(a, b, c) > 0) != (_area(a, b, d) > 0)) and ((_area(c, d, a) > 0) != (_area(c, d, b) > 0)) _bisector = (a, b, c, magnitude = 1) -> if a.equals(b) or b.equals(c) return null sample = a.from(b).normalize() diagonal = sample.plus( sampleB = c.from(b).normalize() ) if diagonal.almostEquals ZERO return null else if sample.almostEquals sampleB return null diagonal = diagonal.normalize() scalar = magnitude / Math.sqrt((1 - diagonal.dot(sample) ** 2)) diagonal.x *= scalar diagonal.y *= scalar if _area(a, b, c) < 0 diagonal.x *= -1 diagonal.y *= -1 return diagonal max = (a, b) -> `(a > b ? a : b)` min = (a, b) -> `(b > a ? a : b)` toRGB = (hex) -> # Convert to 6-char hex if not already there if hex.length is 4 hex = (c + c for c in hex).join('')[1..] # Extract integers from hex r = parseInt hex[1..2], 16 g = parseInt hex[3..4], 16 b = parseInt hex[5..6], 16 return [r, g, b] zeroPad = (str, len) -> if str.length < len ('0' for [str.length...len]).join('') + str else str twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2 toHex = (rgb) -> return '#' + (twoDigitHex(k) for k in rgb).join '' memoizedAvgColor = {} avgColor = (a, factor, b) -> c = (a + ',' + factor + ',' + b) if c of memoizedAvgColor return memoizedAvgColor[c] a = toRGB a b = toRGB b newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a) return memoizedAvgColor[c] = toHex newRGB exports.Draw = class Draw ## Public functions constructor: (@ctx) -> canvas = document.createElement('canvas') @measureCtx = canvas.getContext '2d' @fontSize = 15 @fontFamily = 'Courier New, monospace' @fontAscent = -2 @fontBaseline = 10 @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @ctx.style.fontFamily = @fontFamily @ctx.style.fontSize = @fontSize self = this # ## Point ## # A point knows its x and y coordinate, and can do some vector operations. @Point = Point # ## Size ## # A Size knows its width and height. @Size = Size # ## Rectangle ## # A Rectangle knows its upper-left corner, width, and height, # and can do rectangular overlap, polygonal intersection, # and rectangle or point union (point union is called "swallow"). @Rectangle = Rectangle @NoRectangle = NoRectangle @ElementWrapper = ElementWrapper @Group = Group @Path = Path @Text = Text elementWrapper: (element) -> new ElementWrapper @, element group: (style) -> new Group @, style path: (points, bevel, style) -> new Path @, points, bevel, style text: (point, value, color) -> new Text @, point, value, color refreshFontCapital: -> metrics = helper.fontMetrics(@fontFamily, @fontSize) @fontAscent = metrics.prettytop @fontBaseline = metrics.baseline setGlobalFontSize: (size) -> @fontSize = size @ctx.style.fontSize = size @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() setGlobalFontFamily: (family) -> @fontFamily = family @ctx.style.fontFamily = family @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() getGlobalFontSize: -> @fontSize exports.Point = class Point constructor: (@x, @y) -> clone: -> new Point @x, @y magnitude: -> Math.sqrt @x * @x + @y * @y times: (scalar) -> new Point @x * scalar, @y * scalar normalize: -> @times 1 / @magnitude() translate: (vector) -> @x += vector.x; @y += vector.y add: (x, y) -> @x += x; @y += y dot: (other) -> @x * other.x + @y * other.y plus: ({x, y}) -> new Point @x + x, @y + y toMagnitude: (mag) -> r = mag / @magnitude() return new Point @x * r, @y * r copy: (point) -> @x = point.x; @y = point.y return @ from: (point) -> new Point @x - point.x, @y - point.y clear: -> @x = @y = 0 equals: (point) -> point.x is @x and point.y is @y almostEquals: (point) -> Math.abs(point.x - @x) < EPSILON and Math.abs(point.y - @y) < EPSILON ZERO = new Point 0, 0 exports.Size = class Size constructor: (@width, @height) -> equals: (size) -> @width is size.width and @height is size.height @copy: (size) -> new Size(size.width, size.height) exports.Rectangle = class Rectangle constructor: (@x, @y, @width, @height) -> contains: (point) -> @x? and @y? and not ((point.x < @x) or (point.x > @x + @width) or (point.y < @y) or (point.y > @y + @height)) equals: (other) -> unless other instanceof Rectangle return false return @x is other.x and @y is other.y and @width is other.width and @height is other.height copy: (rect) -> @x = rect.x; @y = rect.y @width = rect.width; @height = rect.height return @ clone: -> rect = new Rectangle(0, 0, 0, 0) rect.copy this return rect clear: -> @width = @height = 0; @x = @y = null bottom: -> @y + @height right: -> @x + @width unite: (rectangle) -> unless @x? and @y? then @copy rectangle else unless rectangle.x? and rectangle.y? then return else @width = max(@right(), rectangle.right()) - (@x = min @x, rectangle.x) @height = max(@bottom(), rectangle.bottom()) - (@y = min @y, rectangle.y) swallow: (point) -> unless @x? and @y? then @copy new Rectangle point.x, point.y, 0, 0 else @width = max(@right(), point.x) - (@x = min @x, point.x) @height = max(@bottom(), point.y) - (@y = min @y, point.y) overlap: (rectangle) -> @x? and @y? and not ((rectangle.right()) < @x or (rectangle.bottom() < @y) or (rectangle.x > @right()) or (rectangle.y > @bottom())) translate: (vector) -> @x += vector.x; @y += vector.y upperLeftCorner: -> new Point @x, @y toPath: -> path = new Path() path.push new Point(point[0], point[1]) for point in [ [@x, @y] [@x, @bottom()] [@right(), @bottom()] [@right(), @y] ] return path # ## NoRectangle ## # NoRectangle is an alternate constructor for Rectangle which starts # the rectangle as nothing (without even a location). It can gain location and size # via unite() and swallow(). exports.NoRectangle = class NoRectangle extends Rectangle constructor: -> super(null, null, 0, 0) # ## ElementWrapper ### exports.ElementWrapper = class ElementWrapper constructor: (@draw, @element) -> if @element? @element.style.display = 'none' @active = false @parent = @element?.parentElement ? @draw.ctx manifest: -> unless @element? @element = @makeElement() @getParentElement().appendChild @element unless @active @element.style.display = 'none' else unless @element.parentElement? @getParentElement().appendChild @element deactivate: -> if @active @active = false @element?.style?.display = 'none' activate: -> @manifest() unless @active @active = true @element?.style?.display = '' focus: -> @activate() @getParentElement().appendChild @element getParentElement: -> if @parent instanceof ElementWrapper @parent.manifest() return @parent.element else return @parent setParent: (parent) -> @parent = parent if @element? parent = @getParentElement() unless parent is @element.parentElement parent.appendChild @element destroy: -> if @element? if @element.parentElement? @element.parentElement.removeChild @element exports.Group = class Group extends ElementWrapper constructor: (@draw, @style) -> super(@draw) if @style? @_lastTransform = @style.transform makeElement: -> return document.createElementNS SVG_STANDARD, 'g' activate: -> super() if @style? and @style.transform? @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform update: -> return unless @element? if @style? and @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform # ## Path ## # This is called Path, but is forced to be closed so is actually a polygon. # It can do fast translation and rectangular intersection. exports.Path = class Path extends ElementWrapper constructor: (@draw, @_points = [], @bevel = false, @style) -> @_cachedTranslation = new Point 0, 0 @_cacheFlag = true @_bounds = new NoRectangle() @_clearCache() @style = helper.extend { 'strokeColor': 'none' 'lineWidth': 1 'fillColor': 'none' 'dotted': '' }, @style super(@draw) _clearCache: -> if @_cacheFlag # If we have no points, return the empty rectangle # as our bounding box if @_points.length is 0 @_bounds = new NoRectangle() @_lightBevelPath = @_darkBevelPath = '' # Otherwise, find our bounding box based # on our points. else # Bounds minX = minY = Infinity maxX = maxY = 0 for point in @_points minX = min minX, point.x maxX = max maxX, point.x minY = min minY, point.y maxY = max maxY, point.y @_bounds.x = minX; @_bounds.y = minY @_bounds.width = maxX - minX; @_bounds.height = maxY - minY # Light bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x > @_points[i].x and point.y <= @_points[i].y) or (point.y < @_points[i].y and point.x >= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x > @_points[@_points.length - 1].x or @_points[0].y < @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_lightBevelPath = subpaths.join(' ') # Dark bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x < @_points[i].x and point.y >= @_points[i].y) or (point.y > @_points[i].y and point.x <= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x < @_points[@_points.length - 1].x or @_points[0].y > @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_darkBevelPath = subpaths.join(' ') @_cacheFlag = false _setPoints_raw: (points) -> @_points = points @_cacheFlag = true @_updateFlag = true setMarkStyle: (style) -> if style? and style.color isnt @markColor? @markColor = style.color @_markFlag = true else if @markColor? @markColor = null @_markFlag = true setPoints: (points) -> if points.length isnt @_points.length @_setPoints_raw points return for el, i in points unless @_points[i].equals(el) @_setPoints_raw points return return push: (point) -> @_points.push point @_cacheFlag = true @_updateFlag = true unshift: (point) -> @_points.unshift point @_cacheFlag = true @_updateFlag = true reverse: -> @_points.reverse() return this # ### Point containment ### # Accomplished with ray-casting contains: (point) -> @_clearCache() if @_points.length is 0 then return false unless @_bounds.contains point then return false # "Ray" to the left dest = new Point @_bounds.x - 10, point.y # Count intersections count = 0 last = @_points[@_points.length - 1] for end in @_points if _intersects(last, end, point, dest) then count += 1 last = end return count % 2 is 1 equals: (other) -> unless other instanceof Path return false if other._points.length isnt @_points.length return false for el, i in other._points unless @_points[i].equals(el) return false return true # ### Rectangular intersection ### # Succeeds if any edges intersect or either shape is # entirely within the other. intersects: (rectangle) -> @_clearCache() if @_points.length is 0 then return false if not rectangle.overlap @_bounds then return false else # Try each pair of edges for intersections last = @_points[@_points.length - 1] rectSides = [ new Point rectangle.x, rectangle.y new Point rectangle.right(), rectangle.y new Point rectangle.right(), rectangle.bottom() new Point rectangle.x, rectangle.bottom() ] for end in @_points lastSide = rectSides[rectSides.length - 1] for side in rectSides if _intersects(last, end, lastSide, side) then return true lastSide = side last = end # Intersections failed; see if we contain the rectangle. # Note that if we contain the rectangle we must contain all of its vertices, # so it suffices to test one vertex. if @contains rectSides[0] then return true # We don't contain the rectangle; see if it contains us. if rectangle.contains @_points[0] then return true # No luck return false bounds: -> @_clearCache(); @_bounds translate: (vector) -> @_cachedTranslation.translate vector @_cacheFlag = true getCommandString: -> if @_points.length is 0 return '' pathCommands = [] pathCommands.push "M#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" for point in @_points pathCommands.push "L#{Math.round(point.x)} #{Math.round(point.y)}" pathCommands.push "L#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" pathCommands.push "Z" return pathCommands.join ' ' getInsetCoordinate: (i, length) -> j = i; prev = @_points[i] while prev.equals(@_points[i]) and j > i - @_points.length j-- prev = @_points[j %% @_points.length] k = i; next = @_points[i] while next.equals(@_points[i]) and k < i + @_points.length k++ next = @_points[k %% @_points.length] vector = _bisector prev, @_points[i], next, length return null unless vector? point = @_points[i].plus vector return point getLightBevelPath: -> @_clearCache(); @_lightBevelPath getDarkBevelPath: -> @_clearCache() return @_darkBevelPath # TODO unhackify makeElement: -> @_clearCache() pathElement = document.createElementNS SVG_STANDARD, 'path' if @style.fillColor? pathElement.setAttribute 'fill', @style.fillColor @__lastFillColor = @style.fillColor @__lastStrokeColor = @style.strokeColor @__lastLineWidth = @style.lineWidth @__lastDotted = @style.dotted @__lastCssClass = @style.cssClass @__lastTransform = @style.transform pathString = @getCommandString() if pathString.length > 0 pathElement.setAttribute 'd', pathString if @bevel @backgroundPathElement = pathElement @backgroundPathElement.setAttribute 'class', 'droplet-background-path' pathElement = document.createElementNS SVG_STANDARD, 'g' @lightPathElement = document.createElementNS SVG_STANDARD, 'path' @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' if pathString.length > 0 @lightPathElement.setAttribute 'd', @getLightBevelPath() @lightPathElement.setAttribute 'class', 'droplet-light-bevel-path' @darkPathElement = document.createElementNS SVG_STANDARD, 'path' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' if pathString.length > 0 @darkPathElement.setAttribute 'd', @getDarkBevelPath() @darkPathElement.setAttribute 'class', 'droplet-dark-bevel-path' pathElement.appendChild @backgroundPathElement pathElement.appendChild @lightPathElement pathElement.appendChild @darkPathElement else pathElement.setAttribute 'stroke', @style.strokeColor pathElement.setAttribute 'stroke-width', @style.lineWidth if (@style.dotted?.length ? 0) > 0 pathElement.setAttribute 'stroke-dasharray', @style.dotted if @style.cssClass? pathElement.setAttribute 'class', @style.cssClass if @style.transform? pathElement.setAttribute 'transform', @style.transform return pathElement update: -> return unless @element? if @style.fillColor isnt @__lastFillColor @__lastFillColor = @style.fillColor if @bevel @backgroundPathElement.setAttribute 'fill', @style.fillColor @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' else @element.setAttribute 'fill', @style.fillColor if not @bevel and @style.strokeColor isnt @__lastStrokeColor @__lastStrokeColor = @style.strokeColor @element.setAttribute 'stroke', @style.strokeColor if not @bevel and @style.dotted isnt @__lastDotted @__lastDotted = @style.dotted @element.setAttribute 'stroke-dasharray', @style.dotted if not @bevel and @style.lineWidth isnt @__lastLineWidth @__lastLineWidth = @style.lineWidth @element.setAttribute 'stroke-width', @style.lineWidth if @style.cssClass? and @style.cssClass isnt @_lastCssClass @_lastCssClass = @style.cssClass @element.setAttribute 'class', @style.cssClass if @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform if @_markFlag if @markColor? if @bevel @backgroundPathElement.setAttribute 'stroke', @markColor @backgroundPathElement.setAttribute 'stroke-width', '2' @lightPathElement.setAttribute 'visibility', 'hidden' @darkPathElement.setAttribute 'visibility', 'hidden' else @element.setAttribute 'stroke', @markColor @element.setAttribute 'stroke-width', '2' else if @bevel @backgroundPathElement.setAttribute 'stroke', 'none' @lightPathElement.setAttribute 'visibility', 'visible' @darkPathElement.setAttribute 'visibility', 'visible' else @element.setAttribute 'stroke', @style.strokeColor @element.setAttribute 'line-width', @style.lineWidth if @_updateFlag @_updateFlag = false pathString = @getCommandString() if pathString.length > 0 if @bevel @backgroundPathElement.setAttribute 'd', pathString @lightPathElement.setAttribute 'd', @getLightBevelPath() @darkPathElement.setAttribute 'd', @getDarkBevelPath() else @element.setAttribute 'd', pathString clone: -> clone = new Path(@_points.slice(0), @bevel, { lineWidth: @style.lineWidth fillColor: @style.fillColor strokeColor: @style.strokeColor dotted: @style.dotted cssClass: @style.cssClass }) clone._clearCache() clone.update() return clone # ## Text ## # A Text element. Mainly this exists for computing bounding boxes, which is # accomplished via ctx.measureText(). exports.Text = class Text extends ElementWrapper constructor: (@draw, @point, @value, @fill = '#000') -> @__lastValue = @__boundsValue = @value @__lastPoint = @point.clone() @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize super(@draw) clone: -> new Text @point, @value equals: (other) -> other? and @point.equals(other.point) and @value is other.value _clearCache: -> if @value is @__boundsValue return else @__boundsValue = @value @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize bounds: -> @_clearCache(); @_bounds contains: (point) -> @_bounds.contains point setPosition: (point) -> @translate point.from @point makeElement: -> element = document.createElementNS SVG_STANDARD, 'text' element.setAttribute 'fill', @fill # We use the alphabetic baseline and add the distance # to base ourselves to avoid a chrome bug where text zooming # doesn't work for non-alphabetic baselines element.setAttribute 'x', @point.x element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 element.setAttribute 'dominant-baseline', 'alphabetic' text = document.createTextNode @value.replace(/ /g, '\u00A0') # Preserve whitespace element.appendChild text return element update: -> return unless @element? unless @point.equals(@__lastPoint) @__lastPoint = @point.clone() @element.setAttribute 'x', @point.x @element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 unless @value is @__lastValue @__lastValue = @value @element.removeChild(@element.lastChild) text = document.createTextNode @value.replace(/ /g, '\u00A0') @element.appendChild text exports._collinear = _collinear = (a, b, c) -> first = b.from(a).normalize() second = c.from(b).normalize() return first.almostEquals(second) or first.almostEquals(second.times(-1))
true
# Copyright (c) 2014 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # MIT License # # Minimalistic HTML5 canvas wrapper. Mainly used as conveneince tools in Droplet. ## Private (convenience) functions BEVEL_SIZE = 1.5 EPSILON = 0.00001 helper = require './helper.coffee' SVG_STANDARD = helper.SVG_STANDARD # ## _area ## # Signed area of the triangle formed by vectors [ab] and [ac] _area = (a, b, c) -> (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y) # ## _intersects ## # Test the intersection of two line segments _intersects = (a, b, c, d) -> ((_area(a, b, c) > 0) != (_area(a, b, d) > 0)) and ((_area(c, d, a) > 0) != (_area(c, d, b) > 0)) _bisector = (a, b, c, magnitude = 1) -> if a.equals(b) or b.equals(c) return null sample = a.from(b).normalize() diagonal = sample.plus( sampleB = c.from(b).normalize() ) if diagonal.almostEquals ZERO return null else if sample.almostEquals sampleB return null diagonal = diagonal.normalize() scalar = magnitude / Math.sqrt((1 - diagonal.dot(sample) ** 2)) diagonal.x *= scalar diagonal.y *= scalar if _area(a, b, c) < 0 diagonal.x *= -1 diagonal.y *= -1 return diagonal max = (a, b) -> `(a > b ? a : b)` min = (a, b) -> `(b > a ? a : b)` toRGB = (hex) -> # Convert to 6-char hex if not already there if hex.length is 4 hex = (c + c for c in hex).join('')[1..] # Extract integers from hex r = parseInt hex[1..2], 16 g = parseInt hex[3..4], 16 b = parseInt hex[5..6], 16 return [r, g, b] zeroPad = (str, len) -> if str.length < len ('0' for [str.length...len]).join('') + str else str twoDigitHex = (n) -> zeroPad Math.round(n).toString(16), 2 toHex = (rgb) -> return '#' + (twoDigitHex(k) for k in rgb).join '' memoizedAvgColor = {} avgColor = (a, factor, b) -> c = (a + ',' + factor + ',' + b) if c of memoizedAvgColor return memoizedAvgColor[c] a = toRGB a b = toRGB b newRGB = (a[i] * factor + b[i] * (1 - factor) for k, i in a) return memoizedAvgColor[c] = toHex newRGB exports.Draw = class Draw ## Public functions constructor: (@ctx) -> canvas = document.createElement('canvas') @measureCtx = canvas.getContext '2d' @fontSize = 15 @fontFamily = 'Courier New, monospace' @fontAscent = -2 @fontBaseline = 10 @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @ctx.style.fontFamily = @fontFamily @ctx.style.fontSize = @fontSize self = this # ## Point ## # A point knows its x and y coordinate, and can do some vector operations. @Point = Point # ## Size ## # A Size knows its width and height. @Size = Size # ## Rectangle ## # A Rectangle knows its upper-left corner, width, and height, # and can do rectangular overlap, polygonal intersection, # and rectangle or point union (point union is called "swallow"). @Rectangle = Rectangle @NoRectangle = NoRectangle @ElementWrapper = ElementWrapper @Group = Group @Path = Path @Text = Text elementWrapper: (element) -> new ElementWrapper @, element group: (style) -> new Group @, style path: (points, bevel, style) -> new Path @, points, bevel, style text: (point, value, color) -> new Text @, point, value, color refreshFontCapital: -> metrics = helper.fontMetrics(@fontFamily, @fontSize) @fontAscent = metrics.prettytop @fontBaseline = metrics.baseline setGlobalFontSize: (size) -> @fontSize = size @ctx.style.fontSize = size @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() setGlobalFontFamily: (family) -> @fontFamily = family @ctx.style.fontFamily = family @measureCtx.font = "#{@fontSize}px #{@fontFamily}" @refreshFontCapital() getGlobalFontSize: -> @fontSize exports.Point = class Point constructor: (@x, @y) -> clone: -> new Point @x, @y magnitude: -> Math.sqrt @x * @x + @y * @y times: (scalar) -> new Point @x * scalar, @y * scalar normalize: -> @times 1 / @magnitude() translate: (vector) -> @x += vector.x; @y += vector.y add: (x, y) -> @x += x; @y += y dot: (other) -> @x * other.x + @y * other.y plus: ({x, y}) -> new Point @x + x, @y + y toMagnitude: (mag) -> r = mag / @magnitude() return new Point @x * r, @y * r copy: (point) -> @x = point.x; @y = point.y return @ from: (point) -> new Point @x - point.x, @y - point.y clear: -> @x = @y = 0 equals: (point) -> point.x is @x and point.y is @y almostEquals: (point) -> Math.abs(point.x - @x) < EPSILON and Math.abs(point.y - @y) < EPSILON ZERO = new Point 0, 0 exports.Size = class Size constructor: (@width, @height) -> equals: (size) -> @width is size.width and @height is size.height @copy: (size) -> new Size(size.width, size.height) exports.Rectangle = class Rectangle constructor: (@x, @y, @width, @height) -> contains: (point) -> @x? and @y? and not ((point.x < @x) or (point.x > @x + @width) or (point.y < @y) or (point.y > @y + @height)) equals: (other) -> unless other instanceof Rectangle return false return @x is other.x and @y is other.y and @width is other.width and @height is other.height copy: (rect) -> @x = rect.x; @y = rect.y @width = rect.width; @height = rect.height return @ clone: -> rect = new Rectangle(0, 0, 0, 0) rect.copy this return rect clear: -> @width = @height = 0; @x = @y = null bottom: -> @y + @height right: -> @x + @width unite: (rectangle) -> unless @x? and @y? then @copy rectangle else unless rectangle.x? and rectangle.y? then return else @width = max(@right(), rectangle.right()) - (@x = min @x, rectangle.x) @height = max(@bottom(), rectangle.bottom()) - (@y = min @y, rectangle.y) swallow: (point) -> unless @x? and @y? then @copy new Rectangle point.x, point.y, 0, 0 else @width = max(@right(), point.x) - (@x = min @x, point.x) @height = max(@bottom(), point.y) - (@y = min @y, point.y) overlap: (rectangle) -> @x? and @y? and not ((rectangle.right()) < @x or (rectangle.bottom() < @y) or (rectangle.x > @right()) or (rectangle.y > @bottom())) translate: (vector) -> @x += vector.x; @y += vector.y upperLeftCorner: -> new Point @x, @y toPath: -> path = new Path() path.push new Point(point[0], point[1]) for point in [ [@x, @y] [@x, @bottom()] [@right(), @bottom()] [@right(), @y] ] return path # ## NoRectangle ## # NoRectangle is an alternate constructor for Rectangle which starts # the rectangle as nothing (without even a location). It can gain location and size # via unite() and swallow(). exports.NoRectangle = class NoRectangle extends Rectangle constructor: -> super(null, null, 0, 0) # ## ElementWrapper ### exports.ElementWrapper = class ElementWrapper constructor: (@draw, @element) -> if @element? @element.style.display = 'none' @active = false @parent = @element?.parentElement ? @draw.ctx manifest: -> unless @element? @element = @makeElement() @getParentElement().appendChild @element unless @active @element.style.display = 'none' else unless @element.parentElement? @getParentElement().appendChild @element deactivate: -> if @active @active = false @element?.style?.display = 'none' activate: -> @manifest() unless @active @active = true @element?.style?.display = '' focus: -> @activate() @getParentElement().appendChild @element getParentElement: -> if @parent instanceof ElementWrapper @parent.manifest() return @parent.element else return @parent setParent: (parent) -> @parent = parent if @element? parent = @getParentElement() unless parent is @element.parentElement parent.appendChild @element destroy: -> if @element? if @element.parentElement? @element.parentElement.removeChild @element exports.Group = class Group extends ElementWrapper constructor: (@draw, @style) -> super(@draw) if @style? @_lastTransform = @style.transform makeElement: -> return document.createElementNS SVG_STANDARD, 'g' activate: -> super() if @style? and @style.transform? @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform update: -> return unless @element? if @style? and @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform # ## Path ## # This is called Path, but is forced to be closed so is actually a polygon. # It can do fast translation and rectangular intersection. exports.Path = class Path extends ElementWrapper constructor: (@draw, @_points = [], @bevel = false, @style) -> @_cachedTranslation = new Point 0, 0 @_cacheFlag = true @_bounds = new NoRectangle() @_clearCache() @style = helper.extend { 'strokeColor': 'none' 'lineWidth': 1 'fillColor': 'none' 'dotted': '' }, @style super(@draw) _clearCache: -> if @_cacheFlag # If we have no points, return the empty rectangle # as our bounding box if @_points.length is 0 @_bounds = new NoRectangle() @_lightBevelPath = @_darkBevelPath = '' # Otherwise, find our bounding box based # on our points. else # Bounds minX = minY = Infinity maxX = maxY = 0 for point in @_points minX = min minX, point.x maxX = max maxX, point.x minY = min minY, point.y maxY = max maxY, point.y @_bounds.x = minX; @_bounds.y = minY @_bounds.width = maxX - minX; @_bounds.height = maxY - minY # Light bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x > @_points[i].x and point.y <= @_points[i].y) or (point.y < @_points[i].y and point.x >= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x > @_points[@_points.length - 1].x or @_points[0].y < @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_lightBevelPath = subpaths.join(' ') # Dark bevels subpaths = [] outsidePoints = [] insidePoints = [] for point, i in @_points[1..] if (point.x < @_points[i].x and point.y >= @_points[i].y) or (point.y > @_points[i].y and point.x <= @_points[i].x) if outsidePoints.length is 0 insetCoord = @getInsetCoordinate i, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[i] insidePoints.push insetCoord insetCoord = @getInsetCoordinate i + 1, BEVEL_SIZE if insetCoord? outsidePoints.push point insidePoints.push insetCoord else unless point.equals(@_points[i]) or outsidePoints.length is 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) outsidePoints.length = insidePoints.length = 0 if @_points[0].x < @_points[@_points.length - 1].x or @_points[0].y > @_points[@_points.length - 1].y if outsidePoints.length is 0 insetCoord = @getInsetCoordinate @_points.length - 1, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[@_points.length - 1] insidePoints.push insetCoord insetCoord = @getInsetCoordinate 0, BEVEL_SIZE if insetCoord? outsidePoints.push @_points[0] insidePoints.push insetCoord if outsidePoints.length > 0 subpaths.push( 'M' + outsidePoints.concat(insidePoints.reverse()).map((point) -> "#{point.x} #{point.y}").join(" L") + ' Z' ) @_darkBevelPath = subpaths.join(' ') @_cacheFlag = false _setPoints_raw: (points) -> @_points = points @_cacheFlag = true @_updateFlag = true setMarkStyle: (style) -> if style? and style.color isnt @markColor? @markColor = style.color @_markFlag = true else if @markColor? @markColor = null @_markFlag = true setPoints: (points) -> if points.length isnt @_points.length @_setPoints_raw points return for el, i in points unless @_points[i].equals(el) @_setPoints_raw points return return push: (point) -> @_points.push point @_cacheFlag = true @_updateFlag = true unshift: (point) -> @_points.unshift point @_cacheFlag = true @_updateFlag = true reverse: -> @_points.reverse() return this # ### Point containment ### # Accomplished with ray-casting contains: (point) -> @_clearCache() if @_points.length is 0 then return false unless @_bounds.contains point then return false # "Ray" to the left dest = new Point @_bounds.x - 10, point.y # Count intersections count = 0 last = @_points[@_points.length - 1] for end in @_points if _intersects(last, end, point, dest) then count += 1 last = end return count % 2 is 1 equals: (other) -> unless other instanceof Path return false if other._points.length isnt @_points.length return false for el, i in other._points unless @_points[i].equals(el) return false return true # ### Rectangular intersection ### # Succeeds if any edges intersect or either shape is # entirely within the other. intersects: (rectangle) -> @_clearCache() if @_points.length is 0 then return false if not rectangle.overlap @_bounds then return false else # Try each pair of edges for intersections last = @_points[@_points.length - 1] rectSides = [ new Point rectangle.x, rectangle.y new Point rectangle.right(), rectangle.y new Point rectangle.right(), rectangle.bottom() new Point rectangle.x, rectangle.bottom() ] for end in @_points lastSide = rectSides[rectSides.length - 1] for side in rectSides if _intersects(last, end, lastSide, side) then return true lastSide = side last = end # Intersections failed; see if we contain the rectangle. # Note that if we contain the rectangle we must contain all of its vertices, # so it suffices to test one vertex. if @contains rectSides[0] then return true # We don't contain the rectangle; see if it contains us. if rectangle.contains @_points[0] then return true # No luck return false bounds: -> @_clearCache(); @_bounds translate: (vector) -> @_cachedTranslation.translate vector @_cacheFlag = true getCommandString: -> if @_points.length is 0 return '' pathCommands = [] pathCommands.push "M#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" for point in @_points pathCommands.push "L#{Math.round(point.x)} #{Math.round(point.y)}" pathCommands.push "L#{Math.round(@_points[0].x)} #{Math.round(@_points[0].y)}" pathCommands.push "Z" return pathCommands.join ' ' getInsetCoordinate: (i, length) -> j = i; prev = @_points[i] while prev.equals(@_points[i]) and j > i - @_points.length j-- prev = @_points[j %% @_points.length] k = i; next = @_points[i] while next.equals(@_points[i]) and k < i + @_points.length k++ next = @_points[k %% @_points.length] vector = _bisector prev, @_points[i], next, length return null unless vector? point = @_points[i].plus vector return point getLightBevelPath: -> @_clearCache(); @_lightBevelPath getDarkBevelPath: -> @_clearCache() return @_darkBevelPath # TODO unhackify makeElement: -> @_clearCache() pathElement = document.createElementNS SVG_STANDARD, 'path' if @style.fillColor? pathElement.setAttribute 'fill', @style.fillColor @__lastFillColor = @style.fillColor @__lastStrokeColor = @style.strokeColor @__lastLineWidth = @style.lineWidth @__lastDotted = @style.dotted @__lastCssClass = @style.cssClass @__lastTransform = @style.transform pathString = @getCommandString() if pathString.length > 0 pathElement.setAttribute 'd', pathString if @bevel @backgroundPathElement = pathElement @backgroundPathElement.setAttribute 'class', 'droplet-background-path' pathElement = document.createElementNS SVG_STANDARD, 'g' @lightPathElement = document.createElementNS SVG_STANDARD, 'path' @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' if pathString.length > 0 @lightPathElement.setAttribute 'd', @getLightBevelPath() @lightPathElement.setAttribute 'class', 'droplet-light-bevel-path' @darkPathElement = document.createElementNS SVG_STANDARD, 'path' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' if pathString.length > 0 @darkPathElement.setAttribute 'd', @getDarkBevelPath() @darkPathElement.setAttribute 'class', 'droplet-dark-bevel-path' pathElement.appendChild @backgroundPathElement pathElement.appendChild @lightPathElement pathElement.appendChild @darkPathElement else pathElement.setAttribute 'stroke', @style.strokeColor pathElement.setAttribute 'stroke-width', @style.lineWidth if (@style.dotted?.length ? 0) > 0 pathElement.setAttribute 'stroke-dasharray', @style.dotted if @style.cssClass? pathElement.setAttribute 'class', @style.cssClass if @style.transform? pathElement.setAttribute 'transform', @style.transform return pathElement update: -> return unless @element? if @style.fillColor isnt @__lastFillColor @__lastFillColor = @style.fillColor if @bevel @backgroundPathElement.setAttribute 'fill', @style.fillColor @lightPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#FFF' @darkPathElement.setAttribute 'fill', avgColor @style.fillColor, 0.7, '#000' else @element.setAttribute 'fill', @style.fillColor if not @bevel and @style.strokeColor isnt @__lastStrokeColor @__lastStrokeColor = @style.strokeColor @element.setAttribute 'stroke', @style.strokeColor if not @bevel and @style.dotted isnt @__lastDotted @__lastDotted = @style.dotted @element.setAttribute 'stroke-dasharray', @style.dotted if not @bevel and @style.lineWidth isnt @__lastLineWidth @__lastLineWidth = @style.lineWidth @element.setAttribute 'stroke-width', @style.lineWidth if @style.cssClass? and @style.cssClass isnt @_lastCssClass @_lastCssClass = @style.cssClass @element.setAttribute 'class', @style.cssClass if @style.transform? and @style.transform isnt @_lastTransform @_lastTransform = @style.transform @element.setAttribute 'transform', @style.transform if @_markFlag if @markColor? if @bevel @backgroundPathElement.setAttribute 'stroke', @markColor @backgroundPathElement.setAttribute 'stroke-width', '2' @lightPathElement.setAttribute 'visibility', 'hidden' @darkPathElement.setAttribute 'visibility', 'hidden' else @element.setAttribute 'stroke', @markColor @element.setAttribute 'stroke-width', '2' else if @bevel @backgroundPathElement.setAttribute 'stroke', 'none' @lightPathElement.setAttribute 'visibility', 'visible' @darkPathElement.setAttribute 'visibility', 'visible' else @element.setAttribute 'stroke', @style.strokeColor @element.setAttribute 'line-width', @style.lineWidth if @_updateFlag @_updateFlag = false pathString = @getCommandString() if pathString.length > 0 if @bevel @backgroundPathElement.setAttribute 'd', pathString @lightPathElement.setAttribute 'd', @getLightBevelPath() @darkPathElement.setAttribute 'd', @getDarkBevelPath() else @element.setAttribute 'd', pathString clone: -> clone = new Path(@_points.slice(0), @bevel, { lineWidth: @style.lineWidth fillColor: @style.fillColor strokeColor: @style.strokeColor dotted: @style.dotted cssClass: @style.cssClass }) clone._clearCache() clone.update() return clone # ## Text ## # A Text element. Mainly this exists for computing bounding boxes, which is # accomplished via ctx.measureText(). exports.Text = class Text extends ElementWrapper constructor: (@draw, @point, @value, @fill = '#000') -> @__lastValue = @__boundsValue = @value @__lastPoint = @point.clone() @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize super(@draw) clone: -> new Text @point, @value equals: (other) -> other? and @point.equals(other.point) and @value is other.value _clearCache: -> if @value is @__boundsValue return else @__boundsValue = @value @_bounds = new Rectangle @point.x, @point.y, @draw.measureCtx.measureText(@value).width, @draw.fontSize bounds: -> @_clearCache(); @_bounds contains: (point) -> @_bounds.contains point setPosition: (point) -> @translate point.from @point makeElement: -> element = document.createElementNS SVG_STANDARD, 'text' element.setAttribute 'fill', @fill # We use the alphabetic baseline and add the distance # to base ourselves to avoid a chrome bug where text zooming # doesn't work for non-alphabetic baselines element.setAttribute 'x', @point.x element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 element.setAttribute 'dominant-baseline', 'alphabetic' text = document.createTextNode @value.replace(/ /g, '\u00A0') # Preserve whitespace element.appendChild text return element update: -> return unless @element? unless @point.equals(@__lastPoint) @__lastPoint = @point.clone() @element.setAttribute 'x', @point.x @element.setAttribute 'y', @point.y + @draw.fontBaseline - @draw.fontAscent / 2 unless @value is @__lastValue @__lastValue = @value @element.removeChild(@element.lastChild) text = document.createTextNode @value.replace(/ /g, '\u00A0') @element.appendChild text exports._collinear = _collinear = (a, b, c) -> first = b.from(a).normalize() second = c.from(b).normalize() return first.almostEquals(second) or first.almostEquals(second.times(-1))
[ { "context": "API and on-render callback for MD Image.\n @author Derek Gransaull <derek@dgtlife.com>\n @copyright DGTLife, LLC 201", "end": 78, "score": 0.9998705983161926, "start": 63, "tag": "NAME", "value": "Derek Gransaull" }, { "context": "callback for MD Image.\n @author Derek Gransaull <derek@dgtlife.com>\n @copyright DGTLife, LLC 2015\n###\n{ Template } ", "end": 97, "score": 0.9999336004257202, "start": 80, "tag": "EMAIL", "value": "derek@dgtlife.com" } ]
client/imports/ui/md-image/md-image.coffee
dgtlife/material-for-meteor
12
### @file API and on-render callback for MD Image. @author Derek Gransaull <derek@dgtlife.com> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' { _ } = require 'meteor/underscore' eqS = require('../../api/md-utils.js').eqS reserveImageSpace = require('../../api/md-image-api.js').reserveImageSpace setPlaceholderBgColor = require('../../api/md-image-api.js').setPlaceholderBgColor setPlaceholderImage = require('../../api/md-image-api.js').setPlaceholderImage setImageAsBackground = require('../../api/md-image-api.js').setImageAsBackground setImgSize = require('../../api/md-image-api.js').setImgSize require './md-image.jade' # On-render callback for MD Image. Template.md_image.onRendered -> instance = @ image = instance.firstNode placeholder = eqS image, '[data-image-placeholder]' reserveImageSpace image setPlaceholderBgColor image, placeholder setPlaceholderImage image, placeholder if instance.data.sizing # The image will be a background to the .md-image div. # # A function to render the image as specified in the 'data-bg-url' attribute # into the background with appropriate sizing. renderImage = (mdImage, templateData) -> setImageAsBackground(mdImage, templateData) mdImagePlaceholder = eqS mdImage, '[data-image-placeholder]' if mdImage.hasAttribute 'data-fade' mdImagePlaceholder.classList.add 'faded-out' else mdImagePlaceholder.setAttribute 'style', 'opacity: 0;' # The initial render. renderImage image, instance.data # Make the image reactive to a change in the values of template data. First, # define a function that detects the relevant changes and calls # renderImage. detectRelevantAttributeChanges = (mutations) -> _.each mutations, (mutation) -> if (mutation.attributeName is 'data-bg-url') or (mutation.attributeName is 'data-height') or (mutation.attributeName is 'data-width') or (mutation.attributeName is 'data-sizing') renderImage(mutation.target) # Define a mutation observer for attribute changes on the image that calls # the detector function. if not onAttributeChange onAttributeChange = new MutationObserver detectRelevantAttributeChanges onAttributeChange.observe image, attributes: true else # The image will be rendered normally. eqS(image, '[data-image-img]').onload = -> setImgSize image, @ if image.hasAttribute 'data-fade' placeholder.classList.add 'faded-out' else placeholder.setAttribute 'style', 'opacity: 0;'
198739
### @file API and on-render callback for MD Image. @author <NAME> <<EMAIL>> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' { _ } = require 'meteor/underscore' eqS = require('../../api/md-utils.js').eqS reserveImageSpace = require('../../api/md-image-api.js').reserveImageSpace setPlaceholderBgColor = require('../../api/md-image-api.js').setPlaceholderBgColor setPlaceholderImage = require('../../api/md-image-api.js').setPlaceholderImage setImageAsBackground = require('../../api/md-image-api.js').setImageAsBackground setImgSize = require('../../api/md-image-api.js').setImgSize require './md-image.jade' # On-render callback for MD Image. Template.md_image.onRendered -> instance = @ image = instance.firstNode placeholder = eqS image, '[data-image-placeholder]' reserveImageSpace image setPlaceholderBgColor image, placeholder setPlaceholderImage image, placeholder if instance.data.sizing # The image will be a background to the .md-image div. # # A function to render the image as specified in the 'data-bg-url' attribute # into the background with appropriate sizing. renderImage = (mdImage, templateData) -> setImageAsBackground(mdImage, templateData) mdImagePlaceholder = eqS mdImage, '[data-image-placeholder]' if mdImage.hasAttribute 'data-fade' mdImagePlaceholder.classList.add 'faded-out' else mdImagePlaceholder.setAttribute 'style', 'opacity: 0;' # The initial render. renderImage image, instance.data # Make the image reactive to a change in the values of template data. First, # define a function that detects the relevant changes and calls # renderImage. detectRelevantAttributeChanges = (mutations) -> _.each mutations, (mutation) -> if (mutation.attributeName is 'data-bg-url') or (mutation.attributeName is 'data-height') or (mutation.attributeName is 'data-width') or (mutation.attributeName is 'data-sizing') renderImage(mutation.target) # Define a mutation observer for attribute changes on the image that calls # the detector function. if not onAttributeChange onAttributeChange = new MutationObserver detectRelevantAttributeChanges onAttributeChange.observe image, attributes: true else # The image will be rendered normally. eqS(image, '[data-image-img]').onload = -> setImgSize image, @ if image.hasAttribute 'data-fade' placeholder.classList.add 'faded-out' else placeholder.setAttribute 'style', 'opacity: 0;'
true
### @file API and on-render callback for MD Image. @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' { _ } = require 'meteor/underscore' eqS = require('../../api/md-utils.js').eqS reserveImageSpace = require('../../api/md-image-api.js').reserveImageSpace setPlaceholderBgColor = require('../../api/md-image-api.js').setPlaceholderBgColor setPlaceholderImage = require('../../api/md-image-api.js').setPlaceholderImage setImageAsBackground = require('../../api/md-image-api.js').setImageAsBackground setImgSize = require('../../api/md-image-api.js').setImgSize require './md-image.jade' # On-render callback for MD Image. Template.md_image.onRendered -> instance = @ image = instance.firstNode placeholder = eqS image, '[data-image-placeholder]' reserveImageSpace image setPlaceholderBgColor image, placeholder setPlaceholderImage image, placeholder if instance.data.sizing # The image will be a background to the .md-image div. # # A function to render the image as specified in the 'data-bg-url' attribute # into the background with appropriate sizing. renderImage = (mdImage, templateData) -> setImageAsBackground(mdImage, templateData) mdImagePlaceholder = eqS mdImage, '[data-image-placeholder]' if mdImage.hasAttribute 'data-fade' mdImagePlaceholder.classList.add 'faded-out' else mdImagePlaceholder.setAttribute 'style', 'opacity: 0;' # The initial render. renderImage image, instance.data # Make the image reactive to a change in the values of template data. First, # define a function that detects the relevant changes and calls # renderImage. detectRelevantAttributeChanges = (mutations) -> _.each mutations, (mutation) -> if (mutation.attributeName is 'data-bg-url') or (mutation.attributeName is 'data-height') or (mutation.attributeName is 'data-width') or (mutation.attributeName is 'data-sizing') renderImage(mutation.target) # Define a mutation observer for attribute changes on the image that calls # the detector function. if not onAttributeChange onAttributeChange = new MutationObserver detectRelevantAttributeChanges onAttributeChange.observe image, attributes: true else # The image will be rendered normally. eqS(image, '[data-image-img]').onload = -> setImgSize image, @ if image.hasAttribute 'data-fade' placeholder.classList.add 'faded-out' else placeholder.setAttribute 'style', 'opacity: 0;'
[ { "context": "-mail addresses can be plain e-mail addresses\n\n name@mymailserver.com\n\nor with formatted name (includes unicode support", "end": 5246, "score": 0.9999156594276428, "start": 5225, "tag": "EMAIL", "value": "name@mymailserver.com" }, { "context": "h formatted name (includes unicode support)\n\n \"My Name\" <name@mymailserver.com>\n\n\nContent\n---------", "end": 5306, "score": 0.8398404121398926, "start": 5304, "tag": "NAME", "value": "My" }, { "context": "formatted name (includes unicode support)\n\n \"My Name\" <name@mymailserver.com>\n\n\nContent\n--------------", "end": 5311, "score": 0.532318651676178, "start": 5307, "tag": "USERNAME", "value": "Name" }, { "context": "d name (includes unicode support)\n\n \"My Name\" <name@mymailserver.com>\n\n\nContent\n--------------------------------------", "end": 5335, "score": 0.9999170303344727, "start": 5314, "tag": "EMAIL", "value": "name@mymailserver.com" } ]
src/configSchema.coffee
alinex/node-mail
0
### Configuration =================================================== The configuration consists of two parts: - Email Template - Collection of Templates ### ### Email Template ------------------------------------------------------ {@schema #email} ### exports.email = email = title: "Email Action" description: "the setup for an individual email action" type: 'object' allowedKeys: true keys: base: title: "Base Template" description: "the template used as basis for this one" type: 'string' list: '<<<context:///email>>>' transport: title: "Service Connection" description: "the service connection to send mails through" type: 'or' or: [ title: "Transport URI" description: "the transport method as URI string through which the mail will be send like `<protocol>://<user>:<password>@<server>:<port>`" type: 'string' , title: "Transport Object" description: "the mail transport settings through which the mail will be send" type: 'object' ] retry: title: "Retry" description: "the number of retries to take if sending failed" type: 'object' allowedKeys: true mandatoryKeys: true keys: times: title: "Number of Attempts" description: "the number of maximal attempts to run successfully" type: 'integer' min: 0 default: 1 interval: title: "Time to Wait" description: "the time to wait before retrying a failed attempt" type: 'interval' unit: 'ms' min: 0 default: 5000 default: {times: 1, interval: 5000} from: title: "From" description: "the address emails are send from" type: 'string' replyTo: title: "Reply To" description: "the address to send answers to" type: 'string' optional: true to: title: "To" description: "the address emails are send to" type: 'array' toArray: true entries: type: 'string' cc: title: "Cc" description: "the carbon copy addresses" type: 'array' toArray: true entries: type: 'string' bcc: title: "Bcc" description: "the blind carbon copy addresses" type: 'array' toArray: true entries: type: 'string' locale: title: "Locale Setting" description: "the locale setting for subject and body dates" type: 'string' minLength: 2 maxLength: 5 lowerCase: true match: /^[a-z]{2}(-[a-z]{2})?$/ subject: title: "Subject" description: "the subject line of the generated email" type: 'handlebars' body: title: "Content" description: "the body content of the generated email" type: 'handlebars' attachments: title: "Attachments" description: "the attachments to be included" type: 'array' allowedKeys: true entries: title: "Attachment" description: "the attachment to be included" type: 'object' allowedKeys: true keys: filename: title: "Reported Filename" description: "the filename to be reported as the name of the attached file (set this value as false to disable, default: created automatically)" type: 'string' content: title: "Content" description: "the content of the attached file" type: 'string' path: title: "Include File" description: "the path to a file or an URL if you want to stream the file instead of including it" type: 'string' contentType: title: "Content Type" description: "the optional content type for the attachment (autodetected)" type: 'string' contentDisposition: title: "Disposition" description: "the optional content disposition type for the attachment (default: attachment)" type: 'string' cid: title: "Content ID" description: "the optional content id for using inline images in HTML message source" type: 'string' encoding: title: "Encoding" description: "the content encoding like: base64, hex, binary etc." type: 'string' ### Collection of Templates ------------------------------------------------------ {@schema #templates} ### exports.templates = title: "Email Templates" description: "the possible templates used for sending emails" type: 'object' entries: [email] ### Addressing -------------------------------------------------------- First you can define the sender address using: ``` yaml from: <string> # the address used as sender(often the same as used in transport) replyTo: <string> # address which should be used for replys ``` And you give the addresses to send the mail to. In the following fields: `to`, `cc` and `bcc` you may give a single address or a list of addresses to use. All e-mail addresses can be plain e-mail addresses name@mymailserver.com or with formatted name (includes unicode support) "My Name" <name@mymailserver.com> Content -------------------------------------------------------- The content of the mail consists of an subject line which should be not to long and the body. The body is given as [Markdown](http://alinex.github.io/develop/lang/markdown.html) syntax and supports all possibilities from [report](http://alinex.github.io/node-report/README.md.html#markup%20syntax). This will be converted to a plain text and html version for sending so that the mail client can choose the format to display. You may also give the 'text' and 'html' content as property itself. But keep in mind that within the base properties no markdown conversions are done. In the 'body' it will. Like you see above, you can use handlebar syntax to use some variables from the code. This is possible in subject and body. And you may specify a locale to use for date formatting. You can also define different templates which can be referenced from within the job. Find more examples at [validator](http://alinex.github.io/node-validator/README.md.html#handlebars). Attachments -------------------------------------------------- The key `attachments` is used to add a list of files attached to the email and consists of the following properties: - `path` path to a file or an URL to include - `filename` filename to be reported as the name of the attached file - `content` String, Buffer or a Stream contents for the attachment - `contentType` optional content type for the attachment, if not set will be derived from the filename property - `contentDisposition` optional content disposition type for the attachment, defaults to ‘attachment’ - `cid` optional content id for using inline images in HTML message source - `encoding` If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, binary etc. - `headers` custom headers for the attachment node ###
157681
### Configuration =================================================== The configuration consists of two parts: - Email Template - Collection of Templates ### ### Email Template ------------------------------------------------------ {@schema #email} ### exports.email = email = title: "Email Action" description: "the setup for an individual email action" type: 'object' allowedKeys: true keys: base: title: "Base Template" description: "the template used as basis for this one" type: 'string' list: '<<<context:///email>>>' transport: title: "Service Connection" description: "the service connection to send mails through" type: 'or' or: [ title: "Transport URI" description: "the transport method as URI string through which the mail will be send like `<protocol>://<user>:<password>@<server>:<port>`" type: 'string' , title: "Transport Object" description: "the mail transport settings through which the mail will be send" type: 'object' ] retry: title: "Retry" description: "the number of retries to take if sending failed" type: 'object' allowedKeys: true mandatoryKeys: true keys: times: title: "Number of Attempts" description: "the number of maximal attempts to run successfully" type: 'integer' min: 0 default: 1 interval: title: "Time to Wait" description: "the time to wait before retrying a failed attempt" type: 'interval' unit: 'ms' min: 0 default: 5000 default: {times: 1, interval: 5000} from: title: "From" description: "the address emails are send from" type: 'string' replyTo: title: "Reply To" description: "the address to send answers to" type: 'string' optional: true to: title: "To" description: "the address emails are send to" type: 'array' toArray: true entries: type: 'string' cc: title: "Cc" description: "the carbon copy addresses" type: 'array' toArray: true entries: type: 'string' bcc: title: "Bcc" description: "the blind carbon copy addresses" type: 'array' toArray: true entries: type: 'string' locale: title: "Locale Setting" description: "the locale setting for subject and body dates" type: 'string' minLength: 2 maxLength: 5 lowerCase: true match: /^[a-z]{2}(-[a-z]{2})?$/ subject: title: "Subject" description: "the subject line of the generated email" type: 'handlebars' body: title: "Content" description: "the body content of the generated email" type: 'handlebars' attachments: title: "Attachments" description: "the attachments to be included" type: 'array' allowedKeys: true entries: title: "Attachment" description: "the attachment to be included" type: 'object' allowedKeys: true keys: filename: title: "Reported Filename" description: "the filename to be reported as the name of the attached file (set this value as false to disable, default: created automatically)" type: 'string' content: title: "Content" description: "the content of the attached file" type: 'string' path: title: "Include File" description: "the path to a file or an URL if you want to stream the file instead of including it" type: 'string' contentType: title: "Content Type" description: "the optional content type for the attachment (autodetected)" type: 'string' contentDisposition: title: "Disposition" description: "the optional content disposition type for the attachment (default: attachment)" type: 'string' cid: title: "Content ID" description: "the optional content id for using inline images in HTML message source" type: 'string' encoding: title: "Encoding" description: "the content encoding like: base64, hex, binary etc." type: 'string' ### Collection of Templates ------------------------------------------------------ {@schema #templates} ### exports.templates = title: "Email Templates" description: "the possible templates used for sending emails" type: 'object' entries: [email] ### Addressing -------------------------------------------------------- First you can define the sender address using: ``` yaml from: <string> # the address used as sender(often the same as used in transport) replyTo: <string> # address which should be used for replys ``` And you give the addresses to send the mail to. In the following fields: `to`, `cc` and `bcc` you may give a single address or a list of addresses to use. All e-mail addresses can be plain e-mail addresses <EMAIL> or with formatted name (includes unicode support) "<NAME> Name" <<EMAIL>> Content -------------------------------------------------------- The content of the mail consists of an subject line which should be not to long and the body. The body is given as [Markdown](http://alinex.github.io/develop/lang/markdown.html) syntax and supports all possibilities from [report](http://alinex.github.io/node-report/README.md.html#markup%20syntax). This will be converted to a plain text and html version for sending so that the mail client can choose the format to display. You may also give the 'text' and 'html' content as property itself. But keep in mind that within the base properties no markdown conversions are done. In the 'body' it will. Like you see above, you can use handlebar syntax to use some variables from the code. This is possible in subject and body. And you may specify a locale to use for date formatting. You can also define different templates which can be referenced from within the job. Find more examples at [validator](http://alinex.github.io/node-validator/README.md.html#handlebars). Attachments -------------------------------------------------- The key `attachments` is used to add a list of files attached to the email and consists of the following properties: - `path` path to a file or an URL to include - `filename` filename to be reported as the name of the attached file - `content` String, Buffer or a Stream contents for the attachment - `contentType` optional content type for the attachment, if not set will be derived from the filename property - `contentDisposition` optional content disposition type for the attachment, defaults to ‘attachment’ - `cid` optional content id for using inline images in HTML message source - `encoding` If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, binary etc. - `headers` custom headers for the attachment node ###
true
### Configuration =================================================== The configuration consists of two parts: - Email Template - Collection of Templates ### ### Email Template ------------------------------------------------------ {@schema #email} ### exports.email = email = title: "Email Action" description: "the setup for an individual email action" type: 'object' allowedKeys: true keys: base: title: "Base Template" description: "the template used as basis for this one" type: 'string' list: '<<<context:///email>>>' transport: title: "Service Connection" description: "the service connection to send mails through" type: 'or' or: [ title: "Transport URI" description: "the transport method as URI string through which the mail will be send like `<protocol>://<user>:<password>@<server>:<port>`" type: 'string' , title: "Transport Object" description: "the mail transport settings through which the mail will be send" type: 'object' ] retry: title: "Retry" description: "the number of retries to take if sending failed" type: 'object' allowedKeys: true mandatoryKeys: true keys: times: title: "Number of Attempts" description: "the number of maximal attempts to run successfully" type: 'integer' min: 0 default: 1 interval: title: "Time to Wait" description: "the time to wait before retrying a failed attempt" type: 'interval' unit: 'ms' min: 0 default: 5000 default: {times: 1, interval: 5000} from: title: "From" description: "the address emails are send from" type: 'string' replyTo: title: "Reply To" description: "the address to send answers to" type: 'string' optional: true to: title: "To" description: "the address emails are send to" type: 'array' toArray: true entries: type: 'string' cc: title: "Cc" description: "the carbon copy addresses" type: 'array' toArray: true entries: type: 'string' bcc: title: "Bcc" description: "the blind carbon copy addresses" type: 'array' toArray: true entries: type: 'string' locale: title: "Locale Setting" description: "the locale setting for subject and body dates" type: 'string' minLength: 2 maxLength: 5 lowerCase: true match: /^[a-z]{2}(-[a-z]{2})?$/ subject: title: "Subject" description: "the subject line of the generated email" type: 'handlebars' body: title: "Content" description: "the body content of the generated email" type: 'handlebars' attachments: title: "Attachments" description: "the attachments to be included" type: 'array' allowedKeys: true entries: title: "Attachment" description: "the attachment to be included" type: 'object' allowedKeys: true keys: filename: title: "Reported Filename" description: "the filename to be reported as the name of the attached file (set this value as false to disable, default: created automatically)" type: 'string' content: title: "Content" description: "the content of the attached file" type: 'string' path: title: "Include File" description: "the path to a file or an URL if you want to stream the file instead of including it" type: 'string' contentType: title: "Content Type" description: "the optional content type for the attachment (autodetected)" type: 'string' contentDisposition: title: "Disposition" description: "the optional content disposition type for the attachment (default: attachment)" type: 'string' cid: title: "Content ID" description: "the optional content id for using inline images in HTML message source" type: 'string' encoding: title: "Encoding" description: "the content encoding like: base64, hex, binary etc." type: 'string' ### Collection of Templates ------------------------------------------------------ {@schema #templates} ### exports.templates = title: "Email Templates" description: "the possible templates used for sending emails" type: 'object' entries: [email] ### Addressing -------------------------------------------------------- First you can define the sender address using: ``` yaml from: <string> # the address used as sender(often the same as used in transport) replyTo: <string> # address which should be used for replys ``` And you give the addresses to send the mail to. In the following fields: `to`, `cc` and `bcc` you may give a single address or a list of addresses to use. All e-mail addresses can be plain e-mail addresses PI:EMAIL:<EMAIL>END_PI or with formatted name (includes unicode support) "PI:NAME:<NAME>END_PI Name" <PI:EMAIL:<EMAIL>END_PI> Content -------------------------------------------------------- The content of the mail consists of an subject line which should be not to long and the body. The body is given as [Markdown](http://alinex.github.io/develop/lang/markdown.html) syntax and supports all possibilities from [report](http://alinex.github.io/node-report/README.md.html#markup%20syntax). This will be converted to a plain text and html version for sending so that the mail client can choose the format to display. You may also give the 'text' and 'html' content as property itself. But keep in mind that within the base properties no markdown conversions are done. In the 'body' it will. Like you see above, you can use handlebar syntax to use some variables from the code. This is possible in subject and body. And you may specify a locale to use for date formatting. You can also define different templates which can be referenced from within the job. Find more examples at [validator](http://alinex.github.io/node-validator/README.md.html#handlebars). Attachments -------------------------------------------------- The key `attachments` is used to add a list of files attached to the email and consists of the following properties: - `path` path to a file or an URL to include - `filename` filename to be reported as the name of the attached file - `content` String, Buffer or a Stream contents for the attachment - `contentType` optional content type for the attachment, if not set will be derived from the filename property - `contentDisposition` optional content disposition type for the attachment, defaults to ‘attachment’ - `cid` optional content id for using inline images in HTML message source - `encoding` If set and content is string, then encodes the content to a Buffer using the specified encoding. Example values: base64, hex, binary etc. - `headers` custom headers for the attachment node ###
[ { "context": "#\n# server.coffee\n# batman.js\n#\n# Created by Nick Small\n# Copyright 2011, Shopify\n#\n\nconnect = require 'c", "end": 55, "score": 0.9996589422225952, "start": 45, "tag": "NAME", "value": "Nick Small" }, { "context": "t: ['h', \"Host to run HTTP server on\", \"string\", \"127.0.0.1\"]\n port: ['p', \"Port to run HTTP server on", "end": 1687, "score": 0.9986317753791809, "start": 1678, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
src/tools/server.coffee
Shipow/batman
1
# # server.coffee # batman.js # # Created by Nick Small # Copyright 2011, Shopify # connect = require 'connect' path = require 'path' fs = require 'fs' cli = require './cli' utils = require './utils' Batman = require '../lib/dist/batman.node.js' # Creates a connect server. This file is required by the main batman executable, # but it can also be required by clients wishing to extend the connect stack for # their own nefarious purposes. # # Options: # * `build` - Boolean : if truthy the server will transparently compile requests for a .js file from a .coffee file if the .coffee file exists. # * `buildDir` - Path : where to place the built Coffeescript files if `build` is true. Defaults to './build' # * `port` - Number : what port to listen on. getServer = (options) -> # Create a connect server with the # * transparent coffee compilation middleware # * staic file serving middle ware for the current directory # * static file serving at the /batman path for the lib dir of batman # and tell it to serve on the passed port. server = connect.createServer( connect.favicon(), connect.logger(), connect.static(process.cwd()), connect.directory(process.cwd()) ) if options.build server.use utils.CoffeeCompiler(src: process.cwd(), dest: path.join(process.cwd(), options.buildDir)) server.use '/batman', connect.static(path.join(__dirname,'..','lib')) server.listen options.port, options.host return server if typeof RUNNING_IN_BATMAN isnt 'undefined' defaultOptions = utils.getConfig() cli.setUsage('batman server [OPTIONS]') .parse host: ['h', "Host to run HTTP server on", "string", "127.0.0.1"] port: ['p', "Port to run HTTP server on", "number", 1047] build: ['b', "Build coffeescripts on the fly into the build dir (default is ./build) and serve them as js", "boolean", defaultOptions.build] 'build-dir': [false, "Where to store built coffeescript files (default is ./build)", "path", defaultOptions.buildDir] cli.main (args, options) -> # Switch to JS style options.buildDir = options['build-dir'] options.buildDir ||= './build' server = getServer(options) info = "Batman is waiting at http://#{options.host}:#{options.port}" if options.build info += ", and building to #{options.buildDir}." @ok info else module.exports = getServer
33127
# # server.coffee # batman.js # # Created by <NAME> # Copyright 2011, Shopify # connect = require 'connect' path = require 'path' fs = require 'fs' cli = require './cli' utils = require './utils' Batman = require '../lib/dist/batman.node.js' # Creates a connect server. This file is required by the main batman executable, # but it can also be required by clients wishing to extend the connect stack for # their own nefarious purposes. # # Options: # * `build` - Boolean : if truthy the server will transparently compile requests for a .js file from a .coffee file if the .coffee file exists. # * `buildDir` - Path : where to place the built Coffeescript files if `build` is true. Defaults to './build' # * `port` - Number : what port to listen on. getServer = (options) -> # Create a connect server with the # * transparent coffee compilation middleware # * staic file serving middle ware for the current directory # * static file serving at the /batman path for the lib dir of batman # and tell it to serve on the passed port. server = connect.createServer( connect.favicon(), connect.logger(), connect.static(process.cwd()), connect.directory(process.cwd()) ) if options.build server.use utils.CoffeeCompiler(src: process.cwd(), dest: path.join(process.cwd(), options.buildDir)) server.use '/batman', connect.static(path.join(__dirname,'..','lib')) server.listen options.port, options.host return server if typeof RUNNING_IN_BATMAN isnt 'undefined' defaultOptions = utils.getConfig() cli.setUsage('batman server [OPTIONS]') .parse host: ['h', "Host to run HTTP server on", "string", "127.0.0.1"] port: ['p', "Port to run HTTP server on", "number", 1047] build: ['b', "Build coffeescripts on the fly into the build dir (default is ./build) and serve them as js", "boolean", defaultOptions.build] 'build-dir': [false, "Where to store built coffeescript files (default is ./build)", "path", defaultOptions.buildDir] cli.main (args, options) -> # Switch to JS style options.buildDir = options['build-dir'] options.buildDir ||= './build' server = getServer(options) info = "Batman is waiting at http://#{options.host}:#{options.port}" if options.build info += ", and building to #{options.buildDir}." @ok info else module.exports = getServer
true
# # server.coffee # batman.js # # Created by PI:NAME:<NAME>END_PI # Copyright 2011, Shopify # connect = require 'connect' path = require 'path' fs = require 'fs' cli = require './cli' utils = require './utils' Batman = require '../lib/dist/batman.node.js' # Creates a connect server. This file is required by the main batman executable, # but it can also be required by clients wishing to extend the connect stack for # their own nefarious purposes. # # Options: # * `build` - Boolean : if truthy the server will transparently compile requests for a .js file from a .coffee file if the .coffee file exists. # * `buildDir` - Path : where to place the built Coffeescript files if `build` is true. Defaults to './build' # * `port` - Number : what port to listen on. getServer = (options) -> # Create a connect server with the # * transparent coffee compilation middleware # * staic file serving middle ware for the current directory # * static file serving at the /batman path for the lib dir of batman # and tell it to serve on the passed port. server = connect.createServer( connect.favicon(), connect.logger(), connect.static(process.cwd()), connect.directory(process.cwd()) ) if options.build server.use utils.CoffeeCompiler(src: process.cwd(), dest: path.join(process.cwd(), options.buildDir)) server.use '/batman', connect.static(path.join(__dirname,'..','lib')) server.listen options.port, options.host return server if typeof RUNNING_IN_BATMAN isnt 'undefined' defaultOptions = utils.getConfig() cli.setUsage('batman server [OPTIONS]') .parse host: ['h', "Host to run HTTP server on", "string", "127.0.0.1"] port: ['p', "Port to run HTTP server on", "number", 1047] build: ['b', "Build coffeescripts on the fly into the build dir (default is ./build) and serve them as js", "boolean", defaultOptions.build] 'build-dir': [false, "Where to store built coffeescript files (default is ./build)", "path", defaultOptions.buildDir] cli.main (args, options) -> # Switch to JS style options.buildDir = options['build-dir'] options.buildDir ||= './build' server = getServer(options) info = "Batman is waiting at http://#{options.host}:#{options.port}" if options.build info += ", and building to #{options.buildDir}." @ok info else module.exports = getServer
[ { "context": "remote'\n ssh:\n host: 'target', username: 'nikita',\n # private_key_path: '~/.ssh/id_rsa'\n ", "end": 284, "score": 0.9996335506439209, "start": 278, "tag": "USERNAME", "value": "nikita" }, { "context": "rivate_key_path: '~/.ssh/id_rsa'\n password: 'secret'\n ]\n", "end": 352, "score": 0.9995735883712769, "start": 346, "tag": "PASSWORD", "value": "secret" } ]
packages/system/env/info_centos6/test.coffee
wdavidw/node-mecano
0
module.exports = tags: system_info_disks: false system_info_os: true expect: os: arch: 'x86_64' distribution: 'centos' linux_version: /5\.10\.\d+/ version: '6.10' config: [ label: 'remote' ssh: host: 'target', username: 'nikita', # private_key_path: '~/.ssh/id_rsa' password: 'secret' ]
190062
module.exports = tags: system_info_disks: false system_info_os: true expect: os: arch: 'x86_64' distribution: 'centos' linux_version: /5\.10\.\d+/ version: '6.10' config: [ label: 'remote' ssh: host: 'target', username: 'nikita', # private_key_path: '~/.ssh/id_rsa' password: '<PASSWORD>' ]
true
module.exports = tags: system_info_disks: false system_info_os: true expect: os: arch: 'x86_64' distribution: 'centos' linux_version: /5\.10\.\d+/ version: '6.10' config: [ label: 'remote' ssh: host: 'target', username: 'nikita', # private_key_path: '~/.ssh/id_rsa' password: 'PI:PASSWORD:<PASSWORD>END_PI' ]
[ { "context": "\"></label>\n <label>Password <input type=\"password\" name=\"password\"></label>\n <button>Sign ", "end": 2115, "score": 0.9888935685157776, "start": 2107, "tag": "PASSWORD", "value": "password" }, { "context": " <label>Password <input type=\"password\" name=\"password\"></label>\n <button>Sign Me Up</button>\n ", "end": 2131, "score": 0.7683659791946411, "start": 2123, "tag": "PASSWORD", "value": "password" }, { "context": "topic: (browser)->\n browser.fill(\"Email\", \"armbiter@zombies\").fill(\"Password\", \"br41nz\").\n pressButt", "end": 4443, "score": 0.9998267292976379, "start": 4427, "tag": "EMAIL", "value": "armbiter@zombies" }, { "context": "ll(\"Email\", \"armbiter@zombies\").fill(\"Password\", \"br41nz\").\n pressButton \"Sign Me Up\", @callback\n", "end": 4470, "score": 0.9991790652275085, "start": 4464, "tag": "PASSWORD", "value": "br41nz" } ]
spec/script-spec.coffee
djanowski/zombie
0
require "./helpers" { vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows") brains.get "/script/context", (req, res)-> res.send """ <script>var foo = 1;</script> <script>foo = foo + 1;</script> <script>document.title = foo;</script> """ brains.get "/script/order", (req, res)-> res.send """ <html> <head> <title>Zero</title> <script src="/script/order.js"></script> </head> <body> <script> document.title = document.title + "Two";</script> </body> </html> """ brains.get "/script/order.js", (req, res)-> res.send "document.title = document.title + 'One'"; brains.get "/dead", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> </head> <body> <script> $(function() { document.title = "The Dead" }); </script> </body> </html> """ brains.get "/script/write", (req, res)-> res.send """ <html> <head> <script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script> </head> <body> <script> $(function() { document.title = "Script document.write" }); </script> </body> </html> """ brains.get "/script/append", (req, res)-> res.send """ <html> <head> <script> var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '/jquery.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s); </script> </head> <body> <script> $(function() { document.title = "Script appendChild" }); </script> </body> </html> """ brains.get "/living", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/app.js"></script> </head> <body> <div id="main"> <a href="/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="password" name="password"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/") }); """ vows.describe("Scripts").addBatch( "script context": zombie.wants "http://localhost:3003/script/context" "should be shared by all scripts": (browser)-> assert.equal browser.text("title"), "2" "script order": zombie.wants "http://localhost:3003/script/order" "should run scripts in order regardless of source": (browser)-> assert.equal browser.text("title"), "ZeroOneTwo" "adding script using document.write": zombie.wants "http://localhost:3003/script/write" "should run script": (browser)-> assert.equal browser.document.title, "Script document.write" "adding script using appendChild": zombie.wants "http://localhost:3003/script/append" "should run script": (browser)-> assert.equal browser.document.title, "Script appendChild" "run without scripts": topic: -> browser = new zombie.Browser(runScripts: false) browser.wants "http://localhost:3003/script/order", @callback "should not run scripts": (browser)-> assert.equal browser.document.title, "Zero" "run app": zombie.wants "http://localhost:3003/living" "should execute route": (browser)-> assert.equal browser.document.title, "The Living" "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "move around": topic: (browser)-> browser.visit browser.location.href + "dead", @callback "should execute route": (browser)-> assert.equal browser.text("#main"), "The Living Dead" "should change location": (browser)-> assert.equal browser.location.href, "http://localhost:3003/living#/dead" "live events": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.fill("Email", "armbiter@zombies").fill("Password", "br41nz"). pressButton "Sign Me Up", @callback "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "should process event": (browser)-> assert.equal browser.document.title, "Signed up" "evaluate": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.evaluate "document.title" "should evaluate in context and return value": (title)-> assert.equal title, "The Living" ).export(module)
216194
require "./helpers" { vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows") brains.get "/script/context", (req, res)-> res.send """ <script>var foo = 1;</script> <script>foo = foo + 1;</script> <script>document.title = foo;</script> """ brains.get "/script/order", (req, res)-> res.send """ <html> <head> <title>Zero</title> <script src="/script/order.js"></script> </head> <body> <script> document.title = document.title + "Two";</script> </body> </html> """ brains.get "/script/order.js", (req, res)-> res.send "document.title = document.title + 'One'"; brains.get "/dead", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> </head> <body> <script> $(function() { document.title = "The Dead" }); </script> </body> </html> """ brains.get "/script/write", (req, res)-> res.send """ <html> <head> <script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script> </head> <body> <script> $(function() { document.title = "Script document.write" }); </script> </body> </html> """ brains.get "/script/append", (req, res)-> res.send """ <html> <head> <script> var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '/jquery.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s); </script> </head> <body> <script> $(function() { document.title = "Script appendChild" }); </script> </body> </html> """ brains.get "/living", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/app.js"></script> </head> <body> <div id="main"> <a href="/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="<PASSWORD>" name="<PASSWORD>"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/") }); """ vows.describe("Scripts").addBatch( "script context": zombie.wants "http://localhost:3003/script/context" "should be shared by all scripts": (browser)-> assert.equal browser.text("title"), "2" "script order": zombie.wants "http://localhost:3003/script/order" "should run scripts in order regardless of source": (browser)-> assert.equal browser.text("title"), "ZeroOneTwo" "adding script using document.write": zombie.wants "http://localhost:3003/script/write" "should run script": (browser)-> assert.equal browser.document.title, "Script document.write" "adding script using appendChild": zombie.wants "http://localhost:3003/script/append" "should run script": (browser)-> assert.equal browser.document.title, "Script appendChild" "run without scripts": topic: -> browser = new zombie.Browser(runScripts: false) browser.wants "http://localhost:3003/script/order", @callback "should not run scripts": (browser)-> assert.equal browser.document.title, "Zero" "run app": zombie.wants "http://localhost:3003/living" "should execute route": (browser)-> assert.equal browser.document.title, "The Living" "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "move around": topic: (browser)-> browser.visit browser.location.href + "dead", @callback "should execute route": (browser)-> assert.equal browser.text("#main"), "The Living Dead" "should change location": (browser)-> assert.equal browser.location.href, "http://localhost:3003/living#/dead" "live events": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.fill("Email", "<EMAIL>").fill("Password", "<PASSWORD>"). pressButton "Sign Me Up", @callback "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "should process event": (browser)-> assert.equal browser.document.title, "Signed up" "evaluate": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.evaluate "document.title" "should evaluate in context and return value": (title)-> assert.equal title, "The Living" ).export(module)
true
require "./helpers" { vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows") brains.get "/script/context", (req, res)-> res.send """ <script>var foo = 1;</script> <script>foo = foo + 1;</script> <script>document.title = foo;</script> """ brains.get "/script/order", (req, res)-> res.send """ <html> <head> <title>Zero</title> <script src="/script/order.js"></script> </head> <body> <script> document.title = document.title + "Two";</script> </body> </html> """ brains.get "/script/order.js", (req, res)-> res.send "document.title = document.title + 'One'"; brains.get "/dead", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> </head> <body> <script> $(function() { document.title = "The Dead" }); </script> </body> </html> """ brains.get "/script/write", (req, res)-> res.send """ <html> <head> <script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script> </head> <body> <script> $(function() { document.title = "Script document.write" }); </script> </body> </html> """ brains.get "/script/append", (req, res)-> res.send """ <html> <head> <script> var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = '/jquery.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s); </script> </head> <body> <script> $(function() { document.title = "Script appendChild" }); </script> </body> </html> """ brains.get "/living", (req, res)-> res.send """ <html> <head> <script src="/jquery.js"></script> <script src="/sammy.js"></script> <script src="/app.js"></script> </head> <body> <div id="main"> <a href="/dead">Kill</a> <form action="#/dead" method="post"> <label>Email <input type="text" name="email"></label> <label>Password <input type="PI:PASSWORD:<PASSWORD>END_PI" name="PI:PASSWORD:<PASSWORD>END_PI"></label> <button>Sign Me Up</button> </form> </div> <div class="now">Walking Aimlessly</div> </body> </html> """ brains.get "/app.js", (req, res)-> res.send """ Sammy("#main", function(app) { app.get("#/", function(context) { document.title = "The Living"; }); app.get("#/dead", function(context) { context.swap("The Living Dead"); }); app.post("#/dead", function(context) { document.title = "Signed up"; }); }); $(function() { Sammy("#main").run("#/") }); """ vows.describe("Scripts").addBatch( "script context": zombie.wants "http://localhost:3003/script/context" "should be shared by all scripts": (browser)-> assert.equal browser.text("title"), "2" "script order": zombie.wants "http://localhost:3003/script/order" "should run scripts in order regardless of source": (browser)-> assert.equal browser.text("title"), "ZeroOneTwo" "adding script using document.write": zombie.wants "http://localhost:3003/script/write" "should run script": (browser)-> assert.equal browser.document.title, "Script document.write" "adding script using appendChild": zombie.wants "http://localhost:3003/script/append" "should run script": (browser)-> assert.equal browser.document.title, "Script appendChild" "run without scripts": topic: -> browser = new zombie.Browser(runScripts: false) browser.wants "http://localhost:3003/script/order", @callback "should not run scripts": (browser)-> assert.equal browser.document.title, "Zero" "run app": zombie.wants "http://localhost:3003/living" "should execute route": (browser)-> assert.equal browser.document.title, "The Living" "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "move around": topic: (browser)-> browser.visit browser.location.href + "dead", @callback "should execute route": (browser)-> assert.equal browser.text("#main"), "The Living Dead" "should change location": (browser)-> assert.equal browser.location.href, "http://localhost:3003/living#/dead" "live events": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.fill("Email", "PI:EMAIL:<EMAIL>END_PI").fill("Password", "PI:PASSWORD:<PASSWORD>END_PI"). pressButton "Sign Me Up", @callback "should change location": (browser)-> assert.equal browser.location, "http://localhost:3003/living#/" "should process event": (browser)-> assert.equal browser.document.title, "Signed up" "evaluate": zombie.wants "http://localhost:3003/living" topic: (browser)-> browser.evaluate "document.title" "should evaluate in context and return value": (title)-> assert.equal title, "The Living" ).export(module)
[ { "context": "-outline\"\n ,\n \"Atom.Heading\": value: \"Bookmard added!\"\n ]\n ,\n \"Molecule.Navigation\": styl", "end": 263, "score": 0.9321402907371521, "start": 249, "tag": "NAME", "value": "Bookmard added" } ]
source/organisms/dialog.form.coffee
tapquo/atoms-app-kitchensink
0
"use strict" class Form extends Atoms.Organism.Dialog constructor: (attributes = {}) -> attributes.children = [ "Organism.Header": children: [ "Atom.Icon": icon: "ios7-checkmark-outline" , "Atom.Heading": value: "Bookmard added!" ] , "Molecule.Navigation": style: "right", children: [ "Atom.Button": text: "Main" , "Atom.Button": text: "Secondary" ] , "Organism.Section": children: [ "Molecule.Form": children: [ "Atom.Label": value: "Name" , "Atom.Input": type: "text", value: "100 Days of Ice Cream", placeholder: "..." , "Atom.Label": value: "Folder" , "Atom.Select": options: ["Bookmarks Bar", "Friends"] ] ] , "Organism.Footer": children: [ "Molecule.Navigation": style: "-block", children: [ "Atom.Button": text: "Remove", style: "left", callbacks: ["onAccept"] , "Atom.Button": text: "Edit", callbacks: ["onAccept"] , "Atom.Button": text: "Done", style: "default", callbacks: ["onCancel"] ] ] ] super attributes onCancel: -> @hide() false new Form()
152356
"use strict" class Form extends Atoms.Organism.Dialog constructor: (attributes = {}) -> attributes.children = [ "Organism.Header": children: [ "Atom.Icon": icon: "ios7-checkmark-outline" , "Atom.Heading": value: "<NAME>!" ] , "Molecule.Navigation": style: "right", children: [ "Atom.Button": text: "Main" , "Atom.Button": text: "Secondary" ] , "Organism.Section": children: [ "Molecule.Form": children: [ "Atom.Label": value: "Name" , "Atom.Input": type: "text", value: "100 Days of Ice Cream", placeholder: "..." , "Atom.Label": value: "Folder" , "Atom.Select": options: ["Bookmarks Bar", "Friends"] ] ] , "Organism.Footer": children: [ "Molecule.Navigation": style: "-block", children: [ "Atom.Button": text: "Remove", style: "left", callbacks: ["onAccept"] , "Atom.Button": text: "Edit", callbacks: ["onAccept"] , "Atom.Button": text: "Done", style: "default", callbacks: ["onCancel"] ] ] ] super attributes onCancel: -> @hide() false new Form()
true
"use strict" class Form extends Atoms.Organism.Dialog constructor: (attributes = {}) -> attributes.children = [ "Organism.Header": children: [ "Atom.Icon": icon: "ios7-checkmark-outline" , "Atom.Heading": value: "PI:NAME:<NAME>END_PI!" ] , "Molecule.Navigation": style: "right", children: [ "Atom.Button": text: "Main" , "Atom.Button": text: "Secondary" ] , "Organism.Section": children: [ "Molecule.Form": children: [ "Atom.Label": value: "Name" , "Atom.Input": type: "text", value: "100 Days of Ice Cream", placeholder: "..." , "Atom.Label": value: "Folder" , "Atom.Select": options: ["Bookmarks Bar", "Friends"] ] ] , "Organism.Footer": children: [ "Molecule.Navigation": style: "-block", children: [ "Atom.Button": text: "Remove", style: "left", callbacks: ["onAccept"] , "Atom.Button": text: "Edit", callbacks: ["onAccept"] , "Atom.Button": text: "Done", style: "default", callbacks: ["onCancel"] ] ] ] super attributes onCancel: -> @hide() false new Form()
[ { "context": "js\n\n PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.", "end": 215, "score": 0.9998429417610168, "start": 198, "tag": "NAME", "value": "Benjamin Blundell" }, { "context": " PXL.js\n Benjamin Blundell - ben@pxljs.com\n http://pxljs.com\n\n This so", "end": 231, "score": 0.9999314546585083, "start": 218, "tag": "EMAIL", "value": "ben@pxljs.com" } ]
src/core/app.coffee
OniDaito/pxljs
1
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js Benjamin Blundell - ben@pxljs.com http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details **Resources** - http://www.yuiblog.com/blog/2007/06/12/module-pattern/ - http://www.plexical.com/blog/2012/01/25/writing-coffeescript-for-browser-and-nod/ - https://github.com/field/FieldKit.js **TODO** -Not sure we want to make this a listener for events. I suspect we need a keyboard eventor style class and touch eventor class that takes a DOM? ### {Vec2,Vec3, Vec4, Matrix4} = require "../math/math" # Makes this Matrix4 global for this file/closure only {Shader} = require "../gl/shader" {PerspCamera, OrthoCamera} = require "../camera/camera" {makeMouseEmitter, removeMouseEmitter } = require "../interact/mouse" {makeTouchEmitter,removeTouchEmitter} = require "../interact/touch" {makeKeyEmitter, removeKeyEmitter} = require "../interact/key" {Colour} = require "../colour/colour" {PXLError, PXLWarning, PXLLog} = require "../util/log" {makeDebugContext} = require "../util/debug" # OnEachFrame function # Taken from http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html # ## App # The master class in effect. This class takes functions from your application and calls them # as and when needed # TODO - is Context a better name? I think so. We should change it class App # **@constructor** # - **params** - an Object with the following attributes - Required # # - **canvas** - canvas element - Required # - **context** - the object to which this App is attached # - **init** - a Function - Required # - **draw** - a Function - Required # - *update** - a Function # - **error** - a Function # - **delay_start** - a Boolean # - **destroy** - a Function # - **debug** - a Boolean constructor: (params) -> # Parse the basic parameters if not params.canvas? PXLError "No WebGL Canvas Provided" return @debug = if not params.debug? then false else params.debug @app_context = params.context @update = params.update @draw = params.draw @init = params.init @user_shutdown = params.shutdown @canvas = document.getElementById params.canvas if not @canvas PXLError "Trying to create an app on canvas that does not exist" @_pause = if not params.pause? then false else params.pause @height = @canvas.height @width = @canvas.width @_context() @ _context : () -> # Deal with Context loss # TODO - Needs testing! :O cl = (event) => event.preventDefault() # Remove the context from the applications list idx = 0 for idx in PXL.Applications.length if PXL.Applications[i][0] = @ break PXL.Applications.splice idx, 1 @_context() @canvas.addEventListener "webglcontextlost", cl, false @_initContext() if not @gl? # Do we want such emitters by default? Generally we do right? makeMouseEmitter @ makeTouchEmitter @ makeKeyEmitter @ @resizeCanvas(@canvas.width, @canvas.height) if @init? @init.call @app_context # Context time is the time im seconds that this context has run # TODO - Do we still use this really? @contextTime = 0 @startTime = @oldTime = Date.now() window.onEachFrame @,@run if window? # Create the Actual webGL Context. This is called at startup and if the context is lost _initContext : () -> names = ["experimental-webgl", "webgl", "moz-webgl", "webkit-3d"] for name in names @gl = @canvas.getContext name if @gl? @_profile() @_framescounter = 0 # TODO - Actually make a proper debug context :P if @debug PXLLog "creating OpenGL debug context" #makeDebugContext @gl return if not @gl @onError() if @onError? # TODO - Add a signal here perhaps? Event? PXLError "WebGL Not supported or context not found", "App" @ # TODO - Move profiling into some context that never changes? # http://www.quirksmode.org/js/detect.html if navigator? `var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (var i=0;i<data.length;i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera", versionSearch: "Version" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] };` # profile - setup the limits of the current system we are on _profile : () -> @profile = {} @profile.antialias = @gl.getContextAttributes().antialias @profile.aa_size = @gl.getParameter @gl.SAMPLES highp = @gl.getShaderPrecisionFormat(@gl.FRAGMENT_SHADER, @gl.HIGH_FLOAT) @profile.highpSupported = highp.precision != 0 @profile.maxTexSize = @gl.getParameter(@gl.MAX_TEXTURE_SIZE) @profile.maxCubeSize = @gl.getParameter(@gl.MAX_CUBE_MAP_TEXTURE_SIZE) @profile.maxRenderbufferSize = @gl.getParameter(@gl.MAX_RENDERBUFFER_SIZE) @profile.vertexTextureUnits = @gl.getParameter(@gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS) @profile.fragmentTextureUnits = @gl.getParameter(@gl.MAX_TEXTURE_IMAGE_UNITS) @profile.combinedUnits = @gl.getParameter(@gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS) @profile.maxVSattribs = @gl.getParameter(@gl.MAX_VERTEX_ATTRIBS) @profile.maxVertexShaderUniforms = @gl.getParameter(@gl.MAX_VERTEX_UNIFORM_VECTORS) @profile.maxFragmentShaderUniforms = @gl.getParameter(@gl.MAX_FRAGMENT_UNIFORM_VECTORS) @profile.maxVaryings = @gl.getParameter(@gl.MAX_VARYING_VECTORS) @profile.extensions = @gl.getSupportedExtensions() @profile.maxBufferSize = 65536 # Just to make sure we are in a browser before we perform this if navigator? BrowserDetect.init(); @profile.browser = BrowserDetect.browser @profile.os = BrowserDetect.OS @profile.version = BrowserDetect.version # Look for extensions that we like # TODO - Maybe allow these to be passed in as params? Maybe not? # These are here because we make use of them quite a bit se = @gl.getSupportedExtensions() @profile.extensions = [] if 'OES_standard_derivatives' in se @profile.extensions.push 'OES_standard_derivatives' @gl.getExtension 'OES_standard_derivatives' if 'OES_texture_float' in se @profile.extensions.push 'OES_texture_float' @gl.getExtension 'OES_texture_float' # http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser `function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } }` @profile.mobile = detectmob() console.log @profile # **run** - called by the frame function # - returns nothing run : () => if @_pause return if @_framescounter > 0 @_framescounter-- if @_framescounter <= 0 @pause true @_draw @getDelta() # **Pause** - pause or un-psue the draw and update loops if needed. # - **force** - a Boolean - optional # - returns this pause : (force) -> if not force? @_pause = !@_pause else @_pause = force if not @_pause @startTime = Date.now() @oldTime = @startTime @canvas.focus() # Gain the focus so we can process keyboard events # Stop / start emitting events @pauseKeyEmitter @_pause @pauseTouchEmitter @_pause @pauseMouseEmitter @_pause @ # **getDelta** - Returns the dt value in milliseconds # - returns a Number getDelta : () => deltaTime = Date.now() - @oldTime @oldTime = Date.now() return deltaTime # **switchContext** # - **context** - a WebGL Context # - returns this switchContext : (context) -> if context? PXL.Context = context window.GL = context.gl if window? else if PXL.Context != @ PXL.Context = @ # Global GL Function for our contexts window.GL = @gl if window? @ # **resizeCanvas** - Called by the surrounding application javascript should you wish # - **width** - a Number # - **height** - a Number # - returns this resizeCanvas: (width, height) -> @switchContext() if @canvas if @gl @width = width @height = height @canvas.width = width @canvas.height = height @ # _draw - Internal draw function. Calls the user's draw function if provided _draw: (dt) -> @contextTime = Date.now() - @startTime @switchContext() if @draw? @draw.call @app_context, dt # **shutdown** - Stop running the loops and destroy the context # - returns this shutdown : () -> @pause true @user_shutdown.call @app_context if @user_shutdown? # Remove emitters removeMouseEmitter @ removeTouchEmitter @ removeKeyEmitter @ @ # TODO - Perform some kind of deletion / garbage collection module.exports = App : App
68720
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js <NAME> - <EMAIL> http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details **Resources** - http://www.yuiblog.com/blog/2007/06/12/module-pattern/ - http://www.plexical.com/blog/2012/01/25/writing-coffeescript-for-browser-and-nod/ - https://github.com/field/FieldKit.js **TODO** -Not sure we want to make this a listener for events. I suspect we need a keyboard eventor style class and touch eventor class that takes a DOM? ### {Vec2,Vec3, Vec4, Matrix4} = require "../math/math" # Makes this Matrix4 global for this file/closure only {Shader} = require "../gl/shader" {PerspCamera, OrthoCamera} = require "../camera/camera" {makeMouseEmitter, removeMouseEmitter } = require "../interact/mouse" {makeTouchEmitter,removeTouchEmitter} = require "../interact/touch" {makeKeyEmitter, removeKeyEmitter} = require "../interact/key" {Colour} = require "../colour/colour" {PXLError, PXLWarning, PXLLog} = require "../util/log" {makeDebugContext} = require "../util/debug" # OnEachFrame function # Taken from http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html # ## App # The master class in effect. This class takes functions from your application and calls them # as and when needed # TODO - is Context a better name? I think so. We should change it class App # **@constructor** # - **params** - an Object with the following attributes - Required # # - **canvas** - canvas element - Required # - **context** - the object to which this App is attached # - **init** - a Function - Required # - **draw** - a Function - Required # - *update** - a Function # - **error** - a Function # - **delay_start** - a Boolean # - **destroy** - a Function # - **debug** - a Boolean constructor: (params) -> # Parse the basic parameters if not params.canvas? PXLError "No WebGL Canvas Provided" return @debug = if not params.debug? then false else params.debug @app_context = params.context @update = params.update @draw = params.draw @init = params.init @user_shutdown = params.shutdown @canvas = document.getElementById params.canvas if not @canvas PXLError "Trying to create an app on canvas that does not exist" @_pause = if not params.pause? then false else params.pause @height = @canvas.height @width = @canvas.width @_context() @ _context : () -> # Deal with Context loss # TODO - Needs testing! :O cl = (event) => event.preventDefault() # Remove the context from the applications list idx = 0 for idx in PXL.Applications.length if PXL.Applications[i][0] = @ break PXL.Applications.splice idx, 1 @_context() @canvas.addEventListener "webglcontextlost", cl, false @_initContext() if not @gl? # Do we want such emitters by default? Generally we do right? makeMouseEmitter @ makeTouchEmitter @ makeKeyEmitter @ @resizeCanvas(@canvas.width, @canvas.height) if @init? @init.call @app_context # Context time is the time im seconds that this context has run # TODO - Do we still use this really? @contextTime = 0 @startTime = @oldTime = Date.now() window.onEachFrame @,@run if window? # Create the Actual webGL Context. This is called at startup and if the context is lost _initContext : () -> names = ["experimental-webgl", "webgl", "moz-webgl", "webkit-3d"] for name in names @gl = @canvas.getContext name if @gl? @_profile() @_framescounter = 0 # TODO - Actually make a proper debug context :P if @debug PXLLog "creating OpenGL debug context" #makeDebugContext @gl return if not @gl @onError() if @onError? # TODO - Add a signal here perhaps? Event? PXLError "WebGL Not supported or context not found", "App" @ # TODO - Move profiling into some context that never changes? # http://www.quirksmode.org/js/detect.html if navigator? `var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (var i=0;i<data.length;i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera", versionSearch: "Version" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] };` # profile - setup the limits of the current system we are on _profile : () -> @profile = {} @profile.antialias = @gl.getContextAttributes().antialias @profile.aa_size = @gl.getParameter @gl.SAMPLES highp = @gl.getShaderPrecisionFormat(@gl.FRAGMENT_SHADER, @gl.HIGH_FLOAT) @profile.highpSupported = highp.precision != 0 @profile.maxTexSize = @gl.getParameter(@gl.MAX_TEXTURE_SIZE) @profile.maxCubeSize = @gl.getParameter(@gl.MAX_CUBE_MAP_TEXTURE_SIZE) @profile.maxRenderbufferSize = @gl.getParameter(@gl.MAX_RENDERBUFFER_SIZE) @profile.vertexTextureUnits = @gl.getParameter(@gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS) @profile.fragmentTextureUnits = @gl.getParameter(@gl.MAX_TEXTURE_IMAGE_UNITS) @profile.combinedUnits = @gl.getParameter(@gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS) @profile.maxVSattribs = @gl.getParameter(@gl.MAX_VERTEX_ATTRIBS) @profile.maxVertexShaderUniforms = @gl.getParameter(@gl.MAX_VERTEX_UNIFORM_VECTORS) @profile.maxFragmentShaderUniforms = @gl.getParameter(@gl.MAX_FRAGMENT_UNIFORM_VECTORS) @profile.maxVaryings = @gl.getParameter(@gl.MAX_VARYING_VECTORS) @profile.extensions = @gl.getSupportedExtensions() @profile.maxBufferSize = 65536 # Just to make sure we are in a browser before we perform this if navigator? BrowserDetect.init(); @profile.browser = BrowserDetect.browser @profile.os = BrowserDetect.OS @profile.version = BrowserDetect.version # Look for extensions that we like # TODO - Maybe allow these to be passed in as params? Maybe not? # These are here because we make use of them quite a bit se = @gl.getSupportedExtensions() @profile.extensions = [] if 'OES_standard_derivatives' in se @profile.extensions.push 'OES_standard_derivatives' @gl.getExtension 'OES_standard_derivatives' if 'OES_texture_float' in se @profile.extensions.push 'OES_texture_float' @gl.getExtension 'OES_texture_float' # http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser `function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } }` @profile.mobile = detectmob() console.log @profile # **run** - called by the frame function # - returns nothing run : () => if @_pause return if @_framescounter > 0 @_framescounter-- if @_framescounter <= 0 @pause true @_draw @getDelta() # **Pause** - pause or un-psue the draw and update loops if needed. # - **force** - a Boolean - optional # - returns this pause : (force) -> if not force? @_pause = !@_pause else @_pause = force if not @_pause @startTime = Date.now() @oldTime = @startTime @canvas.focus() # Gain the focus so we can process keyboard events # Stop / start emitting events @pauseKeyEmitter @_pause @pauseTouchEmitter @_pause @pauseMouseEmitter @_pause @ # **getDelta** - Returns the dt value in milliseconds # - returns a Number getDelta : () => deltaTime = Date.now() - @oldTime @oldTime = Date.now() return deltaTime # **switchContext** # - **context** - a WebGL Context # - returns this switchContext : (context) -> if context? PXL.Context = context window.GL = context.gl if window? else if PXL.Context != @ PXL.Context = @ # Global GL Function for our contexts window.GL = @gl if window? @ # **resizeCanvas** - Called by the surrounding application javascript should you wish # - **width** - a Number # - **height** - a Number # - returns this resizeCanvas: (width, height) -> @switchContext() if @canvas if @gl @width = width @height = height @canvas.width = width @canvas.height = height @ # _draw - Internal draw function. Calls the user's draw function if provided _draw: (dt) -> @contextTime = Date.now() - @startTime @switchContext() if @draw? @draw.call @app_context, dt # **shutdown** - Stop running the loops and destroy the context # - returns this shutdown : () -> @pause true @user_shutdown.call @app_context if @user_shutdown? # Remove emitters removeMouseEmitter @ removeTouchEmitter @ removeKeyEmitter @ @ # TODO - Perform some kind of deletion / garbage collection module.exports = App : App
true
### .__ _________ __| | \____ \ \/ / | | |_> > <| |__ | __/__/\_ \____/ |__| \/ js PXL.js PI:NAME:<NAME>END_PI - PI:EMAIL:<EMAIL>END_PI http://pxljs.com This software is released under the MIT Licence. See LICENCE.txt for details **Resources** - http://www.yuiblog.com/blog/2007/06/12/module-pattern/ - http://www.plexical.com/blog/2012/01/25/writing-coffeescript-for-browser-and-nod/ - https://github.com/field/FieldKit.js **TODO** -Not sure we want to make this a listener for events. I suspect we need a keyboard eventor style class and touch eventor class that takes a DOM? ### {Vec2,Vec3, Vec4, Matrix4} = require "../math/math" # Makes this Matrix4 global for this file/closure only {Shader} = require "../gl/shader" {PerspCamera, OrthoCamera} = require "../camera/camera" {makeMouseEmitter, removeMouseEmitter } = require "../interact/mouse" {makeTouchEmitter,removeTouchEmitter} = require "../interact/touch" {makeKeyEmitter, removeKeyEmitter} = require "../interact/key" {Colour} = require "../colour/colour" {PXLError, PXLWarning, PXLLog} = require "../util/log" {makeDebugContext} = require "../util/debug" # OnEachFrame function # Taken from http://nokarma.org/2011/02/02/javascript-game-development-the-game-loop/index.html # ## App # The master class in effect. This class takes functions from your application and calls them # as and when needed # TODO - is Context a better name? I think so. We should change it class App # **@constructor** # - **params** - an Object with the following attributes - Required # # - **canvas** - canvas element - Required # - **context** - the object to which this App is attached # - **init** - a Function - Required # - **draw** - a Function - Required # - *update** - a Function # - **error** - a Function # - **delay_start** - a Boolean # - **destroy** - a Function # - **debug** - a Boolean constructor: (params) -> # Parse the basic parameters if not params.canvas? PXLError "No WebGL Canvas Provided" return @debug = if not params.debug? then false else params.debug @app_context = params.context @update = params.update @draw = params.draw @init = params.init @user_shutdown = params.shutdown @canvas = document.getElementById params.canvas if not @canvas PXLError "Trying to create an app on canvas that does not exist" @_pause = if not params.pause? then false else params.pause @height = @canvas.height @width = @canvas.width @_context() @ _context : () -> # Deal with Context loss # TODO - Needs testing! :O cl = (event) => event.preventDefault() # Remove the context from the applications list idx = 0 for idx in PXL.Applications.length if PXL.Applications[i][0] = @ break PXL.Applications.splice idx, 1 @_context() @canvas.addEventListener "webglcontextlost", cl, false @_initContext() if not @gl? # Do we want such emitters by default? Generally we do right? makeMouseEmitter @ makeTouchEmitter @ makeKeyEmitter @ @resizeCanvas(@canvas.width, @canvas.height) if @init? @init.call @app_context # Context time is the time im seconds that this context has run # TODO - Do we still use this really? @contextTime = 0 @startTime = @oldTime = Date.now() window.onEachFrame @,@run if window? # Create the Actual webGL Context. This is called at startup and if the context is lost _initContext : () -> names = ["experimental-webgl", "webgl", "moz-webgl", "webkit-3d"] for name in names @gl = @canvas.getContext name if @gl? @_profile() @_framescounter = 0 # TODO - Actually make a proper debug context :P if @debug PXLLog "creating OpenGL debug context" #makeDebugContext @gl return if not @gl @onError() if @onError? # TODO - Add a signal here perhaps? Event? PXLError "WebGL Not supported or context not found", "App" @ # TODO - Move profiling into some context that never changes? # http://www.quirksmode.org/js/detect.html if navigator? `var BrowserDetect = { init: function () { this.browser = this.searchString(this.dataBrowser) || "An unknown browser"; this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version"; this.OS = this.searchString(this.dataOS) || "an unknown OS"; }, searchString: function (data) { for (var i=0;i<data.length;i++) { var dataString = data[i].string; var dataProp = data[i].prop; this.versionSearchString = data[i].versionSearch || data[i].identity; if (dataString) { if (dataString.indexOf(data[i].subString) != -1) return data[i].identity; } else if (dataProp) return data[i].identity; } }, searchVersion: function (dataString) { var index = dataString.indexOf(this.versionSearchString); if (index == -1) return; return parseFloat(dataString.substring(index+this.versionSearchString.length+1)); }, dataBrowser: [ { string: navigator.userAgent, subString: "Chrome", identity: "Chrome" }, { string: navigator.userAgent, subString: "OmniWeb", versionSearch: "OmniWeb/", identity: "OmniWeb" }, { string: navigator.vendor, subString: "Apple", identity: "Safari", versionSearch: "Version" }, { prop: window.opera, identity: "Opera", versionSearch: "Version" }, { string: navigator.vendor, subString: "iCab", identity: "iCab" }, { string: navigator.vendor, subString: "KDE", identity: "Konqueror" }, { string: navigator.userAgent, subString: "Firefox", identity: "Firefox" }, { string: navigator.vendor, subString: "Camino", identity: "Camino" }, { // for newer Netscapes (6+) string: navigator.userAgent, subString: "Netscape", identity: "Netscape" }, { string: navigator.userAgent, subString: "MSIE", identity: "Explorer", versionSearch: "MSIE" }, { string: navigator.userAgent, subString: "Gecko", identity: "Mozilla", versionSearch: "rv" }, { // for older Netscapes (4-) string: navigator.userAgent, subString: "Mozilla", identity: "Netscape", versionSearch: "Mozilla" } ], dataOS : [ { string: navigator.platform, subString: "Win", identity: "Windows" }, { string: navigator.platform, subString: "Mac", identity: "Mac" }, { string: navigator.userAgent, subString: "iPhone", identity: "iPhone/iPod" }, { string: navigator.platform, subString: "Linux", identity: "Linux" } ] };` # profile - setup the limits of the current system we are on _profile : () -> @profile = {} @profile.antialias = @gl.getContextAttributes().antialias @profile.aa_size = @gl.getParameter @gl.SAMPLES highp = @gl.getShaderPrecisionFormat(@gl.FRAGMENT_SHADER, @gl.HIGH_FLOAT) @profile.highpSupported = highp.precision != 0 @profile.maxTexSize = @gl.getParameter(@gl.MAX_TEXTURE_SIZE) @profile.maxCubeSize = @gl.getParameter(@gl.MAX_CUBE_MAP_TEXTURE_SIZE) @profile.maxRenderbufferSize = @gl.getParameter(@gl.MAX_RENDERBUFFER_SIZE) @profile.vertexTextureUnits = @gl.getParameter(@gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS) @profile.fragmentTextureUnits = @gl.getParameter(@gl.MAX_TEXTURE_IMAGE_UNITS) @profile.combinedUnits = @gl.getParameter(@gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS) @profile.maxVSattribs = @gl.getParameter(@gl.MAX_VERTEX_ATTRIBS) @profile.maxVertexShaderUniforms = @gl.getParameter(@gl.MAX_VERTEX_UNIFORM_VECTORS) @profile.maxFragmentShaderUniforms = @gl.getParameter(@gl.MAX_FRAGMENT_UNIFORM_VECTORS) @profile.maxVaryings = @gl.getParameter(@gl.MAX_VARYING_VECTORS) @profile.extensions = @gl.getSupportedExtensions() @profile.maxBufferSize = 65536 # Just to make sure we are in a browser before we perform this if navigator? BrowserDetect.init(); @profile.browser = BrowserDetect.browser @profile.os = BrowserDetect.OS @profile.version = BrowserDetect.version # Look for extensions that we like # TODO - Maybe allow these to be passed in as params? Maybe not? # These are here because we make use of them quite a bit se = @gl.getSupportedExtensions() @profile.extensions = [] if 'OES_standard_derivatives' in se @profile.extensions.push 'OES_standard_derivatives' @gl.getExtension 'OES_standard_derivatives' if 'OES_texture_float' in se @profile.extensions.push 'OES_texture_float' @gl.getExtension 'OES_texture_float' # http://stackoverflow.com/questions/11381673/javascript-solution-to-detect-mobile-browser `function detectmob() { if( navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ){ return true; } else { return false; } }` @profile.mobile = detectmob() console.log @profile # **run** - called by the frame function # - returns nothing run : () => if @_pause return if @_framescounter > 0 @_framescounter-- if @_framescounter <= 0 @pause true @_draw @getDelta() # **Pause** - pause or un-psue the draw and update loops if needed. # - **force** - a Boolean - optional # - returns this pause : (force) -> if not force? @_pause = !@_pause else @_pause = force if not @_pause @startTime = Date.now() @oldTime = @startTime @canvas.focus() # Gain the focus so we can process keyboard events # Stop / start emitting events @pauseKeyEmitter @_pause @pauseTouchEmitter @_pause @pauseMouseEmitter @_pause @ # **getDelta** - Returns the dt value in milliseconds # - returns a Number getDelta : () => deltaTime = Date.now() - @oldTime @oldTime = Date.now() return deltaTime # **switchContext** # - **context** - a WebGL Context # - returns this switchContext : (context) -> if context? PXL.Context = context window.GL = context.gl if window? else if PXL.Context != @ PXL.Context = @ # Global GL Function for our contexts window.GL = @gl if window? @ # **resizeCanvas** - Called by the surrounding application javascript should you wish # - **width** - a Number # - **height** - a Number # - returns this resizeCanvas: (width, height) -> @switchContext() if @canvas if @gl @width = width @height = height @canvas.width = width @canvas.height = height @ # _draw - Internal draw function. Calls the user's draw function if provided _draw: (dt) -> @contextTime = Date.now() - @startTime @switchContext() if @draw? @draw.call @app_context, dt # **shutdown** - Stop running the loops and destroy the context # - returns this shutdown : () -> @pause true @user_shutdown.call @app_context if @user_shutdown? # Remove emitters removeMouseEmitter @ removeTouchEmitter @ removeKeyEmitter @ @ # TODO - Perform some kind of deletion / garbage collection module.exports = App : App
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9993367791175842, "start": 12, "tag": "NAME", "value": "Joyent" } ]
lib/stream.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. # Backwards-compat with node 0.4.x # old-style streams. Note that the pipe method (the only relevant # part of this class) is overridden in the Readable class. Stream = -> EE.call this return "use strict" module.exports = Stream EE = require("events").EventEmitter util = require("util") util.inherits Stream, EE Stream.Readable = require("_stream_readable") Stream.Writable = require("_stream_writable") Stream.Duplex = require("_stream_duplex") Stream.Transform = require("_stream_transform") Stream.PassThrough = require("_stream_passthrough") Stream.Stream = Stream Stream::pipe = (dest, options) -> ondata = (chunk) -> source.pause() if false is dest.write(chunk) and source.pause if dest.writable return ondrain = -> source.resume() if source.readable and source.resume return # If the 'end' option is not supplied, dest.end() will be called when # source gets the 'end' or 'close' events. Only dest.end() once. onend = -> return if didOnEnd didOnEnd = true dest.end() return onclose = -> return if didOnEnd didOnEnd = true dest.destroy() if util.isFunction(dest.destroy) return # don't leave dangling pipes when there are errors. onerror = (er) -> cleanup() throw er if EE.listenerCount(this, "error") is 0 # Unhandled stream error in pipe. return # remove all the event listeners that were added. cleanup = -> source.removeListener "data", ondata dest.removeListener "drain", ondrain source.removeListener "end", onend source.removeListener "close", onclose source.removeListener "error", onerror dest.removeListener "error", onerror source.removeListener "end", cleanup source.removeListener "close", cleanup dest.removeListener "close", cleanup return source = this source.on "data", ondata dest.on "drain", ondrain if not dest._isStdio and (not options or options.end isnt false) source.on "end", onend source.on "close", onclose didOnEnd = false source.on "error", onerror dest.on "error", onerror source.on "end", cleanup source.on "close", cleanup dest.on "close", cleanup dest.emit "pipe", source # Allow for unix-like usage: A.pipe(B).pipe(C) dest
58137
# 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. # Backwards-compat with node 0.4.x # old-style streams. Note that the pipe method (the only relevant # part of this class) is overridden in the Readable class. Stream = -> EE.call this return "use strict" module.exports = Stream EE = require("events").EventEmitter util = require("util") util.inherits Stream, EE Stream.Readable = require("_stream_readable") Stream.Writable = require("_stream_writable") Stream.Duplex = require("_stream_duplex") Stream.Transform = require("_stream_transform") Stream.PassThrough = require("_stream_passthrough") Stream.Stream = Stream Stream::pipe = (dest, options) -> ondata = (chunk) -> source.pause() if false is dest.write(chunk) and source.pause if dest.writable return ondrain = -> source.resume() if source.readable and source.resume return # If the 'end' option is not supplied, dest.end() will be called when # source gets the 'end' or 'close' events. Only dest.end() once. onend = -> return if didOnEnd didOnEnd = true dest.end() return onclose = -> return if didOnEnd didOnEnd = true dest.destroy() if util.isFunction(dest.destroy) return # don't leave dangling pipes when there are errors. onerror = (er) -> cleanup() throw er if EE.listenerCount(this, "error") is 0 # Unhandled stream error in pipe. return # remove all the event listeners that were added. cleanup = -> source.removeListener "data", ondata dest.removeListener "drain", ondrain source.removeListener "end", onend source.removeListener "close", onclose source.removeListener "error", onerror dest.removeListener "error", onerror source.removeListener "end", cleanup source.removeListener "close", cleanup dest.removeListener "close", cleanup return source = this source.on "data", ondata dest.on "drain", ondrain if not dest._isStdio and (not options or options.end isnt false) source.on "end", onend source.on "close", onclose didOnEnd = false source.on "error", onerror dest.on "error", onerror source.on "end", cleanup source.on "close", cleanup dest.on "close", cleanup dest.emit "pipe", source # Allow for unix-like usage: A.pipe(B).pipe(C) dest
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. # Backwards-compat with node 0.4.x # old-style streams. Note that the pipe method (the only relevant # part of this class) is overridden in the Readable class. Stream = -> EE.call this return "use strict" module.exports = Stream EE = require("events").EventEmitter util = require("util") util.inherits Stream, EE Stream.Readable = require("_stream_readable") Stream.Writable = require("_stream_writable") Stream.Duplex = require("_stream_duplex") Stream.Transform = require("_stream_transform") Stream.PassThrough = require("_stream_passthrough") Stream.Stream = Stream Stream::pipe = (dest, options) -> ondata = (chunk) -> source.pause() if false is dest.write(chunk) and source.pause if dest.writable return ondrain = -> source.resume() if source.readable and source.resume return # If the 'end' option is not supplied, dest.end() will be called when # source gets the 'end' or 'close' events. Only dest.end() once. onend = -> return if didOnEnd didOnEnd = true dest.end() return onclose = -> return if didOnEnd didOnEnd = true dest.destroy() if util.isFunction(dest.destroy) return # don't leave dangling pipes when there are errors. onerror = (er) -> cleanup() throw er if EE.listenerCount(this, "error") is 0 # Unhandled stream error in pipe. return # remove all the event listeners that were added. cleanup = -> source.removeListener "data", ondata dest.removeListener "drain", ondrain source.removeListener "end", onend source.removeListener "close", onclose source.removeListener "error", onerror dest.removeListener "error", onerror source.removeListener "end", cleanup source.removeListener "close", cleanup dest.removeListener "close", cleanup return source = this source.on "data", ondata dest.on "drain", ondrain if not dest._isStdio and (not options or options.end isnt false) source.on "end", onend source.on "close", onclose didOnEnd = false source.on "error", onerror dest.on "error", onerror source.on "end", cleanup source.on "close", cleanup dest.on "close", cleanup dest.emit "pipe", source # Allow for unix-like usage: A.pipe(B).pipe(C) dest
[ { "context": ".user\n check password, String\n\n username = 'sprohaska'\n email = 'sprohaska@gmail.com'\n ldapUserna", "end": 991, "score": 0.9996997714042664, "start": 982, "tag": "USERNAME", "value": "sprohaska" }, { "context": ", String\n\n username = 'sprohaska'\n email = 'sprohaska@gmail.com'\n ldapUsername = 'bob'\n ldapgroups = []\n ", "end": 1025, "score": 0.9999293088912964, "start": 1006, "tag": "EMAIL", "value": "sprohaska@gmail.com" }, { "context": "email = 'sprohaska@gmail.com'\n ldapUsername = 'bob'\n ldapgroups = []\n ensureUser username, pas", "end": 1050, "score": 0.9992339015007019, "start": 1047, "tag": "USERNAME", "value": "bob" }, { "context": "roups\n reassignRepos username\n\n username = 'alovelace'\n email = 'homberg@zib.de'\n ldapUsername = ", "end": 1192, "score": 0.9996711611747742, "start": 1183, "tag": "USERNAME", "value": "alovelace" }, { "context": "username\n\n username = 'alovelace'\n email = 'homberg@zib.de'\n ldapUsername = 'alice'\n ldapgroups = ['ou", "end": 1221, "score": 0.9999290108680725, "start": 1207, "tag": "EMAIL", "value": "homberg@zib.de" }, { "context": "\n email = 'homberg@zib.de'\n ldapUsername = 'alice'\n ldapgroups = ['ou_ag-alice', 'srv_lm1']\n ", "end": 1248, "score": 0.9990531802177429, "start": 1243, "tag": "USERNAME", "value": "alice" } ]
apps/nog-app/meteor/testinguser.coffee
nogproject/nog
0
if not Meteor.settings?.public?.optTestingUsers console.log '[app] Testing users are disabled.' return reassignRepos = (username) -> # Update repos in case the testing user got lost. if (user = Meteor.users.findOne {username})? NogContent.repos.find({ owner: username, ownerId: {$ne: user._id} }).map (repo) -> NogContent.repos.update {_id: repo._id}, {$set: {ownerId: user._id}} ensureUser = (username, password, email, ldapUsername, ldapgroups) -> if not Meteor.users.findOne({username})? uid = Accounts.createUser {username, password, email} console.log "[testinguser] Created user #{username}." Roles.addUsersToRoles(uid, 'users') Meteor.users.update({ username }, { $set: { 'services.gittest.username': ldapUsername, 'services.gittest.ldapgroups': ldapgroups, }}) if Meteor.isServer Meteor.startup -> password = Meteor.settings.public?.tests?.passwords?.user check password, String username = 'sprohaska' email = 'sprohaska@gmail.com' ldapUsername = 'bob' ldapgroups = [] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username username = 'alovelace' email = 'homberg@zib.de' ldapUsername = 'alice' ldapgroups = ['ou_ag-alice', 'srv_lm1'] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username
37239
if not Meteor.settings?.public?.optTestingUsers console.log '[app] Testing users are disabled.' return reassignRepos = (username) -> # Update repos in case the testing user got lost. if (user = Meteor.users.findOne {username})? NogContent.repos.find({ owner: username, ownerId: {$ne: user._id} }).map (repo) -> NogContent.repos.update {_id: repo._id}, {$set: {ownerId: user._id}} ensureUser = (username, password, email, ldapUsername, ldapgroups) -> if not Meteor.users.findOne({username})? uid = Accounts.createUser {username, password, email} console.log "[testinguser] Created user #{username}." Roles.addUsersToRoles(uid, 'users') Meteor.users.update({ username }, { $set: { 'services.gittest.username': ldapUsername, 'services.gittest.ldapgroups': ldapgroups, }}) if Meteor.isServer Meteor.startup -> password = Meteor.settings.public?.tests?.passwords?.user check password, String username = 'sprohaska' email = '<EMAIL>' ldapUsername = 'bob' ldapgroups = [] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username username = 'alovelace' email = '<EMAIL>' ldapUsername = 'alice' ldapgroups = ['ou_ag-alice', 'srv_lm1'] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username
true
if not Meteor.settings?.public?.optTestingUsers console.log '[app] Testing users are disabled.' return reassignRepos = (username) -> # Update repos in case the testing user got lost. if (user = Meteor.users.findOne {username})? NogContent.repos.find({ owner: username, ownerId: {$ne: user._id} }).map (repo) -> NogContent.repos.update {_id: repo._id}, {$set: {ownerId: user._id}} ensureUser = (username, password, email, ldapUsername, ldapgroups) -> if not Meteor.users.findOne({username})? uid = Accounts.createUser {username, password, email} console.log "[testinguser] Created user #{username}." Roles.addUsersToRoles(uid, 'users') Meteor.users.update({ username }, { $set: { 'services.gittest.username': ldapUsername, 'services.gittest.ldapgroups': ldapgroups, }}) if Meteor.isServer Meteor.startup -> password = Meteor.settings.public?.tests?.passwords?.user check password, String username = 'sprohaska' email = 'PI:EMAIL:<EMAIL>END_PI' ldapUsername = 'bob' ldapgroups = [] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username username = 'alovelace' email = 'PI:EMAIL:<EMAIL>END_PI' ldapUsername = 'alice' ldapgroups = ['ou_ag-alice', 'srv_lm1'] ensureUser username, password, email, ldapUsername, ldapgroups reassignRepos username
[ { "context": "on', ->\n it 'should authenticate with password \\'hunter2\\''\n it 'should fail authentication with password", "end": 237, "score": 0.9572219252586365, "start": 230, "tag": "PASSWORD", "value": "hunter2" }, { "context": "\n it 'should fail authentication with password \\'foobar\\''\n\n\n", "end": 296, "score": 0.8569827675819397, "start": 290, "tag": "PASSWORD", "value": "foobar" } ]
test/users.coffee
kvchen/mizzen
1
expect = require('chai').expect mongoose = require 'mongoose' nconf = require 'nconf' app = require '../app' User = require '../app/models/user' describe 'User authentication', -> it 'should authenticate with password \'hunter2\'' it 'should fail authentication with password \'foobar\''
188192
expect = require('chai').expect mongoose = require 'mongoose' nconf = require 'nconf' app = require '../app' User = require '../app/models/user' describe 'User authentication', -> it 'should authenticate with password \'<PASSWORD>\'' it 'should fail authentication with password \'<PASSWORD>\''
true
expect = require('chai').expect mongoose = require 'mongoose' nconf = require 'nconf' app = require '../app' User = require '../app/models/user' describe 'User authentication', -> it 'should authenticate with password \'PI:PASSWORD:<PASSWORD>END_PI\'' it 'should fail authentication with password \'PI:PASSWORD:<PASSWORD>END_PI\''
[ { "context": "der.\n#\n# The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub,\n# and released und", "end": 678, "score": 0.7852544188499451, "start": 669, "tag": "USERNAME", "value": "jashkenas" }, { "context": "), a port for the **POSIX shell**.\n# Both are by [Ryan Tomayko](http://github.com/rtomayko). If Python's more\n# ", "end": 1398, "score": 0.998022198677063, "start": 1386, "tag": "NAME", "value": "Ryan Tomayko" }, { "context": "*.\n# Both are by [Ryan Tomayko](http://github.com/rtomayko). If Python's more\n# your speed, take a look at [", "end": 1426, "score": 0.9941210746765137, "start": 1418, "tag": "USERNAME", "value": "rtomayko" }, { "context": "). If Python's more\n# your speed, take a look at [Nick Fitzgerald](http://github.com/fitzgen)'s\n# [Pycco](http://fi", "end": 1491, "score": 0.9997372627258301, "start": 1476, "tag": "NAME", "value": "Nick Fitzgerald" }, { "context": "ake a look at [Nick Fitzgerald](http://github.com/fitzgen)'s\n# [Pycco](http://fitzgen.github.com/pycco/).\n\n", "end": 1518, "score": 0.9996502995491028, "start": 1511, "tag": "USERNAME", "value": "fitzgen" }, { "context": ", -> callback()\n\n# Micro-templating, originally by John Resig, borrowed by way of\n# [Underscore.js](http://docu", "end": 6672, "score": 0.9977421164512634, "start": 6662, "tag": "NAME", "value": "John Resig" } ]
dev/node_modules/docco/src/docco.coffee
stevenyvr987/evergreen-mobile-opac
6
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style # documentation generator. It produces HTML that displays your comments # alongside your code. Comments are passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Pygments](http://pygments.org/) syntax highlighting. # This page is the result of running Docco against its own source file. # # If you install Docco, you can run it from the command-line: # # docco src/*.coffee # # ...will generate linked HTML documentation for the named source files, saving # it into a `docs` folder. # # The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub, # and released under the MIT license. # # To install Docco, first make sure you have [Node.js](http://nodejs.org/), # [Pygments](http://pygments.org/) (install the latest dev version of Pygments # from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and # [CoffeeScript](http://coffeescript.org/). Then, with NPM: # # sudo npm install docco # # If **Node.js** doesn't run on your platform, or you'd prefer a more convenient # package, get [Rocco](http://rtomayko.github.com/rocco/), the Ruby port that's # available as a gem. If you're writing shell scripts, try # [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**. # Both are by [Ryan Tomayko](http://github.com/rtomayko). If Python's more # your speed, take a look at [Nick Fitzgerald](http://github.com/fitzgen)'s # [Pycco](http://fitzgen.github.com/pycco/). #### Main Documentation Generation Functions # Generate the documentation for a source file by reading it in, splitting it # up into comment/code sections, highlighting them for the appropriate language, # and merging them into an HTML template. generate_documentation = (source, callback) -> fs.readFile source, "utf-8", (error, code) -> throw error if error sections = parse source, code highlight source, sections, -> generate_html source, sections callback() # Given a string of source code, parse out each comment and the code that # follows it, and create an individual **section** for it. # Sections take the form: # # { # docs_text: ... # docs_html: ... # code_text: ... # code_html: ... # } # parse = (source, code) -> lines = code.split '\n' sections = [] language = get_language source has_code = docs_text = code_text = '' save = (docs, code) -> sections.push docs_text: docs, code_text: code for line in lines if line.match(language.comment_matcher) and not line.match(language.comment_filter) if has_code save docs_text, code_text has_code = docs_text = code_text = '' docs_text += line.replace(language.comment_matcher, '') + '\n' else has_code = yes code_text += line + '\n' save docs_text, code_text sections # Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio, # and runs the text of its corresponding comment through **Markdown**, using the # **Github-flavored-Markdown** modification of [Showdown.js](http://attacklab.net/showdown/). # # We process the entire file in a single call to Pygments by inserting little # marker comments between each section and then splitting the result string # wherever our markers occur. highlight = (source, sections, callback) -> language = get_language source pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8'] output = '' pygments.stderr.addListener 'data', (error) -> console.error error if error pygments.stdout.addListener 'data', (result) -> output += result if result pygments.addListener 'exit', -> output = output.replace(highlight_start, '').replace(highlight_end, '') fragments = output.split language.divider_html for section, i in sections section.code_html = highlight_start + fragments[i] + highlight_end section.docs_html = showdown.makeHtml section.docs_text callback() pygments.stdin.write((section.code_text for section in sections).join(language.divider_text)) pygments.stdin.end() # Once all of the code is finished highlighting, we can generate the HTML file # and write out the documentation. Pass the completed sections into the template # found in `resources/docco.jst` generate_html = (source, sections) -> title = path.basename source dest = destination source html = docco_template { title: title, sections: sections, sources: sources, path: path, destination: destination } console.log "docco: #{source} -> #{dest}" fs.writeFile dest, html #### Helpers & Setup # Require our external dependencies, including **Showdown.js** # (the JavaScript implementation of Markdown). fs = require 'fs' path = require 'path' showdown = require('./../vendor/showdown').Showdown {spawn, exec} = require 'child_process' # A list of the languages that Docco supports, mapping the file extension to # the name of the Pygments lexer and the symbol that indicates a comment. To # add another language to Docco's repertoire, add it here. languages = '.coffee': name: 'coffee-script', symbol: '#' '.js': name: 'javascript', symbol: '//' '.rb': name: 'ruby', symbol: '#' '.py': name: 'python', symbol: '#' # Build out the appropriate matchers and delimiters for each language. for ext, l of languages # Does the line begin with a comment? l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?') # Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix)) # and interpolations... l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)') # The dividing token we feed into Pygments, to delimit the boundaries between # sections. l.divider_text = '\n' + l.symbol + 'DIVIDER\n' # The mirror of `divider_text` that we expect Pygments to return. We can split # on this to recover the original sections. # Note: the class is "c" for Python and "c1" for the other languages l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*') # Get the current language we're documenting, based on the extension. get_language = (source) -> languages[path.extname(source)] # Compute the destination HTML path for an input source file path. If the source # is `lib/example.coffee`, the HTML will be at `docs/example.html` destination = (filepath) -> 'docs/' + path.basename(filepath, path.extname(filepath)) + '.html' # Ensure that the destination directory exists. ensure_directory = (callback) -> exec 'mkdir -p docs', -> callback() # Micro-templating, originally by John Resig, borrowed by way of # [Underscore.js](http://documentcloud.github.com/underscore/). template = (str) -> new Function 'obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, " ") .replace(/'(?=[^<]*%>)/g,"\t") .split("'").join("\\'") .split("\t").join("'") .replace(/<%=(.+?)%>/g, "',$1,'") .split('<%').join("');") .split('%>').join("p.push('") + "');}return p.join('');" # Create the template that we will use to generate the Docco HTML page. docco_template = template fs.readFileSync(__dirname + '/../resources/docco.jst').toString() # The CSS styles we'd like to apply to the documentation. docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString() # The start of each Pygments highlight block. highlight_start = '<div class="highlight"><pre>' # The end of each Pygments highlight block. highlight_end = '</pre></div>' # Run the script. # For each source file passed in as an argument, generate the documentation. sources = process.ARGV.sort() if sources.length ensure_directory -> fs.writeFile 'docs/docco.css', docco_styles files = sources.slice(0) next_file = -> generate_documentation files.shift(), next_file if files.length next_file()
55361
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style # documentation generator. It produces HTML that displays your comments # alongside your code. Comments are passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Pygments](http://pygments.org/) syntax highlighting. # This page is the result of running Docco against its own source file. # # If you install Docco, you can run it from the command-line: # # docco src/*.coffee # # ...will generate linked HTML documentation for the named source files, saving # it into a `docs` folder. # # The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub, # and released under the MIT license. # # To install Docco, first make sure you have [Node.js](http://nodejs.org/), # [Pygments](http://pygments.org/) (install the latest dev version of Pygments # from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and # [CoffeeScript](http://coffeescript.org/). Then, with NPM: # # sudo npm install docco # # If **Node.js** doesn't run on your platform, or you'd prefer a more convenient # package, get [Rocco](http://rtomayko.github.com/rocco/), the Ruby port that's # available as a gem. If you're writing shell scripts, try # [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**. # Both are by [<NAME>](http://github.com/rtomayko). If Python's more # your speed, take a look at [<NAME>](http://github.com/fitzgen)'s # [Pycco](http://fitzgen.github.com/pycco/). #### Main Documentation Generation Functions # Generate the documentation for a source file by reading it in, splitting it # up into comment/code sections, highlighting them for the appropriate language, # and merging them into an HTML template. generate_documentation = (source, callback) -> fs.readFile source, "utf-8", (error, code) -> throw error if error sections = parse source, code highlight source, sections, -> generate_html source, sections callback() # Given a string of source code, parse out each comment and the code that # follows it, and create an individual **section** for it. # Sections take the form: # # { # docs_text: ... # docs_html: ... # code_text: ... # code_html: ... # } # parse = (source, code) -> lines = code.split '\n' sections = [] language = get_language source has_code = docs_text = code_text = '' save = (docs, code) -> sections.push docs_text: docs, code_text: code for line in lines if line.match(language.comment_matcher) and not line.match(language.comment_filter) if has_code save docs_text, code_text has_code = docs_text = code_text = '' docs_text += line.replace(language.comment_matcher, '') + '\n' else has_code = yes code_text += line + '\n' save docs_text, code_text sections # Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio, # and runs the text of its corresponding comment through **Markdown**, using the # **Github-flavored-Markdown** modification of [Showdown.js](http://attacklab.net/showdown/). # # We process the entire file in a single call to Pygments by inserting little # marker comments between each section and then splitting the result string # wherever our markers occur. highlight = (source, sections, callback) -> language = get_language source pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8'] output = '' pygments.stderr.addListener 'data', (error) -> console.error error if error pygments.stdout.addListener 'data', (result) -> output += result if result pygments.addListener 'exit', -> output = output.replace(highlight_start, '').replace(highlight_end, '') fragments = output.split language.divider_html for section, i in sections section.code_html = highlight_start + fragments[i] + highlight_end section.docs_html = showdown.makeHtml section.docs_text callback() pygments.stdin.write((section.code_text for section in sections).join(language.divider_text)) pygments.stdin.end() # Once all of the code is finished highlighting, we can generate the HTML file # and write out the documentation. Pass the completed sections into the template # found in `resources/docco.jst` generate_html = (source, sections) -> title = path.basename source dest = destination source html = docco_template { title: title, sections: sections, sources: sources, path: path, destination: destination } console.log "docco: #{source} -> #{dest}" fs.writeFile dest, html #### Helpers & Setup # Require our external dependencies, including **Showdown.js** # (the JavaScript implementation of Markdown). fs = require 'fs' path = require 'path' showdown = require('./../vendor/showdown').Showdown {spawn, exec} = require 'child_process' # A list of the languages that Docco supports, mapping the file extension to # the name of the Pygments lexer and the symbol that indicates a comment. To # add another language to Docco's repertoire, add it here. languages = '.coffee': name: 'coffee-script', symbol: '#' '.js': name: 'javascript', symbol: '//' '.rb': name: 'ruby', symbol: '#' '.py': name: 'python', symbol: '#' # Build out the appropriate matchers and delimiters for each language. for ext, l of languages # Does the line begin with a comment? l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?') # Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix)) # and interpolations... l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)') # The dividing token we feed into Pygments, to delimit the boundaries between # sections. l.divider_text = '\n' + l.symbol + 'DIVIDER\n' # The mirror of `divider_text` that we expect Pygments to return. We can split # on this to recover the original sections. # Note: the class is "c" for Python and "c1" for the other languages l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*') # Get the current language we're documenting, based on the extension. get_language = (source) -> languages[path.extname(source)] # Compute the destination HTML path for an input source file path. If the source # is `lib/example.coffee`, the HTML will be at `docs/example.html` destination = (filepath) -> 'docs/' + path.basename(filepath, path.extname(filepath)) + '.html' # Ensure that the destination directory exists. ensure_directory = (callback) -> exec 'mkdir -p docs', -> callback() # Micro-templating, originally by <NAME>, borrowed by way of # [Underscore.js](http://documentcloud.github.com/underscore/). template = (str) -> new Function 'obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, " ") .replace(/'(?=[^<]*%>)/g,"\t") .split("'").join("\\'") .split("\t").join("'") .replace(/<%=(.+?)%>/g, "',$1,'") .split('<%').join("');") .split('%>').join("p.push('") + "');}return p.join('');" # Create the template that we will use to generate the Docco HTML page. docco_template = template fs.readFileSync(__dirname + '/../resources/docco.jst').toString() # The CSS styles we'd like to apply to the documentation. docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString() # The start of each Pygments highlight block. highlight_start = '<div class="highlight"><pre>' # The end of each Pygments highlight block. highlight_end = '</pre></div>' # Run the script. # For each source file passed in as an argument, generate the documentation. sources = process.ARGV.sort() if sources.length ensure_directory -> fs.writeFile 'docs/docco.css', docco_styles files = sources.slice(0) next_file = -> generate_documentation files.shift(), next_file if files.length next_file()
true
# **Docco** is a quick-and-dirty, hundred-line-long, literate-programming-style # documentation generator. It produces HTML that displays your comments # alongside your code. Comments are passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Pygments](http://pygments.org/) syntax highlighting. # This page is the result of running Docco against its own source file. # # If you install Docco, you can run it from the command-line: # # docco src/*.coffee # # ...will generate linked HTML documentation for the named source files, saving # it into a `docs` folder. # # The [source for Docco](http://github.com/jashkenas/docco) is available on GitHub, # and released under the MIT license. # # To install Docco, first make sure you have [Node.js](http://nodejs.org/), # [Pygments](http://pygments.org/) (install the latest dev version of Pygments # from [its Mercurial repo](http://dev.pocoo.org/hg/pygments-main)), and # [CoffeeScript](http://coffeescript.org/). Then, with NPM: # # sudo npm install docco # # If **Node.js** doesn't run on your platform, or you'd prefer a more convenient # package, get [Rocco](http://rtomayko.github.com/rocco/), the Ruby port that's # available as a gem. If you're writing shell scripts, try # [Shocco](http://rtomayko.github.com/shocco/), a port for the **POSIX shell**. # Both are by [PI:NAME:<NAME>END_PI](http://github.com/rtomayko). If Python's more # your speed, take a look at [PI:NAME:<NAME>END_PI](http://github.com/fitzgen)'s # [Pycco](http://fitzgen.github.com/pycco/). #### Main Documentation Generation Functions # Generate the documentation for a source file by reading it in, splitting it # up into comment/code sections, highlighting them for the appropriate language, # and merging them into an HTML template. generate_documentation = (source, callback) -> fs.readFile source, "utf-8", (error, code) -> throw error if error sections = parse source, code highlight source, sections, -> generate_html source, sections callback() # Given a string of source code, parse out each comment and the code that # follows it, and create an individual **section** for it. # Sections take the form: # # { # docs_text: ... # docs_html: ... # code_text: ... # code_html: ... # } # parse = (source, code) -> lines = code.split '\n' sections = [] language = get_language source has_code = docs_text = code_text = '' save = (docs, code) -> sections.push docs_text: docs, code_text: code for line in lines if line.match(language.comment_matcher) and not line.match(language.comment_filter) if has_code save docs_text, code_text has_code = docs_text = code_text = '' docs_text += line.replace(language.comment_matcher, '') + '\n' else has_code = yes code_text += line + '\n' save docs_text, code_text sections # Highlights a single chunk of CoffeeScript code, using **Pygments** over stdio, # and runs the text of its corresponding comment through **Markdown**, using the # **Github-flavored-Markdown** modification of [Showdown.js](http://attacklab.net/showdown/). # # We process the entire file in a single call to Pygments by inserting little # marker comments between each section and then splitting the result string # wherever our markers occur. highlight = (source, sections, callback) -> language = get_language source pygments = spawn 'pygmentize', ['-l', language.name, '-f', 'html', '-O', 'encoding=utf-8'] output = '' pygments.stderr.addListener 'data', (error) -> console.error error if error pygments.stdout.addListener 'data', (result) -> output += result if result pygments.addListener 'exit', -> output = output.replace(highlight_start, '').replace(highlight_end, '') fragments = output.split language.divider_html for section, i in sections section.code_html = highlight_start + fragments[i] + highlight_end section.docs_html = showdown.makeHtml section.docs_text callback() pygments.stdin.write((section.code_text for section in sections).join(language.divider_text)) pygments.stdin.end() # Once all of the code is finished highlighting, we can generate the HTML file # and write out the documentation. Pass the completed sections into the template # found in `resources/docco.jst` generate_html = (source, sections) -> title = path.basename source dest = destination source html = docco_template { title: title, sections: sections, sources: sources, path: path, destination: destination } console.log "docco: #{source} -> #{dest}" fs.writeFile dest, html #### Helpers & Setup # Require our external dependencies, including **Showdown.js** # (the JavaScript implementation of Markdown). fs = require 'fs' path = require 'path' showdown = require('./../vendor/showdown').Showdown {spawn, exec} = require 'child_process' # A list of the languages that Docco supports, mapping the file extension to # the name of the Pygments lexer and the symbol that indicates a comment. To # add another language to Docco's repertoire, add it here. languages = '.coffee': name: 'coffee-script', symbol: '#' '.js': name: 'javascript', symbol: '//' '.rb': name: 'ruby', symbol: '#' '.py': name: 'python', symbol: '#' # Build out the appropriate matchers and delimiters for each language. for ext, l of languages # Does the line begin with a comment? l.comment_matcher = new RegExp('^\\s*' + l.symbol + '\\s?') # Ignore [hashbangs](http://en.wikipedia.org/wiki/Shebang_(Unix)) # and interpolations... l.comment_filter = new RegExp('(^#![/]|^\\s*#\\{)') # The dividing token we feed into Pygments, to delimit the boundaries between # sections. l.divider_text = '\n' + l.symbol + 'DIVIDER\n' # The mirror of `divider_text` that we expect Pygments to return. We can split # on this to recover the original sections. # Note: the class is "c" for Python and "c1" for the other languages l.divider_html = new RegExp('\\n*<span class="c1?">' + l.symbol + 'DIVIDER<\\/span>\\n*') # Get the current language we're documenting, based on the extension. get_language = (source) -> languages[path.extname(source)] # Compute the destination HTML path for an input source file path. If the source # is `lib/example.coffee`, the HTML will be at `docs/example.html` destination = (filepath) -> 'docs/' + path.basename(filepath, path.extname(filepath)) + '.html' # Ensure that the destination directory exists. ensure_directory = (callback) -> exec 'mkdir -p docs', -> callback() # Micro-templating, originally by PI:NAME:<NAME>END_PI, borrowed by way of # [Underscore.js](http://documentcloud.github.com/underscore/). template = (str) -> new Function 'obj', 'var p=[],print=function(){p.push.apply(p,arguments);};' + 'with(obj){p.push(\'' + str.replace(/[\r\t\n]/g, " ") .replace(/'(?=[^<]*%>)/g,"\t") .split("'").join("\\'") .split("\t").join("'") .replace(/<%=(.+?)%>/g, "',$1,'") .split('<%').join("');") .split('%>').join("p.push('") + "');}return p.join('');" # Create the template that we will use to generate the Docco HTML page. docco_template = template fs.readFileSync(__dirname + '/../resources/docco.jst').toString() # The CSS styles we'd like to apply to the documentation. docco_styles = fs.readFileSync(__dirname + '/../resources/docco.css').toString() # The start of each Pygments highlight block. highlight_start = '<div class="highlight"><pre>' # The end of each Pygments highlight block. highlight_end = '</pre></div>' # Run the script. # For each source file passed in as an argument, generate the documentation. sources = process.ARGV.sort() if sources.length ensure_directory -> fs.writeFile 'docs/docco.css', docco_styles files = sources.slice(0) next_file = -> generate_documentation files.shift(), next_file if files.length next_file()
[ { "context": "host\"\r\nusername = process.env.AMQP_USERNAME ? \"guest\"\r\npassword = process.env.AMQP_PASSWORD ? \"gues", "end": 328, "score": 0.9612051844596863, "start": 323, "tag": "USERNAME", "value": "guest" }, { "context": "uest\"\r\npassword = process.env.AMQP_PASSWORD ? \"guest\"\r\n\r\nhos = {}\r\nhosController = {}\r\nswaggerToolsMid", "end": 379, "score": 0.9982442855834961, "start": 374, "tag": "PASSWORD", "value": "guest" } ]
src/HoSApi.coffee
HoS0/HoSApi
0
contract = require('./serviceContract') url = require('url') HoSCom = require('hos-com') swaggerTools = require('swagger-tools') Promise = require 'bluebird' HoSController= require 'hos-controller' amqpurl = process.env.AMQP_URL ? "localhost" username = process.env.AMQP_USERNAME ? "guest" password = process.env.AMQP_PASSWORD ? "guest" hos = {} hosController = {} swaggerToolsMiddleware = {} String.prototype.endsWith = (suffix)-> return this.indexOf(suffix, this.length - suffix.length) isnt -1 setHeaders= (req, method, pathParts)-> if req.headers and req.headers.sid destinationService += ".#{req.headers.sid}" headers = method: method task: '/' + pathParts[1] if req.query for key in Object.keys(req.query) if req.query[key] is 'true' req.query[key] = true if req.query[key] is 'false' req.query[key] = false headers.query = req.query if pathParts[2] headers.taskId = pathParts[2] if req.headers and req.headers.token headers.token = req.headers.token headers.expiration = 1000 headers.replyWholeMessage = true headers.httpHeaders= {} for key in Object.keys(req.headers) headers.httpHeaders[key] = req.headers[key] return headers sendHoSMessage = (req, res, next, method)=> try if typeof req.body is "string" req.body = JSON.parse req.body body = req.body ? {} parseUrl = url.parse(req.url) pathParts = parseUrl.pathname.split('/').filter (e)-> return e.replace(/(\r\n|\n|\r)/gm,"") destinationService = '/' + pathParts[0]; headers = setHeaders(req, method, pathParts) catch error res.status(400) res.send 'wrong argument in the request' return hos.sendMessage body, destinationService, headers .then (reply)=> res.status(reply.properties.headers.statusCode ? 200) if typeof reply.properties.headers.httpHeaders is 'object' for key in Object.keys(reply.properties.headers.httpHeaders) res.setHeader key, reply.properties.headers.httpHeaders[key] res.json reply.content .catch (err)=> res.status(err.code) res.send JSON.stringify err.reason getDocPeriodically = (host)=> tick = ()-> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware .catch # ignore setInterval(tick, 10 * 60 * 1000); module.exports = init: (useSwaggerTool, host)-> new Promise (fullfil, reject) => @hos = new HoSCom contract, amqpurl, username, password @hos.connect() .then ()=> hos = @hos if useSwaggerTool is true @hosController = new HoSController(amqpurl, username, password) @hosController.connect() .then ()=> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware fullfil() getDocPeriodically(host) else fullfil() sendMessage: (content, destination, headers)-> hos.sendMessage(content, destination, headers) middleware: (req, res, next)-> if req and req.method method = req.method.toLowerCase() if req.url.endsWith('.html') next() if typeof next is 'function' else sendHoSMessage(req, res, next, method) swaggerMetadata: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerMetadata()(req, res, next) swaggerValidator: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerValidator()(req, res, next) swaggerUi: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerUi()(req, res, next) destroy: ()-> @hos.destroy() if hosController @hosController.destroy()
160109
contract = require('./serviceContract') url = require('url') HoSCom = require('hos-com') swaggerTools = require('swagger-tools') Promise = require 'bluebird' HoSController= require 'hos-controller' amqpurl = process.env.AMQP_URL ? "localhost" username = process.env.AMQP_USERNAME ? "guest" password = process.env.AMQP_PASSWORD ? "<PASSWORD>" hos = {} hosController = {} swaggerToolsMiddleware = {} String.prototype.endsWith = (suffix)-> return this.indexOf(suffix, this.length - suffix.length) isnt -1 setHeaders= (req, method, pathParts)-> if req.headers and req.headers.sid destinationService += ".#{req.headers.sid}" headers = method: method task: '/' + pathParts[1] if req.query for key in Object.keys(req.query) if req.query[key] is 'true' req.query[key] = true if req.query[key] is 'false' req.query[key] = false headers.query = req.query if pathParts[2] headers.taskId = pathParts[2] if req.headers and req.headers.token headers.token = req.headers.token headers.expiration = 1000 headers.replyWholeMessage = true headers.httpHeaders= {} for key in Object.keys(req.headers) headers.httpHeaders[key] = req.headers[key] return headers sendHoSMessage = (req, res, next, method)=> try if typeof req.body is "string" req.body = JSON.parse req.body body = req.body ? {} parseUrl = url.parse(req.url) pathParts = parseUrl.pathname.split('/').filter (e)-> return e.replace(/(\r\n|\n|\r)/gm,"") destinationService = '/' + pathParts[0]; headers = setHeaders(req, method, pathParts) catch error res.status(400) res.send 'wrong argument in the request' return hos.sendMessage body, destinationService, headers .then (reply)=> res.status(reply.properties.headers.statusCode ? 200) if typeof reply.properties.headers.httpHeaders is 'object' for key in Object.keys(reply.properties.headers.httpHeaders) res.setHeader key, reply.properties.headers.httpHeaders[key] res.json reply.content .catch (err)=> res.status(err.code) res.send JSON.stringify err.reason getDocPeriodically = (host)=> tick = ()-> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware .catch # ignore setInterval(tick, 10 * 60 * 1000); module.exports = init: (useSwaggerTool, host)-> new Promise (fullfil, reject) => @hos = new HoSCom contract, amqpurl, username, password @hos.connect() .then ()=> hos = @hos if useSwaggerTool is true @hosController = new HoSController(amqpurl, username, password) @hosController.connect() .then ()=> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware fullfil() getDocPeriodically(host) else fullfil() sendMessage: (content, destination, headers)-> hos.sendMessage(content, destination, headers) middleware: (req, res, next)-> if req and req.method method = req.method.toLowerCase() if req.url.endsWith('.html') next() if typeof next is 'function' else sendHoSMessage(req, res, next, method) swaggerMetadata: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerMetadata()(req, res, next) swaggerValidator: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerValidator()(req, res, next) swaggerUi: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerUi()(req, res, next) destroy: ()-> @hos.destroy() if hosController @hosController.destroy()
true
contract = require('./serviceContract') url = require('url') HoSCom = require('hos-com') swaggerTools = require('swagger-tools') Promise = require 'bluebird' HoSController= require 'hos-controller' amqpurl = process.env.AMQP_URL ? "localhost" username = process.env.AMQP_USERNAME ? "guest" password = process.env.AMQP_PASSWORD ? "PI:PASSWORD:<PASSWORD>END_PI" hos = {} hosController = {} swaggerToolsMiddleware = {} String.prototype.endsWith = (suffix)-> return this.indexOf(suffix, this.length - suffix.length) isnt -1 setHeaders= (req, method, pathParts)-> if req.headers and req.headers.sid destinationService += ".#{req.headers.sid}" headers = method: method task: '/' + pathParts[1] if req.query for key in Object.keys(req.query) if req.query[key] is 'true' req.query[key] = true if req.query[key] is 'false' req.query[key] = false headers.query = req.query if pathParts[2] headers.taskId = pathParts[2] if req.headers and req.headers.token headers.token = req.headers.token headers.expiration = 1000 headers.replyWholeMessage = true headers.httpHeaders= {} for key in Object.keys(req.headers) headers.httpHeaders[key] = req.headers[key] return headers sendHoSMessage = (req, res, next, method)=> try if typeof req.body is "string" req.body = JSON.parse req.body body = req.body ? {} parseUrl = url.parse(req.url) pathParts = parseUrl.pathname.split('/').filter (e)-> return e.replace(/(\r\n|\n|\r)/gm,"") destinationService = '/' + pathParts[0]; headers = setHeaders(req, method, pathParts) catch error res.status(400) res.send 'wrong argument in the request' return hos.sendMessage body, destinationService, headers .then (reply)=> res.status(reply.properties.headers.statusCode ? 200) if typeof reply.properties.headers.httpHeaders is 'object' for key in Object.keys(reply.properties.headers.httpHeaders) res.setHeader key, reply.properties.headers.httpHeaders[key] res.json reply.content .catch (err)=> res.status(err.code) res.send JSON.stringify err.reason getDocPeriodically = (host)=> tick = ()-> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware .catch # ignore setInterval(tick, 10 * 60 * 1000); module.exports = init: (useSwaggerTool, host)-> new Promise (fullfil, reject) => @hos = new HoSCom contract, amqpurl, username, password @hos.connect() .then ()=> hos = @hos if useSwaggerTool is true @hosController = new HoSController(amqpurl, username, password) @hosController.connect() .then ()=> hos.sendMessage({} , '/ctrlr', {task: '/tasks', method: 'get', query: {docincluded: true, host: host}}) .then (replyPayload)=> swaggerTools.initializeMiddleware replyPayload.doc, (middleware)-> swaggerToolsMiddleware = middleware fullfil() getDocPeriodically(host) else fullfil() sendMessage: (content, destination, headers)-> hos.sendMessage(content, destination, headers) middleware: (req, res, next)-> if req and req.method method = req.method.toLowerCase() if req.url.endsWith('.html') next() if typeof next is 'function' else sendHoSMessage(req, res, next, method) swaggerMetadata: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerMetadata()(req, res, next) swaggerValidator: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerValidator()(req, res, next) swaggerUi: (req, res, next)-> if swaggerToolsMiddleware swaggerToolsMiddleware.swaggerUi()(req, res, next) destroy: ()-> @hos.destroy() if hosController @hosController.destroy()
[ { "context": "->\n MailBox.new('Alice_mbx').then (ret)->\n Alice = ret\n MailBox.new('Bob_mbx').then (ret)->\n ", "end": 698, "score": 0.9033698439598083, "start": 693, "tag": "NAME", "value": "Alice" }, { "context": "\n MailBox.new('Bob_mbx').then (ret)->\n Bob = ret\n expect(Alice.keyRing).not.null\n ", "end": 758, "score": 0.8728388547897339, "start": 755, "tag": "NAME", "value": "Bob" }, { "context": "61, 222])\n m.selfDestruct(true)\n\n H2_KEY = 'vye4sj8BKHopBVXUfv3s3iKyP6TyNoJnHUYWCMcjwTo='\n H2_HPK = new Uint8Array([36, 36, 36, 231, 132, ", "end": 2325, "score": 0.9997733235359192, "start": 2280, "tag": "KEY", "value": "vye4sj8BKHopBVXUfv3s3iKyP6TyNoJnHUYWCMcjwTo='" }, { "context": ".deep.equal H2_HPK\n\n it 'encrypt message', ->\n Alice.encodeMessage('Bob_mbx', pt1 = 'Bob, I heard from", "end": 2984, "score": 0.8019565343856812, "start": 2979, "tag": "NAME", "value": "Alice" }, { "context": "ge', ->\n Alice.encodeMessage('Bob_mbx', pt1 = 'Bob, I heard from Наталья\n Дубровская we have a ", "end": 3020, "score": 0.9914795756340027, "start": 3017, "tag": "NAME", "value": "Bob" }, { "context": " water chip.').then (ret)->\n msg1 = ret\n Bob.encodeMessage('Alice_mbx', pt2 = 'Alice, I will d", "end": 3140, "score": 0.6979458332061768, "start": 3137, "tag": "NAME", "value": "Bob" }, { "context": "(ret)->\n msg1 = ret\n Bob.encodeMessage('Alice_mbx', pt2 = 'Alice, I will dispatch one\n o", "end": 3161, "score": 0.9161929488182068, "start": 3156, "tag": "NAME", "value": "Alice" }, { "context": "= ret\n Bob.encodeMessage('Alice_mbx', pt2 = 'Alice, I will dispatch one\n of the youngsters to", "end": 3180, "score": 0.9955253005027771, "start": 3175, "tag": "NAME", "value": "Alice" }, { "context": " msg2 = ret\n\n it 'decrypt message', ->\n Bob.decodeMessage('Alice_mbx', msg1.nonce, msg1.ctext", "end": 3336, "score": 0.621396005153656, "start": 3333, "tag": "NAME", "value": "Bob" }, { "context": " it 'decrypt message', ->\n Bob.decodeMessage('Alice_mbx', msg1.nonce, msg1.ctext).then (m1)->\n A", "end": 3357, "score": 0.8658271431922913, "start": 3352, "tag": "NAME", "value": "Alice" }, { "context": "ce_mbx', msg1.nonce, msg1.ctext).then (m1)->\n Alice.decodeMessage('Bob_mbx', msg2.nonce, msg2.ctext).", "end": 3411, "score": 0.8546061515808105, "start": 3406, "tag": "NAME", "value": "Alice" }, { "context": "sg1.ctext).then (m1)->\n Alice.decodeMessage('Bob_mbx', msg2.nonce, msg2.ctext).then (m2)->\n ", "end": 3430, "score": 0.8584750890731812, "start": 3427, "tag": "NAME", "value": "Bob" }, { "context": "_SESSION_TIMEOUT = st\n Alice.createSessionKey('session_id_123')\n\n it 'clear mailboxes', ->\n Alice.selfDestr", "end": 3767, "score": 0.9763147234916687, "start": 3753, "tag": "KEY", "value": "session_id_123" } ]
tests/specs/04.mailbox.coffee
vault12/glow
14
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT window.__CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Utils = require 'utils' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Config = require 'config' # ----- Communication MailBox ----- describe 'MailBox, offline Relay', -> return unless window.__globalTest.runTests['mailbox'] [Alice, Bob] = [null, null] # An elegant variable init block [msg1, msg2, msg3, msg4, msg5, msg6, msg7, pt1, pt2, pt3, pt4] = (null for n in [1..11]) it 'create mailbox', -> MailBox.new('Alice_mbx').then (ret)-> Alice = ret MailBox.new('Bob_mbx').then (ret)-> Bob = ret expect(Alice.keyRing).not.null expect(Bob.keyRing).not.null it 'exchange keys', -> expect(Alice.keyRing.getNumberOfGuests()).equal(0) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.null Alice.keyRing.addGuest('Bob_mbx', Bob.getPubCommKey()).then -> expect(Alice.keyRing.getNumberOfGuests()).equal(1) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.not.null expect(Bob.keyRing.getNumberOfGuests()).equal(0) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.null Bob.keyRing.addGuest('Alice_mbx', Alice.getPubCommKey()).then -> expect(Bob.keyRing.getNumberOfGuests()).equal(1) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.not.null it 'nonces with data', -> # data = 0xCDEF89AB data = 0xFFFFFFFF MailBox._makeNonce().then (n1)=> # random nonce with timestamp only expect(MailBox._nonceData n1).is.not.equal data # random nonce with extra data, like message counter MailBox._makeNonce(data).then (n2)=> expect(MailBox._nonceData n2).is.equal data it 'Mailbox from well known seed', -> MailBox.fromSeed('hello').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal '2DM+z1PaxGXVnzsDh4zv+IlH7sV8llEFoEmg9fG3pRA=' m.keyRing.hpk.should.deep.equal new Uint8Array([249, 209, 90, 99, 252, 44, 187, 27, 13, 101, 229, 199, 235, 31, 235, 119, 224, 25, 207, 215, 94, 130, 71, 230, 44, 22, 217, 0, 201, 41, 61, 222]) m.selfDestruct(true) H2_KEY = 'vye4sj8BKHopBVXUfv3s3iKyP6TyNoJnHUYWCMcjwTo=' H2_HPK = new Uint8Array([36, 36, 36, 231, 132, 114, 39, 6, 230, 153, 228, 128, 132, 215, 100, 241, 87, 187, 9, 53, 179, 248, 176, 242, 249, 101, 68, 48, 48, 9, 219, 211]) it 'Mailbox backup & restore', -> MailBox.fromSeed('hello2').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal H2_KEY m.keyRing.hpk.should.deep.equal H2_HPK backup = m.keyRing.backup() m.selfDestruct(true).then -> MailBox.fromBackup(backup,"backup test").then (m2)-> pk = m2.keyRing.getPubCommKey() pk.should.equal H2_KEY m2.keyRing.hpk.should.deep.equal H2_HPK it 'encrypt message', -> Alice.encodeMessage('Bob_mbx', pt1 = 'Bob, I heard from Наталья Дубровская we have a problem with the water chip.').then (ret)-> msg1 = ret Bob.encodeMessage('Alice_mbx', pt2 = 'Alice, I will dispatch one of the youngsters to find a replacement outside. नमस्ते!').then (ret)-> msg2 = ret it 'decrypt message', -> Bob.decodeMessage('Alice_mbx', msg1.nonce, msg1.ctext).then (m1)-> Alice.decodeMessage('Bob_mbx', msg2.nonce, msg2.ctext).then (m2)-> pt1.should.equal(m1) pt2.should.equal(m2) it 'emits session timeout event', -> st = Config.RELAY_SESSION_TIMEOUT Config.RELAY_SESSION_TIMEOUT = 1 Alice.on 'relaysessiontimeout', -> Config.RELAY_SESSION_TIMEOUT = st Alice.createSessionKey('session_id_123') it 'clear mailboxes', -> Alice.selfDestruct(true).then -> Bob.selfDestruct(true)
215566
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT window.__CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Utils = require 'utils' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Config = require 'config' # ----- Communication MailBox ----- describe 'MailBox, offline Relay', -> return unless window.__globalTest.runTests['mailbox'] [Alice, Bob] = [null, null] # An elegant variable init block [msg1, msg2, msg3, msg4, msg5, msg6, msg7, pt1, pt2, pt3, pt4] = (null for n in [1..11]) it 'create mailbox', -> MailBox.new('Alice_mbx').then (ret)-> <NAME> = ret MailBox.new('Bob_mbx').then (ret)-> <NAME> = ret expect(Alice.keyRing).not.null expect(Bob.keyRing).not.null it 'exchange keys', -> expect(Alice.keyRing.getNumberOfGuests()).equal(0) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.null Alice.keyRing.addGuest('Bob_mbx', Bob.getPubCommKey()).then -> expect(Alice.keyRing.getNumberOfGuests()).equal(1) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.not.null expect(Bob.keyRing.getNumberOfGuests()).equal(0) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.null Bob.keyRing.addGuest('Alice_mbx', Alice.getPubCommKey()).then -> expect(Bob.keyRing.getNumberOfGuests()).equal(1) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.not.null it 'nonces with data', -> # data = 0xCDEF89AB data = 0xFFFFFFFF MailBox._makeNonce().then (n1)=> # random nonce with timestamp only expect(MailBox._nonceData n1).is.not.equal data # random nonce with extra data, like message counter MailBox._makeNonce(data).then (n2)=> expect(MailBox._nonceData n2).is.equal data it 'Mailbox from well known seed', -> MailBox.fromSeed('hello').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal '2DM+z1PaxGXVnzsDh4zv+IlH7sV8llEFoEmg9fG3pRA=' m.keyRing.hpk.should.deep.equal new Uint8Array([249, 209, 90, 99, 252, 44, 187, 27, 13, 101, 229, 199, 235, 31, 235, 119, 224, 25, 207, 215, 94, 130, 71, 230, 44, 22, 217, 0, 201, 41, 61, 222]) m.selfDestruct(true) H2_KEY = '<KEY> H2_HPK = new Uint8Array([36, 36, 36, 231, 132, 114, 39, 6, 230, 153, 228, 128, 132, 215, 100, 241, 87, 187, 9, 53, 179, 248, 176, 242, 249, 101, 68, 48, 48, 9, 219, 211]) it 'Mailbox backup & restore', -> MailBox.fromSeed('hello2').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal H2_KEY m.keyRing.hpk.should.deep.equal H2_HPK backup = m.keyRing.backup() m.selfDestruct(true).then -> MailBox.fromBackup(backup,"backup test").then (m2)-> pk = m2.keyRing.getPubCommKey() pk.should.equal H2_KEY m2.keyRing.hpk.should.deep.equal H2_HPK it 'encrypt message', -> <NAME>.encodeMessage('Bob_mbx', pt1 = '<NAME>, I heard from Наталья Дубровская we have a problem with the water chip.').then (ret)-> msg1 = ret <NAME>.encodeMessage('<NAME>_mbx', pt2 = '<NAME>, I will dispatch one of the youngsters to find a replacement outside. नमस्ते!').then (ret)-> msg2 = ret it 'decrypt message', -> <NAME>.decodeMessage('<NAME>_mbx', msg1.nonce, msg1.ctext).then (m1)-> <NAME>.decodeMessage('<NAME>_mbx', msg2.nonce, msg2.ctext).then (m2)-> pt1.should.equal(m1) pt2.should.equal(m2) it 'emits session timeout event', -> st = Config.RELAY_SESSION_TIMEOUT Config.RELAY_SESSION_TIMEOUT = 1 Alice.on 'relaysessiontimeout', -> Config.RELAY_SESSION_TIMEOUT = st Alice.createSessionKey('<KEY>') it 'clear mailboxes', -> Alice.selfDestruct(true).then -> Bob.selfDestruct(true)
true
# Copyright (c) 2015 Vault12, Inc. # MIT License https://opensource.org/licenses/MIT window.__CRYPTO_DEBUG = true # Expose #theglow objects as window globals expect = require('chai').expect Utils = require 'utils' MailBox = require 'mailbox' Nacl = require 'nacl' Relay = require 'relay' Config = require 'config' # ----- Communication MailBox ----- describe 'MailBox, offline Relay', -> return unless window.__globalTest.runTests['mailbox'] [Alice, Bob] = [null, null] # An elegant variable init block [msg1, msg2, msg3, msg4, msg5, msg6, msg7, pt1, pt2, pt3, pt4] = (null for n in [1..11]) it 'create mailbox', -> MailBox.new('Alice_mbx').then (ret)-> PI:NAME:<NAME>END_PI = ret MailBox.new('Bob_mbx').then (ret)-> PI:NAME:<NAME>END_PI = ret expect(Alice.keyRing).not.null expect(Bob.keyRing).not.null it 'exchange keys', -> expect(Alice.keyRing.getNumberOfGuests()).equal(0) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.null Alice.keyRing.addGuest('Bob_mbx', Bob.getPubCommKey()).then -> expect(Alice.keyRing.getNumberOfGuests()).equal(1) expect(Alice.keyRing.getGuestKey('Bob_mbx')).is.not.null expect(Bob.keyRing.getNumberOfGuests()).equal(0) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.null Bob.keyRing.addGuest('Alice_mbx', Alice.getPubCommKey()).then -> expect(Bob.keyRing.getNumberOfGuests()).equal(1) expect(Bob.keyRing.getGuestKey('Alice_mbx')).is.not.null it 'nonces with data', -> # data = 0xCDEF89AB data = 0xFFFFFFFF MailBox._makeNonce().then (n1)=> # random nonce with timestamp only expect(MailBox._nonceData n1).is.not.equal data # random nonce with extra data, like message counter MailBox._makeNonce(data).then (n2)=> expect(MailBox._nonceData n2).is.equal data it 'Mailbox from well known seed', -> MailBox.fromSeed('hello').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal '2DM+z1PaxGXVnzsDh4zv+IlH7sV8llEFoEmg9fG3pRA=' m.keyRing.hpk.should.deep.equal new Uint8Array([249, 209, 90, 99, 252, 44, 187, 27, 13, 101, 229, 199, 235, 31, 235, 119, 224, 25, 207, 215, 94, 130, 71, 230, 44, 22, 217, 0, 201, 41, 61, 222]) m.selfDestruct(true) H2_KEY = 'PI:KEY:<KEY>END_PI H2_HPK = new Uint8Array([36, 36, 36, 231, 132, 114, 39, 6, 230, 153, 228, 128, 132, 215, 100, 241, 87, 187, 9, 53, 179, 248, 176, 242, 249, 101, 68, 48, 48, 9, 219, 211]) it 'Mailbox backup & restore', -> MailBox.fromSeed('hello2').then (m)-> pk = m.keyRing.getPubCommKey() pk.should.equal H2_KEY m.keyRing.hpk.should.deep.equal H2_HPK backup = m.keyRing.backup() m.selfDestruct(true).then -> MailBox.fromBackup(backup,"backup test").then (m2)-> pk = m2.keyRing.getPubCommKey() pk.should.equal H2_KEY m2.keyRing.hpk.should.deep.equal H2_HPK it 'encrypt message', -> PI:NAME:<NAME>END_PI.encodeMessage('Bob_mbx', pt1 = 'PI:NAME:<NAME>END_PI, I heard from Наталья Дубровская we have a problem with the water chip.').then (ret)-> msg1 = ret PI:NAME:<NAME>END_PI.encodeMessage('PI:NAME:<NAME>END_PI_mbx', pt2 = 'PI:NAME:<NAME>END_PI, I will dispatch one of the youngsters to find a replacement outside. नमस्ते!').then (ret)-> msg2 = ret it 'decrypt message', -> PI:NAME:<NAME>END_PI.decodeMessage('PI:NAME:<NAME>END_PI_mbx', msg1.nonce, msg1.ctext).then (m1)-> PI:NAME:<NAME>END_PI.decodeMessage('PI:NAME:<NAME>END_PI_mbx', msg2.nonce, msg2.ctext).then (m2)-> pt1.should.equal(m1) pt2.should.equal(m2) it 'emits session timeout event', -> st = Config.RELAY_SESSION_TIMEOUT Config.RELAY_SESSION_TIMEOUT = 1 Alice.on 'relaysessiontimeout', -> Config.RELAY_SESSION_TIMEOUT = st Alice.createSessionKey('PI:KEY:<KEY>END_PI') it 'clear mailboxes', -> Alice.selfDestruct(true).then -> Bob.selfDestruct(true)
[ { "context": "ve {}\n\n @view.$('input[name=\"name\"]').val 'Damon'\n @view.$('input[name=\"email\"]').val 'damo", "end": 9057, "score": 0.997597336769104, "start": 9052, "tag": "NAME", "value": "Damon" }, { "context": "amon'\n @view.$('input[name=\"email\"]').val 'damon@artsy'\n @view.$('textarea[name=\"message\"]').val ", "end": 9114, "score": 0.8657402992248535, "start": 9103, "tag": "EMAIL", "value": "damon@artsy" }, { "context": ".html()\n .should.containEql 'I attended Foo Fair'\n\n describe '#inquiry', ->\n it 'marks", "end": 11548, "score": 0.9998014569282532, "start": 11540, "tag": "NAME", "value": "Foo Fair" }, { "context": "').click()\n\n @view.user.isAttending id: 'foo-fair'\n .should.be.true()\n", "end": 11839, "score": 0.934004008769989, "start": 11831, "tag": "USERNAME", "value": "foo-fair" } ]
src/desktop/apps/artwork/components/commercial/test/view.coffee
kierangillen/force
0
{ defer, extend } = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' ArtworkCommercialView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template', 'confirmation'] { fabricate } = require 'antigravity' CurrentUser = require '../../../../../models/current_user.coffee' describe 'ArtworkCommercialView', -> before (done) -> user = new CurrentUser fabricate('user') benv.setup -> benv.expose $: benv.require 'jquery' analytics: track: sinon.stub() user: user sd: FORCED_LOGIN_INQUIRY: 'default' stitch: components: TooltipQuestion: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() console.error = sinon.stub() done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe 'an ecommerce work with multiple edition sets', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork.json' @view.render() ArtworkCommercialView.__set__ CurrentUser: orNull: -> { id: 'userid' } describe '#render', -> it 'correctly renders the template', -> @view.$ '.artwork-edition-set' .should.have.lengthOf 4 @view.$ '.js-artwork-acquire-button' .should.have.lengthOf 1 describe '#acquire', -> it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOrder: createOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-acquire-button').click() createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOrder: createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() it 'shows an error modal when create order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() defer -> errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe '#offer', -> it 'should show an auth modal if the user is not logged in', -> createOfferOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOfferOrder: createOfferOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-offer-button').click() createOfferOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new offer order', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOfferOrder: createOfferOrderStub @view.$('.js-artwork-offer-button').click() defer -> createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() location.assign.calledWith("/orders/1234/offer").should.be.ok() it 'shows an error modal when create offer order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOfferOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-offer-button').click() defer -> createOrderStub.calledOnce.should.be.ok() errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe 'an ecommerce work with a single edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_single_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork with a single edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe '#offer', -> it 'purchases an artwork with a single edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe 'an ecommerce work without edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_no_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe 'an inquireable work, not in a fair', -> beforeEach -> @questionnaire = sinon.stub() .returns view: new Backbone.View ArtworkCommercialView.__set__ 'openInquiryQuestionnaireFor', @questionnaire @view = new ArtworkCommercialView require '../../../test/fixtures/inquireable_artwork.json' @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$('textarea').text() .should.containEql 'Hi, I’m interested in purchasing this work. Could you please provide more information about the piece?' @view.$ '.js-artwork-inquire-button' .should.have.lengthOf 1 describe '#inquiry', -> it 'sets up the inquiry and opens the inquiry modal', -> Backbone.sync.returns Promise.resolve {} @view.$('input[name="name"]').val 'Damon' @view.$('input[name="email"]').val 'damon@artsy' @view.$('textarea[name="message"]').val 'I want to buy this' @view.$('.js-artwork-inquire-button').click() Backbone.sync.args[0][1].url() .should.containEql '/api/v1/artwork/lynn-hershman-leeson-wrapped' @view.inquiry.attributes .should.eql notification_delay: 600, session_id: undefined, referring_url: undefined, landing_url: undefined, artwork: 'lynn-hershman-leeson-wrapped', message: 'I want to buy this' describe 'successful inquiry', -> it 'renders the confirmation', -> Backbone.sync.returns Promise.resolve {} @view.inquire $.Event 'click' .then => @view.inquiry.trigger 'sync' html = @view.$el.html() html.should.containEql 'Inquiry Sent' html.should.containEql 'You will receive an email receipt of your inquiry shortly.' describe 'an inquireable work, in a fair', -> describe 'fair is open', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' tomorrow = new Date (new Date()).getTime() + (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: tomorrow.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I will attend Foo Fair' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true() describe 'fair is closed', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' yesterday = new Date (new Date()).getTime() - (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: yesterday.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I attended Foo Fair' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true()
65903
{ defer, extend } = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' ArtworkCommercialView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template', 'confirmation'] { fabricate } = require 'antigravity' CurrentUser = require '../../../../../models/current_user.coffee' describe 'ArtworkCommercialView', -> before (done) -> user = new CurrentUser fabricate('user') benv.setup -> benv.expose $: benv.require 'jquery' analytics: track: sinon.stub() user: user sd: FORCED_LOGIN_INQUIRY: 'default' stitch: components: TooltipQuestion: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() console.error = sinon.stub() done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe 'an ecommerce work with multiple edition sets', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork.json' @view.render() ArtworkCommercialView.__set__ CurrentUser: orNull: -> { id: 'userid' } describe '#render', -> it 'correctly renders the template', -> @view.$ '.artwork-edition-set' .should.have.lengthOf 4 @view.$ '.js-artwork-acquire-button' .should.have.lengthOf 1 describe '#acquire', -> it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOrder: createOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-acquire-button').click() createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOrder: createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() it 'shows an error modal when create order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() defer -> errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe '#offer', -> it 'should show an auth modal if the user is not logged in', -> createOfferOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOfferOrder: createOfferOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-offer-button').click() createOfferOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new offer order', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOfferOrder: createOfferOrderStub @view.$('.js-artwork-offer-button').click() defer -> createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() location.assign.calledWith("/orders/1234/offer").should.be.ok() it 'shows an error modal when create offer order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOfferOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-offer-button').click() defer -> createOrderStub.calledOnce.should.be.ok() errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe 'an ecommerce work with a single edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_single_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork with a single edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe '#offer', -> it 'purchases an artwork with a single edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe 'an ecommerce work without edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_no_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe 'an inquireable work, not in a fair', -> beforeEach -> @questionnaire = sinon.stub() .returns view: new Backbone.View ArtworkCommercialView.__set__ 'openInquiryQuestionnaireFor', @questionnaire @view = new ArtworkCommercialView require '../../../test/fixtures/inquireable_artwork.json' @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$('textarea').text() .should.containEql 'Hi, I’m interested in purchasing this work. Could you please provide more information about the piece?' @view.$ '.js-artwork-inquire-button' .should.have.lengthOf 1 describe '#inquiry', -> it 'sets up the inquiry and opens the inquiry modal', -> Backbone.sync.returns Promise.resolve {} @view.$('input[name="name"]').val '<NAME>' @view.$('input[name="email"]').val '<EMAIL>' @view.$('textarea[name="message"]').val 'I want to buy this' @view.$('.js-artwork-inquire-button').click() Backbone.sync.args[0][1].url() .should.containEql '/api/v1/artwork/lynn-hershman-leeson-wrapped' @view.inquiry.attributes .should.eql notification_delay: 600, session_id: undefined, referring_url: undefined, landing_url: undefined, artwork: 'lynn-hershman-leeson-wrapped', message: 'I want to buy this' describe 'successful inquiry', -> it 'renders the confirmation', -> Backbone.sync.returns Promise.resolve {} @view.inquire $.Event 'click' .then => @view.inquiry.trigger 'sync' html = @view.$el.html() html.should.containEql 'Inquiry Sent' html.should.containEql 'You will receive an email receipt of your inquiry shortly.' describe 'an inquireable work, in a fair', -> describe 'fair is open', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' tomorrow = new Date (new Date()).getTime() + (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: tomorrow.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I will attend Foo Fair' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true() describe 'fair is closed', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' yesterday = new Date (new Date()).getTime() - (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: yesterday.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I attended <NAME>' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true()
true
{ defer, extend } = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' ArtworkCommercialView = benv.requireWithJadeify require.resolve('../view.coffee'), ['template', 'confirmation'] { fabricate } = require 'antigravity' CurrentUser = require '../../../../../models/current_user.coffee' describe 'ArtworkCommercialView', -> before (done) -> user = new CurrentUser fabricate('user') benv.setup -> benv.expose $: benv.require 'jquery' analytics: track: sinon.stub() user: user sd: FORCED_LOGIN_INQUIRY: 'default' stitch: components: TooltipQuestion: sinon.stub() Backbone.$ = $ location.assign = sinon.stub() console.error = sinon.stub() done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe 'an ecommerce work with multiple edition sets', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork.json' @view.render() ArtworkCommercialView.__set__ CurrentUser: orNull: -> { id: 'userid' } describe '#render', -> it 'correctly renders the template', -> @view.$ '.artwork-edition-set' .should.have.lengthOf 4 @view.$ '.js-artwork-acquire-button' .should.have.lengthOf 1 describe '#acquire', -> it 'should show an auth modal if the user is not logged in', -> createOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOrder: createOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-acquire-button').click() createOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new order', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOrder: createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() it 'shows an error modal when create order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() defer -> errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe '#offer', -> it 'should show an auth modal if the user is not logged in', -> createOfferOrderStub = sinon.stub() mediatorStub = trigger: sinon.stub() ArtworkCommercialView.__set__ mediator: mediatorStub createOfferOrder: createOfferOrderStub CurrentUser: orNull: -> null @view.$('.js-artwork-offer-button').click() createOfferOrderStub.callCount.should.equal(0) mediatorStub.trigger.args[0][0].should.equal 'open:auth' mediatorStub.trigger.args[0][1].mode.should.equal 'login' it 'purchases an artwork by creating a new offer order', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ createOfferOrder: createOfferOrderStub @view.$('.js-artwork-offer-button').click() defer -> createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() location.assign.calledWith("/orders/1234/offer").should.be.ok() it 'shows an error modal when create offer order mutation fails', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: error: code: "failed")) ArtworkCommercialView.__set__ 'createOfferOrder', createOrderStub errorModalMock = { render: sinon.spy(), renderBuyNowError: sinon.spy() } ArtworkCommercialView.__set__ 'errorModal', errorModalMock @view.$('.js-artwork-offer-button').click() defer -> createOrderStub.calledOnce.should.be.ok() errorModalMock.renderBuyNowError.calledOnce.should.be.ok() describe 'an ecommerce work with a single edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_single_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork with a single edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe '#offer', -> it 'purchases an artwork with a single edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: '56e866cd275b241d87000510' quantity: 1 user: sinon.match.any .should.be.ok() describe 'an ecommerce work without edition set', -> beforeEach -> @view = new ArtworkCommercialView require '../../../test/fixtures/acquireable_artwork_no_edition.json' @view.render() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOfferOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOfferOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOfferOrder', createOfferOrderStub @view.$('.js-artwork-offer-button').click() createOfferOrderStub.calledOnce.should.be.ok() createOfferOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe '#acquire', -> it 'purchases an artwork without edition set', -> createOrderStub = sinon.stub().returns(Promise.resolve(ecommerceCreateOrderWithArtwork: orderOrError: order: id: "1234")) ArtworkCommercialView.__set__ 'createOrder', createOrderStub @view.$('.js-artwork-acquire-button').click() createOrderStub.calledOnce.should.be.ok() createOrderStub .calledWith artworkId: '56e86588b202a366da000571' editionSetId: undefined quantity: 1 user: sinon.match.any .should.be.ok() describe 'an inquireable work, not in a fair', -> beforeEach -> @questionnaire = sinon.stub() .returns view: new Backbone.View ArtworkCommercialView.__set__ 'openInquiryQuestionnaireFor', @questionnaire @view = new ArtworkCommercialView require '../../../test/fixtures/inquireable_artwork.json' @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$('textarea').text() .should.containEql 'Hi, I’m interested in purchasing this work. Could you please provide more information about the piece?' @view.$ '.js-artwork-inquire-button' .should.have.lengthOf 1 describe '#inquiry', -> it 'sets up the inquiry and opens the inquiry modal', -> Backbone.sync.returns Promise.resolve {} @view.$('input[name="name"]').val 'PI:NAME:<NAME>END_PI' @view.$('input[name="email"]').val 'PI:EMAIL:<EMAIL>END_PI' @view.$('textarea[name="message"]').val 'I want to buy this' @view.$('.js-artwork-inquire-button').click() Backbone.sync.args[0][1].url() .should.containEql '/api/v1/artwork/lynn-hershman-leeson-wrapped' @view.inquiry.attributes .should.eql notification_delay: 600, session_id: undefined, referring_url: undefined, landing_url: undefined, artwork: 'lynn-hershman-leeson-wrapped', message: 'I want to buy this' describe 'successful inquiry', -> it 'renders the confirmation', -> Backbone.sync.returns Promise.resolve {} @view.inquire $.Event 'click' .then => @view.inquiry.trigger 'sync' html = @view.$el.html() html.should.containEql 'Inquiry Sent' html.should.containEql 'You will receive an email receipt of your inquiry shortly.' describe 'an inquireable work, in a fair', -> describe 'fair is open', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' tomorrow = new Date (new Date()).getTime() + (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: tomorrow.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I will attend Foo Fair' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true() describe 'fair is closed', -> beforeEach -> fixture = extend {}, require '../../../test/fixtures/inquireable_artwork.json' yesterday = new Date (new Date()).getTime() - (24*60*60*1000) fixture.data.artwork.fair = id: 'foo-fair', name: 'Foo Fair 2016', end_at: yesterday.toISOString() @view = new ArtworkCommercialView fixture @view.render() describe '#render', -> it 'correctly renders the template', -> @view.$el.html() .should.containEql 'I attended PI:NAME:<NAME>END_PI' describe '#inquiry', -> it 'marks the attendance', -> Backbone.sync.returns then: sinon.stub() @view.$('input[name="attending"]').prop 'checked', true @view.$('.js-artwork-inquire-button').click() @view.user.isAttending id: 'foo-fair' .should.be.true()
[ { "context": " {\n \"type\": \"switch\",\n \"name\": \"Switch\",\n \"state\": {\n \"online\": true", "end": 324, "score": 0.5302637815475464, "start": 318, "tag": "NAME", "value": "Switch" } ]
adapters/switch.coffee
bertreb/pimatic-assistant
1
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' events = require 'events' class SwitchAdapter extends events.EventEmitter constructor: (adapterConfig) -> ### syncDevices: { "42474293.441c2c": { "type": "switch", "name": "Switch", "state": { "online": true, "on": false, } "twoFactor": "ack|pin" "pin": "12345" } } ### @id = adapterConfig.id @device = adapterConfig.pimaticDevice @subDeviceId = adapterConfig.pimaticSubDeviceId @UpdateState = adapterConfig.updateState @twoFa = adapterConfig.twoFa @twoFaPin = adapterConfig.twoFaPin @device.on "state", deviceStateHandler @device.system = @ @state = online: true on: false @device.getState() .then((state)=> @state.on = state @UpdateState(@id, @state) ) deviceStateHandler = (state) -> # device status changed, updating device status in Nora @system.updateState(state) executeAction: (change) -> # device status changed, updating device status in Nora env.logger.debug "Received action, change: " + JSON.stringify(change,null,2) @state.on = change.on @device.changeStateTo(change.on) updateState: (newState) => unless newState is @state.on env.logger.debug "Update state to " + newState @state.on = newState @UpdateState(@id, @state) getType: () -> return "switch" getState: () -> return @state destroy: -> @state.online = false; @UpdateState(@state) @device.removeListener "state", deviceStateHandler
140437
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' events = require 'events' class SwitchAdapter extends events.EventEmitter constructor: (adapterConfig) -> ### syncDevices: { "42474293.441c2c": { "type": "switch", "name": "<NAME>", "state": { "online": true, "on": false, } "twoFactor": "ack|pin" "pin": "12345" } } ### @id = adapterConfig.id @device = adapterConfig.pimaticDevice @subDeviceId = adapterConfig.pimaticSubDeviceId @UpdateState = adapterConfig.updateState @twoFa = adapterConfig.twoFa @twoFaPin = adapterConfig.twoFaPin @device.on "state", deviceStateHandler @device.system = @ @state = online: true on: false @device.getState() .then((state)=> @state.on = state @UpdateState(@id, @state) ) deviceStateHandler = (state) -> # device status changed, updating device status in Nora @system.updateState(state) executeAction: (change) -> # device status changed, updating device status in Nora env.logger.debug "Received action, change: " + JSON.stringify(change,null,2) @state.on = change.on @device.changeStateTo(change.on) updateState: (newState) => unless newState is @state.on env.logger.debug "Update state to " + newState @state.on = newState @UpdateState(@id, @state) getType: () -> return "switch" getState: () -> return @state destroy: -> @state.online = false; @UpdateState(@state) @device.removeListener "state", deviceStateHandler
true
module.exports = (env) -> Promise = env.require 'bluebird' assert = env.require 'cassert' events = require 'events' class SwitchAdapter extends events.EventEmitter constructor: (adapterConfig) -> ### syncDevices: { "42474293.441c2c": { "type": "switch", "name": "PI:NAME:<NAME>END_PI", "state": { "online": true, "on": false, } "twoFactor": "ack|pin" "pin": "12345" } } ### @id = adapterConfig.id @device = adapterConfig.pimaticDevice @subDeviceId = adapterConfig.pimaticSubDeviceId @UpdateState = adapterConfig.updateState @twoFa = adapterConfig.twoFa @twoFaPin = adapterConfig.twoFaPin @device.on "state", deviceStateHandler @device.system = @ @state = online: true on: false @device.getState() .then((state)=> @state.on = state @UpdateState(@id, @state) ) deviceStateHandler = (state) -> # device status changed, updating device status in Nora @system.updateState(state) executeAction: (change) -> # device status changed, updating device status in Nora env.logger.debug "Received action, change: " + JSON.stringify(change,null,2) @state.on = change.on @device.changeStateTo(change.on) updateState: (newState) => unless newState is @state.on env.logger.debug "Update state to " + newState @state.on = newState @UpdateState(@id, @state) getType: () -> return "switch" getState: () -> return @state destroy: -> @state.online = false; @UpdateState(@state) @device.removeListener "state", deviceStateHandler
[ { "context": "###! jquery-fillimg 2.2.2 http://github.com/Se7enSky/jquery-fillimg###\n###\n@name jquery-fillimg\n@descr", "end": 52, "score": 0.9994165897369385, "start": 44, "tag": "USERNAME", "value": "Se7enSky" }, { "context": "escription div > img filler\n@version 2.2.2\n@author Se7enSky studio <info@se7ensky.com>\n###\n\nplugin = ($) ->\n\tcreateP", "end": 164, "score": 0.9312956929206848, "start": 149, "tag": "USERNAME", "value": "Se7enSky studio" }, { "context": "mg filler\n@version 2.2.2\n@author Se7enSky studio <info@se7ensky.com>\n###\n\nplugin = ($) ->\n\tcreatePositionImageFn = ($", "end": 183, "score": 0.9999256134033203, "start": 166, "tag": "EMAIL", "value": "info@se7ensky.com" } ]
jquery-fillimg.coffee
SE7ENSKY/jquery-fillimg
0
###! jquery-fillimg 2.2.2 http://github.com/Se7enSky/jquery-fillimg### ### @name jquery-fillimg @description div > img filler @version 2.2.2 @author Se7enSky studio <info@se7ensky.com> ### plugin = ($) -> createPositionImageFn = ($img, $container) -> -> if not $img.data 'ratio' ratio = $img.width() / $img.height() return if not ratio $img.data 'ratio', ratio originalImageAspectRatio = $img.data 'ratio' hposition = $img.data 'hposition' # console.log hposition # containerWidth = $(window).width() # containerHeight = $(window).height() containerWidth = $container.width() containerHeight = $container.height() containerAspectRatio = containerWidth / containerHeight # console.log containerWidth, containerHeight, containerAspectRatio, originalImageAspectRatio if containerAspectRatio < originalImageAspectRatio $img.css width: "#{containerHeight * originalImageAspectRatio}px" height: "#{containerHeight}px" marginLeft: switch hposition when "left" then 0 when "right" then "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth)}px" else "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth) / 2}px" marginTop: 0 else $img.css width: "#{containerWidth}px" height: "#{containerWidth / originalImageAspectRatio}px" marginLeft: 0 marginTop: "#{-1 * (containerWidth / originalImageAspectRatio - containerHeight) / 2}px" $.fn.fillimg = -> $.each @, -> $(@).css position: "absolute" left: 0 top: 0 height: "100%" width: "100%" overflow: "hidden" $img = $(@).find("> *") $img.css visibility: "hidden" positionImageFn = createPositionImageFn $img, $(@) # $(@).on 'resized', positionImageFn $img.bind 'load', positionImageFn $(window).on "resize orientationchange", positionImageFn $(document).on "heightChanged", positionImageFn setTimeout => positionImageFn() $img.css visibility: "visible" , 1 @ # chaining # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
30452
###! jquery-fillimg 2.2.2 http://github.com/Se7enSky/jquery-fillimg### ### @name jquery-fillimg @description div > img filler @version 2.2.2 @author Se7enSky studio <<EMAIL>> ### plugin = ($) -> createPositionImageFn = ($img, $container) -> -> if not $img.data 'ratio' ratio = $img.width() / $img.height() return if not ratio $img.data 'ratio', ratio originalImageAspectRatio = $img.data 'ratio' hposition = $img.data 'hposition' # console.log hposition # containerWidth = $(window).width() # containerHeight = $(window).height() containerWidth = $container.width() containerHeight = $container.height() containerAspectRatio = containerWidth / containerHeight # console.log containerWidth, containerHeight, containerAspectRatio, originalImageAspectRatio if containerAspectRatio < originalImageAspectRatio $img.css width: "#{containerHeight * originalImageAspectRatio}px" height: "#{containerHeight}px" marginLeft: switch hposition when "left" then 0 when "right" then "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth)}px" else "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth) / 2}px" marginTop: 0 else $img.css width: "#{containerWidth}px" height: "#{containerWidth / originalImageAspectRatio}px" marginLeft: 0 marginTop: "#{-1 * (containerWidth / originalImageAspectRatio - containerHeight) / 2}px" $.fn.fillimg = -> $.each @, -> $(@).css position: "absolute" left: 0 top: 0 height: "100%" width: "100%" overflow: "hidden" $img = $(@).find("> *") $img.css visibility: "hidden" positionImageFn = createPositionImageFn $img, $(@) # $(@).on 'resized', positionImageFn $img.bind 'load', positionImageFn $(window).on "resize orientationchange", positionImageFn $(document).on "heightChanged", positionImageFn setTimeout => positionImageFn() $img.css visibility: "visible" , 1 @ # chaining # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
true
###! jquery-fillimg 2.2.2 http://github.com/Se7enSky/jquery-fillimg### ### @name jquery-fillimg @description div > img filler @version 2.2.2 @author Se7enSky studio <PI:EMAIL:<EMAIL>END_PI> ### plugin = ($) -> createPositionImageFn = ($img, $container) -> -> if not $img.data 'ratio' ratio = $img.width() / $img.height() return if not ratio $img.data 'ratio', ratio originalImageAspectRatio = $img.data 'ratio' hposition = $img.data 'hposition' # console.log hposition # containerWidth = $(window).width() # containerHeight = $(window).height() containerWidth = $container.width() containerHeight = $container.height() containerAspectRatio = containerWidth / containerHeight # console.log containerWidth, containerHeight, containerAspectRatio, originalImageAspectRatio if containerAspectRatio < originalImageAspectRatio $img.css width: "#{containerHeight * originalImageAspectRatio}px" height: "#{containerHeight}px" marginLeft: switch hposition when "left" then 0 when "right" then "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth)}px" else "#{-1 * (containerHeight * originalImageAspectRatio - containerWidth) / 2}px" marginTop: 0 else $img.css width: "#{containerWidth}px" height: "#{containerWidth / originalImageAspectRatio}px" marginLeft: 0 marginTop: "#{-1 * (containerWidth / originalImageAspectRatio - containerHeight) / 2}px" $.fn.fillimg = -> $.each @, -> $(@).css position: "absolute" left: 0 top: 0 height: "100%" width: "100%" overflow: "hidden" $img = $(@).find("> *") $img.css visibility: "hidden" positionImageFn = createPositionImageFn $img, $(@) # $(@).on 'resized', positionImageFn $img.bind 'load', positionImageFn $(window).on "resize orientationchange", positionImageFn $(document).on "heightChanged", positionImageFn setTimeout => positionImageFn() $img.css visibility: "visible" , 1 @ # chaining # UMD if typeof define is 'function' and define.amd then define(['jquery'], plugin) else plugin(jQuery)
[ { "context": "e = sinon.spy()\n Device::generateToken = => 'charizard'\n Device::storeToken = sinon.stub().yields n", "end": 305, "score": 0.9632601737976074, "start": 296, "tag": "PASSWORD", "value": "charizard" }, { "context": "lt', ->\n expect(@result.token).to.equal 'charizard'\n\n it 'should instantiate a Device with the uu", "end": 923, "score": 0.5899922847747803, "start": 918, "tag": "PASSWORD", "value": "izard" }, { "context": "ice::storeToken).to.have.been.calledWith {token: 'charizard'}\n\n describe 'when called with a different uuid ", "end": 1211, "score": 0.9775832891464233, "start": 1202, "tag": "PASSWORD", "value": "charizard" }, { "context": " = sinon.stub()\n Device::generateToken = => 'pikachu'\n Device::storeToken = sinon.stub().yields n", "end": 1375, "score": 0.9893828630447388, "start": 1368, "tag": "PASSWORD", "value": "pikachu" }, { "context": "result', ->\n expect(@result.token).to.equal 'pikachu'\n\n it 'should instantiate a Device with the uu", "end": 1910, "score": 0.6752164363861084, "start": 1903, "tag": "USERNAME", "value": "pikachu" }, { "context": "vice::storeToken).to.have.been.calledWith {token:'pikachu'}\n\n describe 'when called with a uuid, a tag and", "end": 2195, "score": 0.8915196061134338, "start": 2188, "tag": "PASSWORD", "value": "pikachu" }, { "context": " = sinon.stub()\n Device::generateToken = => 'pikachu'\n Device::storeToken = sinon.stub().yields n", "end": 2356, "score": 0.9758914709091187, "start": 2349, "tag": "PASSWORD", "value": "pikachu" }, { "context": "result', ->\n expect(@result.token).to.equal 'pikachu'\n\n it 'should have a tag in the result', ->\n ", "end": 2909, "score": 0.6018044948577881, "start": 2902, "tag": "USERNAME", "value": "pikachu" }, { "context": "vice::storeToken).to.have.been.calledWith {token:'pikachu', tag: 'super-tag'}\n\n describe 'called when stor", "end": 3287, "score": 0.9337495565414429, "start": 3280, "tag": "PASSWORD", "value": "pikachu" }, { "context": "e = sinon.spy()\n Device::generateToken = => 'charizard'\n Device::storeToken = sinon.stub().yields n", "end": 3462, "score": 0.8715837597846985, "start": 3453, "tag": "PASSWORD", "value": "charizard" }, { "context": "e = sinon.spy()\n Device::generateToken = => 'charizard'\n\n @getDevice = sinon.stub().yields null, uu", "end": 4206, "score": 0.9052250385284424, "start": 4197, "tag": "PASSWORD", "value": "charizard" } ]
test/lib/generateAndStoreToken-spec.coffee
CESARBR/knot-cloud-source
4
generateAndStoreToken = require '../../lib/generateAndStoreToken' describe 'generateAndStoreToken', -> beforeEach -> @sut = generateAndStoreToken describe 'when called with a uuid and a callback', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'charizard' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {uuid: '12'}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should return no error', -> expect(@error).to.not.exist it 'should have a token in the result', -> expect(@result.token).to.equal 'charizard' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token: 'charizard'} describe 'when called with a different uuid and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => 'pikachu' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'pikachu'} describe 'when called with a uuid, a tag and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => 'pikachu' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441', tag: 'super-tag'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should have a tag in the result', -> expect(@result.tag).to.equal 'super-tag' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'pikachu', tag: 'super-tag'} describe 'called when storeResults yields an error', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'charizard' Device::storeToken = sinon.stub().yields new Error() @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist describe 'when securityImp.canConfigure returns false', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'charizard' @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, false @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist
196852
generateAndStoreToken = require '../../lib/generateAndStoreToken' describe 'generateAndStoreToken', -> beforeEach -> @sut = generateAndStoreToken describe 'when called with a uuid and a callback', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => '<PASSWORD>' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {uuid: '12'}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should return no error', -> expect(@error).to.not.exist it 'should have a token in the result', -> expect(@result.token).to.equal 'char<PASSWORD>' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token: '<PASSWORD>'} describe 'when called with a different uuid and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => '<PASSWORD>' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'<PASSWORD>'} describe 'when called with a uuid, a tag and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => '<PASSWORD>' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441', tag: 'super-tag'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should have a tag in the result', -> expect(@result.tag).to.equal 'super-tag' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'<PASSWORD>', tag: 'super-tag'} describe 'called when storeResults yields an error', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => '<PASSWORD>' Device::storeToken = sinon.stub().yields new Error() @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist describe 'when securityImp.canConfigure returns false', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => '<PASSWORD>' @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, false @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist
true
generateAndStoreToken = require '../../lib/generateAndStoreToken' describe 'generateAndStoreToken', -> beforeEach -> @sut = generateAndStoreToken describe 'when called with a uuid and a callback', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'PI:PASSWORD:<PASSWORD>END_PI' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {uuid: '12'}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should return no error', -> expect(@error).to.not.exist it 'should have a token in the result', -> expect(@result.token).to.equal 'charPI:PASSWORD:<PASSWORD>END_PI' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token: 'PI:PASSWORD:<PASSWORD>END_PI'} describe 'when called with a different uuid and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => 'PI:PASSWORD:<PASSWORD>END_PI' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'PI:PASSWORD:<PASSWORD>END_PI'} describe 'when called with a uuid, a tag and a callback', -> beforeEach (done) -> Device = sinon.stub() Device::generateToken = => 'PI:PASSWORD:<PASSWORD>END_PI' Device::storeToken = sinon.stub().yields null @getDevice = sinon.stub().yields null, uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'267fb089-1d2e-46cb-be13-9de4e75db441', tag: 'super-tag'}, storeResults, @dependencies it 'should have a token in the result', -> expect(@result.token).to.equal 'pikachu' it 'should have a tag in the result', -> expect(@result.tag).to.equal 'super-tag' it 'should instantiate a Device with the uuid', -> expect(@dependencies.Device).to.have.been.calledWith uuid: '267fb089-1d2e-46cb-be13-9de4e75db441' it 'should store the token', -> expect(@dependencies.Device::storeToken).to.have.been.calledWith {token:'PI:PASSWORD:<PASSWORD>END_PI', tag: 'super-tag'} describe 'called when storeResults yields an error', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'PI:PASSWORD:<PASSWORD>END_PI' Device::storeToken = sinon.stub().yields new Error() @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, true @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid:'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist describe 'when securityImp.canConfigure returns false', -> beforeEach (done) -> Device = sinon.spy() Device::generateToken = => 'PI:PASSWORD:<PASSWORD>END_PI' @getDevice = sinon.stub().yields null, uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa' @securityImpl = canConfigure: sinon.stub().yields null, false @dependencies = Device: Device, getDevice: @getDevice, securityImpl: @securityImpl storeResults = (@error, @result) => done() @sut {}, {uuid: 'ccc2f14f-3a64-4aa0-b64c-8e62fbd52eaa'}, storeResults, @dependencies it 'should yield the error', -> expect(@error).to.exist it 'should have no result', -> expect(@result).to.not.exist
[ { "context": "eql 0\n\n it '.set', ->\n list.set [ {name: 'blue'}, {name: 'yellow'} ]\n expect(list.length).e", "end": 339, "score": 0.952790379524231, "start": 335, "tag": "NAME", "value": "blue" }, { "context": "set', ->\n list.set [ {name: 'blue'}, {name: 'yellow'} ]\n expect(list.length).eql 2\n expect(", "end": 357, "score": 0.932795524597168, "start": 351, "tag": "NAME", "value": "yellow" }, { "context": "h', spy('change:length')\n list.set [ {name: 'blue'}, {name: 'yellow'} ]\n expect(spy('change:le", "end": 565, "score": 0.9183520078659058, "start": 561, "tag": "NAME", "value": "blue" }, { "context": "length')\n list.set [ {name: 'blue'}, {name: 'yellow'} ]\n expect(spy('change:length')).calledOnce", "end": 583, "score": 0.7230744957923889, "start": 577, "tag": "NAME", "value": "yellow" }, { "context": " list = new Items()\n list.set [ {name: 'red'}, {name: 'green'} ]\n\n it 'forEach', ->\n ", "end": 748, "score": 0.9617728590965271, "start": 745, "tag": "NAME", "value": "red" }, { "context": "w Items()\n list.set [ {name: 'red'}, {name: 'green'} ]\n\n it 'forEach', ->\n names = []\n ", "end": 765, "score": 0.9057024121284485, "start": 760, "tag": "NAME", "value": "green" } ]
test/collection_test.coffee
rstacruz/ento
11
require './setup' Items = null list = null describe 'collections', -> beforeEach 'create class', -> Items = Ento() .use(Ento.collection) describe 'empty list', -> beforeEach 'instanciate', -> list = new Items() it 'length', -> expect(list.length).eql 0 it '.set', -> list.set [ {name: 'blue'}, {name: 'yellow'} ] expect(list.length).eql 2 expect(list.get('length')).eql 2 it '.set should trigger change in length', -> list.on 'change:length', spy('change:length') list.set [ {name: 'blue'}, {name: 'yellow'} ] expect(spy('change:length')).calledOnce describe 'full list', -> beforeEach 'instanciate', -> list = new Items() list.set [ {name: 'red'}, {name: 'green'} ] it 'forEach', -> names = [] list.forEach (item) -> names.push(item.name) expect(names).like ['red', 'green'] it 'length', -> expect(list.length).eql 2 it 'at', -> expect(list.at(0).name).eql 'red' describe 'to do', -> it 'model coercion (!)', -> it 'push', -> it 'pop', -> it 'shift', -> it 'unshift', -> it 'sort and filter (!)', ->
224646
require './setup' Items = null list = null describe 'collections', -> beforeEach 'create class', -> Items = Ento() .use(Ento.collection) describe 'empty list', -> beforeEach 'instanciate', -> list = new Items() it 'length', -> expect(list.length).eql 0 it '.set', -> list.set [ {name: '<NAME>'}, {name: '<NAME>'} ] expect(list.length).eql 2 expect(list.get('length')).eql 2 it '.set should trigger change in length', -> list.on 'change:length', spy('change:length') list.set [ {name: '<NAME>'}, {name: '<NAME>'} ] expect(spy('change:length')).calledOnce describe 'full list', -> beforeEach 'instanciate', -> list = new Items() list.set [ {name: '<NAME>'}, {name: '<NAME>'} ] it 'forEach', -> names = [] list.forEach (item) -> names.push(item.name) expect(names).like ['red', 'green'] it 'length', -> expect(list.length).eql 2 it 'at', -> expect(list.at(0).name).eql 'red' describe 'to do', -> it 'model coercion (!)', -> it 'push', -> it 'pop', -> it 'shift', -> it 'unshift', -> it 'sort and filter (!)', ->
true
require './setup' Items = null list = null describe 'collections', -> beforeEach 'create class', -> Items = Ento() .use(Ento.collection) describe 'empty list', -> beforeEach 'instanciate', -> list = new Items() it 'length', -> expect(list.length).eql 0 it '.set', -> list.set [ {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'} ] expect(list.length).eql 2 expect(list.get('length')).eql 2 it '.set should trigger change in length', -> list.on 'change:length', spy('change:length') list.set [ {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'} ] expect(spy('change:length')).calledOnce describe 'full list', -> beforeEach 'instanciate', -> list = new Items() list.set [ {name: 'PI:NAME:<NAME>END_PI'}, {name: 'PI:NAME:<NAME>END_PI'} ] it 'forEach', -> names = [] list.forEach (item) -> names.push(item.name) expect(names).like ['red', 'green'] it 'length', -> expect(list.length).eql 2 it 'at', -> expect(list.at(0).name).eql 'red' describe 'to do', -> it 'model coercion (!)', -> it 'push', -> it 'pop', -> it 'shift', -> it 'unshift', -> it 'sort and filter (!)', ->
[ { "context": "uctively modifies original Vector\n\n hero = {id: 'He-Man', pos: {x: 5, y: 10, z: 20}, original: true, log:", "end": 693, "score": 0.9116077423095703, "start": 687, "tag": "NAME", "value": "He-Man" }, { "context": "original: true, log: console.log}\n enemy = {id: 'Skeletor', pos: {x: 50, y: 50, z: 10}, target: hero", "end": 774, "score": 0.4955803453922272, "start": 773, "tag": "NAME", "value": "S" }, { "context": "riginal: true, log: console.log}\n enemy = {id: 'Skeletor', pos: {x: 50, y: 50, z: 10}, target: hero, origi", "end": 781, "score": 0.8406160473823547, "start": 774, "tag": "USERNAME", "value": "keletor" }, { "context": " var enemy = this.getTarget();\n enemy.id = 'Zelda';\n var enemy2 = this.getTarget();\n enem", "end": 1249, "score": 0.797074019908905, "start": 1244, "tag": "NAME", "value": "Zelda" }, { "context": "py() for p in [p0, p1, p2])\n milo =\n id: \"Milo\"\n pos: p0\n target: p1\n target2: p2", "end": 4701, "score": 0.9412802457809448, "start": 4697, "tag": "NAME", "value": "Milo" }, { "context": " this.infants = 0;\n this.namesLeft = ['Max', 'Jax', 'Dax'];\n this.namesUsed = [];\n ", "end": 7226, "score": 0.9996193647384644, "start": 7223, "tag": "NAME", "value": "Max" }, { "context": "is.infants = 0;\n this.namesLeft = ['Max', 'Jax', 'Dax'];\n this.namesUsed = [];\n th", "end": 7233, "score": 0.9996364712715149, "start": 7230, "tag": "NAME", "value": "Jax" }, { "context": "nts = 0;\n this.namesLeft = ['Max', 'Jax', 'Dax'];\n this.namesUsed = [];\n this.petS", "end": 7240, "score": 0.9992889165878296, "start": 7237, "tag": "NAME", "value": "Dax" }, { "context": " return ++this.infants;\n \"\"\"\n mama = id: \"Mama\", pets: ['dog'], apiProperties: ['pets']\n aeth", "end": 7626, "score": 0.9525995254516602, "start": 7622, "tag": "NAME", "value": "Mama" } ]
test/protect_api_spec.coffee
deepak1556/aether
1
Aether = require '../aether' describe "API Protection Test Suite", -> class Vector @className: "Vector" @add: (a, b) -> a.copy().add b @subtract: (a, b) -> a.copy().subtract b constructor: (@x=0, @y=0, @z=0) -> copy: -> new Vector(@x, @y, @z) equals: (other) -> other and @x is other.x and @y is other.y and @z is other.z add: (other) -> @x += other.x @y += other.y @z += other.z @ subtract: (other) -> @x -= other.x @y -= other.y @z -= other.z @ apiProperties: ['copy', 'equals', 'x', 'y', 'z', 'add', 'subtract'] apiMethods: [] # nothing destructively modifies original Vector hero = {id: 'He-Man', pos: {x: 5, y: 10, z: 20}, original: true, log: console.log} enemy = {id: 'Skeletor', pos: {x: 50, y: 50, z: 10}, target: hero, original: true} hero.target = enemy hero.getTarget = enemy.getTarget = -> @target hero.setTarget = enemy.setTarget = (@target) -> hero.apiProperties = ['id', 'pos', 'target', 'getTarget'] hero.apiMethods = ['setTarget'] enemy.apiProperties = ['id', 'pos', 'target', 'getTarget'] it 'should not let you mess with original objects', -> code = """ var enemy = this.getTarget(); enemy.id = 'Zelda'; var enemy2 = this.getTarget(); enemy2.pos.z = this.pos.z = enemy2.getTarget().pos.z = 9001; return enemy2.id; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual 'Skeletor' # Writes fail to non-writable property expect(enemy.id).toEqual 'Skeletor' expect(hero.pos.z).not.toEqual 9001 expect(enemy.pos.z).not.toEqual 9001 it 'should restore original objects when used as function arguments', -> code = """ var hero = this.getTarget().getTarget(); var heroID = hero.id; hero.setTarget(hero); var hero2 = hero.getTarget(); hero2.id = 'Pikachu'; return heroID; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual "He-Man" expect(hero.id).toEqual 'He-Man' expect(hero.target.id).toEqual 'He-Man' expect(enemy.id).toEqual 'Skeletor' it 'should restrict access to apiProperties', -> hand = {id: 'Hand', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} foot = {id: 'Foot', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} butt = {id: 'Butt', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} hand.enemies = [foot, butt] foot.enemies = [hand] butt.enemies = [hand] hand.getEnemies = foot.getEnemies = butt.getEnemies = -> @enemies code = """ var enemies = this.getEnemies(); enemies[1] = enemies[0]; enemies[0].id = 'The Hammer'; enemies.push(enemies[0]); var thisWorld = this.world; this.world = 'Public'; var theirWorld = enemies[0].world; enemies[0].world = 'Mine'; return {ourWorld: thisWorld, theirWorld: theirWorld, ourEnemies: this.enemies, theirEnemies: enemies[0].enemies, ourWorldAttempted: this.world, ourEnemiesAttempted: enemies}; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hand hand._aetherAPIMethodsAllowed = true result = method() hand._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result.ourWorld).toEqual undefined expect(result.theirWorld).toEqual undefined expect(result.ourEnemies).toEqual undefined expect(result.theirEnemies).toEqual undefined expect(hand.world).toEqual 'Secret' expect(foot.world).toEqual 'Secret' expect(hand.enemies[0].id).toEqual 'Foot' expect(hand.enemies[1].id).toEqual 'Butt' expect(hand.enemies.length).toEqual 2 expect(result.ourWorldAttempted).toEqual 'Public' # Not in API, they can write their own values expect(result.ourEnemiesAttempted.length).toEqual 2 # Don't let them modify the array expect(result.ourEnemiesAttempted[0].id).toEqual 'Foot' # Non-writable it 'should handle instances of classes', -> p0 = new Vector 0, 0, 0 p1 = new Vector 10, 10, 10 p2 = new Vector 100, 100, 100 originalPoints = (p.copy() for p in [p0, p1, p2]) milo = id: "Milo" pos: p0 target: p1 target2: p2 setTarget: (@target) -> move: -> @pos.add Vector.subtract(@target, @pos) apiProperties: ['id', 'pos', 'target', 'target2'] apiMethods: ['setTarget', 'move'] code = """ this.pos.constructor.subtract = this.pos.constructor.add; this.pos.subtract = this.target.subtract = this.target2.subtract = this.pos.add; var points = []; points.push(this.pos.copy()); // points[0] == p0 this.pos.x = this.target.x; points.push(this.pos.copy()); // points[1] == p0 this.pos.add(this.target); points.push(this.pos.copy()); // points[2] == p0 this.move(); points.push(this.pos.copy()); // points[3] == p1 this.setTarget(this.target2); this.move(); points.push(this.pos.copy()); // points[4] == p2 return points; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod milo milo._aetherAPIMethodsAllowed = true points = method() milo._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(milo.pos).toBe p0 expect(milo.target).toBe p2 expect(Vector.add(originalPoints[1], originalPoints[1]).x).toEqual 20 expect(points[0].equals(originalPoints[0])).toBe true expect(points[1].equals(originalPoints[0])).toBe true expect(points[2].equals(originalPoints[0])).toBe true expect(points[3].equals(originalPoints[1])).toBe true expect(points[4].equals(originalPoints[2])).toBe true it 'should protect function arguments', -> p0 = new Vector 10, 10, 10 p1 = new Vector 100, 100, 100 code = """ target.x = 5; home.y = 50; return target.z; """ aether = new Aether protectAPI: true, functionParameters: ['target', 'home', 'nothing'] aether.transpile code result = aether.run null, p0, p1 expect(aether.problems.errors.length).toEqual 0 expect(p0.x).toEqual 10 expect(p1.y).toEqual 100 expect(result).toEqual 10 it 'should protect return values', -> code = """ return hero; """ aether = new Aether protectAPI: true, functionParameters: ['hero'] aether.transpile code result = aether.run null, hero expect(aether.problems.errors.length).toEqual 0 expect(result).toBe hero it 'should not interfere with user-defined properties', -> code = """ if(typeof this.infants === 'undefined') { this.infants = 0; this.namesLeft = ['Max', 'Jax', 'Dax']; this.namesUsed = []; this.petShouldEat = []; this.hackThePets = this.pets; } this.namesUsed.push(this.namesLeft.shift()); this.petShouldEat[0] = this.namesUsed[this.namesUsed.length - 1]; this.hackThePets.push(this.petShouldEat[0]); this.pets.push(this.petShouldEat[0]); return ++this.infants; """ mama = id: "Mama", pets: ['dog'], apiProperties: ['pets'] aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod mama for i in [0 ... 3] mama._aetherAPIMethodsAllowed = true expect(method()).toEqual i + 1 mama._aetherAPIMethodsAllowed = false for prop of mama.__aetherAPIClone when typeof mama[prop] is 'undefined' and not (prop in (mama.apiUserProperties ? [])) mama.apiUserProperties ?= [] mama.apiUserProperties.push prop for prop in (mama.apiUserProperties ? []) mama[prop] = mama.__aetherAPIClone[prop] delete mama.__aetherAPIClone expect(mama.infants).toEqual i + 1 expect(mama.namesUsed.length).toEqual i + 1 expect(mama.namesLeft.length).toEqual 2 - i expect(mama.petShouldEat[0]).toEqual mama.namesUsed[mama.namesUsed.length - 1] expect(mama.pets.length).toEqual 1
215280
Aether = require '../aether' describe "API Protection Test Suite", -> class Vector @className: "Vector" @add: (a, b) -> a.copy().add b @subtract: (a, b) -> a.copy().subtract b constructor: (@x=0, @y=0, @z=0) -> copy: -> new Vector(@x, @y, @z) equals: (other) -> other and @x is other.x and @y is other.y and @z is other.z add: (other) -> @x += other.x @y += other.y @z += other.z @ subtract: (other) -> @x -= other.x @y -= other.y @z -= other.z @ apiProperties: ['copy', 'equals', 'x', 'y', 'z', 'add', 'subtract'] apiMethods: [] # nothing destructively modifies original Vector hero = {id: '<NAME>', pos: {x: 5, y: 10, z: 20}, original: true, log: console.log} enemy = {id: '<NAME>keletor', pos: {x: 50, y: 50, z: 10}, target: hero, original: true} hero.target = enemy hero.getTarget = enemy.getTarget = -> @target hero.setTarget = enemy.setTarget = (@target) -> hero.apiProperties = ['id', 'pos', 'target', 'getTarget'] hero.apiMethods = ['setTarget'] enemy.apiProperties = ['id', 'pos', 'target', 'getTarget'] it 'should not let you mess with original objects', -> code = """ var enemy = this.getTarget(); enemy.id = '<NAME>'; var enemy2 = this.getTarget(); enemy2.pos.z = this.pos.z = enemy2.getTarget().pos.z = 9001; return enemy2.id; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual 'Skeletor' # Writes fail to non-writable property expect(enemy.id).toEqual 'Skeletor' expect(hero.pos.z).not.toEqual 9001 expect(enemy.pos.z).not.toEqual 9001 it 'should restore original objects when used as function arguments', -> code = """ var hero = this.getTarget().getTarget(); var heroID = hero.id; hero.setTarget(hero); var hero2 = hero.getTarget(); hero2.id = 'Pikachu'; return heroID; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual "He-Man" expect(hero.id).toEqual 'He-Man' expect(hero.target.id).toEqual 'He-Man' expect(enemy.id).toEqual 'Skeletor' it 'should restrict access to apiProperties', -> hand = {id: 'Hand', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} foot = {id: 'Foot', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} butt = {id: 'Butt', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} hand.enemies = [foot, butt] foot.enemies = [hand] butt.enemies = [hand] hand.getEnemies = foot.getEnemies = butt.getEnemies = -> @enemies code = """ var enemies = this.getEnemies(); enemies[1] = enemies[0]; enemies[0].id = 'The Hammer'; enemies.push(enemies[0]); var thisWorld = this.world; this.world = 'Public'; var theirWorld = enemies[0].world; enemies[0].world = 'Mine'; return {ourWorld: thisWorld, theirWorld: theirWorld, ourEnemies: this.enemies, theirEnemies: enemies[0].enemies, ourWorldAttempted: this.world, ourEnemiesAttempted: enemies}; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hand hand._aetherAPIMethodsAllowed = true result = method() hand._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result.ourWorld).toEqual undefined expect(result.theirWorld).toEqual undefined expect(result.ourEnemies).toEqual undefined expect(result.theirEnemies).toEqual undefined expect(hand.world).toEqual 'Secret' expect(foot.world).toEqual 'Secret' expect(hand.enemies[0].id).toEqual 'Foot' expect(hand.enemies[1].id).toEqual 'Butt' expect(hand.enemies.length).toEqual 2 expect(result.ourWorldAttempted).toEqual 'Public' # Not in API, they can write their own values expect(result.ourEnemiesAttempted.length).toEqual 2 # Don't let them modify the array expect(result.ourEnemiesAttempted[0].id).toEqual 'Foot' # Non-writable it 'should handle instances of classes', -> p0 = new Vector 0, 0, 0 p1 = new Vector 10, 10, 10 p2 = new Vector 100, 100, 100 originalPoints = (p.copy() for p in [p0, p1, p2]) milo = id: "<NAME>" pos: p0 target: p1 target2: p2 setTarget: (@target) -> move: -> @pos.add Vector.subtract(@target, @pos) apiProperties: ['id', 'pos', 'target', 'target2'] apiMethods: ['setTarget', 'move'] code = """ this.pos.constructor.subtract = this.pos.constructor.add; this.pos.subtract = this.target.subtract = this.target2.subtract = this.pos.add; var points = []; points.push(this.pos.copy()); // points[0] == p0 this.pos.x = this.target.x; points.push(this.pos.copy()); // points[1] == p0 this.pos.add(this.target); points.push(this.pos.copy()); // points[2] == p0 this.move(); points.push(this.pos.copy()); // points[3] == p1 this.setTarget(this.target2); this.move(); points.push(this.pos.copy()); // points[4] == p2 return points; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod milo milo._aetherAPIMethodsAllowed = true points = method() milo._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(milo.pos).toBe p0 expect(milo.target).toBe p2 expect(Vector.add(originalPoints[1], originalPoints[1]).x).toEqual 20 expect(points[0].equals(originalPoints[0])).toBe true expect(points[1].equals(originalPoints[0])).toBe true expect(points[2].equals(originalPoints[0])).toBe true expect(points[3].equals(originalPoints[1])).toBe true expect(points[4].equals(originalPoints[2])).toBe true it 'should protect function arguments', -> p0 = new Vector 10, 10, 10 p1 = new Vector 100, 100, 100 code = """ target.x = 5; home.y = 50; return target.z; """ aether = new Aether protectAPI: true, functionParameters: ['target', 'home', 'nothing'] aether.transpile code result = aether.run null, p0, p1 expect(aether.problems.errors.length).toEqual 0 expect(p0.x).toEqual 10 expect(p1.y).toEqual 100 expect(result).toEqual 10 it 'should protect return values', -> code = """ return hero; """ aether = new Aether protectAPI: true, functionParameters: ['hero'] aether.transpile code result = aether.run null, hero expect(aether.problems.errors.length).toEqual 0 expect(result).toBe hero it 'should not interfere with user-defined properties', -> code = """ if(typeof this.infants === 'undefined') { this.infants = 0; this.namesLeft = ['<NAME>', '<NAME>', '<NAME>']; this.namesUsed = []; this.petShouldEat = []; this.hackThePets = this.pets; } this.namesUsed.push(this.namesLeft.shift()); this.petShouldEat[0] = this.namesUsed[this.namesUsed.length - 1]; this.hackThePets.push(this.petShouldEat[0]); this.pets.push(this.petShouldEat[0]); return ++this.infants; """ mama = id: "<NAME>", pets: ['dog'], apiProperties: ['pets'] aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod mama for i in [0 ... 3] mama._aetherAPIMethodsAllowed = true expect(method()).toEqual i + 1 mama._aetherAPIMethodsAllowed = false for prop of mama.__aetherAPIClone when typeof mama[prop] is 'undefined' and not (prop in (mama.apiUserProperties ? [])) mama.apiUserProperties ?= [] mama.apiUserProperties.push prop for prop in (mama.apiUserProperties ? []) mama[prop] = mama.__aetherAPIClone[prop] delete mama.__aetherAPIClone expect(mama.infants).toEqual i + 1 expect(mama.namesUsed.length).toEqual i + 1 expect(mama.namesLeft.length).toEqual 2 - i expect(mama.petShouldEat[0]).toEqual mama.namesUsed[mama.namesUsed.length - 1] expect(mama.pets.length).toEqual 1
true
Aether = require '../aether' describe "API Protection Test Suite", -> class Vector @className: "Vector" @add: (a, b) -> a.copy().add b @subtract: (a, b) -> a.copy().subtract b constructor: (@x=0, @y=0, @z=0) -> copy: -> new Vector(@x, @y, @z) equals: (other) -> other and @x is other.x and @y is other.y and @z is other.z add: (other) -> @x += other.x @y += other.y @z += other.z @ subtract: (other) -> @x -= other.x @y -= other.y @z -= other.z @ apiProperties: ['copy', 'equals', 'x', 'y', 'z', 'add', 'subtract'] apiMethods: [] # nothing destructively modifies original Vector hero = {id: 'PI:NAME:<NAME>END_PI', pos: {x: 5, y: 10, z: 20}, original: true, log: console.log} enemy = {id: 'PI:NAME:<NAME>END_PIkeletor', pos: {x: 50, y: 50, z: 10}, target: hero, original: true} hero.target = enemy hero.getTarget = enemy.getTarget = -> @target hero.setTarget = enemy.setTarget = (@target) -> hero.apiProperties = ['id', 'pos', 'target', 'getTarget'] hero.apiMethods = ['setTarget'] enemy.apiProperties = ['id', 'pos', 'target', 'getTarget'] it 'should not let you mess with original objects', -> code = """ var enemy = this.getTarget(); enemy.id = 'PI:NAME:<NAME>END_PI'; var enemy2 = this.getTarget(); enemy2.pos.z = this.pos.z = enemy2.getTarget().pos.z = 9001; return enemy2.id; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual 'Skeletor' # Writes fail to non-writable property expect(enemy.id).toEqual 'Skeletor' expect(hero.pos.z).not.toEqual 9001 expect(enemy.pos.z).not.toEqual 9001 it 'should restore original objects when used as function arguments', -> code = """ var hero = this.getTarget().getTarget(); var heroID = hero.id; hero.setTarget(hero); var hero2 = hero.getTarget(); hero2.id = 'Pikachu'; return heroID; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hero hero._aetherAPIMethodsAllowed = true result = method() hero._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result).toEqual "He-Man" expect(hero.id).toEqual 'He-Man' expect(hero.target.id).toEqual 'He-Man' expect(enemy.id).toEqual 'Skeletor' it 'should restrict access to apiProperties', -> hand = {id: 'Hand', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} foot = {id: 'Foot', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} butt = {id: 'Butt', world: "Secret", apiProperties: ["id"], apiMethods: ["getEnemies"]} hand.enemies = [foot, butt] foot.enemies = [hand] butt.enemies = [hand] hand.getEnemies = foot.getEnemies = butt.getEnemies = -> @enemies code = """ var enemies = this.getEnemies(); enemies[1] = enemies[0]; enemies[0].id = 'The Hammer'; enemies.push(enemies[0]); var thisWorld = this.world; this.world = 'Public'; var theirWorld = enemies[0].world; enemies[0].world = 'Mine'; return {ourWorld: thisWorld, theirWorld: theirWorld, ourEnemies: this.enemies, theirEnemies: enemies[0].enemies, ourWorldAttempted: this.world, ourEnemiesAttempted: enemies}; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod hand hand._aetherAPIMethodsAllowed = true result = method() hand._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(result.ourWorld).toEqual undefined expect(result.theirWorld).toEqual undefined expect(result.ourEnemies).toEqual undefined expect(result.theirEnemies).toEqual undefined expect(hand.world).toEqual 'Secret' expect(foot.world).toEqual 'Secret' expect(hand.enemies[0].id).toEqual 'Foot' expect(hand.enemies[1].id).toEqual 'Butt' expect(hand.enemies.length).toEqual 2 expect(result.ourWorldAttempted).toEqual 'Public' # Not in API, they can write their own values expect(result.ourEnemiesAttempted.length).toEqual 2 # Don't let them modify the array expect(result.ourEnemiesAttempted[0].id).toEqual 'Foot' # Non-writable it 'should handle instances of classes', -> p0 = new Vector 0, 0, 0 p1 = new Vector 10, 10, 10 p2 = new Vector 100, 100, 100 originalPoints = (p.copy() for p in [p0, p1, p2]) milo = id: "PI:NAME:<NAME>END_PI" pos: p0 target: p1 target2: p2 setTarget: (@target) -> move: -> @pos.add Vector.subtract(@target, @pos) apiProperties: ['id', 'pos', 'target', 'target2'] apiMethods: ['setTarget', 'move'] code = """ this.pos.constructor.subtract = this.pos.constructor.add; this.pos.subtract = this.target.subtract = this.target2.subtract = this.pos.add; var points = []; points.push(this.pos.copy()); // points[0] == p0 this.pos.x = this.target.x; points.push(this.pos.copy()); // points[1] == p0 this.pos.add(this.target); points.push(this.pos.copy()); // points[2] == p0 this.move(); points.push(this.pos.copy()); // points[3] == p1 this.setTarget(this.target2); this.move(); points.push(this.pos.copy()); // points[4] == p2 return points; """ aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod milo milo._aetherAPIMethodsAllowed = true points = method() milo._aetherAPIMethodsAllowed = false expect(aether.problems.errors.length).toEqual 0 expect(milo.pos).toBe p0 expect(milo.target).toBe p2 expect(Vector.add(originalPoints[1], originalPoints[1]).x).toEqual 20 expect(points[0].equals(originalPoints[0])).toBe true expect(points[1].equals(originalPoints[0])).toBe true expect(points[2].equals(originalPoints[0])).toBe true expect(points[3].equals(originalPoints[1])).toBe true expect(points[4].equals(originalPoints[2])).toBe true it 'should protect function arguments', -> p0 = new Vector 10, 10, 10 p1 = new Vector 100, 100, 100 code = """ target.x = 5; home.y = 50; return target.z; """ aether = new Aether protectAPI: true, functionParameters: ['target', 'home', 'nothing'] aether.transpile code result = aether.run null, p0, p1 expect(aether.problems.errors.length).toEqual 0 expect(p0.x).toEqual 10 expect(p1.y).toEqual 100 expect(result).toEqual 10 it 'should protect return values', -> code = """ return hero; """ aether = new Aether protectAPI: true, functionParameters: ['hero'] aether.transpile code result = aether.run null, hero expect(aether.problems.errors.length).toEqual 0 expect(result).toBe hero it 'should not interfere with user-defined properties', -> code = """ if(typeof this.infants === 'undefined') { this.infants = 0; this.namesLeft = ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI']; this.namesUsed = []; this.petShouldEat = []; this.hackThePets = this.pets; } this.namesUsed.push(this.namesLeft.shift()); this.petShouldEat[0] = this.namesUsed[this.namesUsed.length - 1]; this.hackThePets.push(this.petShouldEat[0]); this.pets.push(this.petShouldEat[0]); return ++this.infants; """ mama = id: "PI:NAME:<NAME>END_PI", pets: ['dog'], apiProperties: ['pets'] aether = new Aether protectAPI: true aether.transpile code method = aether.createMethod mama for i in [0 ... 3] mama._aetherAPIMethodsAllowed = true expect(method()).toEqual i + 1 mama._aetherAPIMethodsAllowed = false for prop of mama.__aetherAPIClone when typeof mama[prop] is 'undefined' and not (prop in (mama.apiUserProperties ? [])) mama.apiUserProperties ?= [] mama.apiUserProperties.push prop for prop in (mama.apiUserProperties ? []) mama[prop] = mama.__aetherAPIClone[prop] delete mama.__aetherAPIClone expect(mama.infants).toEqual i + 1 expect(mama.namesUsed.length).toEqual i + 1 expect(mama.namesLeft.length).toEqual 2 - i expect(mama.petShouldEat[0]).toEqual mama.namesUsed[mama.namesUsed.length - 1] expect(mama.pets.length).toEqual 1
[ { "context": "lue)\n\n typeSelector = \"[#{type}]\"\n key = color.rgbaString()\n\n @colors[key] ||=\n color: color\n ", "end": 4546, "score": 0.9917704463005066, "start": 4528, "tag": "KEY", "value": "color.rgbaString()" } ]
lib/svg_image.coffee
taunoha/postcss-simple-svg
0
Color = require('color') xmldom = require('xmldom') doT = require 'dot' fs = require('fs') _ = require('lodash') SVGO = require('svgo') class SVGImage constructor: (filePath, options = {}) -> @path = filePath @options = options @xml = options.content @sprite = options.sprite || {} @defaults = if _.isString(options.defaults) then @_parseStyle(options.defaults) else {} @colors = {} @sprites = {} @colorCount = 0 @svgo = if options.svgo then svgo = new SVGO(if _.isObject(options.svgo) then options.svgo else {}) else false @_parseSvg() svgFor: (ids) -> return this if !ids || _.isEmpty(ids) id = "#{@sprite.prefix || ''}#{ids[0]}#{@sprite.postfix || ''}" if sprite = @sprites[id] sprite.svgFor ids.slice(1) else throw new Error "Can\'t find sprite with id #{id}" dataUrl: (params = {}) -> params = @_parseStyle(params) if _.isString(params) params = _.extend({}, @defaults, params) svg = @template(params) svg = @_svgoSync(svg) if @svgo "url(\"data:image/svg+xml;charset=utf-8,#{encodeURIComponent(svg)}\")" _svgoSync: (svgString) -> result = false @svgo.optimize(svgString, (str) -> result = str.data) loop return result if result _parseStyle: (string) -> result = {} return result if !string || string.indexOf(':') == -1 for rule in string.replace(/[\s"]/g, '').split(';') unless rule.indexOf(':') == -1 [key, value] = rule.split(':') result[key] = value result _parseSvg: -> result = {} xml = @xml || fs.readFileSync(@path).toString() doc = new xmldom.DOMParser().parseFromString(xml, "image/svg+xml") @svgAttributes = @_parseAttributes(doc.childNodes[0].attributes) doc = @_parseNode(doc, result, (node, attributes) => @_readColors(node, attributes)) @_checkSVG(doc) doc = new xmldom.XMLSerializer().serializeToString(doc) @template = doT.template(doc, _.extend(doT.templateSettings, { strip: false })) _checkSVG: (doc) -> if !(Object.keys(@colors).length > 0) transform = (key) -> "(it['[#{key}]'] ? '#{key}:'+it['[#{key}]']+';' : '')" doc.setAttribute('style', "{{= #{_.map(['fill', 'stroke'], transform).join('+')} }}") unless @svgAttributes.height || @svgAttributes.width doc.setAttribute('height', "{{= it['[height]'] || it['[size]'] || '100%' }}") doc.setAttribute('width', "{{= it['[width]'] || it['[size]'] || '100%' }}") _parseNode: (node, result, callback, path='') -> if node.childNodes for node in node.childNodes nodePath = path if node.tagName attributes = @_parseAttributes(node.attributes) || {} nodePath += "#{if path == '' then '' else '>'}#{node.tagName}" nodePath += "##{attributes.id.value}" if attributes.id && node.tagName != 'svg' nodePath += ".#{attributes.class.value}" if attributes.class @_addSprite(node) if node.tagName == 'symbol' attributes.path = nodePath callback(node, attributes) @_parseNode(node, result, callback, nodePath) node _readColors: (node, attributes) -> @_addColor('fill', attributes, node) if attributes.fill @_addColor('stroke', attributes, node) if attributes.stroke _parseAttributes: (attributes) -> result = {} if attributes for index, attribute of attributes if parseInt(index, 10) > 0 || index == '0' result[attribute.name] = index: index value: attribute.value result _addSprite: (node) -> return unless node.tagName == 'symbol' node = node.cloneNode(true) attributes = @_parseAttributes(node.attributes) node.tagName = 'svg' id = attributes.id && attributes.id.value || "sprite#{Object.keys(@sprites).length}" for key, value of _.assign({}, @svgAttributes, attributes) value.value = value.value.replace(/display:\s*none[^;]*/, '') if key == 'style' if !_.isEmpty(key) && key != 'undefined' && value && !_.isEmpty(value.value) && value != 'undefined' node.setAttribute(key, value.value) svg = new xmldom.XMLSerializer().serializeToString(node) sprite = new SVGImage null, content: svg defaults: @options.defaults @sprites[id] = sprite _addColor: (type, attributes, node) -> try color = if attributes[type].value == 'none' Color('rgba(255, 255, 255, 0)') else Color(attributes[type].value) typeSelector = "[#{type}]" key = color.rgbaString() @colors[key] ||= color: color count: 0 index: Object.keys(@colors).length selectors: [] @colors[key].count++ @colors[key].selectors.push "#{attributes.path}#{typeSelector}" selectors = ["color#{@colorCount++ || '0'}"] selectors.push "##{attributes.id.value}#{typeSelector}" if attributes.id selectors.push "colorGroup#{@colors[key].index || '0'}" selectors.push ".#{attributes.class.value}#{typeSelector}" if attributes.class selectors.push "#{node.tagName}[#{type}]" selectors.push typeSelector selectors.push "[color]" selectors = _.map selectors, (selector) -> "it[\'#{selector}\']" node.attributes[attributes[type].index].value = "{{= #{selectors.join(' || ')} || \'#{attributes[type].value}\'}}" catch module.exports = SVGImage
97541
Color = require('color') xmldom = require('xmldom') doT = require 'dot' fs = require('fs') _ = require('lodash') SVGO = require('svgo') class SVGImage constructor: (filePath, options = {}) -> @path = filePath @options = options @xml = options.content @sprite = options.sprite || {} @defaults = if _.isString(options.defaults) then @_parseStyle(options.defaults) else {} @colors = {} @sprites = {} @colorCount = 0 @svgo = if options.svgo then svgo = new SVGO(if _.isObject(options.svgo) then options.svgo else {}) else false @_parseSvg() svgFor: (ids) -> return this if !ids || _.isEmpty(ids) id = "#{@sprite.prefix || ''}#{ids[0]}#{@sprite.postfix || ''}" if sprite = @sprites[id] sprite.svgFor ids.slice(1) else throw new Error "Can\'t find sprite with id #{id}" dataUrl: (params = {}) -> params = @_parseStyle(params) if _.isString(params) params = _.extend({}, @defaults, params) svg = @template(params) svg = @_svgoSync(svg) if @svgo "url(\"data:image/svg+xml;charset=utf-8,#{encodeURIComponent(svg)}\")" _svgoSync: (svgString) -> result = false @svgo.optimize(svgString, (str) -> result = str.data) loop return result if result _parseStyle: (string) -> result = {} return result if !string || string.indexOf(':') == -1 for rule in string.replace(/[\s"]/g, '').split(';') unless rule.indexOf(':') == -1 [key, value] = rule.split(':') result[key] = value result _parseSvg: -> result = {} xml = @xml || fs.readFileSync(@path).toString() doc = new xmldom.DOMParser().parseFromString(xml, "image/svg+xml") @svgAttributes = @_parseAttributes(doc.childNodes[0].attributes) doc = @_parseNode(doc, result, (node, attributes) => @_readColors(node, attributes)) @_checkSVG(doc) doc = new xmldom.XMLSerializer().serializeToString(doc) @template = doT.template(doc, _.extend(doT.templateSettings, { strip: false })) _checkSVG: (doc) -> if !(Object.keys(@colors).length > 0) transform = (key) -> "(it['[#{key}]'] ? '#{key}:'+it['[#{key}]']+';' : '')" doc.setAttribute('style', "{{= #{_.map(['fill', 'stroke'], transform).join('+')} }}") unless @svgAttributes.height || @svgAttributes.width doc.setAttribute('height', "{{= it['[height]'] || it['[size]'] || '100%' }}") doc.setAttribute('width', "{{= it['[width]'] || it['[size]'] || '100%' }}") _parseNode: (node, result, callback, path='') -> if node.childNodes for node in node.childNodes nodePath = path if node.tagName attributes = @_parseAttributes(node.attributes) || {} nodePath += "#{if path == '' then '' else '>'}#{node.tagName}" nodePath += "##{attributes.id.value}" if attributes.id && node.tagName != 'svg' nodePath += ".#{attributes.class.value}" if attributes.class @_addSprite(node) if node.tagName == 'symbol' attributes.path = nodePath callback(node, attributes) @_parseNode(node, result, callback, nodePath) node _readColors: (node, attributes) -> @_addColor('fill', attributes, node) if attributes.fill @_addColor('stroke', attributes, node) if attributes.stroke _parseAttributes: (attributes) -> result = {} if attributes for index, attribute of attributes if parseInt(index, 10) > 0 || index == '0' result[attribute.name] = index: index value: attribute.value result _addSprite: (node) -> return unless node.tagName == 'symbol' node = node.cloneNode(true) attributes = @_parseAttributes(node.attributes) node.tagName = 'svg' id = attributes.id && attributes.id.value || "sprite#{Object.keys(@sprites).length}" for key, value of _.assign({}, @svgAttributes, attributes) value.value = value.value.replace(/display:\s*none[^;]*/, '') if key == 'style' if !_.isEmpty(key) && key != 'undefined' && value && !_.isEmpty(value.value) && value != 'undefined' node.setAttribute(key, value.value) svg = new xmldom.XMLSerializer().serializeToString(node) sprite = new SVGImage null, content: svg defaults: @options.defaults @sprites[id] = sprite _addColor: (type, attributes, node) -> try color = if attributes[type].value == 'none' Color('rgba(255, 255, 255, 0)') else Color(attributes[type].value) typeSelector = "[#{type}]" key = <KEY> @colors[key] ||= color: color count: 0 index: Object.keys(@colors).length selectors: [] @colors[key].count++ @colors[key].selectors.push "#{attributes.path}#{typeSelector}" selectors = ["color#{@colorCount++ || '0'}"] selectors.push "##{attributes.id.value}#{typeSelector}" if attributes.id selectors.push "colorGroup#{@colors[key].index || '0'}" selectors.push ".#{attributes.class.value}#{typeSelector}" if attributes.class selectors.push "#{node.tagName}[#{type}]" selectors.push typeSelector selectors.push "[color]" selectors = _.map selectors, (selector) -> "it[\'#{selector}\']" node.attributes[attributes[type].index].value = "{{= #{selectors.join(' || ')} || \'#{attributes[type].value}\'}}" catch module.exports = SVGImage
true
Color = require('color') xmldom = require('xmldom') doT = require 'dot' fs = require('fs') _ = require('lodash') SVGO = require('svgo') class SVGImage constructor: (filePath, options = {}) -> @path = filePath @options = options @xml = options.content @sprite = options.sprite || {} @defaults = if _.isString(options.defaults) then @_parseStyle(options.defaults) else {} @colors = {} @sprites = {} @colorCount = 0 @svgo = if options.svgo then svgo = new SVGO(if _.isObject(options.svgo) then options.svgo else {}) else false @_parseSvg() svgFor: (ids) -> return this if !ids || _.isEmpty(ids) id = "#{@sprite.prefix || ''}#{ids[0]}#{@sprite.postfix || ''}" if sprite = @sprites[id] sprite.svgFor ids.slice(1) else throw new Error "Can\'t find sprite with id #{id}" dataUrl: (params = {}) -> params = @_parseStyle(params) if _.isString(params) params = _.extend({}, @defaults, params) svg = @template(params) svg = @_svgoSync(svg) if @svgo "url(\"data:image/svg+xml;charset=utf-8,#{encodeURIComponent(svg)}\")" _svgoSync: (svgString) -> result = false @svgo.optimize(svgString, (str) -> result = str.data) loop return result if result _parseStyle: (string) -> result = {} return result if !string || string.indexOf(':') == -1 for rule in string.replace(/[\s"]/g, '').split(';') unless rule.indexOf(':') == -1 [key, value] = rule.split(':') result[key] = value result _parseSvg: -> result = {} xml = @xml || fs.readFileSync(@path).toString() doc = new xmldom.DOMParser().parseFromString(xml, "image/svg+xml") @svgAttributes = @_parseAttributes(doc.childNodes[0].attributes) doc = @_parseNode(doc, result, (node, attributes) => @_readColors(node, attributes)) @_checkSVG(doc) doc = new xmldom.XMLSerializer().serializeToString(doc) @template = doT.template(doc, _.extend(doT.templateSettings, { strip: false })) _checkSVG: (doc) -> if !(Object.keys(@colors).length > 0) transform = (key) -> "(it['[#{key}]'] ? '#{key}:'+it['[#{key}]']+';' : '')" doc.setAttribute('style', "{{= #{_.map(['fill', 'stroke'], transform).join('+')} }}") unless @svgAttributes.height || @svgAttributes.width doc.setAttribute('height', "{{= it['[height]'] || it['[size]'] || '100%' }}") doc.setAttribute('width', "{{= it['[width]'] || it['[size]'] || '100%' }}") _parseNode: (node, result, callback, path='') -> if node.childNodes for node in node.childNodes nodePath = path if node.tagName attributes = @_parseAttributes(node.attributes) || {} nodePath += "#{if path == '' then '' else '>'}#{node.tagName}" nodePath += "##{attributes.id.value}" if attributes.id && node.tagName != 'svg' nodePath += ".#{attributes.class.value}" if attributes.class @_addSprite(node) if node.tagName == 'symbol' attributes.path = nodePath callback(node, attributes) @_parseNode(node, result, callback, nodePath) node _readColors: (node, attributes) -> @_addColor('fill', attributes, node) if attributes.fill @_addColor('stroke', attributes, node) if attributes.stroke _parseAttributes: (attributes) -> result = {} if attributes for index, attribute of attributes if parseInt(index, 10) > 0 || index == '0' result[attribute.name] = index: index value: attribute.value result _addSprite: (node) -> return unless node.tagName == 'symbol' node = node.cloneNode(true) attributes = @_parseAttributes(node.attributes) node.tagName = 'svg' id = attributes.id && attributes.id.value || "sprite#{Object.keys(@sprites).length}" for key, value of _.assign({}, @svgAttributes, attributes) value.value = value.value.replace(/display:\s*none[^;]*/, '') if key == 'style' if !_.isEmpty(key) && key != 'undefined' && value && !_.isEmpty(value.value) && value != 'undefined' node.setAttribute(key, value.value) svg = new xmldom.XMLSerializer().serializeToString(node) sprite = new SVGImage null, content: svg defaults: @options.defaults @sprites[id] = sprite _addColor: (type, attributes, node) -> try color = if attributes[type].value == 'none' Color('rgba(255, 255, 255, 0)') else Color(attributes[type].value) typeSelector = "[#{type}]" key = PI:KEY:<KEY>END_PI @colors[key] ||= color: color count: 0 index: Object.keys(@colors).length selectors: [] @colors[key].count++ @colors[key].selectors.push "#{attributes.path}#{typeSelector}" selectors = ["color#{@colorCount++ || '0'}"] selectors.push "##{attributes.id.value}#{typeSelector}" if attributes.id selectors.push "colorGroup#{@colors[key].index || '0'}" selectors.push ".#{attributes.class.value}#{typeSelector}" if attributes.class selectors.push "#{node.tagName}[#{type}]" selectors.push typeSelector selectors.push "[color]" selectors = _.map selectors, (selector) -> "it[\'#{selector}\']" node.attributes[attributes[type].index].value = "{{= #{selectors.join(' || ')} || \'#{attributes[type].value}\'}}" catch module.exports = SVGImage
[ { "context": "_BUCKET = 'octoblu-channels'\nCHANNEL_S3_KEY = 'channels.json'\n\nclass ChannelDownloader\n constructor: ->\n @", "end": 143, "score": 0.9649226665496826, "start": 130, "tag": "KEY", "value": "channels.json" } ]
src/channel-downloader.coffee
octoblu/nanocyte-configuration-generator
0
_ = require 'lodash' s3 = require 's3' CHANNEL_S3_BUCKET = 'octoblu-channels' CHANNEL_S3_KEY = 'channels.json' class ChannelDownloader constructor: -> @cached = false @etag = null @data = null @_checkEtag = _.throttle @_checkEtagImmediately, 60*1000*5, leading: true, trailing: false setOptions: (options) => return if _.isEmpty options.accessKeyId @s3client ?= s3.createClient s3Options: accessKeyId: options.accessKeyId secretAccessKey: options.secretAccessKey update: (callback) => return callback null, {} unless @s3client? @_checkEtag() return callback null, @data if @cached downloader = @s3client.downloadBuffer Bucket: CHANNEL_S3_BUCKET Key: CHANNEL_S3_KEY downloader.on 'httpHeaders', (statusCode, headers) -> @etag = headers.etag downloader.on 'error', callback downloader.on 'end', (buffer) => try @data = JSON.parse buffer catch error return callback error @cached = true callback null, @data _checkEtagImmediately: => list = @s3client.listObjects s3Params: Bucket: CHANNEL_S3_BUCKET list.on 'data', (data) => entry = _.find data.Contents, {'Key': 'channels.json'} return unless entry? return if @etag == entry.ETag @etag = entry.ETag @cached = false module.exports = ChannelDownloader
91960
_ = require 'lodash' s3 = require 's3' CHANNEL_S3_BUCKET = 'octoblu-channels' CHANNEL_S3_KEY = '<KEY>' class ChannelDownloader constructor: -> @cached = false @etag = null @data = null @_checkEtag = _.throttle @_checkEtagImmediately, 60*1000*5, leading: true, trailing: false setOptions: (options) => return if _.isEmpty options.accessKeyId @s3client ?= s3.createClient s3Options: accessKeyId: options.accessKeyId secretAccessKey: options.secretAccessKey update: (callback) => return callback null, {} unless @s3client? @_checkEtag() return callback null, @data if @cached downloader = @s3client.downloadBuffer Bucket: CHANNEL_S3_BUCKET Key: CHANNEL_S3_KEY downloader.on 'httpHeaders', (statusCode, headers) -> @etag = headers.etag downloader.on 'error', callback downloader.on 'end', (buffer) => try @data = JSON.parse buffer catch error return callback error @cached = true callback null, @data _checkEtagImmediately: => list = @s3client.listObjects s3Params: Bucket: CHANNEL_S3_BUCKET list.on 'data', (data) => entry = _.find data.Contents, {'Key': 'channels.json'} return unless entry? return if @etag == entry.ETag @etag = entry.ETag @cached = false module.exports = ChannelDownloader
true
_ = require 'lodash' s3 = require 's3' CHANNEL_S3_BUCKET = 'octoblu-channels' CHANNEL_S3_KEY = 'PI:KEY:<KEY>END_PI' class ChannelDownloader constructor: -> @cached = false @etag = null @data = null @_checkEtag = _.throttle @_checkEtagImmediately, 60*1000*5, leading: true, trailing: false setOptions: (options) => return if _.isEmpty options.accessKeyId @s3client ?= s3.createClient s3Options: accessKeyId: options.accessKeyId secretAccessKey: options.secretAccessKey update: (callback) => return callback null, {} unless @s3client? @_checkEtag() return callback null, @data if @cached downloader = @s3client.downloadBuffer Bucket: CHANNEL_S3_BUCKET Key: CHANNEL_S3_KEY downloader.on 'httpHeaders', (statusCode, headers) -> @etag = headers.etag downloader.on 'error', callback downloader.on 'end', (buffer) => try @data = JSON.parse buffer catch error return callback error @cached = true callback null, @data _checkEtagImmediately: => list = @s3client.listObjects s3Params: Bucket: CHANNEL_S3_BUCKET list.on 'data', (data) => entry = _.find data.Contents, {'Key': 'channels.json'} return unless entry? return if @etag == entry.ETag @etag = entry.ETag @cached = false module.exports = ChannelDownloader
[ { "context": "# @author Gianluigi Mango\n# Query Image Collection\nImage = require './../..", "end": 25, "score": 0.9998626112937927, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/api/model/imageModel.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Query Image Collection Image = require './../../models/imageModel' module.exports = class ImageModel # Find one image in collection # @params id[String], cb[Function] # @return callback getProfileImage: (id, cb) -> Image.find profileId: id, (err, body) -> cb err, body
95469
# @author <NAME> # Query Image Collection Image = require './../../models/imageModel' module.exports = class ImageModel # Find one image in collection # @params id[String], cb[Function] # @return callback getProfileImage: (id, cb) -> Image.find profileId: id, (err, body) -> cb err, body
true
# @author PI:NAME:<NAME>END_PI # Query Image Collection Image = require './../../models/imageModel' module.exports = class ImageModel # Find one image in collection # @params id[String], cb[Function] # @return callback getProfileImage: (id, cb) -> Image.find profileId: id, (err, body) -> cb err, body
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999130368232727, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" }, { "context": "tDefault(filters, key)\n\n ret\n\n\n @keys: [\n 'general'\n 'extra'\n 'genre'\n 'language'\n 'mode", "end": 1750, "score": 0.8997535109519958, "start": 1743, "tag": "KEY", "value": "general" } ]
resources/assets/coffee/_classes/beatmapset-filter.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. parseInt10 = (string) -> int = parseInt string, 10 if _.isFinite(int) then int else null class @BeatmapsetFilter @castFromString: mode: parseInt10 genre: parseInt10 language: parseInt10 @charToKey: c: 'general' m: 'mode' s: 'status' g: 'genre' l: 'language' e: 'extra' r: 'rank' played: 'played' q: 'query' sort: 'sort' @filtersFromUrl: (url) -> params = new URL(url).searchParams filters = {} for own char, key of @charToKey value = params.get(char) continue if !value? || value.length == 0 value = @castFromString[key](value) if @castFromString[key] filters[key] = value filters @keyToChar: -> @_keyToChar ?= _.invert @charToKey @defaults: general: '' extra: '' genre: null language: null mode: null played: 'any' query: '' rank: '' status: 'leaderboard' @expand: ['genre', 'language', 'extra', 'rank', 'played'] @fillDefaults: (filters) => ret = {} for key in @keys ret[key] = filters[key] ? @getDefault(filters, key) ret @getDefault: (filters, key) => return @defaults[key] if @defaults.hasOwnProperty(key) if key == 'sort' if filters.query?.trim().length > 0 'relevance_desc' else if filters.status in ['pending', 'graveyard', 'mine'] 'updated_desc' else 'ranked_desc' @getDefaults: (filters) => ret = {} for key in @keys ret[key] = @getDefault(filters, key) ret @keys: [ 'general' 'extra' 'genre' 'language' 'mode' 'played' 'query' 'rank' 'sort' 'status' ] @queryParamsFromFilters: (filters) -> return {} if !currentUser.id? charParams = {} for own key, value of filters if value? && @getDefault(filters, key) != value charParams[@keyToChar()[key]] = value charParams # For UI purposes; server-side has its own check. @supporterRequired: (filters) -> _.reject ['played', 'rank'], (name) => _.isEmpty(filters[name]) || filters[name] == @getDefault(filters, name)
34824
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. parseInt10 = (string) -> int = parseInt string, 10 if _.isFinite(int) then int else null class @BeatmapsetFilter @castFromString: mode: parseInt10 genre: parseInt10 language: parseInt10 @charToKey: c: 'general' m: 'mode' s: 'status' g: 'genre' l: 'language' e: 'extra' r: 'rank' played: 'played' q: 'query' sort: 'sort' @filtersFromUrl: (url) -> params = new URL(url).searchParams filters = {} for own char, key of @charToKey value = params.get(char) continue if !value? || value.length == 0 value = @castFromString[key](value) if @castFromString[key] filters[key] = value filters @keyToChar: -> @_keyToChar ?= _.invert @charToKey @defaults: general: '' extra: '' genre: null language: null mode: null played: 'any' query: '' rank: '' status: 'leaderboard' @expand: ['genre', 'language', 'extra', 'rank', 'played'] @fillDefaults: (filters) => ret = {} for key in @keys ret[key] = filters[key] ? @getDefault(filters, key) ret @getDefault: (filters, key) => return @defaults[key] if @defaults.hasOwnProperty(key) if key == 'sort' if filters.query?.trim().length > 0 'relevance_desc' else if filters.status in ['pending', 'graveyard', 'mine'] 'updated_desc' else 'ranked_desc' @getDefaults: (filters) => ret = {} for key in @keys ret[key] = @getDefault(filters, key) ret @keys: [ '<KEY>' 'extra' 'genre' 'language' 'mode' 'played' 'query' 'rank' 'sort' 'status' ] @queryParamsFromFilters: (filters) -> return {} if !currentUser.id? charParams = {} for own key, value of filters if value? && @getDefault(filters, key) != value charParams[@keyToChar()[key]] = value charParams # For UI purposes; server-side has its own check. @supporterRequired: (filters) -> _.reject ['played', 'rank'], (name) => _.isEmpty(filters[name]) || filters[name] == @getDefault(filters, name)
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. parseInt10 = (string) -> int = parseInt string, 10 if _.isFinite(int) then int else null class @BeatmapsetFilter @castFromString: mode: parseInt10 genre: parseInt10 language: parseInt10 @charToKey: c: 'general' m: 'mode' s: 'status' g: 'genre' l: 'language' e: 'extra' r: 'rank' played: 'played' q: 'query' sort: 'sort' @filtersFromUrl: (url) -> params = new URL(url).searchParams filters = {} for own char, key of @charToKey value = params.get(char) continue if !value? || value.length == 0 value = @castFromString[key](value) if @castFromString[key] filters[key] = value filters @keyToChar: -> @_keyToChar ?= _.invert @charToKey @defaults: general: '' extra: '' genre: null language: null mode: null played: 'any' query: '' rank: '' status: 'leaderboard' @expand: ['genre', 'language', 'extra', 'rank', 'played'] @fillDefaults: (filters) => ret = {} for key in @keys ret[key] = filters[key] ? @getDefault(filters, key) ret @getDefault: (filters, key) => return @defaults[key] if @defaults.hasOwnProperty(key) if key == 'sort' if filters.query?.trim().length > 0 'relevance_desc' else if filters.status in ['pending', 'graveyard', 'mine'] 'updated_desc' else 'ranked_desc' @getDefaults: (filters) => ret = {} for key in @keys ret[key] = @getDefault(filters, key) ret @keys: [ 'PI:KEY:<KEY>END_PI' 'extra' 'genre' 'language' 'mode' 'played' 'query' 'rank' 'sort' 'status' ] @queryParamsFromFilters: (filters) -> return {} if !currentUser.id? charParams = {} for own key, value of filters if value? && @getDefault(filters, key) != value charParams[@keyToChar()[key]] = value charParams # For UI purposes; server-side has its own check. @supporterRequired: (filters) -> _.reject ['played', 'rank'], (name) => _.isEmpty(filters[name]) || filters[name] == @getDefault(filters, name)
[ { "context": "': [\n {type: 'separator'}\n\n {\n label: 'Juno',\n submenu: [\n {label: 'Run Block', c", "end": 177, "score": 0.8452895879745483, "start": 173, "tag": "NAME", "value": "Juno" } ]
menus/language-weave.cson
aminya/language-weave
14
'context-menu': 'atom-text-editor[data-grammar="source weave md"], atom-text-editor[data-grammar="source weave latex"]': [ {type: 'separator'} { label: 'Juno', submenu: [ {label: 'Run Block', command: 'julia-client:run-block'} {label: 'Select Block', command: 'julia-client:select-block'} {type: 'separator'} {label: 'Go to Definition', command: 'julia-client:goto-symbol'} {label: 'Show Documentation', command: 'julia-client:show-documentation'} {type: 'separator'} {label: 'Debug: Run Block', command: 'julia-debug:run-block'} {label: 'Debug: Step through Block', command: 'julia-debug:step-through-block'} {label: 'Toggle Breakpoint', command: 'julia-debug:toggle-breakpoint'} {label: 'Toggle Conditional Breakpoint', command: 'julia-debug:toggle-conditional-breakpoint'} ] } {type: 'separator'} ]
103980
'context-menu': 'atom-text-editor[data-grammar="source weave md"], atom-text-editor[data-grammar="source weave latex"]': [ {type: 'separator'} { label: '<NAME>', submenu: [ {label: 'Run Block', command: 'julia-client:run-block'} {label: 'Select Block', command: 'julia-client:select-block'} {type: 'separator'} {label: 'Go to Definition', command: 'julia-client:goto-symbol'} {label: 'Show Documentation', command: 'julia-client:show-documentation'} {type: 'separator'} {label: 'Debug: Run Block', command: 'julia-debug:run-block'} {label: 'Debug: Step through Block', command: 'julia-debug:step-through-block'} {label: 'Toggle Breakpoint', command: 'julia-debug:toggle-breakpoint'} {label: 'Toggle Conditional Breakpoint', command: 'julia-debug:toggle-conditional-breakpoint'} ] } {type: 'separator'} ]
true
'context-menu': 'atom-text-editor[data-grammar="source weave md"], atom-text-editor[data-grammar="source weave latex"]': [ {type: 'separator'} { label: 'PI:NAME:<NAME>END_PI', submenu: [ {label: 'Run Block', command: 'julia-client:run-block'} {label: 'Select Block', command: 'julia-client:select-block'} {type: 'separator'} {label: 'Go to Definition', command: 'julia-client:goto-symbol'} {label: 'Show Documentation', command: 'julia-client:show-documentation'} {type: 'separator'} {label: 'Debug: Run Block', command: 'julia-debug:run-block'} {label: 'Debug: Step through Block', command: 'julia-debug:step-through-block'} {label: 'Toggle Breakpoint', command: 'julia-debug:toggle-breakpoint'} {label: 'Toggle Conditional Breakpoint', command: 'julia-debug:toggle-conditional-breakpoint'} ] } {type: 'separator'} ]
[ { "context": "uth:\n uuid: 'masseuse'\n token: 'assassin'\n", "end": 926, "score": 0.9984177947044373, "start": 918, "tag": "PASSWORD", "value": "assassin" } ]
test/authenticate-spec.coffee
octoblu/meshblu-server-websocket
0
_ = require 'lodash' UUID = require 'uuid' Connect = require './connect' Server = require '../src/server' MeshbluWebsocket = require 'meshblu-websocket' {JobManagerResponder} = require 'meshblu-core-job-manager' describe 'sendFrame: authenticate', -> beforeEach 'connect', (done) -> @connect = new Connect() @connect.connect (error, {@sut, @workerFunc, @connection}) => done(error) beforeEach 'send authenticate request', (done) -> @workerFunc.yields null, { metadata: code: 204 } @connection.connect (error) => console.log 'connected' done error afterEach 'shutItDown', (done) -> @connect.shutItDown done it 'should create a request', -> expect(@workerFunc.firstCall.args[0]).to.containSubset metadata: jobType: 'Authenticate' auth: uuid: 'masseuse' token: 'assassin'
222189
_ = require 'lodash' UUID = require 'uuid' Connect = require './connect' Server = require '../src/server' MeshbluWebsocket = require 'meshblu-websocket' {JobManagerResponder} = require 'meshblu-core-job-manager' describe 'sendFrame: authenticate', -> beforeEach 'connect', (done) -> @connect = new Connect() @connect.connect (error, {@sut, @workerFunc, @connection}) => done(error) beforeEach 'send authenticate request', (done) -> @workerFunc.yields null, { metadata: code: 204 } @connection.connect (error) => console.log 'connected' done error afterEach 'shutItDown', (done) -> @connect.shutItDown done it 'should create a request', -> expect(@workerFunc.firstCall.args[0]).to.containSubset metadata: jobType: 'Authenticate' auth: uuid: 'masseuse' token: '<PASSWORD>'
true
_ = require 'lodash' UUID = require 'uuid' Connect = require './connect' Server = require '../src/server' MeshbluWebsocket = require 'meshblu-websocket' {JobManagerResponder} = require 'meshblu-core-job-manager' describe 'sendFrame: authenticate', -> beforeEach 'connect', (done) -> @connect = new Connect() @connect.connect (error, {@sut, @workerFunc, @connection}) => done(error) beforeEach 'send authenticate request', (done) -> @workerFunc.yields null, { metadata: code: 204 } @connection.connect (error) => console.log 'connected' done error afterEach 'shutItDown', (done) -> @connect.shutItDown done it 'should create a request', -> expect(@workerFunc.firstCall.args[0]).to.containSubset metadata: jobType: 'Authenticate' auth: uuid: 'masseuse' token: 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": " DocPad application.\n# Extends https://github.com/bevry/event-emitter-grouped\n#\n# You can use it like so:", "end": 1778, "score": 0.9854370951652527, "start": 1773, "tag": "USERNAME", "value": "bevry" }, { "context": ", replacement instructions at: https://github.com/docpad/docpad-plugintester\n\t\t\t\t'''\n\t\t\t)\n\t\t\treturn requir", "end": 2836, "score": 0.9869879484176636, "start": 2830, "tag": "USERNAME", "value": "docpad" }, { "context": "mes\n\t#\n\t# The partials plugin (https://github.com/docpad/docpad-plugin-partials)\n\t# creates a live collect", "end": 15189, "score": 0.992174506187439, "start": 15183, "tag": "USERNAME", "value": "docpad" }, { "context": "\n\t###\n\tgetFiles: (query,sorting,paging) ->\n\t\tkey = JSON.stringify({query, sorting, paging})\n\t\tcollection ", "end": 17412, "score": 0.9425987601280212, "start": 17408, "tag": "KEY", "value": "JSON" }, { "context": "\tgetFiles: (query,sorting,paging) ->\n\t\tkey = JSON.stringify({query, sorting, paging})\n\t\tcollection = @getCollec", "end": 17424, "score": 0.8145074248313904, "start": 17413, "tag": "KEY", "value": "stringify({" }, { "context": "nd the Bevry watchr\n\t# module (https://github.com/bevry/watchr). Used\n\t# internally by DocPad to watch pr", "end": 43040, "score": 0.9996270537376404, "start": 43035, "tag": "USERNAME", "value": "bevry" }, { "context": "occur when stdin is closed\n\t\t# https://github.com/docpad/docpad/pull/1049\n\t\tprocess.stdin?.once? 'error', ", "end": 49949, "score": 0.9995380640029907, "start": 49943, "tag": "USERNAME", "value": "docpad" }, { "context": "atal(err)\n\n\t\t# Close stdin\n\t\t# https://github.com/docpad/docpad/issues/1028\n\t\t# https://github.com/docpad/", "end": 50378, "score": 0.99956214427948, "start": 50372, "tag": "USERNAME", "value": "docpad" }, { "context": "/docpad/docpad/issues/1028\n\t\t# https://github.com/docpad/docpad/pull/1029\n\t\tprocess.stdin?.destroy?() or p", "end": 50427, "score": 0.9995477199554443, "start": 50421, "tag": "USERNAME", "value": "docpad" }, { "context": " package versions\n\t# Combat to https://github.com/npm/npm/issues/4587#issuecomment-35370453\n\t# @private", "end": 66614, "score": 0.9960615634918213, "start": 66611, "tag": "USERNAME", "value": "npm" }, { "context": "ck.\n\t#\n\t# The partials plugin (https://github.com/docpad/docpad-plugin-partials)\n\t# uses this method to lo", "end": 76165, "score": 0.9482181072235107, "start": 76159, "tag": "USERNAME", "value": "docpad" }, { "context": "but initial was false too\n\t\t\t# https://github.com/bevry/docpad/issues/811\n\t\t\telse if docpad.generated is ", "end": 99620, "score": 0.9996528625488281, "start": 99615, "tag": "USERNAME", "value": "bevry" }, { "context": "ons could change our state\n\t\t# https://github.com/bevry/docpad/issues/811\n\t\taddTask 'Figure out options',", "end": 100392, "score": 0.9996761679649353, "start": 100387, "tag": "USERNAME", "value": "bevry" }, { "context": "hen ran docpad again\n\t\t\t\t# See https://github.com/bevry/docpad/issues/705#issuecomment-29243666 for detai", "end": 102729, "score": 0.9993613362312317, "start": 102724, "tag": "USERNAME", "value": "bevry" }, { "context": "be giving us invalid data\n\t\t\t# https://github.com/bevry/docpad/issues/792\n\t\t\tunless fileEitherStat\n\t\t\t\ter", "end": 116911, "score": 0.999654233455658, "start": 116906, "tag": "USERNAME", "value": "bevry" }, { "context": " information you can to:\n\t\t\t\t\t\thttps://github.com/bevry/docpad/issues/792\n\t\t\t\t\t\t\"\"\")\n\t\t\t\treturn docpad.er", "end": 117189, "score": 0.9995765089988708, "start": 117184, "tag": "USERNAME", "value": "bevry" }, { "context": " special for some reason\n\t\t# > https://github.com/bevry/docpad/pull/701\n\t\tdependencies = []\n\t\teachr docpa", "end": 124504, "score": 0.9996989369392395, "start": 124499, "tag": "USERNAME", "value": "bevry" } ]
source/lib/docpad.coffee
samkenxstream/docpad
969
##* # The central module for DocPad # @module DocPad ## # ===================================== # Requires # Standard util = require('util') pathUtil = require('path') # External { Logger, Human, Filter } = require('caterpillar') fsUtil = require('fs') Errlop = require('errlop').default queryEngine = require('query-engine') {uniq, union, pick} = require('underscore') CSON = require('cson') balUtil = require('bal-util') scandir = require('scandirectory') extendr = require('extendr') eachr = require('eachr') typeChecker = require('typechecker') ambi = require('ambi') unbounded = require('unbounded') {TaskGroup} = require('taskgroup') safefs = require('safefs') safeps = require('safeps') ignorefs = require('ignorefs') rimraf = require('rimraf') Progress = require('progress-title') fetch = require('node-fetch') extractOptsAndCallback = require('extract-opts') {EventEmitterGrouped} = require('event-emitter-grouped') envFile = require('envfile') ansiStyles = require('ansistyles') # Base {Events,Model,Collection,QueryCollection} = require('./base') # Utils docpadUtil = require('./util') # Models FileModel = require('./models/file') DocumentModel = require('./models/document') # Collections FilesCollection = require('./collections/files') ElementsCollection = require('./collections/elements') MetaCollection = require('./collections/meta') ScriptsCollection = require('./collections/scripts') StylesCollection = require('./collections/styles') # Plugins PluginLoader = require('@bevry/pluginloader').default BasePlugin = require('docpad-baseplugin') # --------------------------------- # Variables isUser = docpadUtil.isUser() isTruthy = (i) -> Boolean(i) ###* # Contains methods for managing the DocPad application. # Extends https://github.com/bevry/event-emitter-grouped # # You can use it like so: # # new DocPad(docpadConfig, function(err, docpad) { # if (err) return docpad.fatal(err) # return docpad.action(action, function(err) { # if (err) return docpad.fatal(err) # return console.log('OK') # }) # }) # # @class Docpad # @constructor # @extends EventEmitterGrouped ### class DocPad extends EventEmitterGrouped # Libraries # Here for legacy API reasons #@DocPad: DocPad #@Backbone: require('backbone') #@queryEngine: queryEngine # Allow for `DocPad.create()` as an alias for `new DocPad()` @create: (args...) -> return new @(args...) # Require a local DocPad file # Before v6.73.0 this allowed requiring of files inside src/lib, as well as files inside src # After v6.73.0 it only allows requiring of files inside src/lib as that makes more sense # After v6.80.9 it only allows requiring specific aliases @require: (name) -> if name is 'testers' console.log( '''' docpad.require('testers') is deprecated, replacement instructions at: https://github.com/docpad/docpad-plugintester ''' ) return require('docpad-plugintester') else throw new Errlop("docpad.require is limited to requiring: testers") # ================================= # Variables # --------------------------------- # Modules # --------------------------------- # Base ###* # Events class # @property {Object} Events ### Events: Events ###* # Model class # Extension of the Backbone Model class # http://backbonejs.org/#Model # @property {Object} Model ### Model: Model ###* # Collection class # Extension of the Backbone Collection class # http://backbonejs.org/#Collection # @property {Object} Collection ### Collection: Collection ###* # QueryCollection class # Extension of the Query Engine QueryCollection class # @property {Object} QueryCollection ### QueryCollection: QueryCollection # --------------------------------- # Models ###* # File Model class # Extension of the Model class # @property {Object} FileModel ### FileModel: FileModel ###* # Document Model class # Extension of the File Model class # @property {Object} DocumentModel ### DocumentModel: DocumentModel # --------------------------------- # Collections ###* # Collection of files in a DocPad project # Extension of the QueryCollection class # @property {Object} FilesCollection ### FilesCollection: FilesCollection ###* # Collection of elements in a DocPad project # Extension of the Collection class # @property {Object} ElementsCollection ### ElementsCollection: ElementsCollection ###* # Collection of metadata in a DocPad project # Extension of the ElementsCollection class # @property {Object} MetaCollection ### MetaCollection: MetaCollection ###* # Collection of JS script files in a DocPad project # Extension of the ElementsCollection class # @property {Object} ScriptsCollection ### ScriptsCollection: ScriptsCollection ###* # Collection of CSS style files in a DocPad project # Extension of the ElementsCollection class # @property {Object} StylesCollection ### StylesCollection: StylesCollection # --------------------------------- # DocPad ###* # DocPad's version number # @private # @property {Number} version ### version: null ###* # Get the DocPad version number # @method getVersion # @return {Number} ### getVersion: -> @version ?= require(@packagePath).version return @version ###* # Get the DocPad version string # @method getVersionString # @return {String} ### getVersionString: -> if docpadUtil.isLocalDocPadExecutable() return util.format(@getLocale().versionLocal, @getVersion(), @corePath) else return util.format(@getLocale().versionGlobal, @getVersion(), @corePath) ###* # The plugin version requirements # @property {String} pluginVersion ### pluginVersion: '2' # Process getters ###* # Get the process platform # @method getProcessPlatform # @return {Object} ### getProcessPlatform: -> process.platform ###* # Get the process version string # @method getProcessVersion # @return {String} ### getProcessVersion: -> process.version.replace(/^v/,'') ###* # Internal property. The caterpillar logger instance bound to DocPad # @private # @property {Object} loggerInstances ### logger: null ###* # Get the caterpillar logger instance bound to DocPad # @method getLogger # @return {Object} caterpillar logger ### getLogger: -> @logger ###* # Destructor. Destroy the caterpillar logger instances bound to DocPad # @private # @method {Object} destroyLoggers ### destroyLoggers: -> # @logger.end() @logger = null @ ###* # All the timers that exist within DocPad # Used for closing them at shutdown # @private # @property {Object} timers ### timers: null ###* # Create a timer and add it to the known timers # @method timer # @param {string} type - either timeout or interval # @param {number} time - the time to apply to the timer # @param {method} method - the method to use for the timer ### timer: (id, type, time, method) -> @timers ?= {} # Create a new timer if type? @timer(id) # clear if type is 'timeout' if time is -1 timer = setImmediate(method) else timer = setTimeout(method, time) else if type is 'interval' timer = setInterval(method, time) else throw new Errlop('unexpected type on new timer') @timers[id] = {id, type, time, method, timer} # Destroy an old timer else if @timers[id] if @timers[id].type is 'interval' clearInterval(@timers[id].timer) else if @timers[id].type is 'timeout' if @timers[id].time is -1 clearImmediate?(@timers[id].timer) else clearTimeout(@timers[id].timer) else throw new Errlop('unexpected type on stored timer') @timers[id] = null @ ###* # Destructor. Destroy all the timers we have kept. # @private # @method {Object} destroyTimers ### destroyTimers: (timer) -> @timers ?= {} for own key, value of @timers @timer(key) @ ###* # Instance of progress-title # @private # @property {Progress} progressInstance ### progressInstance: null ###* # Update the configuration of the progress instance, to either enable it or disable it # Progress will be enabled if DocPad config 'progress' is true # @private # @method updateProgress # @param {boolean} [enabled] manually enable or disable the progress bar ### updateProgress: (enabled) -> # Prepare docpad = @ config = docpad.getConfig() debug = @getDebugging() # Enabled enabled ?= config.progress # If we are in debug mode, then output more detailed title messages options = {} if debug options.verbose = true options.interval = 0 # options.log = true # If we wish to have it enabled if enabled if @progressInstance @progressInstance.pause().configure(options).resume() else @progressInstance = Progress.create(options).start() else if @progressInstance @progressInstance.stop().configure(options) # Return return this ###* # The action runner instance bound to docpad # @private # @property {Object} actionRunnerInstance ### actionRunnerInstance: null ###* # Get the action runner instance bound to docpad # @method getActionRunner # @return {Object} the action runner instance ### getActionRunner: -> @actionRunnerInstance ###* # Apply the passed DocPad action arguments # @method {Object} action # @param {Object} args # @return {Object} ### action: (action, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) locale = @getLocale() # Log @progressInstance?.resume() @log 'debug', util.format(locale.actionStart, action) # Act docpadUtil.action.call @, action, opts, (args...) => # Prepare err = args[0] # Log @progressInstance?.stop() if err @error(new Errlop( util.format(locale.actionFailure, action), err )) else @log 'debug', util.format(locale.actionSuccess, action) # Act return next?(args...) # Chain @ ###* # Event Listing. String array of event names. # Whenever an event is created, it must be applied here to be available to plugins and configuration files # Events must be sorted by the order of execution, not for a functional need, but for a documentation need # Whenever this array changes, also update: https://docpad.bevry.me/events # @private # @property {Array} string array of event names ### events: [ 'loadPlugins' # fired each load 'extendCollections' # fired each load 'extendTemplateData' # fired each load 'docpadReady' # fired only once 'docpadDestroy' # fired once on shutdown 'consoleSetup' # fired once 'runBefore' 'runAfter' 'generateBefore' 'populateCollectionsBefore' 'populateCollections' 'contextualizeBefore' 'contextualizeAfter' 'renderBefore' 'renderCollectionBefore' 'render' # fired for each extension conversion 'renderDocument' # fired for each document render, including layouts and render passes 'renderCollectionAfter' 'renderAfter' 'writeBefore' 'writeAfter' 'generateAfter' 'generated' 'notify' ] ###* # Get the list of available events # @method getEvents # @return {Object} string array of event names ### getEvents: -> @events # --------------------------------- # Collections # Database collection ###* # QueryEngine collection # @private # @property {Object} database ### database: null ###* # Description for getDatabase # @method {Object} getDatabase ### getDatabase: -> @database ###* # Destructor. Destroy the DocPad database # @private # @method destroyDatabase ### destroyDatabase: -> if @database? @database.destroy() @database = null @ ###* # Blocks # @private # @property {Object} blocks ### blocks: null ### { # A collection of meta elements meta: null # Elements Collection # A collection of script elements scripts: null # Scripts Collection # Collection of style elements styles: null # Styles Collection } ### ###* # Get a block by block name. Optionally clone block. # @method getBlock # @param {String} name # @param {Object} [clone] # @return {Object} block ### getBlock: (name,clone) -> block = @blocks[name] if clone classname = name[0].toUpperCase()+name[1..]+'Collection' block = new @[classname](block.models) return block ###* # Set a block by name and value # @method setBlock # @param {String} name # @param {Object} value ### setBlock: (name,value) -> if @blocks[name]? @blocks[name].destroy() if value @blocks[name] = value else delete @blocks[name] else @blocks[name] = value @ ###* # Get all blocks # @method getBlocks # @return {Object} collection of blocks ### getBlocks: -> @blocks ###* # Set all blocks # @method setBlocks # @param {Object} blocks ### setBlocks: (blocks) -> for own name,value of blocks @setBlock(name,value) @ ###* # Apply the passed function to each block # @method eachBlock # @param {Function} fn ### eachBlock: (fn) -> eachr(@blocks, fn) @ ###* # Destructor. Destroy all blocks # @private # @method destroyBlocks ### destroyBlocks: -> if @blocks for own name,block of @blocks block.destroy() @blocks[name] = null @ ###* # The DocPad collections # @private # @property {Object} collections ### collections: null ###* # Get a collection by collection name or key. # This is often accessed within the docpad.coffee # file or a layout/page via @getCollection. # Because getCollection returns a docpad collection, # a call to this method is often chained with a # QueryEngine style query. # # @getCollection('documents').findAllLive({relativeOutDirPath: 'posts'},[{date:-1}]) # # @method getCollection # @param {String} value # @return {Object} collection ### getCollection: (value) -> if value if typeof value is 'string' if value is 'database' return @getDatabase() else for collection in @collections if value in [collection.options.name, collection.options.key] return collection else for collection in @collections if value is collection return collection return null ###* # Destroy a collection by collection name or key # @method destroyCollection # @param {String} value # @return {Object} description ### destroyCollection: (value) -> if value if typeof value is 'string' and value isnt 'database' @collections = @collections.filter (collection) -> if value in [collection.options.name, collection.options.key] collection?.destroy() return false else return true else if value isnt @getDatabase() @collections = @collections.filter (collection) -> if value is collection collection?.destroy() return false else return true return null ###* # Add a collection # @method addCollection # @param {Object} collection ### addCollection: (collection) -> if collection and collection not in [@getDatabase(), @getCollection(collection)] @collections.push(collection) @ ###* # Set a name for a collection. # A collection can have multiple names # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # creates a live collection and passes this to setCollection with # the name 'partials'. # # # Add our partials collection # docpad.setCollection('partials', database.createLiveChildCollection() # .setQuery('isPartial', { # $or: # isPartial: true # fullPath: $startsWith: config.partialsPath # }) # .on('add', (model) -> # docpad.log('debug', util.format(locale.addingPartial, model.getFilePath())) # model.setDefaults( # isPartial: true # render: false # write: false # ) # ) # ) # # # @method setCollection # @param {String} name the name to give to the collection # @param {Object} collection a DocPad collection ### setCollection: (name, collection) -> if collection if name collection.options.name = name if @getCollection(name) isnt collection @destroyCollection(name) @addCollection(collection) else @destroyCollection(name) ###* # Get the DocPad project's collections # @method getCollections # @return {Object} the collections ### getCollections: -> return @collections ###* # Set the DocPad project's collections # @method setCollections ### setCollections: (collections) -> if Array.isArray(collections) for value in collections @addCollection(value) else for own name,value of collections @setCollection(name, value) @ ###* # Apply the passed function to each collection # @method eachCollection # @param {Function} fn ### eachCollection: (fn) -> fn(@getDatabase(), 'database') for collection,index in @collections fn(collection, collection.options.name or collection.options.key or index) @ ###* # Destructor. Destroy the DocPad project's collections. # @private # @method destroyCollections ### destroyCollections: -> if @collections for collection in @collections collection.destroy() @collections = [] @ # --------------------------------- # Collection Helpers ###* # Get all the files in the DocPad database (will use live collections) # @method getFiles # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} collection ### getFiles: (query,sorting,paging) -> key = JSON.stringify({query, sorting, paging}) collection = @getCollection(key) unless collection collection = @getDatabase().findAllLive(query, sorting, paging) collection.options.key = key @addCollection(collection) return collection ###* # Get a single file based on a query # @method getFile # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFile: (query,sorting,paging) -> file = @getDatabase().findOne(query, sorting, paging) return file ###* # Get files at a path # @method getFilesAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} files ### getFilesAtPath: (path,sorting,paging) -> query = $or: [{relativePath: $startsWith: path}, {fullPath: $startsWith: path}] files = @getFiles(query, sorting, paging) return files ###* # Get a file at a relative or absolute path or url # @method getFileAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFileAtPath: (path,sorting,paging) -> file = @getDatabase().fuzzyFindOne(path, sorting, paging) return file ###* # Get a file by its id # @method getFileById # @param {String} id # @param {Object} [opts={}] # @return {Object} a file ### getFileById: (id,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.get(id) return file ###* # Remove the query string from a url # Pathname convention taken from document.location.pathname # @method getUrlPathname # @param {String} url # @return {String} ### getUrlPathname: (url) -> return url.replace(/\?.*/,'') ###* # Get a file by its selector (this is used to fetch layouts by their name) # @method getFileBySelector # @param {Object} selector # @param {Object} [opts={}] # @return {Object} a file ### getFileBySelector: (selector,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.fuzzyFindOne(selector) return file # --------------------------------- # Plugins ###* # Plugins that are loading really slow # @property {Object} slowPlugins ### slowPlugins: null # {} ###* # Loaded plugins indexed by name # @property {Object} loadedPlugins ### loadedPlugins: null # {} # ----------------------------- # Paths ###* # The DocPad directory # @property {String} corePath ### corePath: pathUtil.resolve(__dirname, '..', '..') ###* # The DocPad library directory # @private # @property {String} libPath ### libPath: __dirname ###* # The main DocPad file # @property {String} mainPath ### mainPath: pathUtil.resolve(__dirname, 'docpad') ###* # The DocPad package.json path # @property {String} packagePath ### packagePath: pathUtil.resolve(__dirname, '..', '..', 'package.json') ###* # The DocPad locale path # @property {String} localePath ### localePath: pathUtil.resolve(__dirname, 'locale') # ----------------------------- # Template Data ###* # Description for initialTemplateData # @private # @property {Object} initialTemplateData ### initialTemplateData: null # {} ###* # Plugin's Extended Template Data # @private # @property {Object} pluginsTemplateData ### pluginsTemplateData: null # {} ###* # Get Complete Template Data # @method getTemplateData # @param {Object} userTemplateData # @return {Object} templateData ### getTemplateData: (userTemplateData) -> # Prepare userTemplateData or= {} docpad = @ locale = @getLocale() # Set the initial docpad template data @initialTemplateData ?= # Site Properties site: {} # Environment getEnvironment: -> return docpad.getEnvironment() # Environments getEnvironments: -> return docpad.getEnvironments() # Set that we reference other files referencesOthers: (flag) -> document = @getDocument() document.referencesOthers() return null # Get the Document getDocument: -> return @documentModel # Get a Path in respect to the current document getPath: (path,parentPath) -> document = @getDocument() path = document.getPath(path, parentPath) return path # Get Files getFiles: (query,sorting,paging) -> @referencesOthers() result = docpad.getFiles(query, sorting, paging) return result # Get another file's URL based on a relative path getFile: (query,sorting,paging) -> @referencesOthers() result = docpad.getFile(query,sorting,paging) return result # Get Files At Path getFilesAtPath: (path,sorting,paging) -> @referencesOthers() path = @getPath(path) result = docpad.getFilesAtPath(path, sorting, paging) return result # Get another file's model based on a relative path getFileAtPath: (relativePath) -> @referencesOthers() path = @getPath(relativePath) result = docpad.getFileAtPath(path) return result # Get a specific file by its id getFileById: (id) -> @referencesOthers() result = docpad.getFileById(id) return result # Get the entire database getDatabase: -> @referencesOthers() return docpad.getDatabase() # Get a pre-defined collection getCollection: (name) -> @referencesOthers() return docpad.getCollection(name) # Get a block getBlock: (name) -> return docpad.getBlock(name,true) # Include another file taking in a relative path include: (subRelativePath,strict=true) -> file = @getFileAtPath(subRelativePath) if file if strict and file.get('rendered') is false if docpad.getConfig().renderPasses is 1 docpad.warn util.format(locale.renderedEarlyViaInclude, subRelativePath) return null return file.getOutContent() else err = new Errlop(util.format(locale.includeFailed, subRelativePath)) throw err # Fetch our result template data templateData = extendr.extend({}, @initialTemplateData, @pluginsTemplateData, @getConfig().templateData, userTemplateData) # Add site data templateData.site.url or= '' templateData.site.date or= new Date() templateData.site.keywords or= [] if typeChecker.isString(templateData.site.keywords) templateData.site.keywords = templateData.site.keywords.split(/,\s*/g) # Return templateData # ----------------------------- # Locales ###* # Determined locale # @private # @property {Object} locale ### locale: null ###* # Get the locale (language code and locale code) # @method getLocale # @return {Object} locale ### getLocale: (key) -> unless @locale? try locales = @getPath('locales').map((locale) -> require(locale)) @locale = extendr.extend(locales...) catch localeError docpad.warn(new Errlop('Failed to load a locale', localeError)) try @locale = require(@getPath('locale')) catch err docpad.fatal(new Errlop('Failed to load any locale', err)) @locale = {} if key return @locale[key] or key else return @locale # ----------------------------- # Environments ###* # Get the DocPad environment, eg: development, # production or static # @method getEnvironment # @return {String} the environment ### getEnvironment: -> return @env ###* # Get the environments # @method getEnvironments # @return {Array} array of environment strings ### getEnvironments: -> return @envs # ----------------------------- # Configuration ###* # Website Package Configuration # @private # @property {Object} websitePackageConfig ### websitePackageConfig: null # {} ###* # Merged Configuration # Merged in the order of: # - initialConfig # - userConfig # - websiteConfig # - instanceConfig # - environmentConfig # Use getConfig to retrieve this value # @private # @property {Object} config ### config: null # {} ###* # Instance Configuration # @private # @property {Object} instanceConfig ### instanceConfig: null # {} ###* # Website Configuration # Merged into the config property # @private # @property {Object} websiteConfig ### websiteConfig: null # {} ###* # User Configuraiton # Merged into the config property # @private # @property {Object} userConfig ### userConfig: null # {} ###* # Initial Configuration. The default docpadConfig # settings that can be overridden in a project's docpad.coffee file. # Merged into the config property # @private # @property {Object} initialConfig ### initialConfig: # ----------------------------- # Plugins # Whether or not we should use the global docpad instance global: false # Configuration to pass to any plugins pluginName: pluginConfiguration plugins: {} # ----------------------------- # Project Paths # The project directory rootPath: process.cwd() # The project's package.json path packagePath: 'package.json' # The project's configuration paths # Reads only the first one that exists # If you want to read multiple configuration paths, then point it to a coffee|js file that requires # the other paths you want and exports the merged config configPaths: [ 'docpad.js' 'docpad.coffee' 'docpad.json' 'docpad.cson' ] # Plugin directories to load pluginPaths: [] # Paths that we should watch for reload changes in reloadPaths: [] # Paths that we should watch for regeneration changes in regeneratePaths: [] # The DocPad debug log path (docpad-debug.log) debugLogPath: 'docpad-debug.log' # The User's configuration path (.docpad.cson) userConfigPath: '.docpad.cson' # ----------------------------- # Project Options # The project's out directory outPath: 'out' # The project's source directory sourcePaths: [ 'source' 'src' ] # The project's documents directories # relative to the source path documentsPaths: [ 'documents' 'render' ] # The project's files directories # relative to the source path filesPaths: [ 'files' 'static' 'public' ] # The project's layouts directory # relative to the source path layoutsPaths: [ 'layouts' ] # Ignored file patterns during directory parsing ignorePaths: false ignoreHiddenFiles: false ignoreCommonPatterns: true ignoreCustomPatterns: false # Watch options watchOptions: null # ----------------------------- # Logging # Log Level # Which level of logging should we actually output logLevel: 6 # Verbose # Set log level to 7 verbose: false # Debug # Output all log messages to the debugLogPath debug: false # Color # Whether or not our terminal output should have color # `null` will default to what the terminal supports color: docpadUtil.isTTY() # Silent # Will set the following # logLevel = 3 # progress = welcome = false silent: false # Progress # Whether or not we should display the progress in the terminal title bar progress: true # ----------------------------- # Other # Catch our own exceptions (error events on the DocPad instance) # use "error"/truthy to report # use "fatal" to report and exit catchOurExceptions: 'error' # Catch any uncaught exception # use "error" to report # use "fatal"/truthy to report and exit catchUncaughtExceptions: 'fatal' # Whether or not DocPad is allowed to set the exit code on fatal errors # May only work on node v0.11.8 and above setExitCodeOnFatal: true # Whether or not DocPad is allowed to set the exit code on standard errors # May only work on node v0.11.8 and above setExitCodeOnError: true # Whether or not DocPad is allowed to set the exit code when some code has requested to # May only work on node v0.11.8 and above setExitCodeOnRequest: true # The time to wait before cancelling a request requestTimeout: 30*1000 # The time to wait when destroying DocPad destroyDelay: -1 # Whether or not to destroy on exit destroyOnExit: true # Whether or not to destroy on signal interrupt (ctrl+c) destroyOnSignalInterrupt: true # The time to wait after a source file has changed before using it to regenerate regenerateDelay: 100 # The time to wait before outputting the files we are waiting on slowFilesDelay: 20*1000 # The time to wait before outputting the plugins we are waiting on slowPluginsDelay: 20*1000 # Utilise the database cache databaseCache: false # [false, true, 'write'] # Detect Encoding # Should we attempt to auto detect the encoding of our files? # Useful when you are using foreign encoding (e.g. GBK) for your files detectEncoding: false # Render Single Extensions # Whether or not we should render single extensions by default renderSingleExtensions: false # Render Passes # How many times should we render documents that reference other documents? renderPasses: 1 # Powered By DocPad # Whether or not we should include DocPad in the Powered-By meta header # Please leave this enabled as it is a standard practice and promotes DocPad in the web eco-system poweredByDocPad: true # Template Data # What data would you like to expose to your templates templateData: {} # Collections # A hash of functions that create collections collections: {} # Events # A hash of event handlers events: {} # Regenerate Every # Performs a regenerate every x milliseconds, useful for always having the latest data regenerateEvery: false # Regerenate Every Options # The generate options to use on the regenerate every call regenerateEveryOptions: populate: true partial: false # ----------------------------- # Environment Configuration # Locale Code # The code we shall use for our locale (e.g. en, fr, etc) localeCode: null # Environment # Whether or not we are in production or development # Separate environments using a comma or a space env: null # Environments # Environment specific configuration to over-ride the global configuration environments: development: # Only do these if we are running standalone (aka not included in a module) welcome: isUser progress: isUser ###* # Get the DocPad configuration # @method getConfig # @return {Object} the DocPad configuration object ### getConfig: -> return @config or {} # ================================= # Initialization Functions ###* # Create our own custom TaskGroup instance for DocPad. # That will listen to tasks as they execute and provide debugging information. # @method createTaskGroup # @param {Object} opts # @return {TaskGroup} ### createTaskGroup: (opts...) => docpad = @ progress = docpad.progressInstance tasks = TaskGroup.create(opts...) # Listen to executing tasks and output their progress tasks.on 'running', -> config = tasks.getConfig() name = tasks.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > running') # Listen to executing tasks and output their progress tasks.on 'item.add', (item) -> config = tasks.getConfig() name = item.getNames() unless progress docpad.log('debug', name+' > added') # Listen to executing tasks and output their progress item.on 'started', (item) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > started') # Listen to executing tasks and output their progress item.done (err) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > done') # Return return tasks ###* # Constructor method. Sets up the DocPad instance. # next(err) # @method constructor # @param {Object} instanceConfig # @param {Function} next callback # @param {Error} next.err # @param {DocPad} next.docpad ### constructor: (instanceConfig,next) -> # Prepare super() [instanceConfig,next] = extractOptsAndCallback(instanceConfig, next) docpad = @ # Allow DocPad to have unlimited event listeners @setMaxListeners(0) # Binders # Using this over coffescript's => on class methods, ensures that the method length is kept for methodName in "action log warn error fatal inspect notify checkRequest activeHandles onBeforeExit onSignalInterruptOne onSignalInterruptTwo onSignalInterruptThree destroyWatchers".split(/\s+/) @[methodName] = @[methodName].bind(@) # Adjust configPaths if typeChecker.isString(instanceConfig.configPaths) instanceConfig.configPaths = [instanceConfig.configPaths] # Dereference and initialise advanced variables # we deliberately ommit initialTemplateData here, as it is setup in getTemplateData @slowPlugins = {} @loadedPlugins = {} @pluginsTemplateData = {} @collections = [] @blocks = {} @websitePackageConfig = {} @websiteConfig = {} @userConfig = {} @initialConfig = extendr.dereferenceJSON(@initialConfig) @instanceConfig = instanceConfig or {} @config = @mergeConfigs() # Prepare the loggers instanceConfig.logLevel ?= @initialConfig.logLevel color = instanceConfig.color lineLevel = -1 if instanceConfig.silent instanceConfig.logLevel = 3 # 3:error, 2:critical, 1:alert, 0:emergency instanceConfig.progress = instanceConfig.welcome = false if instanceConfig.verbose || instanceConfig.debug instanceConfig.logLevel = 7 lineLevel = 7 # Create the loggers logger = new Logger({lineLevel: lineLevel}) filter = new Filter({filterLevel: instanceConfig.logLevel}) # Apply the loggers @logger = logger # Console logger.pipe(filter).pipe( new Human({ color: color }) ).pipe(process.stdout) # File if instanceConfig.debug logPath = @getPath(false, 'log') safefs.unlink logPath, -> logger .pipe( new Human(color: false) ) .pipe( fsUtil.createWriteStream(logPath) ) # Forward log events to the logger @on 'log', (args...) -> docpad.log.apply(@, args) # Setup configuration event wrappers configEventContext = {docpad} # here to allow the config event context to persist between event calls @getEvents().forEach (eventName) -> # Bind to the event docpad.on eventName, (opts,next) -> eventHandler = docpad.getConfig().events?[eventName] # Fire the config event handler for this event, if it exists if typeChecker.isFunction(eventHandler) args = [opts,next] ambi(unbounded.binder.call(eventHandler, configEventContext), args...) # It doesn't exist, so lets continue else next() # Create our action runner @actionRunnerInstance = @createTaskGroup('action runner', {abortOnError: false, destroyOnceDone: false}).whenDone (err) -> docpad.progressInstance?.update('') docpad.error(err) if err # Setup the database @database = new FilesCollection(null, {name:'database'}) .on('remove', (model,options) -> # Skip if we are not a writeable file return if model.get('write') is false # Ensure we regenerate anything (on the next regeneration) that was using the same outPath outPath = model.get('outPath') if outPath updatedModels = docpad.database.findAll({outPath}) updatedModels.remove(model) if updatedModels.length updatedModels.each (model) -> model.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the removal of a similar one:', updatedModels.pluck('relativePath')) # Return safely return true ) .on('add change:outPath', (model) -> # Skip if we are not a writeable file return if model.get('write') is false # Prepare outPath = model.get('outPath') previousOutPath = model.previous('outPath') # Check if we have changed our outPath if previousOutPath # Ensure we regenerate anything (on the next regeneration) that was using the same outPath previousModels = docpad.database.findAll({outPath: previousOutPath}) previousModels.remove(model) if previousModels.length previousModels.each (previousModel) -> previousModel.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the addition of a similar one:', previousModels.pluck('relativePath')) # Determine if there are any conflicts with the new outPath if outPath existingModels = docpad.database.findAll({outPath}) existingModels.each (existingModel) -> if existingModel.id isnt model.id modelPath = model.get('fullPath') or (model.get('relativePath')+':'+model.id) existingModelPath = existingModel.get('fullPath') or (existingModel.get('relativePath')+':'+existingModel.id) docpad.warn util.format(docpad.getLocale().outPathConflict, outPath, modelPath, existingModelPath) # Return safely return true ) # Continue with load and ready @action 'load ready', {}, (err) -> if next? next(err, docpad) else if err docpad.fatal(err) # Chain @ ###* # Has DocPad commenced destruction? ### destroying: false ###* # Destructor. Destroy the DocPad instance # This is an action, and should be called as such # E.g. docpad.action('destroy', next) # @method destroy # @param {Object} opts # @param {Function} next # @param {Error} next.err ### destroy: (opts, next) -> return @ if @destroying @destroying = true # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() locale = @getLocale() # Log docpad.log('info', locale.destroyDocPad) # Drop all the remaining tasks dropped = @getActionRunner().clearRemaining() docpad.error("DocPad destruction had to drop #{Number(dropped)} action tasks") if dropped # Destroy Timers docpad.destroyTimers() # Wait a configurable oment docpad.timer 'destroy', 'timeout', config.destroyDelay, -> # Destroy Plugins docpad.emitSerial 'docpadDestroy', (eventError) -> # Check if eventError # Note err = new Errlop( "DocPad's destroyEvent event failed", eventError ) docpad.fatal(err) # Callback return next?(err) # Final closures and checks try # Destroy Timers docpad.destroyTimers() # Destroy Plugins docpad.destroyPlugins() # Destroy Watchers docpad.destroyWatchers() # Destroy Blocks docpad.destroyBlocks() # Destroy Collections docpad.destroyCollections() # Destroy Database docpad.destroyDatabase() # Destroy progress docpad.updateProgress(false) # Destroy Logging docpad.destroyLoggers() # Destroy Process Listeners process.removeListener('uncaughtException', docpad.fatal) process.removeListener('uncaughtException', docpad.error) process.removeListener('beforeExit', docpad.onBeforeExit) process.removeListener('SIGINT', docpad.onSignalInterruptOne) process.removeListener('SIGINT', docpad.onSignalInterruptTwo) process.removeListener('SIGINT', docpad.onSignalInterruptThree) # Destroy DocPad Listeners docpad.removeAllListeners() catch finalError # Note err = new Errlop( "DocPad's final destruction efforts failed", finalError ) docpad.fatal(err) return next?(err) # Success docpad.log(locale.destroyedDocPad) # log level omitted, as this will hit console.log return next?() # Chain @ ###* # Emit event, serial # @private # @method emitSerial # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitSerial: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ ###* # Emit event, parallel # @private # @method emitParallel # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitParallel: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ # ================================= # Helpers ###* # Get the ignore options for the DocPad project # @method getIgnoreOpts # @return {Array} string array of ignore options ### getIgnoreOpts: -> return pick(@config, ['ignorePaths', 'ignoreHiddenFiles', 'ignoreCommonPatterns', 'ignoreCustomPatterns']) ###* # Is the supplied path ignored? # @method isIgnoredPath # @param {String} path # @param {Object} [opts={}] # @return {Boolean} ### isIgnoredPath: (path,opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return ignorefs.isIgnoredPath(path, opts) ###* # Scan directory # @method scandir # @param {Object} [opts={}] ### #NB: How does this work? What is returned? #Does it require a callback (next) passed as #one of the options scandir: (opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return scandir(opts) ###* # Watch Directory. Wrapper around the Bevry watchr # module (https://github.com/bevry/watchr). Used # internally by DocPad to watch project documents # and files and then activate the regeneration process # when any of those items are updated. # @private # @method watchdir # @param {String} path - the path to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error # @return {Object} the watcher ### watchdir: (path, listeners, next) -> opts = extendr.extend(@getIgnoreOpts(), @config.watchOptions or {}) stalker = require('watchr').create(path) for own key, value of listeners stalker.on(key, value) stalker.setConfig(opts) stalker.watch(next) return stalker ###* # Watch Directories. Wrapper around watchdir. # @private # @method watchdirs # @param {Array} paths - the paths to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error and watchers/stalkers ### watchdirs: (paths, listeners, next) -> docpad = @ stalkers = [] tasks = new TaskGroup('watching directories').setConfig(concurrency:0).done (err) -> if err for stalker in stalkers stalker.close() next(err) else next(err, stalkers) paths.forEach (path) -> tasks.addTask "watching #{path}", (done) -> # check if the dir exists first as reloadPaths may not apparently safefs.exists path, (exists) -> return done() unless exists stalkers.push docpad.watchdir(path, listeners, done) tasks.run() # Chain @ # ================================= # Setup and Loading ###* # DocPad is ready. Peforms the tasks needed after DocPad construction # and DocPad has loaded. Triggers the docpadReady event. # next(err,docpadInstance) # @private # @method ready # @param {Object} [opts] # @param {Function} next # @param {Error} next.err # @param {Object} next.docpadInstance ### ready: (opts,next) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ config = @getConfig() locale = @getLocale() # Render Single Extensions @DocumentModel::defaults.renderSingleExtensions = config.renderSingleExtensions # Fetch the plugins pluginsList = Object.keys(@loadedPlugins).sort().join(', ') # Welcome Output docpad.log 'info', util.format(locale.welcome, @getVersionString()) docpad.log 'notice', locale.welcomeDonate docpad.log 'info', locale.welcomeContribute docpad.log 'info', util.format(locale.welcomePlugins, pluginsList) docpad.log 'info', util.format(locale.welcomeEnvironment, @getEnvironment()) # Prepare tasks = @createTaskGroup('ready tasks').done (err) -> # Error? return docpad.error(err) if err # All done, forward our DocPad instance onto our creator return next?(null,docpad) # kept here in case plugins use it tasks.addTask 'welcome event', (complete) -> # No welcome return complete() unless config.welcome # Welcome docpad.emitSerial('welcome', {docpad}, complete) tasks.addTask 'emit docpadReady', (complete) -> docpad.emitSerial('docpadReady', {docpad}, complete) # Run tasks tasks.run() # Chain @ ###* # Performs the merging of the passed configuration objects # @private # @method mergeConfigs ### mergeConfigs: (configPackages, destination = {}) -> # A plugin is calling us with its configuration unless configPackages # Apply the environment # websitePackageConfig.env is left out of the detection here as it is usually an object # that is already merged with our process.env by the environment runner # rather than a string which is the docpad convention @env = ( @instanceConfig.env or @websiteConfig.env or @initialConfig.env or process.env.NODE_ENV or 'development' ) @envs = @env.split(/[, ]+/) # Merge the configurations together configPackages = [@initialConfig, @userConfig, @websiteConfig, @instanceConfig] # Figure out merging configsToMerge = [destination] for configPackage in configPackages continue unless configPackage configsToMerge.push(configPackage) for env in @envs envConfig = configPackage.environments?[env] configsToMerge.push(envConfig) if envConfig # Merge return extendr.deep(configsToMerge...) ###* # Legacy version of mergeConmergeConfigsfigurations # @private # @method mergeConfigurations ### mergeConfigurations: (configPackages, [destination]) -> return @mergeConfigs(configPackages, destination) ###* # Set the DocPad configuration object. # Performs a number of tasks, including # merging the pass instanceConfig with DocPad's # other config objects. # next(err,config) # @private # @method setConfig # @param {Object} instanceConfig # @param {Object} next # @param {Error} next.err # @param {Object} next.config ### setConfig: (instanceConfig) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ locale = @getLocale() # Apply the instance configuration, generally we won't have it at this level # as it would have been applied earlier the load step extendr.deepDefaults(@instanceConfig, instanceConfig) if instanceConfig # Merge the configurations together @config = @mergeConfigs() # Update the progress bar configuration @updateProgress() # Handle errors process.removeListener('uncaughtException', @fatal) process.removeListener('uncaughtException', @error) @removeListener('error', @fatal) @removeListener('error', @error) if @config.catchExceptions # legacy @config.catchOurExceptions = @config.catchUncaughtExceptions = 'error' if @config.catchUncaughtExceptions process.setMaxListeners(0) if @config.catchUncaughtExceptions is 'error' process.on('uncaughtException', @error) else process.on('uncaughtException', @fatal) if @config.catchOurExceptions if @config.catchUncaughtExceptions is 'fatal' @on('error', @fatal) else @on('error', @error) # Handle interrupt process.removeListener('beforeExit', @onBeforeExit) process.removeListener('SIGINT', @onSignalInterruptOne) process.removeListener('SIGINT', @onSignalInterruptTwo) process.removeListener('SIGINT', @onSignalInterruptThree) if @config.destroyOnExit process.once('beforeExit', @onBeforeExit) if @config.destroyOnSignalInterrupt process.once('SIGINT', @onSignalInterruptOne) # Chain @ onSignalInterruptOne: -> # Log @log('notice', "Signal Interrupt received, queued DocPad's destruction") # Escalate next time process.once('SIGINT', @onSignalInterruptTwo) # Act @action('destroy') # Chain @ onSignalInterruptTwo: -> # Log @log('alert', 'Signal Interrupt received again, closing stdin and dumping handles') # Escalate next time process.once('SIGINT', @onSignalInterruptThree) # Handle any errors that occur when stdin is closed # https://github.com/docpad/docpad/pull/1049 process.stdin?.once? 'error', (stdinError) -> # ignore ENOTCONN as it means stdin was already closed when we called stdin.end # node v8 and above have stdin.destroy to avoid emitting this error if stdinError.toString().indexOf('ENOTCONN') is -1 err = new Errlop( "closing stdin encountered an error", stdinError ) docpad.fatal(err) # Close stdin # https://github.com/docpad/docpad/issues/1028 # https://github.com/docpad/docpad/pull/1029 process.stdin?.destroy?() or process.stdin?.end?() # Wait a moment before outputting things that are preventing closure setImmediate(@activeHandles) # Chain @ onSignalInterruptThree: -> # Log @log('alert', 'Signal Interrupt received yet again, skipping queue and destroying DocPad right now') # Act @exitCode(130) @destroy() # Chain @ onBeforeExit: -> @action('destroy') activeHandles: -> # Note any requests that are still active activeRequests = process._getActiveRequests?() if activeRequests?.length docpadUtil.writeStderr """ Waiting on these #{activeRequests.length} requests to close: #{@inspect activeRequests} """ # Note any handles that are still active activeHandles = process._getActiveHandles?() if activeHandles?.length docpadUtil.writeStderr """ Waiting on these #{activeHandles.length} handles to close: #{@inspect activeHandles} """ ###* # Load the various configuration files from the # file system. Set the instanceConfig. # next(err,config) # @private # @method load # @param {Object} opts # @param {Function} next # @param {Error} next.err ### load: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare the Load Tasks loadTasks = @createTaskGroup('load tasks').done(next) # User Configuration loadTasks.addTask "load the user's configuration", (complete) => userConfigPath = @getPath('user') return complete() unless userConfigPath docpad.log 'debug', util.format(locale.loadingUserConfig, userConfigPath) @loadConfigPath userConfigPath, (err,data) => return complete(err) if err # Apply if data @userConfig = data docpad.log 'debug', util.format(locale.loadedUserConfig, userConfigPath) return complete() # Complete return complete() # Website Env Configuration loadTasks.addTask "read the .env file if it exists", (complete) => envPath = @getPath('env') return complete() unless envPath docpad.log 'debug', util.format(locale.loadingEnvConfig, envPath) envFile.parseFile envPath, (err,data) -> return complete(err) if err for own key,value of data process.env[key] = value docpad.log 'debug', util.format(locale.loadedEnvConfig, envPath) return complete() # Website Package Configuration loadTasks.addTask "load the website's package data", (complete) => packagePath = @getPath('package') return complete() unless packagePath docpad.log 'debug', util.format(locale.loadingWebsitePackageConfig, packagePath) @loadConfigPath packagePath, (err,data) => return complete(err) if err # Apply if data @websitePackageConfig = data docpad.log 'debug', util.format(locale.loadedWebsitePackageConfig, packagePath) # Complete return complete() # Website Configuration loadTasks.addTask "load the website's configuration", (complete) => configPath = @getPath('config') return complete() unless configPath docpad.log 'debug', util.format(locale.loadingWebsiteConfig, configPath) @loadConfigPath configPath, (err,data) => return complete(err) if err # Apply if data @websiteConfig = data docpad.log 'debug', util.format(locale.loadedWebsiteConfig, configPath) # Complete return complete() loadTasks.addTask "update the configurations", => @setConfig() ### loadTasks.addTask 'lazy dependencies: encoding', (complete) => lazyRequire = require('lazy-require') return complete() unless @config.detectEncoding return lazyRequire 'encoding', {cwd:corePath, stdio:'inherit'}, (err) -> docpad.warn(locale.encodingLoadFailed) if err return complete() ### loadTasks.addTask 'load plugins', (complete) -> docpad.loadPlugins(complete) loadTasks.addTask 'extend collections', (complete) -> docpad.extendCollections(complete) loadTasks.addTask 'fetch plugins templateData', (complete) -> docpad.emitSerial('extendTemplateData', {templateData:docpad.pluginsTemplateData}, complete) # Fire post tasks loadTasks.run() # Chain @ # ================================= # Configuration ###* # Update user configuration with the passed data # @method updateUserConfig # @param {Object} [data={}] # @param {Function} next # @param {Error} next.err ### updateUserConfig: (data={},next) -> # Prepare [data,next] = extractOptsAndCallback(data,next) docpad = @ userConfigPath = @getConfig(false, 'user') # Apply back to our loaded configuration # does not apply to @config as we would have to reparse everything # and that appears to be an imaginary problem extendr.extend(@userConfig, data) if data # Convert to CSON CSON.createCSONString @userConfig, (parseError, userConfigString) -> if parseError err = new Errlop( "Failed to create the CSON string for the user configuration", parseError ) return next(err) # Write it safefs.writeFile userConfigPath, userConfigString, 'utf8', (writeError) -> if writeError err = new Errlop( "Failed to write the CSON string for the user configuration to #{userConfigPath}", writeError ) return next(err) # Forward return next() # Chain @ ###* # Load a configuration url. # @method loadConfigUrl # @param {String} configUrl # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigUrl: (configUrl,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() # Log docpad.log 'debug', util.format(locale.loadingConfigUrl, configUrl) # Read the URL fetch(configUrl, {timeout: config.requestTimeout}) .then((res) -> res.text()) .then((text) -> CSON.parseCSONString(text)) .catch(next) .then((data) -> next(null, data)) # Chain @ ###* # Load the configuration from a file path # passed as one of the options (opts.configPath) or # from DocPad's configPaths # @private # @method loadConfigPath # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigPath: (configPath,next) -> # Prepare docpad = @ locale = @getLocale() # Check return next() unless configPath # Log docpad.log 'debug', util.format(locale.loadingConfigPath, configPath) # Prepare CSON Options csonOptions = cson: true json: true coffeescript: true javascript: true # Read the path using CSON CSON.requireFile configPath, csonOptions, (parseError, data) -> if parseError err = new Errlop( util.format(locale.loadingConfigPathFailed, configPath), parseError ) return next(err) # Check if the data is a function, if so, then execute it as one while typeChecker.isFunction(data) try data = data(docpad) catch executeError err = new Errlop( util.format(locale.executeConfigPathFailed, configPath), executeError ) return next(err) unless typeChecker.isObject(data) err = new Errlop( util.format(locale.invalidConfigPathData, configPath, docpad.inspect(data)) ) return next(err) # Return the data return next(null, data) # Chain @ resolvePath: (args...) -> try path = pathUtil.resolve(args...) return path if safefs.existsSync(path) catch error @log('error', 'failed to resolve the path:', {path, error}) throw error return false getPath: (args...) -> # Use join if first argument is false if typeChecker.isBoolean(args[0]) [check, name, tail...] = args else check = true [name, tail...] = args # Prepare method = if check then @resolvePath else pathUtil.resolve config = @getConfig() # Determine path = switch name when 'locales' then [pathUtil.resolve(@localePath, 'en.js')] ### uniq([ safeps.getLocaleCode config.localeCode safeps.getLocaleCode safeps.getLocaleCode() safeps.getLanguageCode config.localeCode safeps.getLanguageCode safeps.getLocaleCode() 'en' ]).map((code) => @resolvePath(@localePath, code + '.js')) ### when 'locale' then @getPath(check, 'locales')[0] when 'root' then method(check, config.rootPath) when 'log' then method(check, process.cwd(), config.debugLogPath) when 'out' then @getPath(check, 'root', config.outPath) when 'env' then @getPath(check, 'root', '.env') when 'home' then require('os').homedir() # works in node v4 and above when 'dropbox' then @getPath(check, 'home', 'Dropbox') when 'users' then [@getPath(check, 'dropbox', config.userConfigPath), @getPath(check, 'root', config.userConfigPath)].filter(isTruthy) when 'user' then @getPath(check, 'users')[0] or false when 'package' then @getPath(check, 'root', config.packagePath) when 'sources' then config.sourcePaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'source' then @getPath(check, 'sources')[0] or false when 'configs' then config.configPaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'config' then @getPath(check, 'configs')[0] or false when 'documents' then config.documentsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'document' then @getPath(check, 'documents')[0] or false when 'files' then config.filesPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'file' then @getPath(check, 'files')[0] or false when 'layouts' then config.layoutsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'layout' then @getPath(check, 'layouts')[0] or false when 'reloads' then config.reloadPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'regenerates' then config.regeneratePaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) else null try if typeof path is 'string' and tail.length return method(check, path, tail...) else return path catch error @log('error', 'failed to get the path:', {check, name, tail, error}) throw error ###* # Extend collections. Create DocPad's # standard (documents, files # layouts) and special (generate, referencesOthers, # hasLayout, html, stylesheet) collections. Set blocks # @private # @method extendCollections # @param {Function} next # @param {Error} next.err ### extendCollections: (next) -> # Prepare docpad = @ docpadConfig = @getConfig() locale = @getLocale() database = @getDatabase() # Standard Collections @setCollections({ # Standard Collections documents: database.createLiveChildCollection() .setQuery('isDocument', { render: true write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingDocument, model.getFilePath())) ) files: database.createLiveChildCollection() .setQuery('isFile', { render: false write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingFile, model.getFilePath())) ) layouts: database.createLiveChildCollection() .setQuery('isLayout', { $or: isLayout: true fullPath: $startsWith: @getPath('layouts') }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingLayout, model.getFilePath())) model.setDefaults({ isLayout: true render: false write: false }) ) # Special Collections generate: database.createLiveChildCollection() .setQuery('generate', { ignored: false }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingGenerate, model.getFilePath())) ) referencesOthers: database.createLiveChildCollection() .setQuery('referencesOthers', { ignored: false referencesOthers: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingReferencesOthers, model.getFilePath())) ) hasLayout: database.createLiveChildCollection() .setQuery('hasLayout', { ignored: false layout: $exists: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHasLayout, model.getFilePath())) ) html: database.createLiveChildCollection() .setQuery('isHTML', { write: true outExtension: 'html' }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHtml, model.getFilePath())) ) stylesheet: database.createLiveChildCollection() .setQuery('isStylesheet', { write: true outExtension: 'css' }) }) # Blocks @setBlocks({ meta: new MetaCollection() scripts: new ScriptsCollection() styles: new StylesCollection() }) # Custom Collections Group tasks = @createTaskGroup("extendCollections tasks", concurrency:0).done (err) -> docpad.error(err) if err docpad.emitSerial('extendCollections', next) # Cycle through Custom Collections eachr docpadConfig.collections or {}, (fn,name) -> if !name or !typeChecker.isString(name) err = new Errlop("Inside your DocPad configuration you have a custom collection with an invalid name of: #{docpad.inspect name}") docpad.error(err) return if !fn or !typeChecker.isFunction(fn) err = new Errlop("Inside your DocPad configuration you have a custom collection called #{docpad.inspect name} with an invalid method of: #{docpad.inspect fn}") docpad.error(err) return tasks.addTask "creating the custom collection: #{name}", (complete) -> # Init ambi unbounded.binder.call(fn, docpad), database, (err, collection) -> # Check for error if err docpad.error(err) return complete() # Check the type of the collection else unless collection instanceof QueryCollection docpad.warn util.format(locale.errorInvalidCollection, name) return complete() # Make it a live collection collection.live(true) if collection # Apply the collection docpad.setCollection(name, collection) return complete() # Run Custom collections tasks.run() # Chain @ ###* # Reset collections. Perform a complete clean of our collections # @private # @method resetCollections # @param {Object} opts # @param {Function} next # @param {Error} next.err ### resetCollections: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ database = docpad.getDatabase() # Make it as if we have never generated before docpad.generated = false # Perform a complete clean of our collections database.reset([]) meta = @getBlock('meta').reset([]) scripts = @getBlock('scripts').reset([]) styles = @getBlock('styles').reset([]) # ^ Backbone.js v1.1 changes the return values of these, however we change that in our Element class # because if we didn't, all our projects would fail # Add default block entries meta.add("""<meta name="generator" content="DocPad v#{docpad.getVersion()}" />""") if docpad.getConfig().poweredByDocPad isnt false # Chain next() @ ###* # Initialise git repo # @private # @method initGitRepo # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initGitRepo: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') # Forward safeps.initGitRepo(opts, next) # Chain @ ###* # Init node modules # @private # @method initNodeModules # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initNodeModules: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] # Command command = ['npm', 'install'] command.push(opts.args...) # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Fix node package versions # Combat to https://github.com/npm/npm/issues/4587#issuecomment-35370453 # @private # @method fixNodePackageVersions # @param {Object} opts # @param {Function} next # @param {Error} next.err ### fixNodePackageVersions: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.packagePath ?= @getPath('package') # Read and replace safefs.readFile opts.packagePath, (err,buffer) -> data = buffer.toString() data = data.replace(/("docpad(?:.*?)": ")\^/g, '$1~') safefs.writeFile opts.packagePath, data, (err) -> return next(err) # Chain @ ###* # Install node module. Same as running # 'npm install' through the command line # @private # @method installNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### installNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = [] if opts.global opts.save = ['--save'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'install'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) names.forEach (name) -> # Check return unless name # Ensure latest if version isn't specfied name += '@latest' if name.indexOf('@') is -1 # Push the name to the commands command.push(name) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save and opts.save.length command.push('--global') if opts.global # Log docpad.log('info', command.join(' ')) if opts.output # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Uninstall node module. Same as running # 'npm uninstall' through the command line # @private # @method uninstallNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### uninstallNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = ['--save', '--save-dev'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'uninstall'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) command.push(names...) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ # ================================= # Logging ###* # Get the log level # @method getLogLevel # @return {Number} the log level ### getLogLevel: -> return @getConfig().logLevel ###* # Are we debugging? # @method getDebugging # @return {Boolean} ### getDebugging: -> config = @getConfig() return config.logLevel is 7 or config.debug ###* # Check Request # @private # @method checkRequest # @param {Function} next # @param {Error} next.err # @param {Object} next.res ### checkRequest: (next) -> next ?= @error.bind(@) return (err,res) -> # Check return next(err, res) if err # Check if res.body?.success is false or res.body?.error err = new Errlop(res.body.error or 'unknown request error') return next(err, res) # Success return next(null, res) ###* # Send a notify event to plugins (like growl) # @method notify # @param {String} message # @param {Object} [opts={}] ### notify: (message,opts={}) -> # Prepare docpad = @ # Emit docpad.emitSerial 'notify', {message,opts}, (err) -> docpad.error(err) if err # Chain @ ###* # Inspect. Converts object to JSON string. Wrapper around nodes util.inspect method. # Can't use the inspect namespace as for some silly reason it destroys everything # @method inspect # @param {Object} obj # @param {Object} opts # @return {String} JSON string of passed object ### inspect: (obj, opts) -> opts ?= {} opts.colors ?= @getConfig().color return util.inspect(obj, opts) ###* # Log arguments to # @property {Object} log # @param {Mixed} args... ### log: (args...) -> # Log logger = @getLogger() if logger?.log? logger.log.apply(logger, args) else # logger doesn't exist, this is probably because it was destroyed # so handle the most basic case ourselves # that case being when the first argument is a log level string # as we don't want to interpret log(new Date().getTime()) as a log level number # @todo # ideally, this logic would be static methods inside caterpillar # as caterpillar methods is already where this logic exist, they just have to be made static logLevels = require('rfc-log-levels') logLevel = logLevels[args[0]] ? 6 if @getLogLevel() >= logLevel console.log(args...) # Chain @ ###* # Create an error and log it # This is called by all sorts of things, including docpad.warn # As such, the err.level is important # @method error # @param {*} value # @return {Error} ### error: (value) -> # Prepare locale = @getLocale() # Ensure it is an error err = Errlop.ensure(value) err.level ?= 'error' err.log ?= true err.logged ?= false err.notify ?= true err.notified ?= false err.report ?= err.level isnt 'warn' # Set the exit code @exitCode(err) # Log the error if err.log isnt false and err.logged isnt true err.logged = true @log( err.logLevel or err.level, err.stack + (err.report and ('\n' + locale.errorSubmission) or '') ) # Notify the error if err.notify isnt false and err.notified isnt true err.notified = true title = locale[err.level + 'Occured'] or locale.errorOccured @notify(err.message, {title}) # Return the result error return err ###* # Log an error of level 'warn' # @method warn # @param {*} value # @return {Error} ### warn: (value) -> err = Errlop.ensure(value) err.level ?= 'warn' # Foward return @error(err) ###* # Handle a fatal error # @private # @method fatal # @param {*} value # @param {Function} [next] # @return {Error} ### fatal: (value, next) -> # Check return @ unless value # Enforce errlop with fatal level err = new Errlop('A fatal error occured within DocPad', value) err.level = 'fatal' err.logLevel = 'critical' # Handle @error(err) # Set the exit code if we are allowed to @exitCode(err) # Destroy DocPad @destroy({}, next) # Return the error return err ###* # Sets the exit code if we are allowed to, and if it hasn't already been set # @method exitCode # @param {number|Error [input] # @return {number} ### exitCode: (input) -> # Determine if necessary unless process.exitCode # Prepare {setExitCodeOnRequest, setExitCodeOnError, setExitCodeOnFatal} = @getConfig() # Number if typeChecker.isNumber(input) code = input level = null # Error else if input instanceof Error code = input.exitCode level = input.level or null error = input # Defaults if !code or isNaN(Number(code)) exitCode = 1 else exitCode = code # Determine desire because = ( (!level and setExitCodeOnRequest and 'requested') or (level is 'fatal' and setExitCodeOnFatal and 'fatal') or (level is 'error' and setExitCodeOnFatal and 'error') ) if because # Fetch before we apply so we can log it shortly originalExitCode = process.exitCode or 'unset' # Apply process.exitCode = exitCode # And log it message = ['Set the exit code from', originalExitCode, 'to', exitCode, 'because of', because] message.push('from:', error.message) if error and error.message @log('note', message...) # Return the application return process.exitCode # ================================= # Models and Collections # --------------------------------- # b/c compat functions ###* # Create file model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'file' modelType. # @method createFile # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} FileModel ### createFile: (attrs={},opts={}) -> opts.modelType = 'file' return @createModel(attrs, opts) ###* # Create document model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'document' modelType. # @method createDocument # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} DocumentModel ### createDocument: (attrs={},opts={}) -> opts.modelType = 'document' return @createModel(attrs, opts) ###* # Parse the files directory and # return a files collection to # the passed callback # @method parseFileDirectory # @param {Object} [opts={}] # @param {Function} next callback # @param {Error} next.err # @param {Object} next.files files collection ### parseFileDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'file' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) ###* # Parse the documents directory and # return a documents collection to # the passed callback. # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # uses this method to load a collection of # files from the partials directory. # # docpad.parseDocumentDirectory({path: config.partialsPath}, next) # # @method parseDocumentDirectory # @param {Object} [opts={}] # @param {String} [opts.modelType='document'] # @param {Object} [opts.collection=docpad.database] # @param {Object} [opts.path] # @param {Function} next # @param {Error} next.err # @param {Object} next.files files collection of documents ### parseDocumentDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'document' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) # --------------------------------- # Standard functions ###* # Attach events to a document model. # @private # @method attachModelEvents # @param {Object} model ### attachModelEvents: (model) -> # Prepare docpad = @ # Only attach events if we haven't already done so if model.attachedDocumentEvents isnt true model.attachedDocumentEvents = true # Attach document events if model.type is 'document' # Clone model.on 'clone', (clonedModel) -> docpad.attachModelEvents(clonedModel) # Render model.on 'render', (args...) -> docpad.emitSerial('render', args...) # Render document model.on 'renderDocument', (args...) -> docpad.emitSerial('renderDocument', args...) # Fetch a layout model.on 'getLayout', (opts,next) -> opts.collection = docpad.getCollection('layouts') layout = docpad.getFileBySelector(opts.selector, opts) next(null, {layout}) # Remove #model.on 'remove', (file) -> # docpad.getDatabase().remove(file) # ^ Commented out as for some reason this stops layouts from working # Error model.on 'error', (args...) -> docpad.emit('error', args...) # Log model.on 'log', (args...) -> # .error and .warn only accept one argument # so only forward to them if args length is 2 if args.length is 2 if args[0] in ['err', 'error'] docpad.error(args[1]) return if args[0] in ['warn', 'warning'] docpad.warn(args[1]) return # otherwise forward to log docpad.log(args...) return # Chain @ ###* # Add supplied model to the DocPad database. If the passed # model definition is a plain object of properties, a new # model will be created prior to adding to the database. # Calls {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # before adding the model to the database. # # # Override the stat's mtime to now # # This is because renames will not update the mtime # fileCurrentStat?.mtime = new Date() # # # Create the file object # file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) # # @method addModel # @param {Object} model either a plain object defining the required properties, in particular # the file path or an actual model object # @param {Object} opts # @return {Object} the model ### addModel: (model, opts) -> model = @createModel(model, opts) @getDatabase().add(model) return model ###* # Add the supplied collection of models to the DocPad database. # Calls {{#crossLink "DocPad/createModels:method"}}{{/crossLink}} # before adding the models to the database. # # databaseData = JSON.parse data.toString() # models = docpad.addModels(databaseData.models) # # @method addModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### addModels: (models, opts) -> models = @createModels(models, opts) @getDatabase().add(models) return models ###* # Create a collection of models from the supplied collection # ensuring that the collection is suitable for adding to the # DocPad database. The method calls {{#crossLink "DocPad/createModel"}}{{/crossLink}} # for each model in the models array. # @private # @method createModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### createModels: (models, opts) -> for model in models @createModel(model, opts) # return the for loop results ###* # Creates either a file or document model. # The model type to be created can be passed # as an opts property, if not, the method will # attempt to determing the model type by checking # if the file is in one of the documents or # layout paths. # # Ensures a duplicate model is not created # and all required attributes are present and # events attached. # # Generally it is not necessary for an application # to manually create a model via creatModel as DocPad # will handle this process when watching a project's # file and document directories. However, it is possible # that a plugin might have a requirement to do so. # # model = @docpad.createModel({fullPath:fullPath}) # model.load() # @docpad.getDatabase().add(model) # # @method createModel # @param {Object} [attrs={}] # @param {String} attrs.fullPath the full path to the file # @param {Object} [opts={}] # @param {String} opts.modelType either 'file' or 'document' # @return {Object} the file or document model ### createModel: (attrs={},opts={}) -> # Check if attrs instanceof FileModel return attrs # Prepare docpad = @ config = @getConfig() database = @getDatabase() fileFullPath = attrs.fullPath or null # Find or create # This functionality use to be inside ensureModel # But that caused duplicates in some instances # So now we will always check if attrs.fullPath result = database.findOne(fullPath: attrs.fullPath) if result return result # ----------------------------- # Try and determine the model type # If the type hasn't been specified try and detemrine it based on the full path if fileFullPath # Check if we have a document or layout unless opts.modelType for dirPath in @getPath('documents').concat(@getPath('layouts')).filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'document' break # Check if we have a file unless opts.modelType for dirPath in @getPath('files').filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'file' break # ----------------------------- # Create the appropriate emodel # Extend the opts with things we need opts = extendr.extend({ detectEncoding: config.detectEncoding rootOutDirPath: @getPath(false, 'out') locale: @getLocale() createTaskGroup: @createTaskGroup # @TODO this a bit dodgy, but works well enough }, opts) if opts.modelType is 'file' # Create a file model model = new FileModel(attrs, opts) else # Create document model model = new DocumentModel(attrs, opts) # ----------------------------- # Finish up # Attach Events @attachModelEvents(model) # Return return model ###* # Parse a directory and return a # files collection # @method parseDirectory # @param {Object} [opts={}] # @param {Object} next # @param {Error} next.err # @param {Object} next.files files collection ### parseDirectory: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() # Extract {path,createFunction} = opts createFunction ?= @createModel files = opts.collection or new FilesCollection() # Check if the directory exists safefs.exists path, (exists) -> # Check unless exists # Log docpad.log 'debug', util.format(locale.renderDirectoryNonexistant, path) # Forward return next() # Log docpad.log 'debug', util.format(locale.renderDirectoryParsing, path) # Tasks tasks = new TaskGroup('parse directory').setConfig(concurrency:0).done (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderDirectoryParsed, path) # Forward return next(null, files) # Files docpad.scandir( # Path path: path # File Action fileAction: (fileFullPath, fileRelativePath, filename, fileStat) -> # Prepare data = fullPath: fileFullPath relativePath: fileRelativePath stat: fileStat # Create file file = createFunction.call(docpad, data, opts) # Create a task to load the file tasks.addTask "load the file #{fileRelativePath}", (complete) -> # Update the file's stat # To ensure changes files are handled correctly in generation file.action 'load', (err) -> # Error? return complete(err) if err # Add the file to the collection files.add(file) # Next complete() # Return return # Next next: (err) -> return next(err) if err tasks.run() ) # Chain @ # ================================= # Plugins ###* # Get a plugin by it's name # @method getPlugin # @param {Object} pluginName # @return {Object} a DocPad plugin ### getPlugin: (pluginName) -> @loadedPlugins[pluginName] ###* # Check if we have any plugins # @method hasPlugins # @return {Boolean} ### hasPlugins: -> return typeChecker.isEmptyPlainObject(@loadedPlugins) is false ###* # Destructor. Destroy plugins # @private # @method destroyPlugins ### destroyPlugins: -> for own name,plugin of @loadedPlugins plugin.destroy() @loadedPlugins[name] = null @ ###* # Load plugins from the file system # next(err) # @private # @method loadPlugins # @param {Function} next # @param {Error} next.err ### loadPlugins: (next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() # Track the slow plugins @slowPlugins = {} @timer 'slowplugins', 'interval', config.slowPluginsDelay, -> docpad.log 'notice', util.format(locale.pluginsSlow, Object.keys(docpad.slowPlugins).join(', ')) # Async tasks = @createTaskGroup("loadPlugins tasks").done (err) -> docpad.timer('slowplugins') docpad.slowPlugins = {} return next(err) # Prepare the plugins to loaded plugins = new Set( Object.keys(docpad.websitePackageConfig.dependencies or {}).concat( Object.keys(docpad.websitePackageConfig.devDependencies or {}) ) .filter((name) -> name.startsWith('docpad-plugin-')) .concat(config.pluginPaths or []) .map((name) -> { pluginPath: docpad.getPath(false, 'root', 'node_modules', name) }) ) # Emit the even tasks.addTask 'emit loadPlugins', (complete) -> docpad.emitSerial('loadPlugins', {docpad, plugins}, complete) # Load the plugins tasks.addTaskGroup 'load plugins', {concurrency: 0}, (suite, task) -> plugins.forEach (plugin) -> tasks.addTask "load the plugin at: #{plugin.pluginPath}", (complete) -> docpad.loadPlugin(plugin, complete) # Execute the loading asynchronously tasks.run() # Chain @ ###* # Load a plugin from its full file path # _next(err) # @private # @method loadPlugin # @param {Object} opts # @param {Function} _next # @param {Error} _next.err ### loadPlugin: (opts = {}, _next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() next = (err) -> # Remove from slow plugins delete docpad.slowPlugins[pluginName] if pluginName # Forward _next(err) # Chain return docpad # Default opts opts.keyword ?= 'docpad-plugin' opts.prefix ?= 'docpad-plugin-' opts.BasePlugin ?= BasePlugin opts.log ?= @log # Load and validate the plugin try loader = new PluginLoader(opts) catch unsupportedError docpad.warn(new Errlop( util.format(locale.pluginUnsupported, opts.pluginPath), unsupportedError )) return next() # Prepare pluginName = loader.pluginName enabled = config.plugins[pluginName] isnt false # If we've already been loaded, then exit early as there is no use for us to load again if docpad.loadedPlugins[pluginName]? # However we probably want to reload the configuration as perhaps the user or environment configuration has changed docpad.loadedPlugins[pluginName].setConfig() # Complete return next() # Add to loading stores docpad.slowPlugins[pluginName] = true # Check unless enabled # Skip docpad.log 'info', util.format(locale.pluginDisabled, opts.pluginName) return next() else # Load docpad.log 'debug', util.format(locale.pluginLoading, opts.pluginPath) # Create an instance try # Add to plugin stores docpad.loadedPlugins[pluginName] = loader.create({docpad}) catch failedError err = new Errlop( util.format(locale.pluginFailed, opts.pluginPath), failedError ) return next(err) # Log completion docpad.log 'debug', util.format(locale.pluginLoaded, opts.pluginPath) return next() # ================================= # Utilities # --------------------------------- # Utilities: Files ###* # Contextualize files. # Contextualizing is the process of adding layouts and # awareness of other documents to our document. The # contextualizeBefore and contextualizeAfter events # are emitted here. # @private # @method contextualizeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### contextualizeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.contextualizingFiles, collection.length) # Start contextualizing docpad.emitSerial 'contextualizeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("contextualizeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'contextualizeAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.contextualizedFiles, collection.length) # Forward return next() # Add contextualize tasks collection.forEach (file,index) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') or file.id tasks.addTask "conextualizing: #{filePath}", (complete) -> file.action 'contextualize', (err) -> delete slowFilesObject[file.id] return complete(err) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'contextualizeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Render the DocPad project's files. # The renderCollectionBefore, renderCollectionAfter, # renderBefore, renderAfter events are all emitted here. # @private # @method renderFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### renderFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData,renderPasses} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.renderingFiles, collection.length) # Render File # next(null, outContent, file) renderFile = (file,next) -> # Render if file.get('render') is false or !file.get('relativePath') file.attributes.rtime = new Date() next(null, file.getOutContent(), file) else file.action('render', {templateData}, next) # Return return file # Render Collection renderCollection = (collectionToRender,{renderPass},next) -> # Plugin Event docpad.emitSerial 'renderCollectionBefore', {collection:collectionToRender,renderPass}, (err) -> # Prepare return next(err) if err subTasks = docpad.createTaskGroup("renderFiles: Pass #{renderPass}]: renderCollection: #{collectionToRender.options.name}", concurrency:0).done (err) -> # Prepare return next(err) if err # Plugin Event docpad.emitSerial('renderCollectionAfter', {collection:collectionToRender,renderPass}, next) # Cycle collectionToRender.forEach (file) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') subTasks.addTask "rendering: #{filePath}", (complete) -> renderFile file, (err) -> delete slowFilesObject[file.id] or file.id return complete(err) # Return subTasks.run() return collectionToRender # Plugin Event docpad.emitSerial 'renderBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Async tasks = docpad.createTaskGroup("renderFiles: renderCollection: renderBefore").done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'renderAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderedFiles, collection.length) # Forward return next() # Queue the initial render initialCollection = collection.findAll('referencesOthers':false) subsequentCollection = null tasks.addTask "rendering the initial collection", (complete) -> renderCollection initialCollection, {renderPass:1}, (err) -> return complete(err) if err subsequentCollection = collection.findAll('referencesOthers':true) renderCollection(subsequentCollection, {renderPass:2}, complete) # Queue the subsequent renders if renderPasses > 1 [3..renderPasses].forEach (renderPass) -> tasks.addTask "rendering the subsequent collection index #{renderPass}", (complete) -> renderCollection(subsequentCollection, {renderPass}, complete) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'renderFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Write rendered files to the DocPad out directory. # The writeBefore and writeAfter events are emitted here. # @private # @method writeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### writeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.writingFiles, collection.length) # Plugin Event docpad.emitSerial 'writeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("writeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'writeAfter', {collection}, (err) -> # Check return next(err) if err # docpad.log 'debug', util.format(locale.wroteFiles, collection.length) return next() # Add write tasks collection.forEach (file,index) -> filePath = file.getFilePath() tasks.addTask "writing the file: #{filePath}", (complete) -> # Prepare slowFilesObject[file.id] = file.get('relativePath') # Create sub tasks fileTasks = docpad.createTaskGroup("tasks for file write: #{filePath}", concurrency:0).done (err) -> delete slowFilesObject[file.id] return complete(err) # Write out if file.get('write') isnt false and file.get('outPath') fileTasks.addTask "write out", (complete) -> file.action('write', complete) # Write source if file.get('writeSource') is true and file.get('fullPath') fileTasks.addTask "write source", (complete) -> file.action('writeSource', complete) # Run sub tasks fileTasks.run() # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'writeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ # --------------------------------- # Generate # Generate Helpers ###* # Has DocPad's generation process started? # @private # @property {Boolean} generateStarted ### generateStarted: null ###* # Has DocPad's generation process ended? # @private # @property {Boolean} generateEnded ### generateEnded: null ###* # Is DocPad currently generating? # @private # @property {Boolean} generating ### generating: false ###* # Has DocPad done at least one generation? # True once the first generation has occured. # @private # @property {Object} generated ### generated: false ###* # Set off DocPad's generation process. # The generated, populateCollectionsBefore, populateCollections, populateCollections # generateBefore and generateAfter events are emitted here # @method generate # @param {Object} opts # @param {Function} next # @param {Error} next.err ### generate: (opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = docpad.getConfig() locale = docpad.getLocale() database = docpad.getDatabase() # Check return next() if opts.collection?.length is 0 # Update generating flag lastGenerateStarted = docpad.generateStarted docpad.generateStarted = new Date() docpad.generateEnded = null docpad.generating = true # Grab the template data we will use for rendering opts.templateData = docpad.getTemplateData(opts.templateData or {}) # How many render passes will we require? # Can be over-written by API calls opts.renderPasses or= config.renderPasses # Destroy Regenerate Timer docpad.timer('regenerate') # Check plugin count docpad.log('notice', locale.renderNoPlugins) unless docpad.hasPlugins() # Log docpad.log('info', locale.renderGenerating) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratingNotification} # Tasks tasks = @createTaskGroup("generate tasks").done (err) -> # Update generating flag docpad.generating = false docpad.generateEnded = new Date() # Create Regenerate Timer if config.regenerateEvery docpad.timer 'regenerate', 'timeout', config.regenerateEvery, -> docpad.log('info', locale.renderInterval) docpad.action('generate', config.regenerateEveryOptions) # Error? return next(err) if err # Log success message seconds = (docpad.generateEnded - docpad.generateStarted) / 1000 howMany = "#{opts.collection?.length or 0}/#{database.length}" docpad.log 'info', util.format(locale.renderGenerated, howMany, seconds) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratedNotification} # Generated if opts.initial is true docpad.generated = true return docpad.emitSerial('generated', opts, next) # Safety check if generated is false but initial was false too # https://github.com/bevry/docpad/issues/811 else if docpad.generated is false return next( new Errlop('DocPad is in an invalid state, please report this. Reference 3360') ) else return next() # Extract functions from tasks for simplicity # when dealing with nested tasks/groups addGroup = tasks.addGroup.bind(tasks) addTask = tasks.addTask.bind(tasks) # Setup a clean database addTask 'Reset our collections', (complete) -> # Skip if we are not a reset generation, or an initial generation (generated is false) return complete() unless opts.reset is true or docpad.generated is false return docpad.resetCollections(opts, complete) # Figure out the options # This is here as resetCollections could change our state # https://github.com/bevry/docpad/issues/811 addTask 'Figure out options', -> # Mode: Initial # Shall we do some basic initial checks # Set to the opts.reset value if specified, or whether are the initial generation opts.initial ?= !(docpad.generated) # Mode: Reset # Shall we reset the database # Set to true if we are the initial generation opts.reset ?= opts.initial # Mode: Populate # Shall we fetch in new data? # Set to the opts.reset value if specified, or the opts.initial value opts.populate ?= opts.reset # Mode: Reload # Shall we rescan the file system for changes? # Set to the opts.reset value if specified, or the opts.initial value opts.reload ?= opts.reset # Mode: Partial # Shall we perform a partial generation (false) or a completion generation (true)? # Set to false if we are the initial generation opts.partial ?= !(opts.reset) # Log our opts docpad.log( 'debug' 'Generate options:' pick(opts, ['initial', 'reset', 'populate', 'reload', 'partial', 'renderPasses']) ) # Check directory structure addTask 'check source directory exists', (complete) -> # Skip if we are not the initial generation return complete() unless opts.initial is true # Continue if we are the initial generation sourcePath = docpad.getPath('source') unless sourcePath err = new Errlop(util.format(locale.renderNonexistant, docpad.getPath(false, 'source'))) return complete(err) # Forward return complete() # Check directory structure addTask 'ensure out directory exists', (complete) -> outPath = docpad.getPath(false, 'out') return safefs.ensurePath(outPath, complete) addGroup 'fetch data to render', (addGroup, addTask) -> # Fetch new data # If we are a populate generation (by default an initial generation) if opts.populate is true # This will pull in new data from plugins addTask 'populateCollectionsBefore', (complete) -> docpad.emitSerial('populateCollectionsBefore', opts, complete) # Rescan the file system # If we are a reload generation (by default an initial generation) # This is useful when the database is out of sync with the source files # For instance, someone shut down docpad, and made some changes, then ran docpad again # See https://github.com/bevry/docpad/issues/705#issuecomment-29243666 for details if opts.reload is true addGroup 'import data from file system', (addGroup, addTask) -> # Documents docpad.getPath('documents').forEach (documentsPath) -> addTask 'import documents', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: documentsPath next: complete }) # Files docpad.getPath('files').forEach (filesPath) -> addTask 'import files', (complete) -> docpad.parseDirectory({ modelType: 'file' collection: database path: filesPath next: complete }) # Layouts docpad.getPath('layouts').forEach (layoutsPath) -> addTask 'import layouts', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: layoutsPath next: complete }) # This will pull in new data from plugins addTask 'populateCollections', (complete) -> docpad.emitSerial('populateCollections', opts, complete) addGroup 'determine files to render', (addGroup, addTask) -> # Perform a complete regeneration if opts.partial is false # Use Entire Collection addTask 'Add all database models to render queue', -> opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').models) # Perform a partial regeneration # If we are not a reset generation (by default any non-initial generation) else # Use Partial Collection addTask 'Add only changed models to render queue', -> changedQuery = $or: # Get changed files mtime: $gte: lastGenerateStarted # Get new files $and: wtime: null write: true opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').findAll(changedQuery).models) addTask 'generateBefore', (complete) -> # If we have nothing to generate if opts.collection.length is 0 # then there is no need to execute further tasks tasks.clear() complete() # Otherwise continue down the task loop else docpad.emitSerial('generateBefore', opts, complete) addTask 'prepare files', (complete) -> # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Add anything that references other documents (e.g. partials, listing, etc) # This could eventually be way better standalones = opts.collection.pluck('standalone') allStandalone = standalones.indexOf(false) is -1 if allStandalone is false opts.collection.add(docpad.getCollection('referencesOthers').models) # Deeply/recursively add the layout children addLayoutChildren = (collection) -> collection.forEach (file) -> if file.get('isLayout') is true # Find layoutChildrenQuery = layoutRelativePath: file.get('relativePath') layoutChildrenCollection = docpad.getCollection('hasLayout').findAll(layoutChildrenQuery) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Layout children to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') write: model.get('write') } for model in layoutChildrenCollection.models ), '\n', layoutChildrenQuery # Recurse addLayoutChildren(layoutChildrenCollection) # Add opts.collection.add(layoutChildrenCollection.models) addLayoutChildren(opts.collection) # Filter out ignored, and no-render no-write files opts.collection.reset opts.collection.reject (file) -> return (file.get('render') is false and file.get('write') is false) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Forward return complete() addGroup 'process file', (addGroup, addTask) -> addTask 'contextualizeFiles', {args:[opts]}, docpad.contextualizeFiles.bind(docpad) addTask 'renderFiles', {args:[opts]}, docpad.renderFiles.bind(docpad) addTask 'writeFiles', {args:[opts]}, docpad.writeFiles.bind(docpad) addTask 'generateAfter', (complete) -> docpad.emitSerial('generateAfter', opts, complete) # Run tasks.run() # Chain @ # --------------------------------- # Render ###* # Load a document # @private # @method loadDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Load # @TODO: don't load if already loaded document.action('load contextualize', opts, next) # Chain @ ###* # Load and render a document # @method loadAndRenderDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadAndRenderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ # Load docpad.loadDocument document, opts, (err) -> return next(err) if err # Render docpad.renderDocument(document, opts, next) # Chain @ ###* # Render a document # @method renderDocument # @param {Object} document # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### renderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Render clone = document.clone().action 'render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render a document at a file path # next(err,result) # @method renderPath # @param {String} path # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderPath: (path,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ fullPath: path }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ ###* # Render the passed content data as a # document. Required option, filename # (opts.filename) # next(err,result) # @method renderData # @param {String} content # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderData: (content,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ filename: opts.filename data: content }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ # Render Text # Doesn't extract meta information, or render layouts # TODO: Why not? Why not just have renderData? ###* # Render the passed text data as a # document. Required option, filename # (opts.filename) # next(err,result) # @private # @method renderText # @param {String} text # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered content # @param {Object} next.document the rendered document model ### renderText: (text,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) opts.actions ?= ['renderExtensions', 'renderDocument'] attributes = extendr.extend({ filename: opts.filename data: text body: text content: text }, opts.attributes or {}) # Handle document = @createDocument(attributes) # Render clone = document.clone().action 'normalize contextualize render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render action # @method render # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### render: (opts,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() [opts,next] = extractOptsAndCallback(opts,next) opts.stdin ?= false # Completion unless opts.output complete = next else complete = (err, result, document) -> # Forward return next(err) if err # Output if opts.output is true process.stdout.write(result) else if opts.output return safefs.writeFile opts.output, result, (err) -> return next(err, result, document) # Forward return next(null, result, document) # Render if opts.stdin docpad.renderStdin(opts, complete) else if opts.document docpad.renderDocument(opts.document, opts, complete) else if opts.data docpad.renderData(opts.data, opts, complete) else if opts.text docpad.renderText(opts.text, opts, complete) else path = opts.path or opts.fullPath or opts.filename or null if path docpad.renderPath(path, opts, complete) else err = new Errlop(locale.renderInvalidOptions) return complete(err) # Chain @ renderStdin: (opts, next) -> # Prepare docpad = @ [opts,next] = extractOptsAndCallback(opts,next) data = '' # Read stdin = process.stdin stdin.resume() stdin.setEncoding('utf8') stdin.on 'data', (_data) -> docpad.timer('render') data += _data.toString() process.stdin.on 'end', -> docpad.timer('render') docpad.renderData(data, opts, next) # Chain @ # --------------------------------- # Watch ###* # Array of file watchers # @private # @property {Array} watchers ### watchers: null ###* # Destructor. Destroy the watchers used # by DocPad # @private # @method destroyWatchers ### destroyWatchers: -> # Prepare docpad = @ # Check if docpad.watchers # Close each of them for watcher in docpad.watchers watcher.close() # Reset the array docpad.watchers = [] # Chain @ ###* # Start up file watchers used by DocPad # @private # @method watch # @param {Object} opts # @param {Function} next # @param {Error} next.err ### watch: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() database = @getDatabase() @watchers ?= [] # Restart our watchers restartWatchers = (next) -> # Close our watchers docpad.destroyWatchers() # Start a group tasks = docpad.createTaskGroup("watch tasks", concurrency:0).done(next) # Watch reload paths reloadPaths = union(docpad.getPath('reloads'), docpad.getPath('configs')) tasks.addTask "watch reload paths", (complete) -> docpad.watchdirs( reloadPaths, { 'log': docpad.log 'error': docpad.error 'change': -> docpad.log 'info', util.format(locale.watchReloadChange, new Date().toLocaleTimeString()) docpad.action 'load', (err) -> return docpad.fatal(err) if err performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the reload paths has failed:\n"+docpad.inspect(reloadPaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch regenerate paths regeneratePaths = docpad.getPath('regenerates') tasks.addTask "watch regenerate paths", (complete) -> docpad.watchdirs( regeneratePaths, { 'log': docpad.log 'error': docpad.error 'change': -> performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the regenerate paths has failed:\n"+docpad.inspect(regeneratePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch the source sourcePaths = docpad.getPath('sources') tasks.addTask "watch the source path", (complete) -> docpad.watchdirs( sourcePaths, { 'log': docpad.log 'error': docpad.error 'change': changeHandler }, (err,_watchers) -> if err docpad.warn("Watching the source paths has failed:\n"+docpad.inspect(sourcePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Run tasks.run() # Chain @ # Timer queueRegeneration = -> docpad.timer('regeneration', 'timeout', config.regenerateDelay, performGenerate) # Generate performGenerate = (opts={}) -> # Q: Should we also pass over the collection? # A: No, doing the mtime query in generate is more robust # Log docpad.log util.format(locale.watchRegenerating, new Date().toLocaleTimeString()) # Afterwards, re-render anything that should always re-render docpad.action 'generate', opts, (err) -> docpad.error(err) if err docpad.log util.format(locale.watchRegenerated, new Date().toLocaleTimeString()) # Change event handler changeHandler = (changeType,filePath,fileCurrentStat,filePreviousStat) -> # Prepare fileEitherStat = (fileCurrentStat or filePreviousStat) # For some reason neither of the stats may exist, this will cause errors as this is an invalid state # as we depend on at least one stat existing, otherwise, what on earth is going on? # Whatever the case, this should be fixed within watchr, not docpad # as watchr should not be giving us invalid data # https://github.com/bevry/docpad/issues/792 unless fileEitherStat err = new Errlop(""" DocPad has encountered an invalid state while detecting changes for your files. So the DocPad team can fix this right away, please provide any information you can to: https://github.com/bevry/docpad/issues/792 """) return docpad.error(err) # Log the change docpad.log 'info', util.format(locale.watchChange, new Date().toLocaleTimeString()), changeType, filePath # Check if we are a file we don't care about # This check should not be needed with v2.3.3 of watchr # however we've still got it here as it may still be an issue isIgnored = docpad.isIgnoredPath(filePath) if isIgnored docpad.log 'debug', util.format(locale.watchIgnoredChange, new Date().toLocaleTimeString()), filePath return # Don't care if we are a directory isDirectory = fileEitherStat.isDirectory() if isDirectory docpad.log 'debug', util.format(locale.watchDirectoryChange, new Date().toLocaleTimeString()), filePath return # Override the stat's mtime to now # This is because renames will not update the mtime fileCurrentStat?.mtime = new Date() # Create the file object file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) file.setStat(fileCurrentStat) if changeType is 'update' # File was deleted, delete the rendered file, and remove it from the database if changeType is 'delete' database.remove(file) file.action 'delete', (err) -> return docpad.error(err) if err queueRegeneration() # File is new or was changed, update it's mtime by setting the stat else if changeType in ['create', 'update'] file.action 'load', (err) -> return docpad.error(err) if err queueRegeneration() # Watch docpad.log(locale.watchStart) restartWatchers (err) -> return next(err) if err docpad.log(locale.watchStarted) return next() # Chain @ # --------------------------------- # Run Action ###* # Run an action # @method run # @param {Object} opts # @param {Function} next # @param {Error} next.err ### run: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare run = (next) -> docpad.emitSerial 'runBefore', (err) -> return next(err) if err balUtil.flow( object: docpad action: 'generate watch' args: [opts] next: (err) -> docpad.emitSerial('runAfter', next) ) # Check if have the correct structure, if so let's proceed with DocPad sourcePath = @getPath('source') return run(next) if sourcePath # We don't have the correct structure # Check if we are running on an empty directory rootPath = @getPath('root') safefs.readdir rootPath, (err,files) -> return next(err) if err # Check if our directory is empty if files.length # It isn't empty, display a warning docpad.warn util.format(locale.invalidProject, rootPath) return next() else docpad.init opts, (err) -> # Check return next(err) if err # Keep in global? return run(next) if opts.global is true or docpad.getConfig().global is true # Log docpad.log('notice', locale.startLocal) # Destroy our DocPad instance so we can boot the local one docpad.destroy (err) -> # Check return next(err) if err # Forward onto the local DocPad Instance now that it has been installed return docpadUtil.startLocalDocPadExecutable(next) # Chain @ ###* # Info action # @private # @method info # @param {Object} opts # @param {Function} next ### info: (opts, next) -> [opts,next] = extractOptsAndCallback(opts,next) console.log @inspect @getConfig() next?() @ # --------------------------------- # Project ###* # Initialize the project install process. # @private # @method initInstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### initInstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Exists? packagePath = @getPath(false, 'package') safefs.exists packagePath, (exists) -> # Check return next() if exists # Write data = JSON.stringify({ name: 'no-skeleton.docpad' version: '0.1.0' description: 'New DocPad project without using a skeleton' dependencies: docpad: '~'+docpad.getVersion() scripts: start: 'docpad run' test: 'docpad generate' }, null, ' ') safefs.writeFile(packagePath, data, next) # Chain @ ###* # Uninstall a plugin. # @private # @method uninstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### uninstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("uninstall tasks").done(next) # Uninstall a plugin if opts.plugin tasks.addTask "uninstall the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin docpad.uninstallNodeModule(plugins, complete) # Re-load configuration tasks.addTask "re-load configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Install a plugin # @private # @method install # @param {Object} opts # @param {Function} next # @param {Error} next.err ### install: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("install tasks").done(next) tasks.addTask "init the installation", (complete) -> docpad.initInstall(opts, complete) # Install a plugin if opts.plugin tasks.addTask "install the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin += '@'+docpad.pluginVersion if plugin.indexOf('@') is -1 plugin docpad.installNodeModule(plugins, complete) tasks.addTask "re-initialize the website's modules", (complete) -> docpad.initNodeModules(complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-load the configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Update global NPM and DocPad # @private # @method upgrade # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### upgrade: (opts,next) -> # Update Global NPM and DocPad @installNodeModule('npm docpad@6', {global: true}, next) # Chain @ ###* # Update the local DocPad and plugin dependencies # @private # @method update # @param {Object} opts # @param {Object} next # @param {Error} next.err ### update: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("update tasks").done(next) tasks.addTask "init the install", (complete) -> docpad.initInstall(opts, complete) # Update the local docpad and plugin dependencies # Grouped together to avoid npm dependency shortcuts that can cause missing dependencies # But don't update git/http/https dependencies, those are special for some reason # > https://github.com/bevry/docpad/pull/701 dependencies = [] eachr docpad.websitePackageConfig.dependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false or /// :// ///.test(version) is true dependencies.push(name+'@'+docpad.pluginVersion) if dependencies.length isnt 0 tasks.addTask "update plugins that are dependencies", (complete) -> docpad.installNodeModule('docpad@6 '+dependencies, complete) # Update the plugin dev dependencies devDependencies = [] eachr docpad.websitePackageConfig.devDependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false devDependencies.push(name+'@'+docpad.pluginVersion) if devDependencies.length isnt 0 tasks.addTask "update plugins that are dev dependencies", (complete) -> docpad.installNodeModule(devDependencies, {save: '--save-dev'}, complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-initialize the rest of the website's modules", (complete) -> docpad.initNodeModules(complete) # Run tasks.run() # Chain @ ###* # DocPad cleanup tasks. # @private # @method clean # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### clean: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() paths = [] # Log docpad.log('info', locale.cleanStarted) # Tasks tasks = @createTaskGroup("clean tasks", concurrency:0).done (err) -> # Error? return next(err) if err # Log message = util.format( locale.cleanFinish, paths.length ) if paths.length message += ': ' if paths.length isnt 1 message += '\n' message += paths.join('\n') docpad.log('info', message) # Forward return next() tasks.addTask 'reset the collections', (complete) -> docpad.resetCollections(opts, complete) # Delete out path # but only if our outPath is not a parent of our rootPath tasks.addTask 'delete out path', (complete) -> rootPath = docpad.getPath('root') outPath = docpad.getPath('out') # Only remove outpath if it does not contain our root path if outPath and pathUtil.relative(outPath, rootPath).startsWith('..') paths.push(outPath) rimraf(outPath, complete) else complete() # Run tasks tasks.run() # Chain @ ###* # Initialize the directory for DocPad # @private # @method init # @param {Function} next # @param {Error} next.err ### init: (opts,next) -> # Prepare docpad = @ config = @getConfig() rootPath = @getPath(false, 'root') # Tasks tasks = @createTaskGroup("init tasks").done(next) tasks.addTask "ensure the path we are writing to exists", (complete) -> safefs.ensurePath(rootPath, complete) tasks.addTask "ensure src path exists", (complete) -> safefs.ensurePath(docpad.getPath(false, 'source'), complete) tasks.addGroup "initialize the website directory files", -> @setConfig(concurrency:0) # README @addTask "README.md", (complete) -> readmePath = docpad.getPath(false, 'root', 'README.md') data = """ # Your [DocPad](https://docpad.bevry.me) Project ## License Copyright &copy; #{(new Date()).getFullYear()}+ All rights reserved. """ safefs.writeFile(readmePath, data, complete) # Config @addTask "docpad.coffee configuration file", (complete) -> configPath = docpad.getPath(false, 'root', 'docpad.js') data = """ // DocPad Configuration File // https://docpad.bevry.me/config // Define the DocPad Configuration const docpadConfig = { // ... } // Export the DocPad Configuration module.exports = docpadConfig """ safefs.writeFile(configPath, data, complete) # Documents @addTask "documents directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'document'), complete) # Layouts @addTask "layouts directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'layout'), complete) # Files @addTask "files directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'file'), complete) # Run tasks.run() # Chain @ # --------------------------------- # Export module.exports = DocPad
133839
##* # The central module for DocPad # @module DocPad ## # ===================================== # Requires # Standard util = require('util') pathUtil = require('path') # External { Logger, Human, Filter } = require('caterpillar') fsUtil = require('fs') Errlop = require('errlop').default queryEngine = require('query-engine') {uniq, union, pick} = require('underscore') CSON = require('cson') balUtil = require('bal-util') scandir = require('scandirectory') extendr = require('extendr') eachr = require('eachr') typeChecker = require('typechecker') ambi = require('ambi') unbounded = require('unbounded') {TaskGroup} = require('taskgroup') safefs = require('safefs') safeps = require('safeps') ignorefs = require('ignorefs') rimraf = require('rimraf') Progress = require('progress-title') fetch = require('node-fetch') extractOptsAndCallback = require('extract-opts') {EventEmitterGrouped} = require('event-emitter-grouped') envFile = require('envfile') ansiStyles = require('ansistyles') # Base {Events,Model,Collection,QueryCollection} = require('./base') # Utils docpadUtil = require('./util') # Models FileModel = require('./models/file') DocumentModel = require('./models/document') # Collections FilesCollection = require('./collections/files') ElementsCollection = require('./collections/elements') MetaCollection = require('./collections/meta') ScriptsCollection = require('./collections/scripts') StylesCollection = require('./collections/styles') # Plugins PluginLoader = require('@bevry/pluginloader').default BasePlugin = require('docpad-baseplugin') # --------------------------------- # Variables isUser = docpadUtil.isUser() isTruthy = (i) -> Boolean(i) ###* # Contains methods for managing the DocPad application. # Extends https://github.com/bevry/event-emitter-grouped # # You can use it like so: # # new DocPad(docpadConfig, function(err, docpad) { # if (err) return docpad.fatal(err) # return docpad.action(action, function(err) { # if (err) return docpad.fatal(err) # return console.log('OK') # }) # }) # # @class Docpad # @constructor # @extends EventEmitterGrouped ### class DocPad extends EventEmitterGrouped # Libraries # Here for legacy API reasons #@DocPad: DocPad #@Backbone: require('backbone') #@queryEngine: queryEngine # Allow for `DocPad.create()` as an alias for `new DocPad()` @create: (args...) -> return new @(args...) # Require a local DocPad file # Before v6.73.0 this allowed requiring of files inside src/lib, as well as files inside src # After v6.73.0 it only allows requiring of files inside src/lib as that makes more sense # After v6.80.9 it only allows requiring specific aliases @require: (name) -> if name is 'testers' console.log( '''' docpad.require('testers') is deprecated, replacement instructions at: https://github.com/docpad/docpad-plugintester ''' ) return require('docpad-plugintester') else throw new Errlop("docpad.require is limited to requiring: testers") # ================================= # Variables # --------------------------------- # Modules # --------------------------------- # Base ###* # Events class # @property {Object} Events ### Events: Events ###* # Model class # Extension of the Backbone Model class # http://backbonejs.org/#Model # @property {Object} Model ### Model: Model ###* # Collection class # Extension of the Backbone Collection class # http://backbonejs.org/#Collection # @property {Object} Collection ### Collection: Collection ###* # QueryCollection class # Extension of the Query Engine QueryCollection class # @property {Object} QueryCollection ### QueryCollection: QueryCollection # --------------------------------- # Models ###* # File Model class # Extension of the Model class # @property {Object} FileModel ### FileModel: FileModel ###* # Document Model class # Extension of the File Model class # @property {Object} DocumentModel ### DocumentModel: DocumentModel # --------------------------------- # Collections ###* # Collection of files in a DocPad project # Extension of the QueryCollection class # @property {Object} FilesCollection ### FilesCollection: FilesCollection ###* # Collection of elements in a DocPad project # Extension of the Collection class # @property {Object} ElementsCollection ### ElementsCollection: ElementsCollection ###* # Collection of metadata in a DocPad project # Extension of the ElementsCollection class # @property {Object} MetaCollection ### MetaCollection: MetaCollection ###* # Collection of JS script files in a DocPad project # Extension of the ElementsCollection class # @property {Object} ScriptsCollection ### ScriptsCollection: ScriptsCollection ###* # Collection of CSS style files in a DocPad project # Extension of the ElementsCollection class # @property {Object} StylesCollection ### StylesCollection: StylesCollection # --------------------------------- # DocPad ###* # DocPad's version number # @private # @property {Number} version ### version: null ###* # Get the DocPad version number # @method getVersion # @return {Number} ### getVersion: -> @version ?= require(@packagePath).version return @version ###* # Get the DocPad version string # @method getVersionString # @return {String} ### getVersionString: -> if docpadUtil.isLocalDocPadExecutable() return util.format(@getLocale().versionLocal, @getVersion(), @corePath) else return util.format(@getLocale().versionGlobal, @getVersion(), @corePath) ###* # The plugin version requirements # @property {String} pluginVersion ### pluginVersion: '2' # Process getters ###* # Get the process platform # @method getProcessPlatform # @return {Object} ### getProcessPlatform: -> process.platform ###* # Get the process version string # @method getProcessVersion # @return {String} ### getProcessVersion: -> process.version.replace(/^v/,'') ###* # Internal property. The caterpillar logger instance bound to DocPad # @private # @property {Object} loggerInstances ### logger: null ###* # Get the caterpillar logger instance bound to DocPad # @method getLogger # @return {Object} caterpillar logger ### getLogger: -> @logger ###* # Destructor. Destroy the caterpillar logger instances bound to DocPad # @private # @method {Object} destroyLoggers ### destroyLoggers: -> # @logger.end() @logger = null @ ###* # All the timers that exist within DocPad # Used for closing them at shutdown # @private # @property {Object} timers ### timers: null ###* # Create a timer and add it to the known timers # @method timer # @param {string} type - either timeout or interval # @param {number} time - the time to apply to the timer # @param {method} method - the method to use for the timer ### timer: (id, type, time, method) -> @timers ?= {} # Create a new timer if type? @timer(id) # clear if type is 'timeout' if time is -1 timer = setImmediate(method) else timer = setTimeout(method, time) else if type is 'interval' timer = setInterval(method, time) else throw new Errlop('unexpected type on new timer') @timers[id] = {id, type, time, method, timer} # Destroy an old timer else if @timers[id] if @timers[id].type is 'interval' clearInterval(@timers[id].timer) else if @timers[id].type is 'timeout' if @timers[id].time is -1 clearImmediate?(@timers[id].timer) else clearTimeout(@timers[id].timer) else throw new Errlop('unexpected type on stored timer') @timers[id] = null @ ###* # Destructor. Destroy all the timers we have kept. # @private # @method {Object} destroyTimers ### destroyTimers: (timer) -> @timers ?= {} for own key, value of @timers @timer(key) @ ###* # Instance of progress-title # @private # @property {Progress} progressInstance ### progressInstance: null ###* # Update the configuration of the progress instance, to either enable it or disable it # Progress will be enabled if DocPad config 'progress' is true # @private # @method updateProgress # @param {boolean} [enabled] manually enable or disable the progress bar ### updateProgress: (enabled) -> # Prepare docpad = @ config = docpad.getConfig() debug = @getDebugging() # Enabled enabled ?= config.progress # If we are in debug mode, then output more detailed title messages options = {} if debug options.verbose = true options.interval = 0 # options.log = true # If we wish to have it enabled if enabled if @progressInstance @progressInstance.pause().configure(options).resume() else @progressInstance = Progress.create(options).start() else if @progressInstance @progressInstance.stop().configure(options) # Return return this ###* # The action runner instance bound to docpad # @private # @property {Object} actionRunnerInstance ### actionRunnerInstance: null ###* # Get the action runner instance bound to docpad # @method getActionRunner # @return {Object} the action runner instance ### getActionRunner: -> @actionRunnerInstance ###* # Apply the passed DocPad action arguments # @method {Object} action # @param {Object} args # @return {Object} ### action: (action, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) locale = @getLocale() # Log @progressInstance?.resume() @log 'debug', util.format(locale.actionStart, action) # Act docpadUtil.action.call @, action, opts, (args...) => # Prepare err = args[0] # Log @progressInstance?.stop() if err @error(new Errlop( util.format(locale.actionFailure, action), err )) else @log 'debug', util.format(locale.actionSuccess, action) # Act return next?(args...) # Chain @ ###* # Event Listing. String array of event names. # Whenever an event is created, it must be applied here to be available to plugins and configuration files # Events must be sorted by the order of execution, not for a functional need, but for a documentation need # Whenever this array changes, also update: https://docpad.bevry.me/events # @private # @property {Array} string array of event names ### events: [ 'loadPlugins' # fired each load 'extendCollections' # fired each load 'extendTemplateData' # fired each load 'docpadReady' # fired only once 'docpadDestroy' # fired once on shutdown 'consoleSetup' # fired once 'runBefore' 'runAfter' 'generateBefore' 'populateCollectionsBefore' 'populateCollections' 'contextualizeBefore' 'contextualizeAfter' 'renderBefore' 'renderCollectionBefore' 'render' # fired for each extension conversion 'renderDocument' # fired for each document render, including layouts and render passes 'renderCollectionAfter' 'renderAfter' 'writeBefore' 'writeAfter' 'generateAfter' 'generated' 'notify' ] ###* # Get the list of available events # @method getEvents # @return {Object} string array of event names ### getEvents: -> @events # --------------------------------- # Collections # Database collection ###* # QueryEngine collection # @private # @property {Object} database ### database: null ###* # Description for getDatabase # @method {Object} getDatabase ### getDatabase: -> @database ###* # Destructor. Destroy the DocPad database # @private # @method destroyDatabase ### destroyDatabase: -> if @database? @database.destroy() @database = null @ ###* # Blocks # @private # @property {Object} blocks ### blocks: null ### { # A collection of meta elements meta: null # Elements Collection # A collection of script elements scripts: null # Scripts Collection # Collection of style elements styles: null # Styles Collection } ### ###* # Get a block by block name. Optionally clone block. # @method getBlock # @param {String} name # @param {Object} [clone] # @return {Object} block ### getBlock: (name,clone) -> block = @blocks[name] if clone classname = name[0].toUpperCase()+name[1..]+'Collection' block = new @[classname](block.models) return block ###* # Set a block by name and value # @method setBlock # @param {String} name # @param {Object} value ### setBlock: (name,value) -> if @blocks[name]? @blocks[name].destroy() if value @blocks[name] = value else delete @blocks[name] else @blocks[name] = value @ ###* # Get all blocks # @method getBlocks # @return {Object} collection of blocks ### getBlocks: -> @blocks ###* # Set all blocks # @method setBlocks # @param {Object} blocks ### setBlocks: (blocks) -> for own name,value of blocks @setBlock(name,value) @ ###* # Apply the passed function to each block # @method eachBlock # @param {Function} fn ### eachBlock: (fn) -> eachr(@blocks, fn) @ ###* # Destructor. Destroy all blocks # @private # @method destroyBlocks ### destroyBlocks: -> if @blocks for own name,block of @blocks block.destroy() @blocks[name] = null @ ###* # The DocPad collections # @private # @property {Object} collections ### collections: null ###* # Get a collection by collection name or key. # This is often accessed within the docpad.coffee # file or a layout/page via @getCollection. # Because getCollection returns a docpad collection, # a call to this method is often chained with a # QueryEngine style query. # # @getCollection('documents').findAllLive({relativeOutDirPath: 'posts'},[{date:-1}]) # # @method getCollection # @param {String} value # @return {Object} collection ### getCollection: (value) -> if value if typeof value is 'string' if value is 'database' return @getDatabase() else for collection in @collections if value in [collection.options.name, collection.options.key] return collection else for collection in @collections if value is collection return collection return null ###* # Destroy a collection by collection name or key # @method destroyCollection # @param {String} value # @return {Object} description ### destroyCollection: (value) -> if value if typeof value is 'string' and value isnt 'database' @collections = @collections.filter (collection) -> if value in [collection.options.name, collection.options.key] collection?.destroy() return false else return true else if value isnt @getDatabase() @collections = @collections.filter (collection) -> if value is collection collection?.destroy() return false else return true return null ###* # Add a collection # @method addCollection # @param {Object} collection ### addCollection: (collection) -> if collection and collection not in [@getDatabase(), @getCollection(collection)] @collections.push(collection) @ ###* # Set a name for a collection. # A collection can have multiple names # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # creates a live collection and passes this to setCollection with # the name 'partials'. # # # Add our partials collection # docpad.setCollection('partials', database.createLiveChildCollection() # .setQuery('isPartial', { # $or: # isPartial: true # fullPath: $startsWith: config.partialsPath # }) # .on('add', (model) -> # docpad.log('debug', util.format(locale.addingPartial, model.getFilePath())) # model.setDefaults( # isPartial: true # render: false # write: false # ) # ) # ) # # # @method setCollection # @param {String} name the name to give to the collection # @param {Object} collection a DocPad collection ### setCollection: (name, collection) -> if collection if name collection.options.name = name if @getCollection(name) isnt collection @destroyCollection(name) @addCollection(collection) else @destroyCollection(name) ###* # Get the DocPad project's collections # @method getCollections # @return {Object} the collections ### getCollections: -> return @collections ###* # Set the DocPad project's collections # @method setCollections ### setCollections: (collections) -> if Array.isArray(collections) for value in collections @addCollection(value) else for own name,value of collections @setCollection(name, value) @ ###* # Apply the passed function to each collection # @method eachCollection # @param {Function} fn ### eachCollection: (fn) -> fn(@getDatabase(), 'database') for collection,index in @collections fn(collection, collection.options.name or collection.options.key or index) @ ###* # Destructor. Destroy the DocPad project's collections. # @private # @method destroyCollections ### destroyCollections: -> if @collections for collection in @collections collection.destroy() @collections = [] @ # --------------------------------- # Collection Helpers ###* # Get all the files in the DocPad database (will use live collections) # @method getFiles # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} collection ### getFiles: (query,sorting,paging) -> key = <KEY>.<KEY>query, sorting, paging}) collection = @getCollection(key) unless collection collection = @getDatabase().findAllLive(query, sorting, paging) collection.options.key = key @addCollection(collection) return collection ###* # Get a single file based on a query # @method getFile # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFile: (query,sorting,paging) -> file = @getDatabase().findOne(query, sorting, paging) return file ###* # Get files at a path # @method getFilesAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} files ### getFilesAtPath: (path,sorting,paging) -> query = $or: [{relativePath: $startsWith: path}, {fullPath: $startsWith: path}] files = @getFiles(query, sorting, paging) return files ###* # Get a file at a relative or absolute path or url # @method getFileAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFileAtPath: (path,sorting,paging) -> file = @getDatabase().fuzzyFindOne(path, sorting, paging) return file ###* # Get a file by its id # @method getFileById # @param {String} id # @param {Object} [opts={}] # @return {Object} a file ### getFileById: (id,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.get(id) return file ###* # Remove the query string from a url # Pathname convention taken from document.location.pathname # @method getUrlPathname # @param {String} url # @return {String} ### getUrlPathname: (url) -> return url.replace(/\?.*/,'') ###* # Get a file by its selector (this is used to fetch layouts by their name) # @method getFileBySelector # @param {Object} selector # @param {Object} [opts={}] # @return {Object} a file ### getFileBySelector: (selector,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.fuzzyFindOne(selector) return file # --------------------------------- # Plugins ###* # Plugins that are loading really slow # @property {Object} slowPlugins ### slowPlugins: null # {} ###* # Loaded plugins indexed by name # @property {Object} loadedPlugins ### loadedPlugins: null # {} # ----------------------------- # Paths ###* # The DocPad directory # @property {String} corePath ### corePath: pathUtil.resolve(__dirname, '..', '..') ###* # The DocPad library directory # @private # @property {String} libPath ### libPath: __dirname ###* # The main DocPad file # @property {String} mainPath ### mainPath: pathUtil.resolve(__dirname, 'docpad') ###* # The DocPad package.json path # @property {String} packagePath ### packagePath: pathUtil.resolve(__dirname, '..', '..', 'package.json') ###* # The DocPad locale path # @property {String} localePath ### localePath: pathUtil.resolve(__dirname, 'locale') # ----------------------------- # Template Data ###* # Description for initialTemplateData # @private # @property {Object} initialTemplateData ### initialTemplateData: null # {} ###* # Plugin's Extended Template Data # @private # @property {Object} pluginsTemplateData ### pluginsTemplateData: null # {} ###* # Get Complete Template Data # @method getTemplateData # @param {Object} userTemplateData # @return {Object} templateData ### getTemplateData: (userTemplateData) -> # Prepare userTemplateData or= {} docpad = @ locale = @getLocale() # Set the initial docpad template data @initialTemplateData ?= # Site Properties site: {} # Environment getEnvironment: -> return docpad.getEnvironment() # Environments getEnvironments: -> return docpad.getEnvironments() # Set that we reference other files referencesOthers: (flag) -> document = @getDocument() document.referencesOthers() return null # Get the Document getDocument: -> return @documentModel # Get a Path in respect to the current document getPath: (path,parentPath) -> document = @getDocument() path = document.getPath(path, parentPath) return path # Get Files getFiles: (query,sorting,paging) -> @referencesOthers() result = docpad.getFiles(query, sorting, paging) return result # Get another file's URL based on a relative path getFile: (query,sorting,paging) -> @referencesOthers() result = docpad.getFile(query,sorting,paging) return result # Get Files At Path getFilesAtPath: (path,sorting,paging) -> @referencesOthers() path = @getPath(path) result = docpad.getFilesAtPath(path, sorting, paging) return result # Get another file's model based on a relative path getFileAtPath: (relativePath) -> @referencesOthers() path = @getPath(relativePath) result = docpad.getFileAtPath(path) return result # Get a specific file by its id getFileById: (id) -> @referencesOthers() result = docpad.getFileById(id) return result # Get the entire database getDatabase: -> @referencesOthers() return docpad.getDatabase() # Get a pre-defined collection getCollection: (name) -> @referencesOthers() return docpad.getCollection(name) # Get a block getBlock: (name) -> return docpad.getBlock(name,true) # Include another file taking in a relative path include: (subRelativePath,strict=true) -> file = @getFileAtPath(subRelativePath) if file if strict and file.get('rendered') is false if docpad.getConfig().renderPasses is 1 docpad.warn util.format(locale.renderedEarlyViaInclude, subRelativePath) return null return file.getOutContent() else err = new Errlop(util.format(locale.includeFailed, subRelativePath)) throw err # Fetch our result template data templateData = extendr.extend({}, @initialTemplateData, @pluginsTemplateData, @getConfig().templateData, userTemplateData) # Add site data templateData.site.url or= '' templateData.site.date or= new Date() templateData.site.keywords or= [] if typeChecker.isString(templateData.site.keywords) templateData.site.keywords = templateData.site.keywords.split(/,\s*/g) # Return templateData # ----------------------------- # Locales ###* # Determined locale # @private # @property {Object} locale ### locale: null ###* # Get the locale (language code and locale code) # @method getLocale # @return {Object} locale ### getLocale: (key) -> unless @locale? try locales = @getPath('locales').map((locale) -> require(locale)) @locale = extendr.extend(locales...) catch localeError docpad.warn(new Errlop('Failed to load a locale', localeError)) try @locale = require(@getPath('locale')) catch err docpad.fatal(new Errlop('Failed to load any locale', err)) @locale = {} if key return @locale[key] or key else return @locale # ----------------------------- # Environments ###* # Get the DocPad environment, eg: development, # production or static # @method getEnvironment # @return {String} the environment ### getEnvironment: -> return @env ###* # Get the environments # @method getEnvironments # @return {Array} array of environment strings ### getEnvironments: -> return @envs # ----------------------------- # Configuration ###* # Website Package Configuration # @private # @property {Object} websitePackageConfig ### websitePackageConfig: null # {} ###* # Merged Configuration # Merged in the order of: # - initialConfig # - userConfig # - websiteConfig # - instanceConfig # - environmentConfig # Use getConfig to retrieve this value # @private # @property {Object} config ### config: null # {} ###* # Instance Configuration # @private # @property {Object} instanceConfig ### instanceConfig: null # {} ###* # Website Configuration # Merged into the config property # @private # @property {Object} websiteConfig ### websiteConfig: null # {} ###* # User Configuraiton # Merged into the config property # @private # @property {Object} userConfig ### userConfig: null # {} ###* # Initial Configuration. The default docpadConfig # settings that can be overridden in a project's docpad.coffee file. # Merged into the config property # @private # @property {Object} initialConfig ### initialConfig: # ----------------------------- # Plugins # Whether or not we should use the global docpad instance global: false # Configuration to pass to any plugins pluginName: pluginConfiguration plugins: {} # ----------------------------- # Project Paths # The project directory rootPath: process.cwd() # The project's package.json path packagePath: 'package.json' # The project's configuration paths # Reads only the first one that exists # If you want to read multiple configuration paths, then point it to a coffee|js file that requires # the other paths you want and exports the merged config configPaths: [ 'docpad.js' 'docpad.coffee' 'docpad.json' 'docpad.cson' ] # Plugin directories to load pluginPaths: [] # Paths that we should watch for reload changes in reloadPaths: [] # Paths that we should watch for regeneration changes in regeneratePaths: [] # The DocPad debug log path (docpad-debug.log) debugLogPath: 'docpad-debug.log' # The User's configuration path (.docpad.cson) userConfigPath: '.docpad.cson' # ----------------------------- # Project Options # The project's out directory outPath: 'out' # The project's source directory sourcePaths: [ 'source' 'src' ] # The project's documents directories # relative to the source path documentsPaths: [ 'documents' 'render' ] # The project's files directories # relative to the source path filesPaths: [ 'files' 'static' 'public' ] # The project's layouts directory # relative to the source path layoutsPaths: [ 'layouts' ] # Ignored file patterns during directory parsing ignorePaths: false ignoreHiddenFiles: false ignoreCommonPatterns: true ignoreCustomPatterns: false # Watch options watchOptions: null # ----------------------------- # Logging # Log Level # Which level of logging should we actually output logLevel: 6 # Verbose # Set log level to 7 verbose: false # Debug # Output all log messages to the debugLogPath debug: false # Color # Whether or not our terminal output should have color # `null` will default to what the terminal supports color: docpadUtil.isTTY() # Silent # Will set the following # logLevel = 3 # progress = welcome = false silent: false # Progress # Whether or not we should display the progress in the terminal title bar progress: true # ----------------------------- # Other # Catch our own exceptions (error events on the DocPad instance) # use "error"/truthy to report # use "fatal" to report and exit catchOurExceptions: 'error' # Catch any uncaught exception # use "error" to report # use "fatal"/truthy to report and exit catchUncaughtExceptions: 'fatal' # Whether or not DocPad is allowed to set the exit code on fatal errors # May only work on node v0.11.8 and above setExitCodeOnFatal: true # Whether or not DocPad is allowed to set the exit code on standard errors # May only work on node v0.11.8 and above setExitCodeOnError: true # Whether or not DocPad is allowed to set the exit code when some code has requested to # May only work on node v0.11.8 and above setExitCodeOnRequest: true # The time to wait before cancelling a request requestTimeout: 30*1000 # The time to wait when destroying DocPad destroyDelay: -1 # Whether or not to destroy on exit destroyOnExit: true # Whether or not to destroy on signal interrupt (ctrl+c) destroyOnSignalInterrupt: true # The time to wait after a source file has changed before using it to regenerate regenerateDelay: 100 # The time to wait before outputting the files we are waiting on slowFilesDelay: 20*1000 # The time to wait before outputting the plugins we are waiting on slowPluginsDelay: 20*1000 # Utilise the database cache databaseCache: false # [false, true, 'write'] # Detect Encoding # Should we attempt to auto detect the encoding of our files? # Useful when you are using foreign encoding (e.g. GBK) for your files detectEncoding: false # Render Single Extensions # Whether or not we should render single extensions by default renderSingleExtensions: false # Render Passes # How many times should we render documents that reference other documents? renderPasses: 1 # Powered By DocPad # Whether or not we should include DocPad in the Powered-By meta header # Please leave this enabled as it is a standard practice and promotes DocPad in the web eco-system poweredByDocPad: true # Template Data # What data would you like to expose to your templates templateData: {} # Collections # A hash of functions that create collections collections: {} # Events # A hash of event handlers events: {} # Regenerate Every # Performs a regenerate every x milliseconds, useful for always having the latest data regenerateEvery: false # Regerenate Every Options # The generate options to use on the regenerate every call regenerateEveryOptions: populate: true partial: false # ----------------------------- # Environment Configuration # Locale Code # The code we shall use for our locale (e.g. en, fr, etc) localeCode: null # Environment # Whether or not we are in production or development # Separate environments using a comma or a space env: null # Environments # Environment specific configuration to over-ride the global configuration environments: development: # Only do these if we are running standalone (aka not included in a module) welcome: isUser progress: isUser ###* # Get the DocPad configuration # @method getConfig # @return {Object} the DocPad configuration object ### getConfig: -> return @config or {} # ================================= # Initialization Functions ###* # Create our own custom TaskGroup instance for DocPad. # That will listen to tasks as they execute and provide debugging information. # @method createTaskGroup # @param {Object} opts # @return {TaskGroup} ### createTaskGroup: (opts...) => docpad = @ progress = docpad.progressInstance tasks = TaskGroup.create(opts...) # Listen to executing tasks and output their progress tasks.on 'running', -> config = tasks.getConfig() name = tasks.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > running') # Listen to executing tasks and output their progress tasks.on 'item.add', (item) -> config = tasks.getConfig() name = item.getNames() unless progress docpad.log('debug', name+' > added') # Listen to executing tasks and output their progress item.on 'started', (item) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > started') # Listen to executing tasks and output their progress item.done (err) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > done') # Return return tasks ###* # Constructor method. Sets up the DocPad instance. # next(err) # @method constructor # @param {Object} instanceConfig # @param {Function} next callback # @param {Error} next.err # @param {DocPad} next.docpad ### constructor: (instanceConfig,next) -> # Prepare super() [instanceConfig,next] = extractOptsAndCallback(instanceConfig, next) docpad = @ # Allow DocPad to have unlimited event listeners @setMaxListeners(0) # Binders # Using this over coffescript's => on class methods, ensures that the method length is kept for methodName in "action log warn error fatal inspect notify checkRequest activeHandles onBeforeExit onSignalInterruptOne onSignalInterruptTwo onSignalInterruptThree destroyWatchers".split(/\s+/) @[methodName] = @[methodName].bind(@) # Adjust configPaths if typeChecker.isString(instanceConfig.configPaths) instanceConfig.configPaths = [instanceConfig.configPaths] # Dereference and initialise advanced variables # we deliberately ommit initialTemplateData here, as it is setup in getTemplateData @slowPlugins = {} @loadedPlugins = {} @pluginsTemplateData = {} @collections = [] @blocks = {} @websitePackageConfig = {} @websiteConfig = {} @userConfig = {} @initialConfig = extendr.dereferenceJSON(@initialConfig) @instanceConfig = instanceConfig or {} @config = @mergeConfigs() # Prepare the loggers instanceConfig.logLevel ?= @initialConfig.logLevel color = instanceConfig.color lineLevel = -1 if instanceConfig.silent instanceConfig.logLevel = 3 # 3:error, 2:critical, 1:alert, 0:emergency instanceConfig.progress = instanceConfig.welcome = false if instanceConfig.verbose || instanceConfig.debug instanceConfig.logLevel = 7 lineLevel = 7 # Create the loggers logger = new Logger({lineLevel: lineLevel}) filter = new Filter({filterLevel: instanceConfig.logLevel}) # Apply the loggers @logger = logger # Console logger.pipe(filter).pipe( new Human({ color: color }) ).pipe(process.stdout) # File if instanceConfig.debug logPath = @getPath(false, 'log') safefs.unlink logPath, -> logger .pipe( new Human(color: false) ) .pipe( fsUtil.createWriteStream(logPath) ) # Forward log events to the logger @on 'log', (args...) -> docpad.log.apply(@, args) # Setup configuration event wrappers configEventContext = {docpad} # here to allow the config event context to persist between event calls @getEvents().forEach (eventName) -> # Bind to the event docpad.on eventName, (opts,next) -> eventHandler = docpad.getConfig().events?[eventName] # Fire the config event handler for this event, if it exists if typeChecker.isFunction(eventHandler) args = [opts,next] ambi(unbounded.binder.call(eventHandler, configEventContext), args...) # It doesn't exist, so lets continue else next() # Create our action runner @actionRunnerInstance = @createTaskGroup('action runner', {abortOnError: false, destroyOnceDone: false}).whenDone (err) -> docpad.progressInstance?.update('') docpad.error(err) if err # Setup the database @database = new FilesCollection(null, {name:'database'}) .on('remove', (model,options) -> # Skip if we are not a writeable file return if model.get('write') is false # Ensure we regenerate anything (on the next regeneration) that was using the same outPath outPath = model.get('outPath') if outPath updatedModels = docpad.database.findAll({outPath}) updatedModels.remove(model) if updatedModels.length updatedModels.each (model) -> model.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the removal of a similar one:', updatedModels.pluck('relativePath')) # Return safely return true ) .on('add change:outPath', (model) -> # Skip if we are not a writeable file return if model.get('write') is false # Prepare outPath = model.get('outPath') previousOutPath = model.previous('outPath') # Check if we have changed our outPath if previousOutPath # Ensure we regenerate anything (on the next regeneration) that was using the same outPath previousModels = docpad.database.findAll({outPath: previousOutPath}) previousModels.remove(model) if previousModels.length previousModels.each (previousModel) -> previousModel.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the addition of a similar one:', previousModels.pluck('relativePath')) # Determine if there are any conflicts with the new outPath if outPath existingModels = docpad.database.findAll({outPath}) existingModels.each (existingModel) -> if existingModel.id isnt model.id modelPath = model.get('fullPath') or (model.get('relativePath')+':'+model.id) existingModelPath = existingModel.get('fullPath') or (existingModel.get('relativePath')+':'+existingModel.id) docpad.warn util.format(docpad.getLocale().outPathConflict, outPath, modelPath, existingModelPath) # Return safely return true ) # Continue with load and ready @action 'load ready', {}, (err) -> if next? next(err, docpad) else if err docpad.fatal(err) # Chain @ ###* # Has DocPad commenced destruction? ### destroying: false ###* # Destructor. Destroy the DocPad instance # This is an action, and should be called as such # E.g. docpad.action('destroy', next) # @method destroy # @param {Object} opts # @param {Function} next # @param {Error} next.err ### destroy: (opts, next) -> return @ if @destroying @destroying = true # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() locale = @getLocale() # Log docpad.log('info', locale.destroyDocPad) # Drop all the remaining tasks dropped = @getActionRunner().clearRemaining() docpad.error("DocPad destruction had to drop #{Number(dropped)} action tasks") if dropped # Destroy Timers docpad.destroyTimers() # Wait a configurable oment docpad.timer 'destroy', 'timeout', config.destroyDelay, -> # Destroy Plugins docpad.emitSerial 'docpadDestroy', (eventError) -> # Check if eventError # Note err = new Errlop( "DocPad's destroyEvent event failed", eventError ) docpad.fatal(err) # Callback return next?(err) # Final closures and checks try # Destroy Timers docpad.destroyTimers() # Destroy Plugins docpad.destroyPlugins() # Destroy Watchers docpad.destroyWatchers() # Destroy Blocks docpad.destroyBlocks() # Destroy Collections docpad.destroyCollections() # Destroy Database docpad.destroyDatabase() # Destroy progress docpad.updateProgress(false) # Destroy Logging docpad.destroyLoggers() # Destroy Process Listeners process.removeListener('uncaughtException', docpad.fatal) process.removeListener('uncaughtException', docpad.error) process.removeListener('beforeExit', docpad.onBeforeExit) process.removeListener('SIGINT', docpad.onSignalInterruptOne) process.removeListener('SIGINT', docpad.onSignalInterruptTwo) process.removeListener('SIGINT', docpad.onSignalInterruptThree) # Destroy DocPad Listeners docpad.removeAllListeners() catch finalError # Note err = new Errlop( "DocPad's final destruction efforts failed", finalError ) docpad.fatal(err) return next?(err) # Success docpad.log(locale.destroyedDocPad) # log level omitted, as this will hit console.log return next?() # Chain @ ###* # Emit event, serial # @private # @method emitSerial # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitSerial: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ ###* # Emit event, parallel # @private # @method emitParallel # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitParallel: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ # ================================= # Helpers ###* # Get the ignore options for the DocPad project # @method getIgnoreOpts # @return {Array} string array of ignore options ### getIgnoreOpts: -> return pick(@config, ['ignorePaths', 'ignoreHiddenFiles', 'ignoreCommonPatterns', 'ignoreCustomPatterns']) ###* # Is the supplied path ignored? # @method isIgnoredPath # @param {String} path # @param {Object} [opts={}] # @return {Boolean} ### isIgnoredPath: (path,opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return ignorefs.isIgnoredPath(path, opts) ###* # Scan directory # @method scandir # @param {Object} [opts={}] ### #NB: How does this work? What is returned? #Does it require a callback (next) passed as #one of the options scandir: (opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return scandir(opts) ###* # Watch Directory. Wrapper around the Bevry watchr # module (https://github.com/bevry/watchr). Used # internally by DocPad to watch project documents # and files and then activate the regeneration process # when any of those items are updated. # @private # @method watchdir # @param {String} path - the path to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error # @return {Object} the watcher ### watchdir: (path, listeners, next) -> opts = extendr.extend(@getIgnoreOpts(), @config.watchOptions or {}) stalker = require('watchr').create(path) for own key, value of listeners stalker.on(key, value) stalker.setConfig(opts) stalker.watch(next) return stalker ###* # Watch Directories. Wrapper around watchdir. # @private # @method watchdirs # @param {Array} paths - the paths to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error and watchers/stalkers ### watchdirs: (paths, listeners, next) -> docpad = @ stalkers = [] tasks = new TaskGroup('watching directories').setConfig(concurrency:0).done (err) -> if err for stalker in stalkers stalker.close() next(err) else next(err, stalkers) paths.forEach (path) -> tasks.addTask "watching #{path}", (done) -> # check if the dir exists first as reloadPaths may not apparently safefs.exists path, (exists) -> return done() unless exists stalkers.push docpad.watchdir(path, listeners, done) tasks.run() # Chain @ # ================================= # Setup and Loading ###* # DocPad is ready. Peforms the tasks needed after DocPad construction # and DocPad has loaded. Triggers the docpadReady event. # next(err,docpadInstance) # @private # @method ready # @param {Object} [opts] # @param {Function} next # @param {Error} next.err # @param {Object} next.docpadInstance ### ready: (opts,next) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ config = @getConfig() locale = @getLocale() # Render Single Extensions @DocumentModel::defaults.renderSingleExtensions = config.renderSingleExtensions # Fetch the plugins pluginsList = Object.keys(@loadedPlugins).sort().join(', ') # Welcome Output docpad.log 'info', util.format(locale.welcome, @getVersionString()) docpad.log 'notice', locale.welcomeDonate docpad.log 'info', locale.welcomeContribute docpad.log 'info', util.format(locale.welcomePlugins, pluginsList) docpad.log 'info', util.format(locale.welcomeEnvironment, @getEnvironment()) # Prepare tasks = @createTaskGroup('ready tasks').done (err) -> # Error? return docpad.error(err) if err # All done, forward our DocPad instance onto our creator return next?(null,docpad) # kept here in case plugins use it tasks.addTask 'welcome event', (complete) -> # No welcome return complete() unless config.welcome # Welcome docpad.emitSerial('welcome', {docpad}, complete) tasks.addTask 'emit docpadReady', (complete) -> docpad.emitSerial('docpadReady', {docpad}, complete) # Run tasks tasks.run() # Chain @ ###* # Performs the merging of the passed configuration objects # @private # @method mergeConfigs ### mergeConfigs: (configPackages, destination = {}) -> # A plugin is calling us with its configuration unless configPackages # Apply the environment # websitePackageConfig.env is left out of the detection here as it is usually an object # that is already merged with our process.env by the environment runner # rather than a string which is the docpad convention @env = ( @instanceConfig.env or @websiteConfig.env or @initialConfig.env or process.env.NODE_ENV or 'development' ) @envs = @env.split(/[, ]+/) # Merge the configurations together configPackages = [@initialConfig, @userConfig, @websiteConfig, @instanceConfig] # Figure out merging configsToMerge = [destination] for configPackage in configPackages continue unless configPackage configsToMerge.push(configPackage) for env in @envs envConfig = configPackage.environments?[env] configsToMerge.push(envConfig) if envConfig # Merge return extendr.deep(configsToMerge...) ###* # Legacy version of mergeConmergeConfigsfigurations # @private # @method mergeConfigurations ### mergeConfigurations: (configPackages, [destination]) -> return @mergeConfigs(configPackages, destination) ###* # Set the DocPad configuration object. # Performs a number of tasks, including # merging the pass instanceConfig with DocPad's # other config objects. # next(err,config) # @private # @method setConfig # @param {Object} instanceConfig # @param {Object} next # @param {Error} next.err # @param {Object} next.config ### setConfig: (instanceConfig) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ locale = @getLocale() # Apply the instance configuration, generally we won't have it at this level # as it would have been applied earlier the load step extendr.deepDefaults(@instanceConfig, instanceConfig) if instanceConfig # Merge the configurations together @config = @mergeConfigs() # Update the progress bar configuration @updateProgress() # Handle errors process.removeListener('uncaughtException', @fatal) process.removeListener('uncaughtException', @error) @removeListener('error', @fatal) @removeListener('error', @error) if @config.catchExceptions # legacy @config.catchOurExceptions = @config.catchUncaughtExceptions = 'error' if @config.catchUncaughtExceptions process.setMaxListeners(0) if @config.catchUncaughtExceptions is 'error' process.on('uncaughtException', @error) else process.on('uncaughtException', @fatal) if @config.catchOurExceptions if @config.catchUncaughtExceptions is 'fatal' @on('error', @fatal) else @on('error', @error) # Handle interrupt process.removeListener('beforeExit', @onBeforeExit) process.removeListener('SIGINT', @onSignalInterruptOne) process.removeListener('SIGINT', @onSignalInterruptTwo) process.removeListener('SIGINT', @onSignalInterruptThree) if @config.destroyOnExit process.once('beforeExit', @onBeforeExit) if @config.destroyOnSignalInterrupt process.once('SIGINT', @onSignalInterruptOne) # Chain @ onSignalInterruptOne: -> # Log @log('notice', "Signal Interrupt received, queued DocPad's destruction") # Escalate next time process.once('SIGINT', @onSignalInterruptTwo) # Act @action('destroy') # Chain @ onSignalInterruptTwo: -> # Log @log('alert', 'Signal Interrupt received again, closing stdin and dumping handles') # Escalate next time process.once('SIGINT', @onSignalInterruptThree) # Handle any errors that occur when stdin is closed # https://github.com/docpad/docpad/pull/1049 process.stdin?.once? 'error', (stdinError) -> # ignore ENOTCONN as it means stdin was already closed when we called stdin.end # node v8 and above have stdin.destroy to avoid emitting this error if stdinError.toString().indexOf('ENOTCONN') is -1 err = new Errlop( "closing stdin encountered an error", stdinError ) docpad.fatal(err) # Close stdin # https://github.com/docpad/docpad/issues/1028 # https://github.com/docpad/docpad/pull/1029 process.stdin?.destroy?() or process.stdin?.end?() # Wait a moment before outputting things that are preventing closure setImmediate(@activeHandles) # Chain @ onSignalInterruptThree: -> # Log @log('alert', 'Signal Interrupt received yet again, skipping queue and destroying DocPad right now') # Act @exitCode(130) @destroy() # Chain @ onBeforeExit: -> @action('destroy') activeHandles: -> # Note any requests that are still active activeRequests = process._getActiveRequests?() if activeRequests?.length docpadUtil.writeStderr """ Waiting on these #{activeRequests.length} requests to close: #{@inspect activeRequests} """ # Note any handles that are still active activeHandles = process._getActiveHandles?() if activeHandles?.length docpadUtil.writeStderr """ Waiting on these #{activeHandles.length} handles to close: #{@inspect activeHandles} """ ###* # Load the various configuration files from the # file system. Set the instanceConfig. # next(err,config) # @private # @method load # @param {Object} opts # @param {Function} next # @param {Error} next.err ### load: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare the Load Tasks loadTasks = @createTaskGroup('load tasks').done(next) # User Configuration loadTasks.addTask "load the user's configuration", (complete) => userConfigPath = @getPath('user') return complete() unless userConfigPath docpad.log 'debug', util.format(locale.loadingUserConfig, userConfigPath) @loadConfigPath userConfigPath, (err,data) => return complete(err) if err # Apply if data @userConfig = data docpad.log 'debug', util.format(locale.loadedUserConfig, userConfigPath) return complete() # Complete return complete() # Website Env Configuration loadTasks.addTask "read the .env file if it exists", (complete) => envPath = @getPath('env') return complete() unless envPath docpad.log 'debug', util.format(locale.loadingEnvConfig, envPath) envFile.parseFile envPath, (err,data) -> return complete(err) if err for own key,value of data process.env[key] = value docpad.log 'debug', util.format(locale.loadedEnvConfig, envPath) return complete() # Website Package Configuration loadTasks.addTask "load the website's package data", (complete) => packagePath = @getPath('package') return complete() unless packagePath docpad.log 'debug', util.format(locale.loadingWebsitePackageConfig, packagePath) @loadConfigPath packagePath, (err,data) => return complete(err) if err # Apply if data @websitePackageConfig = data docpad.log 'debug', util.format(locale.loadedWebsitePackageConfig, packagePath) # Complete return complete() # Website Configuration loadTasks.addTask "load the website's configuration", (complete) => configPath = @getPath('config') return complete() unless configPath docpad.log 'debug', util.format(locale.loadingWebsiteConfig, configPath) @loadConfigPath configPath, (err,data) => return complete(err) if err # Apply if data @websiteConfig = data docpad.log 'debug', util.format(locale.loadedWebsiteConfig, configPath) # Complete return complete() loadTasks.addTask "update the configurations", => @setConfig() ### loadTasks.addTask 'lazy dependencies: encoding', (complete) => lazyRequire = require('lazy-require') return complete() unless @config.detectEncoding return lazyRequire 'encoding', {cwd:corePath, stdio:'inherit'}, (err) -> docpad.warn(locale.encodingLoadFailed) if err return complete() ### loadTasks.addTask 'load plugins', (complete) -> docpad.loadPlugins(complete) loadTasks.addTask 'extend collections', (complete) -> docpad.extendCollections(complete) loadTasks.addTask 'fetch plugins templateData', (complete) -> docpad.emitSerial('extendTemplateData', {templateData:docpad.pluginsTemplateData}, complete) # Fire post tasks loadTasks.run() # Chain @ # ================================= # Configuration ###* # Update user configuration with the passed data # @method updateUserConfig # @param {Object} [data={}] # @param {Function} next # @param {Error} next.err ### updateUserConfig: (data={},next) -> # Prepare [data,next] = extractOptsAndCallback(data,next) docpad = @ userConfigPath = @getConfig(false, 'user') # Apply back to our loaded configuration # does not apply to @config as we would have to reparse everything # and that appears to be an imaginary problem extendr.extend(@userConfig, data) if data # Convert to CSON CSON.createCSONString @userConfig, (parseError, userConfigString) -> if parseError err = new Errlop( "Failed to create the CSON string for the user configuration", parseError ) return next(err) # Write it safefs.writeFile userConfigPath, userConfigString, 'utf8', (writeError) -> if writeError err = new Errlop( "Failed to write the CSON string for the user configuration to #{userConfigPath}", writeError ) return next(err) # Forward return next() # Chain @ ###* # Load a configuration url. # @method loadConfigUrl # @param {String} configUrl # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigUrl: (configUrl,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() # Log docpad.log 'debug', util.format(locale.loadingConfigUrl, configUrl) # Read the URL fetch(configUrl, {timeout: config.requestTimeout}) .then((res) -> res.text()) .then((text) -> CSON.parseCSONString(text)) .catch(next) .then((data) -> next(null, data)) # Chain @ ###* # Load the configuration from a file path # passed as one of the options (opts.configPath) or # from DocPad's configPaths # @private # @method loadConfigPath # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigPath: (configPath,next) -> # Prepare docpad = @ locale = @getLocale() # Check return next() unless configPath # Log docpad.log 'debug', util.format(locale.loadingConfigPath, configPath) # Prepare CSON Options csonOptions = cson: true json: true coffeescript: true javascript: true # Read the path using CSON CSON.requireFile configPath, csonOptions, (parseError, data) -> if parseError err = new Errlop( util.format(locale.loadingConfigPathFailed, configPath), parseError ) return next(err) # Check if the data is a function, if so, then execute it as one while typeChecker.isFunction(data) try data = data(docpad) catch executeError err = new Errlop( util.format(locale.executeConfigPathFailed, configPath), executeError ) return next(err) unless typeChecker.isObject(data) err = new Errlop( util.format(locale.invalidConfigPathData, configPath, docpad.inspect(data)) ) return next(err) # Return the data return next(null, data) # Chain @ resolvePath: (args...) -> try path = pathUtil.resolve(args...) return path if safefs.existsSync(path) catch error @log('error', 'failed to resolve the path:', {path, error}) throw error return false getPath: (args...) -> # Use join if first argument is false if typeChecker.isBoolean(args[0]) [check, name, tail...] = args else check = true [name, tail...] = args # Prepare method = if check then @resolvePath else pathUtil.resolve config = @getConfig() # Determine path = switch name when 'locales' then [pathUtil.resolve(@localePath, 'en.js')] ### uniq([ safeps.getLocaleCode config.localeCode safeps.getLocaleCode safeps.getLocaleCode() safeps.getLanguageCode config.localeCode safeps.getLanguageCode safeps.getLocaleCode() 'en' ]).map((code) => @resolvePath(@localePath, code + '.js')) ### when 'locale' then @getPath(check, 'locales')[0] when 'root' then method(check, config.rootPath) when 'log' then method(check, process.cwd(), config.debugLogPath) when 'out' then @getPath(check, 'root', config.outPath) when 'env' then @getPath(check, 'root', '.env') when 'home' then require('os').homedir() # works in node v4 and above when 'dropbox' then @getPath(check, 'home', 'Dropbox') when 'users' then [@getPath(check, 'dropbox', config.userConfigPath), @getPath(check, 'root', config.userConfigPath)].filter(isTruthy) when 'user' then @getPath(check, 'users')[0] or false when 'package' then @getPath(check, 'root', config.packagePath) when 'sources' then config.sourcePaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'source' then @getPath(check, 'sources')[0] or false when 'configs' then config.configPaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'config' then @getPath(check, 'configs')[0] or false when 'documents' then config.documentsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'document' then @getPath(check, 'documents')[0] or false when 'files' then config.filesPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'file' then @getPath(check, 'files')[0] or false when 'layouts' then config.layoutsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'layout' then @getPath(check, 'layouts')[0] or false when 'reloads' then config.reloadPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'regenerates' then config.regeneratePaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) else null try if typeof path is 'string' and tail.length return method(check, path, tail...) else return path catch error @log('error', 'failed to get the path:', {check, name, tail, error}) throw error ###* # Extend collections. Create DocPad's # standard (documents, files # layouts) and special (generate, referencesOthers, # hasLayout, html, stylesheet) collections. Set blocks # @private # @method extendCollections # @param {Function} next # @param {Error} next.err ### extendCollections: (next) -> # Prepare docpad = @ docpadConfig = @getConfig() locale = @getLocale() database = @getDatabase() # Standard Collections @setCollections({ # Standard Collections documents: database.createLiveChildCollection() .setQuery('isDocument', { render: true write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingDocument, model.getFilePath())) ) files: database.createLiveChildCollection() .setQuery('isFile', { render: false write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingFile, model.getFilePath())) ) layouts: database.createLiveChildCollection() .setQuery('isLayout', { $or: isLayout: true fullPath: $startsWith: @getPath('layouts') }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingLayout, model.getFilePath())) model.setDefaults({ isLayout: true render: false write: false }) ) # Special Collections generate: database.createLiveChildCollection() .setQuery('generate', { ignored: false }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingGenerate, model.getFilePath())) ) referencesOthers: database.createLiveChildCollection() .setQuery('referencesOthers', { ignored: false referencesOthers: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingReferencesOthers, model.getFilePath())) ) hasLayout: database.createLiveChildCollection() .setQuery('hasLayout', { ignored: false layout: $exists: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHasLayout, model.getFilePath())) ) html: database.createLiveChildCollection() .setQuery('isHTML', { write: true outExtension: 'html' }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHtml, model.getFilePath())) ) stylesheet: database.createLiveChildCollection() .setQuery('isStylesheet', { write: true outExtension: 'css' }) }) # Blocks @setBlocks({ meta: new MetaCollection() scripts: new ScriptsCollection() styles: new StylesCollection() }) # Custom Collections Group tasks = @createTaskGroup("extendCollections tasks", concurrency:0).done (err) -> docpad.error(err) if err docpad.emitSerial('extendCollections', next) # Cycle through Custom Collections eachr docpadConfig.collections or {}, (fn,name) -> if !name or !typeChecker.isString(name) err = new Errlop("Inside your DocPad configuration you have a custom collection with an invalid name of: #{docpad.inspect name}") docpad.error(err) return if !fn or !typeChecker.isFunction(fn) err = new Errlop("Inside your DocPad configuration you have a custom collection called #{docpad.inspect name} with an invalid method of: #{docpad.inspect fn}") docpad.error(err) return tasks.addTask "creating the custom collection: #{name}", (complete) -> # Init ambi unbounded.binder.call(fn, docpad), database, (err, collection) -> # Check for error if err docpad.error(err) return complete() # Check the type of the collection else unless collection instanceof QueryCollection docpad.warn util.format(locale.errorInvalidCollection, name) return complete() # Make it a live collection collection.live(true) if collection # Apply the collection docpad.setCollection(name, collection) return complete() # Run Custom collections tasks.run() # Chain @ ###* # Reset collections. Perform a complete clean of our collections # @private # @method resetCollections # @param {Object} opts # @param {Function} next # @param {Error} next.err ### resetCollections: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ database = docpad.getDatabase() # Make it as if we have never generated before docpad.generated = false # Perform a complete clean of our collections database.reset([]) meta = @getBlock('meta').reset([]) scripts = @getBlock('scripts').reset([]) styles = @getBlock('styles').reset([]) # ^ Backbone.js v1.1 changes the return values of these, however we change that in our Element class # because if we didn't, all our projects would fail # Add default block entries meta.add("""<meta name="generator" content="DocPad v#{docpad.getVersion()}" />""") if docpad.getConfig().poweredByDocPad isnt false # Chain next() @ ###* # Initialise git repo # @private # @method initGitRepo # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initGitRepo: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') # Forward safeps.initGitRepo(opts, next) # Chain @ ###* # Init node modules # @private # @method initNodeModules # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initNodeModules: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] # Command command = ['npm', 'install'] command.push(opts.args...) # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Fix node package versions # Combat to https://github.com/npm/npm/issues/4587#issuecomment-35370453 # @private # @method fixNodePackageVersions # @param {Object} opts # @param {Function} next # @param {Error} next.err ### fixNodePackageVersions: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.packagePath ?= @getPath('package') # Read and replace safefs.readFile opts.packagePath, (err,buffer) -> data = buffer.toString() data = data.replace(/("docpad(?:.*?)": ")\^/g, '$1~') safefs.writeFile opts.packagePath, data, (err) -> return next(err) # Chain @ ###* # Install node module. Same as running # 'npm install' through the command line # @private # @method installNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### installNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = [] if opts.global opts.save = ['--save'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'install'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) names.forEach (name) -> # Check return unless name # Ensure latest if version isn't specfied name += '@latest' if name.indexOf('@') is -1 # Push the name to the commands command.push(name) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save and opts.save.length command.push('--global') if opts.global # Log docpad.log('info', command.join(' ')) if opts.output # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Uninstall node module. Same as running # 'npm uninstall' through the command line # @private # @method uninstallNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### uninstallNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = ['--save', '--save-dev'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'uninstall'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) command.push(names...) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ # ================================= # Logging ###* # Get the log level # @method getLogLevel # @return {Number} the log level ### getLogLevel: -> return @getConfig().logLevel ###* # Are we debugging? # @method getDebugging # @return {Boolean} ### getDebugging: -> config = @getConfig() return config.logLevel is 7 or config.debug ###* # Check Request # @private # @method checkRequest # @param {Function} next # @param {Error} next.err # @param {Object} next.res ### checkRequest: (next) -> next ?= @error.bind(@) return (err,res) -> # Check return next(err, res) if err # Check if res.body?.success is false or res.body?.error err = new Errlop(res.body.error or 'unknown request error') return next(err, res) # Success return next(null, res) ###* # Send a notify event to plugins (like growl) # @method notify # @param {String} message # @param {Object} [opts={}] ### notify: (message,opts={}) -> # Prepare docpad = @ # Emit docpad.emitSerial 'notify', {message,opts}, (err) -> docpad.error(err) if err # Chain @ ###* # Inspect. Converts object to JSON string. Wrapper around nodes util.inspect method. # Can't use the inspect namespace as for some silly reason it destroys everything # @method inspect # @param {Object} obj # @param {Object} opts # @return {String} JSON string of passed object ### inspect: (obj, opts) -> opts ?= {} opts.colors ?= @getConfig().color return util.inspect(obj, opts) ###* # Log arguments to # @property {Object} log # @param {Mixed} args... ### log: (args...) -> # Log logger = @getLogger() if logger?.log? logger.log.apply(logger, args) else # logger doesn't exist, this is probably because it was destroyed # so handle the most basic case ourselves # that case being when the first argument is a log level string # as we don't want to interpret log(new Date().getTime()) as a log level number # @todo # ideally, this logic would be static methods inside caterpillar # as caterpillar methods is already where this logic exist, they just have to be made static logLevels = require('rfc-log-levels') logLevel = logLevels[args[0]] ? 6 if @getLogLevel() >= logLevel console.log(args...) # Chain @ ###* # Create an error and log it # This is called by all sorts of things, including docpad.warn # As such, the err.level is important # @method error # @param {*} value # @return {Error} ### error: (value) -> # Prepare locale = @getLocale() # Ensure it is an error err = Errlop.ensure(value) err.level ?= 'error' err.log ?= true err.logged ?= false err.notify ?= true err.notified ?= false err.report ?= err.level isnt 'warn' # Set the exit code @exitCode(err) # Log the error if err.log isnt false and err.logged isnt true err.logged = true @log( err.logLevel or err.level, err.stack + (err.report and ('\n' + locale.errorSubmission) or '') ) # Notify the error if err.notify isnt false and err.notified isnt true err.notified = true title = locale[err.level + 'Occured'] or locale.errorOccured @notify(err.message, {title}) # Return the result error return err ###* # Log an error of level 'warn' # @method warn # @param {*} value # @return {Error} ### warn: (value) -> err = Errlop.ensure(value) err.level ?= 'warn' # Foward return @error(err) ###* # Handle a fatal error # @private # @method fatal # @param {*} value # @param {Function} [next] # @return {Error} ### fatal: (value, next) -> # Check return @ unless value # Enforce errlop with fatal level err = new Errlop('A fatal error occured within DocPad', value) err.level = 'fatal' err.logLevel = 'critical' # Handle @error(err) # Set the exit code if we are allowed to @exitCode(err) # Destroy DocPad @destroy({}, next) # Return the error return err ###* # Sets the exit code if we are allowed to, and if it hasn't already been set # @method exitCode # @param {number|Error [input] # @return {number} ### exitCode: (input) -> # Determine if necessary unless process.exitCode # Prepare {setExitCodeOnRequest, setExitCodeOnError, setExitCodeOnFatal} = @getConfig() # Number if typeChecker.isNumber(input) code = input level = null # Error else if input instanceof Error code = input.exitCode level = input.level or null error = input # Defaults if !code or isNaN(Number(code)) exitCode = 1 else exitCode = code # Determine desire because = ( (!level and setExitCodeOnRequest and 'requested') or (level is 'fatal' and setExitCodeOnFatal and 'fatal') or (level is 'error' and setExitCodeOnFatal and 'error') ) if because # Fetch before we apply so we can log it shortly originalExitCode = process.exitCode or 'unset' # Apply process.exitCode = exitCode # And log it message = ['Set the exit code from', originalExitCode, 'to', exitCode, 'because of', because] message.push('from:', error.message) if error and error.message @log('note', message...) # Return the application return process.exitCode # ================================= # Models and Collections # --------------------------------- # b/c compat functions ###* # Create file model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'file' modelType. # @method createFile # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} FileModel ### createFile: (attrs={},opts={}) -> opts.modelType = 'file' return @createModel(attrs, opts) ###* # Create document model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'document' modelType. # @method createDocument # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} DocumentModel ### createDocument: (attrs={},opts={}) -> opts.modelType = 'document' return @createModel(attrs, opts) ###* # Parse the files directory and # return a files collection to # the passed callback # @method parseFileDirectory # @param {Object} [opts={}] # @param {Function} next callback # @param {Error} next.err # @param {Object} next.files files collection ### parseFileDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'file' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) ###* # Parse the documents directory and # return a documents collection to # the passed callback. # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # uses this method to load a collection of # files from the partials directory. # # docpad.parseDocumentDirectory({path: config.partialsPath}, next) # # @method parseDocumentDirectory # @param {Object} [opts={}] # @param {String} [opts.modelType='document'] # @param {Object} [opts.collection=docpad.database] # @param {Object} [opts.path] # @param {Function} next # @param {Error} next.err # @param {Object} next.files files collection of documents ### parseDocumentDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'document' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) # --------------------------------- # Standard functions ###* # Attach events to a document model. # @private # @method attachModelEvents # @param {Object} model ### attachModelEvents: (model) -> # Prepare docpad = @ # Only attach events if we haven't already done so if model.attachedDocumentEvents isnt true model.attachedDocumentEvents = true # Attach document events if model.type is 'document' # Clone model.on 'clone', (clonedModel) -> docpad.attachModelEvents(clonedModel) # Render model.on 'render', (args...) -> docpad.emitSerial('render', args...) # Render document model.on 'renderDocument', (args...) -> docpad.emitSerial('renderDocument', args...) # Fetch a layout model.on 'getLayout', (opts,next) -> opts.collection = docpad.getCollection('layouts') layout = docpad.getFileBySelector(opts.selector, opts) next(null, {layout}) # Remove #model.on 'remove', (file) -> # docpad.getDatabase().remove(file) # ^ Commented out as for some reason this stops layouts from working # Error model.on 'error', (args...) -> docpad.emit('error', args...) # Log model.on 'log', (args...) -> # .error and .warn only accept one argument # so only forward to them if args length is 2 if args.length is 2 if args[0] in ['err', 'error'] docpad.error(args[1]) return if args[0] in ['warn', 'warning'] docpad.warn(args[1]) return # otherwise forward to log docpad.log(args...) return # Chain @ ###* # Add supplied model to the DocPad database. If the passed # model definition is a plain object of properties, a new # model will be created prior to adding to the database. # Calls {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # before adding the model to the database. # # # Override the stat's mtime to now # # This is because renames will not update the mtime # fileCurrentStat?.mtime = new Date() # # # Create the file object # file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) # # @method addModel # @param {Object} model either a plain object defining the required properties, in particular # the file path or an actual model object # @param {Object} opts # @return {Object} the model ### addModel: (model, opts) -> model = @createModel(model, opts) @getDatabase().add(model) return model ###* # Add the supplied collection of models to the DocPad database. # Calls {{#crossLink "DocPad/createModels:method"}}{{/crossLink}} # before adding the models to the database. # # databaseData = JSON.parse data.toString() # models = docpad.addModels(databaseData.models) # # @method addModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### addModels: (models, opts) -> models = @createModels(models, opts) @getDatabase().add(models) return models ###* # Create a collection of models from the supplied collection # ensuring that the collection is suitable for adding to the # DocPad database. The method calls {{#crossLink "DocPad/createModel"}}{{/crossLink}} # for each model in the models array. # @private # @method createModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### createModels: (models, opts) -> for model in models @createModel(model, opts) # return the for loop results ###* # Creates either a file or document model. # The model type to be created can be passed # as an opts property, if not, the method will # attempt to determing the model type by checking # if the file is in one of the documents or # layout paths. # # Ensures a duplicate model is not created # and all required attributes are present and # events attached. # # Generally it is not necessary for an application # to manually create a model via creatModel as DocPad # will handle this process when watching a project's # file and document directories. However, it is possible # that a plugin might have a requirement to do so. # # model = @docpad.createModel({fullPath:fullPath}) # model.load() # @docpad.getDatabase().add(model) # # @method createModel # @param {Object} [attrs={}] # @param {String} attrs.fullPath the full path to the file # @param {Object} [opts={}] # @param {String} opts.modelType either 'file' or 'document' # @return {Object} the file or document model ### createModel: (attrs={},opts={}) -> # Check if attrs instanceof FileModel return attrs # Prepare docpad = @ config = @getConfig() database = @getDatabase() fileFullPath = attrs.fullPath or null # Find or create # This functionality use to be inside ensureModel # But that caused duplicates in some instances # So now we will always check if attrs.fullPath result = database.findOne(fullPath: attrs.fullPath) if result return result # ----------------------------- # Try and determine the model type # If the type hasn't been specified try and detemrine it based on the full path if fileFullPath # Check if we have a document or layout unless opts.modelType for dirPath in @getPath('documents').concat(@getPath('layouts')).filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'document' break # Check if we have a file unless opts.modelType for dirPath in @getPath('files').filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'file' break # ----------------------------- # Create the appropriate emodel # Extend the opts with things we need opts = extendr.extend({ detectEncoding: config.detectEncoding rootOutDirPath: @getPath(false, 'out') locale: @getLocale() createTaskGroup: @createTaskGroup # @TODO this a bit dodgy, but works well enough }, opts) if opts.modelType is 'file' # Create a file model model = new FileModel(attrs, opts) else # Create document model model = new DocumentModel(attrs, opts) # ----------------------------- # Finish up # Attach Events @attachModelEvents(model) # Return return model ###* # Parse a directory and return a # files collection # @method parseDirectory # @param {Object} [opts={}] # @param {Object} next # @param {Error} next.err # @param {Object} next.files files collection ### parseDirectory: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() # Extract {path,createFunction} = opts createFunction ?= @createModel files = opts.collection or new FilesCollection() # Check if the directory exists safefs.exists path, (exists) -> # Check unless exists # Log docpad.log 'debug', util.format(locale.renderDirectoryNonexistant, path) # Forward return next() # Log docpad.log 'debug', util.format(locale.renderDirectoryParsing, path) # Tasks tasks = new TaskGroup('parse directory').setConfig(concurrency:0).done (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderDirectoryParsed, path) # Forward return next(null, files) # Files docpad.scandir( # Path path: path # File Action fileAction: (fileFullPath, fileRelativePath, filename, fileStat) -> # Prepare data = fullPath: fileFullPath relativePath: fileRelativePath stat: fileStat # Create file file = createFunction.call(docpad, data, opts) # Create a task to load the file tasks.addTask "load the file #{fileRelativePath}", (complete) -> # Update the file's stat # To ensure changes files are handled correctly in generation file.action 'load', (err) -> # Error? return complete(err) if err # Add the file to the collection files.add(file) # Next complete() # Return return # Next next: (err) -> return next(err) if err tasks.run() ) # Chain @ # ================================= # Plugins ###* # Get a plugin by it's name # @method getPlugin # @param {Object} pluginName # @return {Object} a DocPad plugin ### getPlugin: (pluginName) -> @loadedPlugins[pluginName] ###* # Check if we have any plugins # @method hasPlugins # @return {Boolean} ### hasPlugins: -> return typeChecker.isEmptyPlainObject(@loadedPlugins) is false ###* # Destructor. Destroy plugins # @private # @method destroyPlugins ### destroyPlugins: -> for own name,plugin of @loadedPlugins plugin.destroy() @loadedPlugins[name] = null @ ###* # Load plugins from the file system # next(err) # @private # @method loadPlugins # @param {Function} next # @param {Error} next.err ### loadPlugins: (next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() # Track the slow plugins @slowPlugins = {} @timer 'slowplugins', 'interval', config.slowPluginsDelay, -> docpad.log 'notice', util.format(locale.pluginsSlow, Object.keys(docpad.slowPlugins).join(', ')) # Async tasks = @createTaskGroup("loadPlugins tasks").done (err) -> docpad.timer('slowplugins') docpad.slowPlugins = {} return next(err) # Prepare the plugins to loaded plugins = new Set( Object.keys(docpad.websitePackageConfig.dependencies or {}).concat( Object.keys(docpad.websitePackageConfig.devDependencies or {}) ) .filter((name) -> name.startsWith('docpad-plugin-')) .concat(config.pluginPaths or []) .map((name) -> { pluginPath: docpad.getPath(false, 'root', 'node_modules', name) }) ) # Emit the even tasks.addTask 'emit loadPlugins', (complete) -> docpad.emitSerial('loadPlugins', {docpad, plugins}, complete) # Load the plugins tasks.addTaskGroup 'load plugins', {concurrency: 0}, (suite, task) -> plugins.forEach (plugin) -> tasks.addTask "load the plugin at: #{plugin.pluginPath}", (complete) -> docpad.loadPlugin(plugin, complete) # Execute the loading asynchronously tasks.run() # Chain @ ###* # Load a plugin from its full file path # _next(err) # @private # @method loadPlugin # @param {Object} opts # @param {Function} _next # @param {Error} _next.err ### loadPlugin: (opts = {}, _next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() next = (err) -> # Remove from slow plugins delete docpad.slowPlugins[pluginName] if pluginName # Forward _next(err) # Chain return docpad # Default opts opts.keyword ?= 'docpad-plugin' opts.prefix ?= 'docpad-plugin-' opts.BasePlugin ?= BasePlugin opts.log ?= @log # Load and validate the plugin try loader = new PluginLoader(opts) catch unsupportedError docpad.warn(new Errlop( util.format(locale.pluginUnsupported, opts.pluginPath), unsupportedError )) return next() # Prepare pluginName = loader.pluginName enabled = config.plugins[pluginName] isnt false # If we've already been loaded, then exit early as there is no use for us to load again if docpad.loadedPlugins[pluginName]? # However we probably want to reload the configuration as perhaps the user or environment configuration has changed docpad.loadedPlugins[pluginName].setConfig() # Complete return next() # Add to loading stores docpad.slowPlugins[pluginName] = true # Check unless enabled # Skip docpad.log 'info', util.format(locale.pluginDisabled, opts.pluginName) return next() else # Load docpad.log 'debug', util.format(locale.pluginLoading, opts.pluginPath) # Create an instance try # Add to plugin stores docpad.loadedPlugins[pluginName] = loader.create({docpad}) catch failedError err = new Errlop( util.format(locale.pluginFailed, opts.pluginPath), failedError ) return next(err) # Log completion docpad.log 'debug', util.format(locale.pluginLoaded, opts.pluginPath) return next() # ================================= # Utilities # --------------------------------- # Utilities: Files ###* # Contextualize files. # Contextualizing is the process of adding layouts and # awareness of other documents to our document. The # contextualizeBefore and contextualizeAfter events # are emitted here. # @private # @method contextualizeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### contextualizeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.contextualizingFiles, collection.length) # Start contextualizing docpad.emitSerial 'contextualizeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("contextualizeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'contextualizeAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.contextualizedFiles, collection.length) # Forward return next() # Add contextualize tasks collection.forEach (file,index) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') or file.id tasks.addTask "conextualizing: #{filePath}", (complete) -> file.action 'contextualize', (err) -> delete slowFilesObject[file.id] return complete(err) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'contextualizeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Render the DocPad project's files. # The renderCollectionBefore, renderCollectionAfter, # renderBefore, renderAfter events are all emitted here. # @private # @method renderFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### renderFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData,renderPasses} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.renderingFiles, collection.length) # Render File # next(null, outContent, file) renderFile = (file,next) -> # Render if file.get('render') is false or !file.get('relativePath') file.attributes.rtime = new Date() next(null, file.getOutContent(), file) else file.action('render', {templateData}, next) # Return return file # Render Collection renderCollection = (collectionToRender,{renderPass},next) -> # Plugin Event docpad.emitSerial 'renderCollectionBefore', {collection:collectionToRender,renderPass}, (err) -> # Prepare return next(err) if err subTasks = docpad.createTaskGroup("renderFiles: Pass #{renderPass}]: renderCollection: #{collectionToRender.options.name}", concurrency:0).done (err) -> # Prepare return next(err) if err # Plugin Event docpad.emitSerial('renderCollectionAfter', {collection:collectionToRender,renderPass}, next) # Cycle collectionToRender.forEach (file) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') subTasks.addTask "rendering: #{filePath}", (complete) -> renderFile file, (err) -> delete slowFilesObject[file.id] or file.id return complete(err) # Return subTasks.run() return collectionToRender # Plugin Event docpad.emitSerial 'renderBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Async tasks = docpad.createTaskGroup("renderFiles: renderCollection: renderBefore").done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'renderAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderedFiles, collection.length) # Forward return next() # Queue the initial render initialCollection = collection.findAll('referencesOthers':false) subsequentCollection = null tasks.addTask "rendering the initial collection", (complete) -> renderCollection initialCollection, {renderPass:1}, (err) -> return complete(err) if err subsequentCollection = collection.findAll('referencesOthers':true) renderCollection(subsequentCollection, {renderPass:2}, complete) # Queue the subsequent renders if renderPasses > 1 [3..renderPasses].forEach (renderPass) -> tasks.addTask "rendering the subsequent collection index #{renderPass}", (complete) -> renderCollection(subsequentCollection, {renderPass}, complete) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'renderFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Write rendered files to the DocPad out directory. # The writeBefore and writeAfter events are emitted here. # @private # @method writeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### writeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.writingFiles, collection.length) # Plugin Event docpad.emitSerial 'writeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("writeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'writeAfter', {collection}, (err) -> # Check return next(err) if err # docpad.log 'debug', util.format(locale.wroteFiles, collection.length) return next() # Add write tasks collection.forEach (file,index) -> filePath = file.getFilePath() tasks.addTask "writing the file: #{filePath}", (complete) -> # Prepare slowFilesObject[file.id] = file.get('relativePath') # Create sub tasks fileTasks = docpad.createTaskGroup("tasks for file write: #{filePath}", concurrency:0).done (err) -> delete slowFilesObject[file.id] return complete(err) # Write out if file.get('write') isnt false and file.get('outPath') fileTasks.addTask "write out", (complete) -> file.action('write', complete) # Write source if file.get('writeSource') is true and file.get('fullPath') fileTasks.addTask "write source", (complete) -> file.action('writeSource', complete) # Run sub tasks fileTasks.run() # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'writeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ # --------------------------------- # Generate # Generate Helpers ###* # Has DocPad's generation process started? # @private # @property {Boolean} generateStarted ### generateStarted: null ###* # Has DocPad's generation process ended? # @private # @property {Boolean} generateEnded ### generateEnded: null ###* # Is DocPad currently generating? # @private # @property {Boolean} generating ### generating: false ###* # Has DocPad done at least one generation? # True once the first generation has occured. # @private # @property {Object} generated ### generated: false ###* # Set off DocPad's generation process. # The generated, populateCollectionsBefore, populateCollections, populateCollections # generateBefore and generateAfter events are emitted here # @method generate # @param {Object} opts # @param {Function} next # @param {Error} next.err ### generate: (opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = docpad.getConfig() locale = docpad.getLocale() database = docpad.getDatabase() # Check return next() if opts.collection?.length is 0 # Update generating flag lastGenerateStarted = docpad.generateStarted docpad.generateStarted = new Date() docpad.generateEnded = null docpad.generating = true # Grab the template data we will use for rendering opts.templateData = docpad.getTemplateData(opts.templateData or {}) # How many render passes will we require? # Can be over-written by API calls opts.renderPasses or= config.renderPasses # Destroy Regenerate Timer docpad.timer('regenerate') # Check plugin count docpad.log('notice', locale.renderNoPlugins) unless docpad.hasPlugins() # Log docpad.log('info', locale.renderGenerating) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratingNotification} # Tasks tasks = @createTaskGroup("generate tasks").done (err) -> # Update generating flag docpad.generating = false docpad.generateEnded = new Date() # Create Regenerate Timer if config.regenerateEvery docpad.timer 'regenerate', 'timeout', config.regenerateEvery, -> docpad.log('info', locale.renderInterval) docpad.action('generate', config.regenerateEveryOptions) # Error? return next(err) if err # Log success message seconds = (docpad.generateEnded - docpad.generateStarted) / 1000 howMany = "#{opts.collection?.length or 0}/#{database.length}" docpad.log 'info', util.format(locale.renderGenerated, howMany, seconds) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratedNotification} # Generated if opts.initial is true docpad.generated = true return docpad.emitSerial('generated', opts, next) # Safety check if generated is false but initial was false too # https://github.com/bevry/docpad/issues/811 else if docpad.generated is false return next( new Errlop('DocPad is in an invalid state, please report this. Reference 3360') ) else return next() # Extract functions from tasks for simplicity # when dealing with nested tasks/groups addGroup = tasks.addGroup.bind(tasks) addTask = tasks.addTask.bind(tasks) # Setup a clean database addTask 'Reset our collections', (complete) -> # Skip if we are not a reset generation, or an initial generation (generated is false) return complete() unless opts.reset is true or docpad.generated is false return docpad.resetCollections(opts, complete) # Figure out the options # This is here as resetCollections could change our state # https://github.com/bevry/docpad/issues/811 addTask 'Figure out options', -> # Mode: Initial # Shall we do some basic initial checks # Set to the opts.reset value if specified, or whether are the initial generation opts.initial ?= !(docpad.generated) # Mode: Reset # Shall we reset the database # Set to true if we are the initial generation opts.reset ?= opts.initial # Mode: Populate # Shall we fetch in new data? # Set to the opts.reset value if specified, or the opts.initial value opts.populate ?= opts.reset # Mode: Reload # Shall we rescan the file system for changes? # Set to the opts.reset value if specified, or the opts.initial value opts.reload ?= opts.reset # Mode: Partial # Shall we perform a partial generation (false) or a completion generation (true)? # Set to false if we are the initial generation opts.partial ?= !(opts.reset) # Log our opts docpad.log( 'debug' 'Generate options:' pick(opts, ['initial', 'reset', 'populate', 'reload', 'partial', 'renderPasses']) ) # Check directory structure addTask 'check source directory exists', (complete) -> # Skip if we are not the initial generation return complete() unless opts.initial is true # Continue if we are the initial generation sourcePath = docpad.getPath('source') unless sourcePath err = new Errlop(util.format(locale.renderNonexistant, docpad.getPath(false, 'source'))) return complete(err) # Forward return complete() # Check directory structure addTask 'ensure out directory exists', (complete) -> outPath = docpad.getPath(false, 'out') return safefs.ensurePath(outPath, complete) addGroup 'fetch data to render', (addGroup, addTask) -> # Fetch new data # If we are a populate generation (by default an initial generation) if opts.populate is true # This will pull in new data from plugins addTask 'populateCollectionsBefore', (complete) -> docpad.emitSerial('populateCollectionsBefore', opts, complete) # Rescan the file system # If we are a reload generation (by default an initial generation) # This is useful when the database is out of sync with the source files # For instance, someone shut down docpad, and made some changes, then ran docpad again # See https://github.com/bevry/docpad/issues/705#issuecomment-29243666 for details if opts.reload is true addGroup 'import data from file system', (addGroup, addTask) -> # Documents docpad.getPath('documents').forEach (documentsPath) -> addTask 'import documents', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: documentsPath next: complete }) # Files docpad.getPath('files').forEach (filesPath) -> addTask 'import files', (complete) -> docpad.parseDirectory({ modelType: 'file' collection: database path: filesPath next: complete }) # Layouts docpad.getPath('layouts').forEach (layoutsPath) -> addTask 'import layouts', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: layoutsPath next: complete }) # This will pull in new data from plugins addTask 'populateCollections', (complete) -> docpad.emitSerial('populateCollections', opts, complete) addGroup 'determine files to render', (addGroup, addTask) -> # Perform a complete regeneration if opts.partial is false # Use Entire Collection addTask 'Add all database models to render queue', -> opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').models) # Perform a partial regeneration # If we are not a reset generation (by default any non-initial generation) else # Use Partial Collection addTask 'Add only changed models to render queue', -> changedQuery = $or: # Get changed files mtime: $gte: lastGenerateStarted # Get new files $and: wtime: null write: true opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').findAll(changedQuery).models) addTask 'generateBefore', (complete) -> # If we have nothing to generate if opts.collection.length is 0 # then there is no need to execute further tasks tasks.clear() complete() # Otherwise continue down the task loop else docpad.emitSerial('generateBefore', opts, complete) addTask 'prepare files', (complete) -> # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Add anything that references other documents (e.g. partials, listing, etc) # This could eventually be way better standalones = opts.collection.pluck('standalone') allStandalone = standalones.indexOf(false) is -1 if allStandalone is false opts.collection.add(docpad.getCollection('referencesOthers').models) # Deeply/recursively add the layout children addLayoutChildren = (collection) -> collection.forEach (file) -> if file.get('isLayout') is true # Find layoutChildrenQuery = layoutRelativePath: file.get('relativePath') layoutChildrenCollection = docpad.getCollection('hasLayout').findAll(layoutChildrenQuery) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Layout children to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') write: model.get('write') } for model in layoutChildrenCollection.models ), '\n', layoutChildrenQuery # Recurse addLayoutChildren(layoutChildrenCollection) # Add opts.collection.add(layoutChildrenCollection.models) addLayoutChildren(opts.collection) # Filter out ignored, and no-render no-write files opts.collection.reset opts.collection.reject (file) -> return (file.get('render') is false and file.get('write') is false) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Forward return complete() addGroup 'process file', (addGroup, addTask) -> addTask 'contextualizeFiles', {args:[opts]}, docpad.contextualizeFiles.bind(docpad) addTask 'renderFiles', {args:[opts]}, docpad.renderFiles.bind(docpad) addTask 'writeFiles', {args:[opts]}, docpad.writeFiles.bind(docpad) addTask 'generateAfter', (complete) -> docpad.emitSerial('generateAfter', opts, complete) # Run tasks.run() # Chain @ # --------------------------------- # Render ###* # Load a document # @private # @method loadDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Load # @TODO: don't load if already loaded document.action('load contextualize', opts, next) # Chain @ ###* # Load and render a document # @method loadAndRenderDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadAndRenderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ # Load docpad.loadDocument document, opts, (err) -> return next(err) if err # Render docpad.renderDocument(document, opts, next) # Chain @ ###* # Render a document # @method renderDocument # @param {Object} document # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### renderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Render clone = document.clone().action 'render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render a document at a file path # next(err,result) # @method renderPath # @param {String} path # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderPath: (path,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ fullPath: path }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ ###* # Render the passed content data as a # document. Required option, filename # (opts.filename) # next(err,result) # @method renderData # @param {String} content # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderData: (content,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ filename: opts.filename data: content }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ # Render Text # Doesn't extract meta information, or render layouts # TODO: Why not? Why not just have renderData? ###* # Render the passed text data as a # document. Required option, filename # (opts.filename) # next(err,result) # @private # @method renderText # @param {String} text # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered content # @param {Object} next.document the rendered document model ### renderText: (text,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) opts.actions ?= ['renderExtensions', 'renderDocument'] attributes = extendr.extend({ filename: opts.filename data: text body: text content: text }, opts.attributes or {}) # Handle document = @createDocument(attributes) # Render clone = document.clone().action 'normalize contextualize render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render action # @method render # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### render: (opts,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() [opts,next] = extractOptsAndCallback(opts,next) opts.stdin ?= false # Completion unless opts.output complete = next else complete = (err, result, document) -> # Forward return next(err) if err # Output if opts.output is true process.stdout.write(result) else if opts.output return safefs.writeFile opts.output, result, (err) -> return next(err, result, document) # Forward return next(null, result, document) # Render if opts.stdin docpad.renderStdin(opts, complete) else if opts.document docpad.renderDocument(opts.document, opts, complete) else if opts.data docpad.renderData(opts.data, opts, complete) else if opts.text docpad.renderText(opts.text, opts, complete) else path = opts.path or opts.fullPath or opts.filename or null if path docpad.renderPath(path, opts, complete) else err = new Errlop(locale.renderInvalidOptions) return complete(err) # Chain @ renderStdin: (opts, next) -> # Prepare docpad = @ [opts,next] = extractOptsAndCallback(opts,next) data = '' # Read stdin = process.stdin stdin.resume() stdin.setEncoding('utf8') stdin.on 'data', (_data) -> docpad.timer('render') data += _data.toString() process.stdin.on 'end', -> docpad.timer('render') docpad.renderData(data, opts, next) # Chain @ # --------------------------------- # Watch ###* # Array of file watchers # @private # @property {Array} watchers ### watchers: null ###* # Destructor. Destroy the watchers used # by DocPad # @private # @method destroyWatchers ### destroyWatchers: -> # Prepare docpad = @ # Check if docpad.watchers # Close each of them for watcher in docpad.watchers watcher.close() # Reset the array docpad.watchers = [] # Chain @ ###* # Start up file watchers used by DocPad # @private # @method watch # @param {Object} opts # @param {Function} next # @param {Error} next.err ### watch: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() database = @getDatabase() @watchers ?= [] # Restart our watchers restartWatchers = (next) -> # Close our watchers docpad.destroyWatchers() # Start a group tasks = docpad.createTaskGroup("watch tasks", concurrency:0).done(next) # Watch reload paths reloadPaths = union(docpad.getPath('reloads'), docpad.getPath('configs')) tasks.addTask "watch reload paths", (complete) -> docpad.watchdirs( reloadPaths, { 'log': docpad.log 'error': docpad.error 'change': -> docpad.log 'info', util.format(locale.watchReloadChange, new Date().toLocaleTimeString()) docpad.action 'load', (err) -> return docpad.fatal(err) if err performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the reload paths has failed:\n"+docpad.inspect(reloadPaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch regenerate paths regeneratePaths = docpad.getPath('regenerates') tasks.addTask "watch regenerate paths", (complete) -> docpad.watchdirs( regeneratePaths, { 'log': docpad.log 'error': docpad.error 'change': -> performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the regenerate paths has failed:\n"+docpad.inspect(regeneratePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch the source sourcePaths = docpad.getPath('sources') tasks.addTask "watch the source path", (complete) -> docpad.watchdirs( sourcePaths, { 'log': docpad.log 'error': docpad.error 'change': changeHandler }, (err,_watchers) -> if err docpad.warn("Watching the source paths has failed:\n"+docpad.inspect(sourcePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Run tasks.run() # Chain @ # Timer queueRegeneration = -> docpad.timer('regeneration', 'timeout', config.regenerateDelay, performGenerate) # Generate performGenerate = (opts={}) -> # Q: Should we also pass over the collection? # A: No, doing the mtime query in generate is more robust # Log docpad.log util.format(locale.watchRegenerating, new Date().toLocaleTimeString()) # Afterwards, re-render anything that should always re-render docpad.action 'generate', opts, (err) -> docpad.error(err) if err docpad.log util.format(locale.watchRegenerated, new Date().toLocaleTimeString()) # Change event handler changeHandler = (changeType,filePath,fileCurrentStat,filePreviousStat) -> # Prepare fileEitherStat = (fileCurrentStat or filePreviousStat) # For some reason neither of the stats may exist, this will cause errors as this is an invalid state # as we depend on at least one stat existing, otherwise, what on earth is going on? # Whatever the case, this should be fixed within watchr, not docpad # as watchr should not be giving us invalid data # https://github.com/bevry/docpad/issues/792 unless fileEitherStat err = new Errlop(""" DocPad has encountered an invalid state while detecting changes for your files. So the DocPad team can fix this right away, please provide any information you can to: https://github.com/bevry/docpad/issues/792 """) return docpad.error(err) # Log the change docpad.log 'info', util.format(locale.watchChange, new Date().toLocaleTimeString()), changeType, filePath # Check if we are a file we don't care about # This check should not be needed with v2.3.3 of watchr # however we've still got it here as it may still be an issue isIgnored = docpad.isIgnoredPath(filePath) if isIgnored docpad.log 'debug', util.format(locale.watchIgnoredChange, new Date().toLocaleTimeString()), filePath return # Don't care if we are a directory isDirectory = fileEitherStat.isDirectory() if isDirectory docpad.log 'debug', util.format(locale.watchDirectoryChange, new Date().toLocaleTimeString()), filePath return # Override the stat's mtime to now # This is because renames will not update the mtime fileCurrentStat?.mtime = new Date() # Create the file object file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) file.setStat(fileCurrentStat) if changeType is 'update' # File was deleted, delete the rendered file, and remove it from the database if changeType is 'delete' database.remove(file) file.action 'delete', (err) -> return docpad.error(err) if err queueRegeneration() # File is new or was changed, update it's mtime by setting the stat else if changeType in ['create', 'update'] file.action 'load', (err) -> return docpad.error(err) if err queueRegeneration() # Watch docpad.log(locale.watchStart) restartWatchers (err) -> return next(err) if err docpad.log(locale.watchStarted) return next() # Chain @ # --------------------------------- # Run Action ###* # Run an action # @method run # @param {Object} opts # @param {Function} next # @param {Error} next.err ### run: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare run = (next) -> docpad.emitSerial 'runBefore', (err) -> return next(err) if err balUtil.flow( object: docpad action: 'generate watch' args: [opts] next: (err) -> docpad.emitSerial('runAfter', next) ) # Check if have the correct structure, if so let's proceed with DocPad sourcePath = @getPath('source') return run(next) if sourcePath # We don't have the correct structure # Check if we are running on an empty directory rootPath = @getPath('root') safefs.readdir rootPath, (err,files) -> return next(err) if err # Check if our directory is empty if files.length # It isn't empty, display a warning docpad.warn util.format(locale.invalidProject, rootPath) return next() else docpad.init opts, (err) -> # Check return next(err) if err # Keep in global? return run(next) if opts.global is true or docpad.getConfig().global is true # Log docpad.log('notice', locale.startLocal) # Destroy our DocPad instance so we can boot the local one docpad.destroy (err) -> # Check return next(err) if err # Forward onto the local DocPad Instance now that it has been installed return docpadUtil.startLocalDocPadExecutable(next) # Chain @ ###* # Info action # @private # @method info # @param {Object} opts # @param {Function} next ### info: (opts, next) -> [opts,next] = extractOptsAndCallback(opts,next) console.log @inspect @getConfig() next?() @ # --------------------------------- # Project ###* # Initialize the project install process. # @private # @method initInstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### initInstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Exists? packagePath = @getPath(false, 'package') safefs.exists packagePath, (exists) -> # Check return next() if exists # Write data = JSON.stringify({ name: 'no-skeleton.docpad' version: '0.1.0' description: 'New DocPad project without using a skeleton' dependencies: docpad: '~'+docpad.getVersion() scripts: start: 'docpad run' test: 'docpad generate' }, null, ' ') safefs.writeFile(packagePath, data, next) # Chain @ ###* # Uninstall a plugin. # @private # @method uninstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### uninstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("uninstall tasks").done(next) # Uninstall a plugin if opts.plugin tasks.addTask "uninstall the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin docpad.uninstallNodeModule(plugins, complete) # Re-load configuration tasks.addTask "re-load configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Install a plugin # @private # @method install # @param {Object} opts # @param {Function} next # @param {Error} next.err ### install: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("install tasks").done(next) tasks.addTask "init the installation", (complete) -> docpad.initInstall(opts, complete) # Install a plugin if opts.plugin tasks.addTask "install the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin += '@'+docpad.pluginVersion if plugin.indexOf('@') is -1 plugin docpad.installNodeModule(plugins, complete) tasks.addTask "re-initialize the website's modules", (complete) -> docpad.initNodeModules(complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-load the configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Update global NPM and DocPad # @private # @method upgrade # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### upgrade: (opts,next) -> # Update Global NPM and DocPad @installNodeModule('npm docpad@6', {global: true}, next) # Chain @ ###* # Update the local DocPad and plugin dependencies # @private # @method update # @param {Object} opts # @param {Object} next # @param {Error} next.err ### update: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("update tasks").done(next) tasks.addTask "init the install", (complete) -> docpad.initInstall(opts, complete) # Update the local docpad and plugin dependencies # Grouped together to avoid npm dependency shortcuts that can cause missing dependencies # But don't update git/http/https dependencies, those are special for some reason # > https://github.com/bevry/docpad/pull/701 dependencies = [] eachr docpad.websitePackageConfig.dependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false or /// :// ///.test(version) is true dependencies.push(name+'@'+docpad.pluginVersion) if dependencies.length isnt 0 tasks.addTask "update plugins that are dependencies", (complete) -> docpad.installNodeModule('docpad@6 '+dependencies, complete) # Update the plugin dev dependencies devDependencies = [] eachr docpad.websitePackageConfig.devDependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false devDependencies.push(name+'@'+docpad.pluginVersion) if devDependencies.length isnt 0 tasks.addTask "update plugins that are dev dependencies", (complete) -> docpad.installNodeModule(devDependencies, {save: '--save-dev'}, complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-initialize the rest of the website's modules", (complete) -> docpad.initNodeModules(complete) # Run tasks.run() # Chain @ ###* # DocPad cleanup tasks. # @private # @method clean # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### clean: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() paths = [] # Log docpad.log('info', locale.cleanStarted) # Tasks tasks = @createTaskGroup("clean tasks", concurrency:0).done (err) -> # Error? return next(err) if err # Log message = util.format( locale.cleanFinish, paths.length ) if paths.length message += ': ' if paths.length isnt 1 message += '\n' message += paths.join('\n') docpad.log('info', message) # Forward return next() tasks.addTask 'reset the collections', (complete) -> docpad.resetCollections(opts, complete) # Delete out path # but only if our outPath is not a parent of our rootPath tasks.addTask 'delete out path', (complete) -> rootPath = docpad.getPath('root') outPath = docpad.getPath('out') # Only remove outpath if it does not contain our root path if outPath and pathUtil.relative(outPath, rootPath).startsWith('..') paths.push(outPath) rimraf(outPath, complete) else complete() # Run tasks tasks.run() # Chain @ ###* # Initialize the directory for DocPad # @private # @method init # @param {Function} next # @param {Error} next.err ### init: (opts,next) -> # Prepare docpad = @ config = @getConfig() rootPath = @getPath(false, 'root') # Tasks tasks = @createTaskGroup("init tasks").done(next) tasks.addTask "ensure the path we are writing to exists", (complete) -> safefs.ensurePath(rootPath, complete) tasks.addTask "ensure src path exists", (complete) -> safefs.ensurePath(docpad.getPath(false, 'source'), complete) tasks.addGroup "initialize the website directory files", -> @setConfig(concurrency:0) # README @addTask "README.md", (complete) -> readmePath = docpad.getPath(false, 'root', 'README.md') data = """ # Your [DocPad](https://docpad.bevry.me) Project ## License Copyright &copy; #{(new Date()).getFullYear()}+ All rights reserved. """ safefs.writeFile(readmePath, data, complete) # Config @addTask "docpad.coffee configuration file", (complete) -> configPath = docpad.getPath(false, 'root', 'docpad.js') data = """ // DocPad Configuration File // https://docpad.bevry.me/config // Define the DocPad Configuration const docpadConfig = { // ... } // Export the DocPad Configuration module.exports = docpadConfig """ safefs.writeFile(configPath, data, complete) # Documents @addTask "documents directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'document'), complete) # Layouts @addTask "layouts directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'layout'), complete) # Files @addTask "files directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'file'), complete) # Run tasks.run() # Chain @ # --------------------------------- # Export module.exports = DocPad
true
##* # The central module for DocPad # @module DocPad ## # ===================================== # Requires # Standard util = require('util') pathUtil = require('path') # External { Logger, Human, Filter } = require('caterpillar') fsUtil = require('fs') Errlop = require('errlop').default queryEngine = require('query-engine') {uniq, union, pick} = require('underscore') CSON = require('cson') balUtil = require('bal-util') scandir = require('scandirectory') extendr = require('extendr') eachr = require('eachr') typeChecker = require('typechecker') ambi = require('ambi') unbounded = require('unbounded') {TaskGroup} = require('taskgroup') safefs = require('safefs') safeps = require('safeps') ignorefs = require('ignorefs') rimraf = require('rimraf') Progress = require('progress-title') fetch = require('node-fetch') extractOptsAndCallback = require('extract-opts') {EventEmitterGrouped} = require('event-emitter-grouped') envFile = require('envfile') ansiStyles = require('ansistyles') # Base {Events,Model,Collection,QueryCollection} = require('./base') # Utils docpadUtil = require('./util') # Models FileModel = require('./models/file') DocumentModel = require('./models/document') # Collections FilesCollection = require('./collections/files') ElementsCollection = require('./collections/elements') MetaCollection = require('./collections/meta') ScriptsCollection = require('./collections/scripts') StylesCollection = require('./collections/styles') # Plugins PluginLoader = require('@bevry/pluginloader').default BasePlugin = require('docpad-baseplugin') # --------------------------------- # Variables isUser = docpadUtil.isUser() isTruthy = (i) -> Boolean(i) ###* # Contains methods for managing the DocPad application. # Extends https://github.com/bevry/event-emitter-grouped # # You can use it like so: # # new DocPad(docpadConfig, function(err, docpad) { # if (err) return docpad.fatal(err) # return docpad.action(action, function(err) { # if (err) return docpad.fatal(err) # return console.log('OK') # }) # }) # # @class Docpad # @constructor # @extends EventEmitterGrouped ### class DocPad extends EventEmitterGrouped # Libraries # Here for legacy API reasons #@DocPad: DocPad #@Backbone: require('backbone') #@queryEngine: queryEngine # Allow for `DocPad.create()` as an alias for `new DocPad()` @create: (args...) -> return new @(args...) # Require a local DocPad file # Before v6.73.0 this allowed requiring of files inside src/lib, as well as files inside src # After v6.73.0 it only allows requiring of files inside src/lib as that makes more sense # After v6.80.9 it only allows requiring specific aliases @require: (name) -> if name is 'testers' console.log( '''' docpad.require('testers') is deprecated, replacement instructions at: https://github.com/docpad/docpad-plugintester ''' ) return require('docpad-plugintester') else throw new Errlop("docpad.require is limited to requiring: testers") # ================================= # Variables # --------------------------------- # Modules # --------------------------------- # Base ###* # Events class # @property {Object} Events ### Events: Events ###* # Model class # Extension of the Backbone Model class # http://backbonejs.org/#Model # @property {Object} Model ### Model: Model ###* # Collection class # Extension of the Backbone Collection class # http://backbonejs.org/#Collection # @property {Object} Collection ### Collection: Collection ###* # QueryCollection class # Extension of the Query Engine QueryCollection class # @property {Object} QueryCollection ### QueryCollection: QueryCollection # --------------------------------- # Models ###* # File Model class # Extension of the Model class # @property {Object} FileModel ### FileModel: FileModel ###* # Document Model class # Extension of the File Model class # @property {Object} DocumentModel ### DocumentModel: DocumentModel # --------------------------------- # Collections ###* # Collection of files in a DocPad project # Extension of the QueryCollection class # @property {Object} FilesCollection ### FilesCollection: FilesCollection ###* # Collection of elements in a DocPad project # Extension of the Collection class # @property {Object} ElementsCollection ### ElementsCollection: ElementsCollection ###* # Collection of metadata in a DocPad project # Extension of the ElementsCollection class # @property {Object} MetaCollection ### MetaCollection: MetaCollection ###* # Collection of JS script files in a DocPad project # Extension of the ElementsCollection class # @property {Object} ScriptsCollection ### ScriptsCollection: ScriptsCollection ###* # Collection of CSS style files in a DocPad project # Extension of the ElementsCollection class # @property {Object} StylesCollection ### StylesCollection: StylesCollection # --------------------------------- # DocPad ###* # DocPad's version number # @private # @property {Number} version ### version: null ###* # Get the DocPad version number # @method getVersion # @return {Number} ### getVersion: -> @version ?= require(@packagePath).version return @version ###* # Get the DocPad version string # @method getVersionString # @return {String} ### getVersionString: -> if docpadUtil.isLocalDocPadExecutable() return util.format(@getLocale().versionLocal, @getVersion(), @corePath) else return util.format(@getLocale().versionGlobal, @getVersion(), @corePath) ###* # The plugin version requirements # @property {String} pluginVersion ### pluginVersion: '2' # Process getters ###* # Get the process platform # @method getProcessPlatform # @return {Object} ### getProcessPlatform: -> process.platform ###* # Get the process version string # @method getProcessVersion # @return {String} ### getProcessVersion: -> process.version.replace(/^v/,'') ###* # Internal property. The caterpillar logger instance bound to DocPad # @private # @property {Object} loggerInstances ### logger: null ###* # Get the caterpillar logger instance bound to DocPad # @method getLogger # @return {Object} caterpillar logger ### getLogger: -> @logger ###* # Destructor. Destroy the caterpillar logger instances bound to DocPad # @private # @method {Object} destroyLoggers ### destroyLoggers: -> # @logger.end() @logger = null @ ###* # All the timers that exist within DocPad # Used for closing them at shutdown # @private # @property {Object} timers ### timers: null ###* # Create a timer and add it to the known timers # @method timer # @param {string} type - either timeout or interval # @param {number} time - the time to apply to the timer # @param {method} method - the method to use for the timer ### timer: (id, type, time, method) -> @timers ?= {} # Create a new timer if type? @timer(id) # clear if type is 'timeout' if time is -1 timer = setImmediate(method) else timer = setTimeout(method, time) else if type is 'interval' timer = setInterval(method, time) else throw new Errlop('unexpected type on new timer') @timers[id] = {id, type, time, method, timer} # Destroy an old timer else if @timers[id] if @timers[id].type is 'interval' clearInterval(@timers[id].timer) else if @timers[id].type is 'timeout' if @timers[id].time is -1 clearImmediate?(@timers[id].timer) else clearTimeout(@timers[id].timer) else throw new Errlop('unexpected type on stored timer') @timers[id] = null @ ###* # Destructor. Destroy all the timers we have kept. # @private # @method {Object} destroyTimers ### destroyTimers: (timer) -> @timers ?= {} for own key, value of @timers @timer(key) @ ###* # Instance of progress-title # @private # @property {Progress} progressInstance ### progressInstance: null ###* # Update the configuration of the progress instance, to either enable it or disable it # Progress will be enabled if DocPad config 'progress' is true # @private # @method updateProgress # @param {boolean} [enabled] manually enable or disable the progress bar ### updateProgress: (enabled) -> # Prepare docpad = @ config = docpad.getConfig() debug = @getDebugging() # Enabled enabled ?= config.progress # If we are in debug mode, then output more detailed title messages options = {} if debug options.verbose = true options.interval = 0 # options.log = true # If we wish to have it enabled if enabled if @progressInstance @progressInstance.pause().configure(options).resume() else @progressInstance = Progress.create(options).start() else if @progressInstance @progressInstance.stop().configure(options) # Return return this ###* # The action runner instance bound to docpad # @private # @property {Object} actionRunnerInstance ### actionRunnerInstance: null ###* # Get the action runner instance bound to docpad # @method getActionRunner # @return {Object} the action runner instance ### getActionRunner: -> @actionRunnerInstance ###* # Apply the passed DocPad action arguments # @method {Object} action # @param {Object} args # @return {Object} ### action: (action, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) locale = @getLocale() # Log @progressInstance?.resume() @log 'debug', util.format(locale.actionStart, action) # Act docpadUtil.action.call @, action, opts, (args...) => # Prepare err = args[0] # Log @progressInstance?.stop() if err @error(new Errlop( util.format(locale.actionFailure, action), err )) else @log 'debug', util.format(locale.actionSuccess, action) # Act return next?(args...) # Chain @ ###* # Event Listing. String array of event names. # Whenever an event is created, it must be applied here to be available to plugins and configuration files # Events must be sorted by the order of execution, not for a functional need, but for a documentation need # Whenever this array changes, also update: https://docpad.bevry.me/events # @private # @property {Array} string array of event names ### events: [ 'loadPlugins' # fired each load 'extendCollections' # fired each load 'extendTemplateData' # fired each load 'docpadReady' # fired only once 'docpadDestroy' # fired once on shutdown 'consoleSetup' # fired once 'runBefore' 'runAfter' 'generateBefore' 'populateCollectionsBefore' 'populateCollections' 'contextualizeBefore' 'contextualizeAfter' 'renderBefore' 'renderCollectionBefore' 'render' # fired for each extension conversion 'renderDocument' # fired for each document render, including layouts and render passes 'renderCollectionAfter' 'renderAfter' 'writeBefore' 'writeAfter' 'generateAfter' 'generated' 'notify' ] ###* # Get the list of available events # @method getEvents # @return {Object} string array of event names ### getEvents: -> @events # --------------------------------- # Collections # Database collection ###* # QueryEngine collection # @private # @property {Object} database ### database: null ###* # Description for getDatabase # @method {Object} getDatabase ### getDatabase: -> @database ###* # Destructor. Destroy the DocPad database # @private # @method destroyDatabase ### destroyDatabase: -> if @database? @database.destroy() @database = null @ ###* # Blocks # @private # @property {Object} blocks ### blocks: null ### { # A collection of meta elements meta: null # Elements Collection # A collection of script elements scripts: null # Scripts Collection # Collection of style elements styles: null # Styles Collection } ### ###* # Get a block by block name. Optionally clone block. # @method getBlock # @param {String} name # @param {Object} [clone] # @return {Object} block ### getBlock: (name,clone) -> block = @blocks[name] if clone classname = name[0].toUpperCase()+name[1..]+'Collection' block = new @[classname](block.models) return block ###* # Set a block by name and value # @method setBlock # @param {String} name # @param {Object} value ### setBlock: (name,value) -> if @blocks[name]? @blocks[name].destroy() if value @blocks[name] = value else delete @blocks[name] else @blocks[name] = value @ ###* # Get all blocks # @method getBlocks # @return {Object} collection of blocks ### getBlocks: -> @blocks ###* # Set all blocks # @method setBlocks # @param {Object} blocks ### setBlocks: (blocks) -> for own name,value of blocks @setBlock(name,value) @ ###* # Apply the passed function to each block # @method eachBlock # @param {Function} fn ### eachBlock: (fn) -> eachr(@blocks, fn) @ ###* # Destructor. Destroy all blocks # @private # @method destroyBlocks ### destroyBlocks: -> if @blocks for own name,block of @blocks block.destroy() @blocks[name] = null @ ###* # The DocPad collections # @private # @property {Object} collections ### collections: null ###* # Get a collection by collection name or key. # This is often accessed within the docpad.coffee # file or a layout/page via @getCollection. # Because getCollection returns a docpad collection, # a call to this method is often chained with a # QueryEngine style query. # # @getCollection('documents').findAllLive({relativeOutDirPath: 'posts'},[{date:-1}]) # # @method getCollection # @param {String} value # @return {Object} collection ### getCollection: (value) -> if value if typeof value is 'string' if value is 'database' return @getDatabase() else for collection in @collections if value in [collection.options.name, collection.options.key] return collection else for collection in @collections if value is collection return collection return null ###* # Destroy a collection by collection name or key # @method destroyCollection # @param {String} value # @return {Object} description ### destroyCollection: (value) -> if value if typeof value is 'string' and value isnt 'database' @collections = @collections.filter (collection) -> if value in [collection.options.name, collection.options.key] collection?.destroy() return false else return true else if value isnt @getDatabase() @collections = @collections.filter (collection) -> if value is collection collection?.destroy() return false else return true return null ###* # Add a collection # @method addCollection # @param {Object} collection ### addCollection: (collection) -> if collection and collection not in [@getDatabase(), @getCollection(collection)] @collections.push(collection) @ ###* # Set a name for a collection. # A collection can have multiple names # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # creates a live collection and passes this to setCollection with # the name 'partials'. # # # Add our partials collection # docpad.setCollection('partials', database.createLiveChildCollection() # .setQuery('isPartial', { # $or: # isPartial: true # fullPath: $startsWith: config.partialsPath # }) # .on('add', (model) -> # docpad.log('debug', util.format(locale.addingPartial, model.getFilePath())) # model.setDefaults( # isPartial: true # render: false # write: false # ) # ) # ) # # # @method setCollection # @param {String} name the name to give to the collection # @param {Object} collection a DocPad collection ### setCollection: (name, collection) -> if collection if name collection.options.name = name if @getCollection(name) isnt collection @destroyCollection(name) @addCollection(collection) else @destroyCollection(name) ###* # Get the DocPad project's collections # @method getCollections # @return {Object} the collections ### getCollections: -> return @collections ###* # Set the DocPad project's collections # @method setCollections ### setCollections: (collections) -> if Array.isArray(collections) for value in collections @addCollection(value) else for own name,value of collections @setCollection(name, value) @ ###* # Apply the passed function to each collection # @method eachCollection # @param {Function} fn ### eachCollection: (fn) -> fn(@getDatabase(), 'database') for collection,index in @collections fn(collection, collection.options.name or collection.options.key or index) @ ###* # Destructor. Destroy the DocPad project's collections. # @private # @method destroyCollections ### destroyCollections: -> if @collections for collection in @collections collection.destroy() @collections = [] @ # --------------------------------- # Collection Helpers ###* # Get all the files in the DocPad database (will use live collections) # @method getFiles # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} collection ### getFiles: (query,sorting,paging) -> key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PIquery, sorting, paging}) collection = @getCollection(key) unless collection collection = @getDatabase().findAllLive(query, sorting, paging) collection.options.key = key @addCollection(collection) return collection ###* # Get a single file based on a query # @method getFile # @param {Object} query # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFile: (query,sorting,paging) -> file = @getDatabase().findOne(query, sorting, paging) return file ###* # Get files at a path # @method getFilesAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} files ### getFilesAtPath: (path,sorting,paging) -> query = $or: [{relativePath: $startsWith: path}, {fullPath: $startsWith: path}] files = @getFiles(query, sorting, paging) return files ###* # Get a file at a relative or absolute path or url # @method getFileAtPath # @param {String} path # @param {Object} sorting # @param {Object} paging # @return {Object} a file ### getFileAtPath: (path,sorting,paging) -> file = @getDatabase().fuzzyFindOne(path, sorting, paging) return file ###* # Get a file by its id # @method getFileById # @param {String} id # @param {Object} [opts={}] # @return {Object} a file ### getFileById: (id,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.get(id) return file ###* # Remove the query string from a url # Pathname convention taken from document.location.pathname # @method getUrlPathname # @param {String} url # @return {String} ### getUrlPathname: (url) -> return url.replace(/\?.*/,'') ###* # Get a file by its selector (this is used to fetch layouts by their name) # @method getFileBySelector # @param {Object} selector # @param {Object} [opts={}] # @return {Object} a file ### getFileBySelector: (selector,opts={}) -> opts.collection ?= @getDatabase() file = opts.collection.fuzzyFindOne(selector) return file # --------------------------------- # Plugins ###* # Plugins that are loading really slow # @property {Object} slowPlugins ### slowPlugins: null # {} ###* # Loaded plugins indexed by name # @property {Object} loadedPlugins ### loadedPlugins: null # {} # ----------------------------- # Paths ###* # The DocPad directory # @property {String} corePath ### corePath: pathUtil.resolve(__dirname, '..', '..') ###* # The DocPad library directory # @private # @property {String} libPath ### libPath: __dirname ###* # The main DocPad file # @property {String} mainPath ### mainPath: pathUtil.resolve(__dirname, 'docpad') ###* # The DocPad package.json path # @property {String} packagePath ### packagePath: pathUtil.resolve(__dirname, '..', '..', 'package.json') ###* # The DocPad locale path # @property {String} localePath ### localePath: pathUtil.resolve(__dirname, 'locale') # ----------------------------- # Template Data ###* # Description for initialTemplateData # @private # @property {Object} initialTemplateData ### initialTemplateData: null # {} ###* # Plugin's Extended Template Data # @private # @property {Object} pluginsTemplateData ### pluginsTemplateData: null # {} ###* # Get Complete Template Data # @method getTemplateData # @param {Object} userTemplateData # @return {Object} templateData ### getTemplateData: (userTemplateData) -> # Prepare userTemplateData or= {} docpad = @ locale = @getLocale() # Set the initial docpad template data @initialTemplateData ?= # Site Properties site: {} # Environment getEnvironment: -> return docpad.getEnvironment() # Environments getEnvironments: -> return docpad.getEnvironments() # Set that we reference other files referencesOthers: (flag) -> document = @getDocument() document.referencesOthers() return null # Get the Document getDocument: -> return @documentModel # Get a Path in respect to the current document getPath: (path,parentPath) -> document = @getDocument() path = document.getPath(path, parentPath) return path # Get Files getFiles: (query,sorting,paging) -> @referencesOthers() result = docpad.getFiles(query, sorting, paging) return result # Get another file's URL based on a relative path getFile: (query,sorting,paging) -> @referencesOthers() result = docpad.getFile(query,sorting,paging) return result # Get Files At Path getFilesAtPath: (path,sorting,paging) -> @referencesOthers() path = @getPath(path) result = docpad.getFilesAtPath(path, sorting, paging) return result # Get another file's model based on a relative path getFileAtPath: (relativePath) -> @referencesOthers() path = @getPath(relativePath) result = docpad.getFileAtPath(path) return result # Get a specific file by its id getFileById: (id) -> @referencesOthers() result = docpad.getFileById(id) return result # Get the entire database getDatabase: -> @referencesOthers() return docpad.getDatabase() # Get a pre-defined collection getCollection: (name) -> @referencesOthers() return docpad.getCollection(name) # Get a block getBlock: (name) -> return docpad.getBlock(name,true) # Include another file taking in a relative path include: (subRelativePath,strict=true) -> file = @getFileAtPath(subRelativePath) if file if strict and file.get('rendered') is false if docpad.getConfig().renderPasses is 1 docpad.warn util.format(locale.renderedEarlyViaInclude, subRelativePath) return null return file.getOutContent() else err = new Errlop(util.format(locale.includeFailed, subRelativePath)) throw err # Fetch our result template data templateData = extendr.extend({}, @initialTemplateData, @pluginsTemplateData, @getConfig().templateData, userTemplateData) # Add site data templateData.site.url or= '' templateData.site.date or= new Date() templateData.site.keywords or= [] if typeChecker.isString(templateData.site.keywords) templateData.site.keywords = templateData.site.keywords.split(/,\s*/g) # Return templateData # ----------------------------- # Locales ###* # Determined locale # @private # @property {Object} locale ### locale: null ###* # Get the locale (language code and locale code) # @method getLocale # @return {Object} locale ### getLocale: (key) -> unless @locale? try locales = @getPath('locales').map((locale) -> require(locale)) @locale = extendr.extend(locales...) catch localeError docpad.warn(new Errlop('Failed to load a locale', localeError)) try @locale = require(@getPath('locale')) catch err docpad.fatal(new Errlop('Failed to load any locale', err)) @locale = {} if key return @locale[key] or key else return @locale # ----------------------------- # Environments ###* # Get the DocPad environment, eg: development, # production or static # @method getEnvironment # @return {String} the environment ### getEnvironment: -> return @env ###* # Get the environments # @method getEnvironments # @return {Array} array of environment strings ### getEnvironments: -> return @envs # ----------------------------- # Configuration ###* # Website Package Configuration # @private # @property {Object} websitePackageConfig ### websitePackageConfig: null # {} ###* # Merged Configuration # Merged in the order of: # - initialConfig # - userConfig # - websiteConfig # - instanceConfig # - environmentConfig # Use getConfig to retrieve this value # @private # @property {Object} config ### config: null # {} ###* # Instance Configuration # @private # @property {Object} instanceConfig ### instanceConfig: null # {} ###* # Website Configuration # Merged into the config property # @private # @property {Object} websiteConfig ### websiteConfig: null # {} ###* # User Configuraiton # Merged into the config property # @private # @property {Object} userConfig ### userConfig: null # {} ###* # Initial Configuration. The default docpadConfig # settings that can be overridden in a project's docpad.coffee file. # Merged into the config property # @private # @property {Object} initialConfig ### initialConfig: # ----------------------------- # Plugins # Whether or not we should use the global docpad instance global: false # Configuration to pass to any plugins pluginName: pluginConfiguration plugins: {} # ----------------------------- # Project Paths # The project directory rootPath: process.cwd() # The project's package.json path packagePath: 'package.json' # The project's configuration paths # Reads only the first one that exists # If you want to read multiple configuration paths, then point it to a coffee|js file that requires # the other paths you want and exports the merged config configPaths: [ 'docpad.js' 'docpad.coffee' 'docpad.json' 'docpad.cson' ] # Plugin directories to load pluginPaths: [] # Paths that we should watch for reload changes in reloadPaths: [] # Paths that we should watch for regeneration changes in regeneratePaths: [] # The DocPad debug log path (docpad-debug.log) debugLogPath: 'docpad-debug.log' # The User's configuration path (.docpad.cson) userConfigPath: '.docpad.cson' # ----------------------------- # Project Options # The project's out directory outPath: 'out' # The project's source directory sourcePaths: [ 'source' 'src' ] # The project's documents directories # relative to the source path documentsPaths: [ 'documents' 'render' ] # The project's files directories # relative to the source path filesPaths: [ 'files' 'static' 'public' ] # The project's layouts directory # relative to the source path layoutsPaths: [ 'layouts' ] # Ignored file patterns during directory parsing ignorePaths: false ignoreHiddenFiles: false ignoreCommonPatterns: true ignoreCustomPatterns: false # Watch options watchOptions: null # ----------------------------- # Logging # Log Level # Which level of logging should we actually output logLevel: 6 # Verbose # Set log level to 7 verbose: false # Debug # Output all log messages to the debugLogPath debug: false # Color # Whether or not our terminal output should have color # `null` will default to what the terminal supports color: docpadUtil.isTTY() # Silent # Will set the following # logLevel = 3 # progress = welcome = false silent: false # Progress # Whether or not we should display the progress in the terminal title bar progress: true # ----------------------------- # Other # Catch our own exceptions (error events on the DocPad instance) # use "error"/truthy to report # use "fatal" to report and exit catchOurExceptions: 'error' # Catch any uncaught exception # use "error" to report # use "fatal"/truthy to report and exit catchUncaughtExceptions: 'fatal' # Whether or not DocPad is allowed to set the exit code on fatal errors # May only work on node v0.11.8 and above setExitCodeOnFatal: true # Whether or not DocPad is allowed to set the exit code on standard errors # May only work on node v0.11.8 and above setExitCodeOnError: true # Whether or not DocPad is allowed to set the exit code when some code has requested to # May only work on node v0.11.8 and above setExitCodeOnRequest: true # The time to wait before cancelling a request requestTimeout: 30*1000 # The time to wait when destroying DocPad destroyDelay: -1 # Whether or not to destroy on exit destroyOnExit: true # Whether or not to destroy on signal interrupt (ctrl+c) destroyOnSignalInterrupt: true # The time to wait after a source file has changed before using it to regenerate regenerateDelay: 100 # The time to wait before outputting the files we are waiting on slowFilesDelay: 20*1000 # The time to wait before outputting the plugins we are waiting on slowPluginsDelay: 20*1000 # Utilise the database cache databaseCache: false # [false, true, 'write'] # Detect Encoding # Should we attempt to auto detect the encoding of our files? # Useful when you are using foreign encoding (e.g. GBK) for your files detectEncoding: false # Render Single Extensions # Whether or not we should render single extensions by default renderSingleExtensions: false # Render Passes # How many times should we render documents that reference other documents? renderPasses: 1 # Powered By DocPad # Whether or not we should include DocPad in the Powered-By meta header # Please leave this enabled as it is a standard practice and promotes DocPad in the web eco-system poweredByDocPad: true # Template Data # What data would you like to expose to your templates templateData: {} # Collections # A hash of functions that create collections collections: {} # Events # A hash of event handlers events: {} # Regenerate Every # Performs a regenerate every x milliseconds, useful for always having the latest data regenerateEvery: false # Regerenate Every Options # The generate options to use on the regenerate every call regenerateEveryOptions: populate: true partial: false # ----------------------------- # Environment Configuration # Locale Code # The code we shall use for our locale (e.g. en, fr, etc) localeCode: null # Environment # Whether or not we are in production or development # Separate environments using a comma or a space env: null # Environments # Environment specific configuration to over-ride the global configuration environments: development: # Only do these if we are running standalone (aka not included in a module) welcome: isUser progress: isUser ###* # Get the DocPad configuration # @method getConfig # @return {Object} the DocPad configuration object ### getConfig: -> return @config or {} # ================================= # Initialization Functions ###* # Create our own custom TaskGroup instance for DocPad. # That will listen to tasks as they execute and provide debugging information. # @method createTaskGroup # @param {Object} opts # @return {TaskGroup} ### createTaskGroup: (opts...) => docpad = @ progress = docpad.progressInstance tasks = TaskGroup.create(opts...) # Listen to executing tasks and output their progress tasks.on 'running', -> config = tasks.getConfig() name = tasks.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > running') # Listen to executing tasks and output their progress tasks.on 'item.add', (item) -> config = tasks.getConfig() name = item.getNames() unless progress docpad.log('debug', name+' > added') # Listen to executing tasks and output their progress item.on 'started', (item) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > started') # Listen to executing tasks and output their progress item.done (err) -> config = tasks.getConfig() name = item.getNames() if progress totals = tasks.getItemTotals() progress.update(name, totals) else docpad.log('debug', name+' > done') # Return return tasks ###* # Constructor method. Sets up the DocPad instance. # next(err) # @method constructor # @param {Object} instanceConfig # @param {Function} next callback # @param {Error} next.err # @param {DocPad} next.docpad ### constructor: (instanceConfig,next) -> # Prepare super() [instanceConfig,next] = extractOptsAndCallback(instanceConfig, next) docpad = @ # Allow DocPad to have unlimited event listeners @setMaxListeners(0) # Binders # Using this over coffescript's => on class methods, ensures that the method length is kept for methodName in "action log warn error fatal inspect notify checkRequest activeHandles onBeforeExit onSignalInterruptOne onSignalInterruptTwo onSignalInterruptThree destroyWatchers".split(/\s+/) @[methodName] = @[methodName].bind(@) # Adjust configPaths if typeChecker.isString(instanceConfig.configPaths) instanceConfig.configPaths = [instanceConfig.configPaths] # Dereference and initialise advanced variables # we deliberately ommit initialTemplateData here, as it is setup in getTemplateData @slowPlugins = {} @loadedPlugins = {} @pluginsTemplateData = {} @collections = [] @blocks = {} @websitePackageConfig = {} @websiteConfig = {} @userConfig = {} @initialConfig = extendr.dereferenceJSON(@initialConfig) @instanceConfig = instanceConfig or {} @config = @mergeConfigs() # Prepare the loggers instanceConfig.logLevel ?= @initialConfig.logLevel color = instanceConfig.color lineLevel = -1 if instanceConfig.silent instanceConfig.logLevel = 3 # 3:error, 2:critical, 1:alert, 0:emergency instanceConfig.progress = instanceConfig.welcome = false if instanceConfig.verbose || instanceConfig.debug instanceConfig.logLevel = 7 lineLevel = 7 # Create the loggers logger = new Logger({lineLevel: lineLevel}) filter = new Filter({filterLevel: instanceConfig.logLevel}) # Apply the loggers @logger = logger # Console logger.pipe(filter).pipe( new Human({ color: color }) ).pipe(process.stdout) # File if instanceConfig.debug logPath = @getPath(false, 'log') safefs.unlink logPath, -> logger .pipe( new Human(color: false) ) .pipe( fsUtil.createWriteStream(logPath) ) # Forward log events to the logger @on 'log', (args...) -> docpad.log.apply(@, args) # Setup configuration event wrappers configEventContext = {docpad} # here to allow the config event context to persist between event calls @getEvents().forEach (eventName) -> # Bind to the event docpad.on eventName, (opts,next) -> eventHandler = docpad.getConfig().events?[eventName] # Fire the config event handler for this event, if it exists if typeChecker.isFunction(eventHandler) args = [opts,next] ambi(unbounded.binder.call(eventHandler, configEventContext), args...) # It doesn't exist, so lets continue else next() # Create our action runner @actionRunnerInstance = @createTaskGroup('action runner', {abortOnError: false, destroyOnceDone: false}).whenDone (err) -> docpad.progressInstance?.update('') docpad.error(err) if err # Setup the database @database = new FilesCollection(null, {name:'database'}) .on('remove', (model,options) -> # Skip if we are not a writeable file return if model.get('write') is false # Ensure we regenerate anything (on the next regeneration) that was using the same outPath outPath = model.get('outPath') if outPath updatedModels = docpad.database.findAll({outPath}) updatedModels.remove(model) if updatedModels.length updatedModels.each (model) -> model.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the removal of a similar one:', updatedModels.pluck('relativePath')) # Return safely return true ) .on('add change:outPath', (model) -> # Skip if we are not a writeable file return if model.get('write') is false # Prepare outPath = model.get('outPath') previousOutPath = model.previous('outPath') # Check if we have changed our outPath if previousOutPath # Ensure we regenerate anything (on the next regeneration) that was using the same outPath previousModels = docpad.database.findAll({outPath: previousOutPath}) previousModels.remove(model) if previousModels.length previousModels.each (previousModel) -> previousModel.set('mtime': new Date()) docpad.log('info', 'Updated mtime for these models due to the addition of a similar one:', previousModels.pluck('relativePath')) # Determine if there are any conflicts with the new outPath if outPath existingModels = docpad.database.findAll({outPath}) existingModels.each (existingModel) -> if existingModel.id isnt model.id modelPath = model.get('fullPath') or (model.get('relativePath')+':'+model.id) existingModelPath = existingModel.get('fullPath') or (existingModel.get('relativePath')+':'+existingModel.id) docpad.warn util.format(docpad.getLocale().outPathConflict, outPath, modelPath, existingModelPath) # Return safely return true ) # Continue with load and ready @action 'load ready', {}, (err) -> if next? next(err, docpad) else if err docpad.fatal(err) # Chain @ ###* # Has DocPad commenced destruction? ### destroying: false ###* # Destructor. Destroy the DocPad instance # This is an action, and should be called as such # E.g. docpad.action('destroy', next) # @method destroy # @param {Object} opts # @param {Function} next # @param {Error} next.err ### destroy: (opts, next) -> return @ if @destroying @destroying = true # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() locale = @getLocale() # Log docpad.log('info', locale.destroyDocPad) # Drop all the remaining tasks dropped = @getActionRunner().clearRemaining() docpad.error("DocPad destruction had to drop #{Number(dropped)} action tasks") if dropped # Destroy Timers docpad.destroyTimers() # Wait a configurable oment docpad.timer 'destroy', 'timeout', config.destroyDelay, -> # Destroy Plugins docpad.emitSerial 'docpadDestroy', (eventError) -> # Check if eventError # Note err = new Errlop( "DocPad's destroyEvent event failed", eventError ) docpad.fatal(err) # Callback return next?(err) # Final closures and checks try # Destroy Timers docpad.destroyTimers() # Destroy Plugins docpad.destroyPlugins() # Destroy Watchers docpad.destroyWatchers() # Destroy Blocks docpad.destroyBlocks() # Destroy Collections docpad.destroyCollections() # Destroy Database docpad.destroyDatabase() # Destroy progress docpad.updateProgress(false) # Destroy Logging docpad.destroyLoggers() # Destroy Process Listeners process.removeListener('uncaughtException', docpad.fatal) process.removeListener('uncaughtException', docpad.error) process.removeListener('beforeExit', docpad.onBeforeExit) process.removeListener('SIGINT', docpad.onSignalInterruptOne) process.removeListener('SIGINT', docpad.onSignalInterruptTwo) process.removeListener('SIGINT', docpad.onSignalInterruptThree) # Destroy DocPad Listeners docpad.removeAllListeners() catch finalError # Note err = new Errlop( "DocPad's final destruction efforts failed", finalError ) docpad.fatal(err) return next?(err) # Success docpad.log(locale.destroyedDocPad) # log level omitted, as this will hit console.log return next?() # Chain @ ###* # Emit event, serial # @private # @method emitSerial # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitSerial: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ ###* # Emit event, parallel # @private # @method emitParallel # @param {String} eventName # @param {Object} opts # @param {Function} next # @param {Error} next.err ### emitParallel: (eventName, opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = docpad.getLocale() # Log docpad.log 'debug', util.format(locale.emittingEvent, eventName) # Emit super eventName, opts, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.emittedEvent, eventName) # Forward return next(err) # Chain @ # ================================= # Helpers ###* # Get the ignore options for the DocPad project # @method getIgnoreOpts # @return {Array} string array of ignore options ### getIgnoreOpts: -> return pick(@config, ['ignorePaths', 'ignoreHiddenFiles', 'ignoreCommonPatterns', 'ignoreCustomPatterns']) ###* # Is the supplied path ignored? # @method isIgnoredPath # @param {String} path # @param {Object} [opts={}] # @return {Boolean} ### isIgnoredPath: (path,opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return ignorefs.isIgnoredPath(path, opts) ###* # Scan directory # @method scandir # @param {Object} [opts={}] ### #NB: How does this work? What is returned? #Does it require a callback (next) passed as #one of the options scandir: (opts={}) -> opts = extendr.extend(@getIgnoreOpts(), opts) return scandir(opts) ###* # Watch Directory. Wrapper around the Bevry watchr # module (https://github.com/bevry/watchr). Used # internally by DocPad to watch project documents # and files and then activate the regeneration process # when any of those items are updated. # @private # @method watchdir # @param {String} path - the path to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error # @return {Object} the watcher ### watchdir: (path, listeners, next) -> opts = extendr.extend(@getIgnoreOpts(), @config.watchOptions or {}) stalker = require('watchr').create(path) for own key, value of listeners stalker.on(key, value) stalker.setConfig(opts) stalker.watch(next) return stalker ###* # Watch Directories. Wrapper around watchdir. # @private # @method watchdirs # @param {Array} paths - the paths to watch # @param {Object} listeners - listeners to attach to the watcher # @param {Function} next - completion callback accepting error and watchers/stalkers ### watchdirs: (paths, listeners, next) -> docpad = @ stalkers = [] tasks = new TaskGroup('watching directories').setConfig(concurrency:0).done (err) -> if err for stalker in stalkers stalker.close() next(err) else next(err, stalkers) paths.forEach (path) -> tasks.addTask "watching #{path}", (done) -> # check if the dir exists first as reloadPaths may not apparently safefs.exists path, (exists) -> return done() unless exists stalkers.push docpad.watchdir(path, listeners, done) tasks.run() # Chain @ # ================================= # Setup and Loading ###* # DocPad is ready. Peforms the tasks needed after DocPad construction # and DocPad has loaded. Triggers the docpadReady event. # next(err,docpadInstance) # @private # @method ready # @param {Object} [opts] # @param {Function} next # @param {Error} next.err # @param {Object} next.docpadInstance ### ready: (opts,next) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ config = @getConfig() locale = @getLocale() # Render Single Extensions @DocumentModel::defaults.renderSingleExtensions = config.renderSingleExtensions # Fetch the plugins pluginsList = Object.keys(@loadedPlugins).sort().join(', ') # Welcome Output docpad.log 'info', util.format(locale.welcome, @getVersionString()) docpad.log 'notice', locale.welcomeDonate docpad.log 'info', locale.welcomeContribute docpad.log 'info', util.format(locale.welcomePlugins, pluginsList) docpad.log 'info', util.format(locale.welcomeEnvironment, @getEnvironment()) # Prepare tasks = @createTaskGroup('ready tasks').done (err) -> # Error? return docpad.error(err) if err # All done, forward our DocPad instance onto our creator return next?(null,docpad) # kept here in case plugins use it tasks.addTask 'welcome event', (complete) -> # No welcome return complete() unless config.welcome # Welcome docpad.emitSerial('welcome', {docpad}, complete) tasks.addTask 'emit docpadReady', (complete) -> docpad.emitSerial('docpadReady', {docpad}, complete) # Run tasks tasks.run() # Chain @ ###* # Performs the merging of the passed configuration objects # @private # @method mergeConfigs ### mergeConfigs: (configPackages, destination = {}) -> # A plugin is calling us with its configuration unless configPackages # Apply the environment # websitePackageConfig.env is left out of the detection here as it is usually an object # that is already merged with our process.env by the environment runner # rather than a string which is the docpad convention @env = ( @instanceConfig.env or @websiteConfig.env or @initialConfig.env or process.env.NODE_ENV or 'development' ) @envs = @env.split(/[, ]+/) # Merge the configurations together configPackages = [@initialConfig, @userConfig, @websiteConfig, @instanceConfig] # Figure out merging configsToMerge = [destination] for configPackage in configPackages continue unless configPackage configsToMerge.push(configPackage) for env in @envs envConfig = configPackage.environments?[env] configsToMerge.push(envConfig) if envConfig # Merge return extendr.deep(configsToMerge...) ###* # Legacy version of mergeConmergeConfigsfigurations # @private # @method mergeConfigurations ### mergeConfigurations: (configPackages, [destination]) -> return @mergeConfigs(configPackages, destination) ###* # Set the DocPad configuration object. # Performs a number of tasks, including # merging the pass instanceConfig with DocPad's # other config objects. # next(err,config) # @private # @method setConfig # @param {Object} instanceConfig # @param {Object} next # @param {Error} next.err # @param {Object} next.config ### setConfig: (instanceConfig) -> # Prepare [instanceConfig,next] = extractOptsAndCallback(instanceConfig,next) docpad = @ locale = @getLocale() # Apply the instance configuration, generally we won't have it at this level # as it would have been applied earlier the load step extendr.deepDefaults(@instanceConfig, instanceConfig) if instanceConfig # Merge the configurations together @config = @mergeConfigs() # Update the progress bar configuration @updateProgress() # Handle errors process.removeListener('uncaughtException', @fatal) process.removeListener('uncaughtException', @error) @removeListener('error', @fatal) @removeListener('error', @error) if @config.catchExceptions # legacy @config.catchOurExceptions = @config.catchUncaughtExceptions = 'error' if @config.catchUncaughtExceptions process.setMaxListeners(0) if @config.catchUncaughtExceptions is 'error' process.on('uncaughtException', @error) else process.on('uncaughtException', @fatal) if @config.catchOurExceptions if @config.catchUncaughtExceptions is 'fatal' @on('error', @fatal) else @on('error', @error) # Handle interrupt process.removeListener('beforeExit', @onBeforeExit) process.removeListener('SIGINT', @onSignalInterruptOne) process.removeListener('SIGINT', @onSignalInterruptTwo) process.removeListener('SIGINT', @onSignalInterruptThree) if @config.destroyOnExit process.once('beforeExit', @onBeforeExit) if @config.destroyOnSignalInterrupt process.once('SIGINT', @onSignalInterruptOne) # Chain @ onSignalInterruptOne: -> # Log @log('notice', "Signal Interrupt received, queued DocPad's destruction") # Escalate next time process.once('SIGINT', @onSignalInterruptTwo) # Act @action('destroy') # Chain @ onSignalInterruptTwo: -> # Log @log('alert', 'Signal Interrupt received again, closing stdin and dumping handles') # Escalate next time process.once('SIGINT', @onSignalInterruptThree) # Handle any errors that occur when stdin is closed # https://github.com/docpad/docpad/pull/1049 process.stdin?.once? 'error', (stdinError) -> # ignore ENOTCONN as it means stdin was already closed when we called stdin.end # node v8 and above have stdin.destroy to avoid emitting this error if stdinError.toString().indexOf('ENOTCONN') is -1 err = new Errlop( "closing stdin encountered an error", stdinError ) docpad.fatal(err) # Close stdin # https://github.com/docpad/docpad/issues/1028 # https://github.com/docpad/docpad/pull/1029 process.stdin?.destroy?() or process.stdin?.end?() # Wait a moment before outputting things that are preventing closure setImmediate(@activeHandles) # Chain @ onSignalInterruptThree: -> # Log @log('alert', 'Signal Interrupt received yet again, skipping queue and destroying DocPad right now') # Act @exitCode(130) @destroy() # Chain @ onBeforeExit: -> @action('destroy') activeHandles: -> # Note any requests that are still active activeRequests = process._getActiveRequests?() if activeRequests?.length docpadUtil.writeStderr """ Waiting on these #{activeRequests.length} requests to close: #{@inspect activeRequests} """ # Note any handles that are still active activeHandles = process._getActiveHandles?() if activeHandles?.length docpadUtil.writeStderr """ Waiting on these #{activeHandles.length} handles to close: #{@inspect activeHandles} """ ###* # Load the various configuration files from the # file system. Set the instanceConfig. # next(err,config) # @private # @method load # @param {Object} opts # @param {Function} next # @param {Error} next.err ### load: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare the Load Tasks loadTasks = @createTaskGroup('load tasks').done(next) # User Configuration loadTasks.addTask "load the user's configuration", (complete) => userConfigPath = @getPath('user') return complete() unless userConfigPath docpad.log 'debug', util.format(locale.loadingUserConfig, userConfigPath) @loadConfigPath userConfigPath, (err,data) => return complete(err) if err # Apply if data @userConfig = data docpad.log 'debug', util.format(locale.loadedUserConfig, userConfigPath) return complete() # Complete return complete() # Website Env Configuration loadTasks.addTask "read the .env file if it exists", (complete) => envPath = @getPath('env') return complete() unless envPath docpad.log 'debug', util.format(locale.loadingEnvConfig, envPath) envFile.parseFile envPath, (err,data) -> return complete(err) if err for own key,value of data process.env[key] = value docpad.log 'debug', util.format(locale.loadedEnvConfig, envPath) return complete() # Website Package Configuration loadTasks.addTask "load the website's package data", (complete) => packagePath = @getPath('package') return complete() unless packagePath docpad.log 'debug', util.format(locale.loadingWebsitePackageConfig, packagePath) @loadConfigPath packagePath, (err,data) => return complete(err) if err # Apply if data @websitePackageConfig = data docpad.log 'debug', util.format(locale.loadedWebsitePackageConfig, packagePath) # Complete return complete() # Website Configuration loadTasks.addTask "load the website's configuration", (complete) => configPath = @getPath('config') return complete() unless configPath docpad.log 'debug', util.format(locale.loadingWebsiteConfig, configPath) @loadConfigPath configPath, (err,data) => return complete(err) if err # Apply if data @websiteConfig = data docpad.log 'debug', util.format(locale.loadedWebsiteConfig, configPath) # Complete return complete() loadTasks.addTask "update the configurations", => @setConfig() ### loadTasks.addTask 'lazy dependencies: encoding', (complete) => lazyRequire = require('lazy-require') return complete() unless @config.detectEncoding return lazyRequire 'encoding', {cwd:corePath, stdio:'inherit'}, (err) -> docpad.warn(locale.encodingLoadFailed) if err return complete() ### loadTasks.addTask 'load plugins', (complete) -> docpad.loadPlugins(complete) loadTasks.addTask 'extend collections', (complete) -> docpad.extendCollections(complete) loadTasks.addTask 'fetch plugins templateData', (complete) -> docpad.emitSerial('extendTemplateData', {templateData:docpad.pluginsTemplateData}, complete) # Fire post tasks loadTasks.run() # Chain @ # ================================= # Configuration ###* # Update user configuration with the passed data # @method updateUserConfig # @param {Object} [data={}] # @param {Function} next # @param {Error} next.err ### updateUserConfig: (data={},next) -> # Prepare [data,next] = extractOptsAndCallback(data,next) docpad = @ userConfigPath = @getConfig(false, 'user') # Apply back to our loaded configuration # does not apply to @config as we would have to reparse everything # and that appears to be an imaginary problem extendr.extend(@userConfig, data) if data # Convert to CSON CSON.createCSONString @userConfig, (parseError, userConfigString) -> if parseError err = new Errlop( "Failed to create the CSON string for the user configuration", parseError ) return next(err) # Write it safefs.writeFile userConfigPath, userConfigString, 'utf8', (writeError) -> if writeError err = new Errlop( "Failed to write the CSON string for the user configuration to #{userConfigPath}", writeError ) return next(err) # Forward return next() # Chain @ ###* # Load a configuration url. # @method loadConfigUrl # @param {String} configUrl # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigUrl: (configUrl,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() # Log docpad.log 'debug', util.format(locale.loadingConfigUrl, configUrl) # Read the URL fetch(configUrl, {timeout: config.requestTimeout}) .then((res) -> res.text()) .then((text) -> CSON.parseCSONString(text)) .catch(next) .then((data) -> next(null, data)) # Chain @ ###* # Load the configuration from a file path # passed as one of the options (opts.configPath) or # from DocPad's configPaths # @private # @method loadConfigPath # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.parsedData ### loadConfigPath: (configPath,next) -> # Prepare docpad = @ locale = @getLocale() # Check return next() unless configPath # Log docpad.log 'debug', util.format(locale.loadingConfigPath, configPath) # Prepare CSON Options csonOptions = cson: true json: true coffeescript: true javascript: true # Read the path using CSON CSON.requireFile configPath, csonOptions, (parseError, data) -> if parseError err = new Errlop( util.format(locale.loadingConfigPathFailed, configPath), parseError ) return next(err) # Check if the data is a function, if so, then execute it as one while typeChecker.isFunction(data) try data = data(docpad) catch executeError err = new Errlop( util.format(locale.executeConfigPathFailed, configPath), executeError ) return next(err) unless typeChecker.isObject(data) err = new Errlop( util.format(locale.invalidConfigPathData, configPath, docpad.inspect(data)) ) return next(err) # Return the data return next(null, data) # Chain @ resolvePath: (args...) -> try path = pathUtil.resolve(args...) return path if safefs.existsSync(path) catch error @log('error', 'failed to resolve the path:', {path, error}) throw error return false getPath: (args...) -> # Use join if first argument is false if typeChecker.isBoolean(args[0]) [check, name, tail...] = args else check = true [name, tail...] = args # Prepare method = if check then @resolvePath else pathUtil.resolve config = @getConfig() # Determine path = switch name when 'locales' then [pathUtil.resolve(@localePath, 'en.js')] ### uniq([ safeps.getLocaleCode config.localeCode safeps.getLocaleCode safeps.getLocaleCode() safeps.getLanguageCode config.localeCode safeps.getLanguageCode safeps.getLocaleCode() 'en' ]).map((code) => @resolvePath(@localePath, code + '.js')) ### when 'locale' then @getPath(check, 'locales')[0] when 'root' then method(check, config.rootPath) when 'log' then method(check, process.cwd(), config.debugLogPath) when 'out' then @getPath(check, 'root', config.outPath) when 'env' then @getPath(check, 'root', '.env') when 'home' then require('os').homedir() # works in node v4 and above when 'dropbox' then @getPath(check, 'home', 'Dropbox') when 'users' then [@getPath(check, 'dropbox', config.userConfigPath), @getPath(check, 'root', config.userConfigPath)].filter(isTruthy) when 'user' then @getPath(check, 'users')[0] or false when 'package' then @getPath(check, 'root', config.packagePath) when 'sources' then config.sourcePaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'source' then @getPath(check, 'sources')[0] or false when 'configs' then config.configPaths.map((path) => @getPath(check, 'root', path)).filter(isTruthy) when 'config' then @getPath(check, 'configs')[0] or false when 'documents' then config.documentsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'document' then @getPath(check, 'documents')[0] or false when 'files' then config.filesPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'file' then @getPath(check, 'files')[0] or false when 'layouts' then config.layoutsPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'layout' then @getPath(check, 'layouts')[0] or false when 'reloads' then config.reloadPaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) when 'regenerates' then config.regeneratePaths.map((path) => @getPath(check, 'source', path)).filter(isTruthy) else null try if typeof path is 'string' and tail.length return method(check, path, tail...) else return path catch error @log('error', 'failed to get the path:', {check, name, tail, error}) throw error ###* # Extend collections. Create DocPad's # standard (documents, files # layouts) and special (generate, referencesOthers, # hasLayout, html, stylesheet) collections. Set blocks # @private # @method extendCollections # @param {Function} next # @param {Error} next.err ### extendCollections: (next) -> # Prepare docpad = @ docpadConfig = @getConfig() locale = @getLocale() database = @getDatabase() # Standard Collections @setCollections({ # Standard Collections documents: database.createLiveChildCollection() .setQuery('isDocument', { render: true write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingDocument, model.getFilePath())) ) files: database.createLiveChildCollection() .setQuery('isFile', { render: false write: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingFile, model.getFilePath())) ) layouts: database.createLiveChildCollection() .setQuery('isLayout', { $or: isLayout: true fullPath: $startsWith: @getPath('layouts') }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingLayout, model.getFilePath())) model.setDefaults({ isLayout: true render: false write: false }) ) # Special Collections generate: database.createLiveChildCollection() .setQuery('generate', { ignored: false }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingGenerate, model.getFilePath())) ) referencesOthers: database.createLiveChildCollection() .setQuery('referencesOthers', { ignored: false referencesOthers: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingReferencesOthers, model.getFilePath())) ) hasLayout: database.createLiveChildCollection() .setQuery('hasLayout', { ignored: false layout: $exists: true }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHasLayout, model.getFilePath())) ) html: database.createLiveChildCollection() .setQuery('isHTML', { write: true outExtension: 'html' }) .on('add', (model) -> docpad.log('debug', util.format(locale.addingHtml, model.getFilePath())) ) stylesheet: database.createLiveChildCollection() .setQuery('isStylesheet', { write: true outExtension: 'css' }) }) # Blocks @setBlocks({ meta: new MetaCollection() scripts: new ScriptsCollection() styles: new StylesCollection() }) # Custom Collections Group tasks = @createTaskGroup("extendCollections tasks", concurrency:0).done (err) -> docpad.error(err) if err docpad.emitSerial('extendCollections', next) # Cycle through Custom Collections eachr docpadConfig.collections or {}, (fn,name) -> if !name or !typeChecker.isString(name) err = new Errlop("Inside your DocPad configuration you have a custom collection with an invalid name of: #{docpad.inspect name}") docpad.error(err) return if !fn or !typeChecker.isFunction(fn) err = new Errlop("Inside your DocPad configuration you have a custom collection called #{docpad.inspect name} with an invalid method of: #{docpad.inspect fn}") docpad.error(err) return tasks.addTask "creating the custom collection: #{name}", (complete) -> # Init ambi unbounded.binder.call(fn, docpad), database, (err, collection) -> # Check for error if err docpad.error(err) return complete() # Check the type of the collection else unless collection instanceof QueryCollection docpad.warn util.format(locale.errorInvalidCollection, name) return complete() # Make it a live collection collection.live(true) if collection # Apply the collection docpad.setCollection(name, collection) return complete() # Run Custom collections tasks.run() # Chain @ ###* # Reset collections. Perform a complete clean of our collections # @private # @method resetCollections # @param {Object} opts # @param {Function} next # @param {Error} next.err ### resetCollections: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ database = docpad.getDatabase() # Make it as if we have never generated before docpad.generated = false # Perform a complete clean of our collections database.reset([]) meta = @getBlock('meta').reset([]) scripts = @getBlock('scripts').reset([]) styles = @getBlock('styles').reset([]) # ^ Backbone.js v1.1 changes the return values of these, however we change that in our Element class # because if we didn't, all our projects would fail # Add default block entries meta.add("""<meta name="generator" content="DocPad v#{docpad.getVersion()}" />""") if docpad.getConfig().poweredByDocPad isnt false # Chain next() @ ###* # Initialise git repo # @private # @method initGitRepo # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initGitRepo: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') # Forward safeps.initGitRepo(opts, next) # Chain @ ###* # Init node modules # @private # @method initNodeModules # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.results ### initNodeModules: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] # Command command = ['npm', 'install'] command.push(opts.args...) # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Fix node package versions # Combat to https://github.com/npm/npm/issues/4587#issuecomment-35370453 # @private # @method fixNodePackageVersions # @param {Object} opts # @param {Function} next # @param {Error} next.err ### fixNodePackageVersions: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.packagePath ?= @getPath('package') # Read and replace safefs.readFile opts.packagePath, (err,buffer) -> data = buffer.toString() data = data.replace(/("docpad(?:.*?)": ")\^/g, '$1~') safefs.writeFile opts.packagePath, data, (err) -> return next(err) # Chain @ ###* # Install node module. Same as running # 'npm install' through the command line # @private # @method installNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### installNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = [] if opts.global opts.save = ['--save'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'install'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) names.forEach (name) -> # Check return unless name # Ensure latest if version isn't specfied name += '@latest' if name.indexOf('@') is -1 # Push the name to the commands command.push(name) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save and opts.save.length command.push('--global') if opts.global # Log docpad.log('info', command.join(' ')) if opts.output # Forward safeps.spawn(command, opts, next) # Chain @ ###* # Uninstall node module. Same as running # 'npm uninstall' through the command line # @private # @method uninstallNodeModule # @param {Array} names # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result ### uninstallNodeModule: (names,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ config = @getConfig() # Extract opts.stdio = 'inherit' opts.cwd ?= @getPath('root') opts.args ?= [] opts.save = ['--save', '--save-dev'] if opts.save is true opts.save = [opts.save] if opts.save and Array.isArray(opts.save) is false # Command command = ['npm', 'uninstall'] # Names names = names.split(/[,\s]+/) unless typeChecker.isArray(names) command.push(names...) # Arguments command.push(opts.args...) command.push(opts.save...) if opts.save # Log docpad.log('info', command.join(' ')) # Forward safeps.spawn(command, opts, next) # Chain @ # ================================= # Logging ###* # Get the log level # @method getLogLevel # @return {Number} the log level ### getLogLevel: -> return @getConfig().logLevel ###* # Are we debugging? # @method getDebugging # @return {Boolean} ### getDebugging: -> config = @getConfig() return config.logLevel is 7 or config.debug ###* # Check Request # @private # @method checkRequest # @param {Function} next # @param {Error} next.err # @param {Object} next.res ### checkRequest: (next) -> next ?= @error.bind(@) return (err,res) -> # Check return next(err, res) if err # Check if res.body?.success is false or res.body?.error err = new Errlop(res.body.error or 'unknown request error') return next(err, res) # Success return next(null, res) ###* # Send a notify event to plugins (like growl) # @method notify # @param {String} message # @param {Object} [opts={}] ### notify: (message,opts={}) -> # Prepare docpad = @ # Emit docpad.emitSerial 'notify', {message,opts}, (err) -> docpad.error(err) if err # Chain @ ###* # Inspect. Converts object to JSON string. Wrapper around nodes util.inspect method. # Can't use the inspect namespace as for some silly reason it destroys everything # @method inspect # @param {Object} obj # @param {Object} opts # @return {String} JSON string of passed object ### inspect: (obj, opts) -> opts ?= {} opts.colors ?= @getConfig().color return util.inspect(obj, opts) ###* # Log arguments to # @property {Object} log # @param {Mixed} args... ### log: (args...) -> # Log logger = @getLogger() if logger?.log? logger.log.apply(logger, args) else # logger doesn't exist, this is probably because it was destroyed # so handle the most basic case ourselves # that case being when the first argument is a log level string # as we don't want to interpret log(new Date().getTime()) as a log level number # @todo # ideally, this logic would be static methods inside caterpillar # as caterpillar methods is already where this logic exist, they just have to be made static logLevels = require('rfc-log-levels') logLevel = logLevels[args[0]] ? 6 if @getLogLevel() >= logLevel console.log(args...) # Chain @ ###* # Create an error and log it # This is called by all sorts of things, including docpad.warn # As such, the err.level is important # @method error # @param {*} value # @return {Error} ### error: (value) -> # Prepare locale = @getLocale() # Ensure it is an error err = Errlop.ensure(value) err.level ?= 'error' err.log ?= true err.logged ?= false err.notify ?= true err.notified ?= false err.report ?= err.level isnt 'warn' # Set the exit code @exitCode(err) # Log the error if err.log isnt false and err.logged isnt true err.logged = true @log( err.logLevel or err.level, err.stack + (err.report and ('\n' + locale.errorSubmission) or '') ) # Notify the error if err.notify isnt false and err.notified isnt true err.notified = true title = locale[err.level + 'Occured'] or locale.errorOccured @notify(err.message, {title}) # Return the result error return err ###* # Log an error of level 'warn' # @method warn # @param {*} value # @return {Error} ### warn: (value) -> err = Errlop.ensure(value) err.level ?= 'warn' # Foward return @error(err) ###* # Handle a fatal error # @private # @method fatal # @param {*} value # @param {Function} [next] # @return {Error} ### fatal: (value, next) -> # Check return @ unless value # Enforce errlop with fatal level err = new Errlop('A fatal error occured within DocPad', value) err.level = 'fatal' err.logLevel = 'critical' # Handle @error(err) # Set the exit code if we are allowed to @exitCode(err) # Destroy DocPad @destroy({}, next) # Return the error return err ###* # Sets the exit code if we are allowed to, and if it hasn't already been set # @method exitCode # @param {number|Error [input] # @return {number} ### exitCode: (input) -> # Determine if necessary unless process.exitCode # Prepare {setExitCodeOnRequest, setExitCodeOnError, setExitCodeOnFatal} = @getConfig() # Number if typeChecker.isNumber(input) code = input level = null # Error else if input instanceof Error code = input.exitCode level = input.level or null error = input # Defaults if !code or isNaN(Number(code)) exitCode = 1 else exitCode = code # Determine desire because = ( (!level and setExitCodeOnRequest and 'requested') or (level is 'fatal' and setExitCodeOnFatal and 'fatal') or (level is 'error' and setExitCodeOnFatal and 'error') ) if because # Fetch before we apply so we can log it shortly originalExitCode = process.exitCode or 'unset' # Apply process.exitCode = exitCode # And log it message = ['Set the exit code from', originalExitCode, 'to', exitCode, 'because of', because] message.push('from:', error.message) if error and error.message @log('note', message...) # Return the application return process.exitCode # ================================= # Models and Collections # --------------------------------- # b/c compat functions ###* # Create file model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'file' modelType. # @method createFile # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} FileModel ### createFile: (attrs={},opts={}) -> opts.modelType = 'file' return @createModel(attrs, opts) ###* # Create document model. Calls # {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # with the 'document' modelType. # @method createDocument # @param {Object} [attrs={}] # @param {Object} [opts={}] # @return {Object} DocumentModel ### createDocument: (attrs={},opts={}) -> opts.modelType = 'document' return @createModel(attrs, opts) ###* # Parse the files directory and # return a files collection to # the passed callback # @method parseFileDirectory # @param {Object} [opts={}] # @param {Function} next callback # @param {Error} next.err # @param {Object} next.files files collection ### parseFileDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'file' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) ###* # Parse the documents directory and # return a documents collection to # the passed callback. # # The partials plugin (https://github.com/docpad/docpad-plugin-partials) # uses this method to load a collection of # files from the partials directory. # # docpad.parseDocumentDirectory({path: config.partialsPath}, next) # # @method parseDocumentDirectory # @param {Object} [opts={}] # @param {String} [opts.modelType='document'] # @param {Object} [opts.collection=docpad.database] # @param {Object} [opts.path] # @param {Function} next # @param {Error} next.err # @param {Object} next.files files collection of documents ### parseDocumentDirectory: (opts,next) -> [opts,next] = extractOptsAndCallback(opts, next) opts.modelType ?= 'document' opts.collection ?= @getDatabase() return @parseDirectory(opts, next) # --------------------------------- # Standard functions ###* # Attach events to a document model. # @private # @method attachModelEvents # @param {Object} model ### attachModelEvents: (model) -> # Prepare docpad = @ # Only attach events if we haven't already done so if model.attachedDocumentEvents isnt true model.attachedDocumentEvents = true # Attach document events if model.type is 'document' # Clone model.on 'clone', (clonedModel) -> docpad.attachModelEvents(clonedModel) # Render model.on 'render', (args...) -> docpad.emitSerial('render', args...) # Render document model.on 'renderDocument', (args...) -> docpad.emitSerial('renderDocument', args...) # Fetch a layout model.on 'getLayout', (opts,next) -> opts.collection = docpad.getCollection('layouts') layout = docpad.getFileBySelector(opts.selector, opts) next(null, {layout}) # Remove #model.on 'remove', (file) -> # docpad.getDatabase().remove(file) # ^ Commented out as for some reason this stops layouts from working # Error model.on 'error', (args...) -> docpad.emit('error', args...) # Log model.on 'log', (args...) -> # .error and .warn only accept one argument # so only forward to them if args length is 2 if args.length is 2 if args[0] in ['err', 'error'] docpad.error(args[1]) return if args[0] in ['warn', 'warning'] docpad.warn(args[1]) return # otherwise forward to log docpad.log(args...) return # Chain @ ###* # Add supplied model to the DocPad database. If the passed # model definition is a plain object of properties, a new # model will be created prior to adding to the database. # Calls {{#crossLink "DocPad/createModel:method"}}{{/crossLink}} # before adding the model to the database. # # # Override the stat's mtime to now # # This is because renames will not update the mtime # fileCurrentStat?.mtime = new Date() # # # Create the file object # file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) # # @method addModel # @param {Object} model either a plain object defining the required properties, in particular # the file path or an actual model object # @param {Object} opts # @return {Object} the model ### addModel: (model, opts) -> model = @createModel(model, opts) @getDatabase().add(model) return model ###* # Add the supplied collection of models to the DocPad database. # Calls {{#crossLink "DocPad/createModels:method"}}{{/crossLink}} # before adding the models to the database. # # databaseData = JSON.parse data.toString() # models = docpad.addModels(databaseData.models) # # @method addModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### addModels: (models, opts) -> models = @createModels(models, opts) @getDatabase().add(models) return models ###* # Create a collection of models from the supplied collection # ensuring that the collection is suitable for adding to the # DocPad database. The method calls {{#crossLink "DocPad/createModel"}}{{/crossLink}} # for each model in the models array. # @private # @method createModels # @param {Object} models DocPad collection of models # @param {Object} opts # @return {Object} the models ### createModels: (models, opts) -> for model in models @createModel(model, opts) # return the for loop results ###* # Creates either a file or document model. # The model type to be created can be passed # as an opts property, if not, the method will # attempt to determing the model type by checking # if the file is in one of the documents or # layout paths. # # Ensures a duplicate model is not created # and all required attributes are present and # events attached. # # Generally it is not necessary for an application # to manually create a model via creatModel as DocPad # will handle this process when watching a project's # file and document directories. However, it is possible # that a plugin might have a requirement to do so. # # model = @docpad.createModel({fullPath:fullPath}) # model.load() # @docpad.getDatabase().add(model) # # @method createModel # @param {Object} [attrs={}] # @param {String} attrs.fullPath the full path to the file # @param {Object} [opts={}] # @param {String} opts.modelType either 'file' or 'document' # @return {Object} the file or document model ### createModel: (attrs={},opts={}) -> # Check if attrs instanceof FileModel return attrs # Prepare docpad = @ config = @getConfig() database = @getDatabase() fileFullPath = attrs.fullPath or null # Find or create # This functionality use to be inside ensureModel # But that caused duplicates in some instances # So now we will always check if attrs.fullPath result = database.findOne(fullPath: attrs.fullPath) if result return result # ----------------------------- # Try and determine the model type # If the type hasn't been specified try and detemrine it based on the full path if fileFullPath # Check if we have a document or layout unless opts.modelType for dirPath in @getPath('documents').concat(@getPath('layouts')).filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'document' break # Check if we have a file unless opts.modelType for dirPath in @getPath('files').filter(isTruthy) if fileFullPath.indexOf(dirPath) is 0 attrs.relativePath or= fileFullPath.replace(dirPath, '').replace(/^[\/\\]/,'') opts.modelType = 'file' break # ----------------------------- # Create the appropriate emodel # Extend the opts with things we need opts = extendr.extend({ detectEncoding: config.detectEncoding rootOutDirPath: @getPath(false, 'out') locale: @getLocale() createTaskGroup: @createTaskGroup # @TODO this a bit dodgy, but works well enough }, opts) if opts.modelType is 'file' # Create a file model model = new FileModel(attrs, opts) else # Create document model model = new DocumentModel(attrs, opts) # ----------------------------- # Finish up # Attach Events @attachModelEvents(model) # Return return model ###* # Parse a directory and return a # files collection # @method parseDirectory # @param {Object} [opts={}] # @param {Object} next # @param {Error} next.err # @param {Object} next.files files collection ### parseDirectory: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() # Extract {path,createFunction} = opts createFunction ?= @createModel files = opts.collection or new FilesCollection() # Check if the directory exists safefs.exists path, (exists) -> # Check unless exists # Log docpad.log 'debug', util.format(locale.renderDirectoryNonexistant, path) # Forward return next() # Log docpad.log 'debug', util.format(locale.renderDirectoryParsing, path) # Tasks tasks = new TaskGroup('parse directory').setConfig(concurrency:0).done (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderDirectoryParsed, path) # Forward return next(null, files) # Files docpad.scandir( # Path path: path # File Action fileAction: (fileFullPath, fileRelativePath, filename, fileStat) -> # Prepare data = fullPath: fileFullPath relativePath: fileRelativePath stat: fileStat # Create file file = createFunction.call(docpad, data, opts) # Create a task to load the file tasks.addTask "load the file #{fileRelativePath}", (complete) -> # Update the file's stat # To ensure changes files are handled correctly in generation file.action 'load', (err) -> # Error? return complete(err) if err # Add the file to the collection files.add(file) # Next complete() # Return return # Next next: (err) -> return next(err) if err tasks.run() ) # Chain @ # ================================= # Plugins ###* # Get a plugin by it's name # @method getPlugin # @param {Object} pluginName # @return {Object} a DocPad plugin ### getPlugin: (pluginName) -> @loadedPlugins[pluginName] ###* # Check if we have any plugins # @method hasPlugins # @return {Boolean} ### hasPlugins: -> return typeChecker.isEmptyPlainObject(@loadedPlugins) is false ###* # Destructor. Destroy plugins # @private # @method destroyPlugins ### destroyPlugins: -> for own name,plugin of @loadedPlugins plugin.destroy() @loadedPlugins[name] = null @ ###* # Load plugins from the file system # next(err) # @private # @method loadPlugins # @param {Function} next # @param {Error} next.err ### loadPlugins: (next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() # Track the slow plugins @slowPlugins = {} @timer 'slowplugins', 'interval', config.slowPluginsDelay, -> docpad.log 'notice', util.format(locale.pluginsSlow, Object.keys(docpad.slowPlugins).join(', ')) # Async tasks = @createTaskGroup("loadPlugins tasks").done (err) -> docpad.timer('slowplugins') docpad.slowPlugins = {} return next(err) # Prepare the plugins to loaded plugins = new Set( Object.keys(docpad.websitePackageConfig.dependencies or {}).concat( Object.keys(docpad.websitePackageConfig.devDependencies or {}) ) .filter((name) -> name.startsWith('docpad-plugin-')) .concat(config.pluginPaths or []) .map((name) -> { pluginPath: docpad.getPath(false, 'root', 'node_modules', name) }) ) # Emit the even tasks.addTask 'emit loadPlugins', (complete) -> docpad.emitSerial('loadPlugins', {docpad, plugins}, complete) # Load the plugins tasks.addTaskGroup 'load plugins', {concurrency: 0}, (suite, task) -> plugins.forEach (plugin) -> tasks.addTask "load the plugin at: #{plugin.pluginPath}", (complete) -> docpad.loadPlugin(plugin, complete) # Execute the loading asynchronously tasks.run() # Chain @ ###* # Load a plugin from its full file path # _next(err) # @private # @method loadPlugin # @param {Object} opts # @param {Function} _next # @param {Error} _next.err ### loadPlugin: (opts = {}, _next) -> # Prepare docpad = @ config = @getConfig() locale = @getLocale() next = (err) -> # Remove from slow plugins delete docpad.slowPlugins[pluginName] if pluginName # Forward _next(err) # Chain return docpad # Default opts opts.keyword ?= 'docpad-plugin' opts.prefix ?= 'docpad-plugin-' opts.BasePlugin ?= BasePlugin opts.log ?= @log # Load and validate the plugin try loader = new PluginLoader(opts) catch unsupportedError docpad.warn(new Errlop( util.format(locale.pluginUnsupported, opts.pluginPath), unsupportedError )) return next() # Prepare pluginName = loader.pluginName enabled = config.plugins[pluginName] isnt false # If we've already been loaded, then exit early as there is no use for us to load again if docpad.loadedPlugins[pluginName]? # However we probably want to reload the configuration as perhaps the user or environment configuration has changed docpad.loadedPlugins[pluginName].setConfig() # Complete return next() # Add to loading stores docpad.slowPlugins[pluginName] = true # Check unless enabled # Skip docpad.log 'info', util.format(locale.pluginDisabled, opts.pluginName) return next() else # Load docpad.log 'debug', util.format(locale.pluginLoading, opts.pluginPath) # Create an instance try # Add to plugin stores docpad.loadedPlugins[pluginName] = loader.create({docpad}) catch failedError err = new Errlop( util.format(locale.pluginFailed, opts.pluginPath), failedError ) return next(err) # Log completion docpad.log 'debug', util.format(locale.pluginLoaded, opts.pluginPath) return next() # ================================= # Utilities # --------------------------------- # Utilities: Files ###* # Contextualize files. # Contextualizing is the process of adding layouts and # awareness of other documents to our document. The # contextualizeBefore and contextualizeAfter events # are emitted here. # @private # @method contextualizeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### contextualizeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.contextualizingFiles, collection.length) # Start contextualizing docpad.emitSerial 'contextualizeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("contextualizeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'contextualizeAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.contextualizedFiles, collection.length) # Forward return next() # Add contextualize tasks collection.forEach (file,index) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') or file.id tasks.addTask "conextualizing: #{filePath}", (complete) -> file.action 'contextualize', (err) -> delete slowFilesObject[file.id] return complete(err) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'contextualizeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Render the DocPad project's files. # The renderCollectionBefore, renderCollectionAfter, # renderBefore, renderAfter events are all emitted here. # @private # @method renderFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### renderFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData,renderPasses} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.renderingFiles, collection.length) # Render File # next(null, outContent, file) renderFile = (file,next) -> # Render if file.get('render') is false or !file.get('relativePath') file.attributes.rtime = new Date() next(null, file.getOutContent(), file) else file.action('render', {templateData}, next) # Return return file # Render Collection renderCollection = (collectionToRender,{renderPass},next) -> # Plugin Event docpad.emitSerial 'renderCollectionBefore', {collection:collectionToRender,renderPass}, (err) -> # Prepare return next(err) if err subTasks = docpad.createTaskGroup("renderFiles: Pass #{renderPass}]: renderCollection: #{collectionToRender.options.name}", concurrency:0).done (err) -> # Prepare return next(err) if err # Plugin Event docpad.emitSerial('renderCollectionAfter', {collection:collectionToRender,renderPass}, next) # Cycle collectionToRender.forEach (file) -> filePath = file.getFilePath() slowFilesObject[file.id] = file.get('relativePath') subTasks.addTask "rendering: #{filePath}", (complete) -> renderFile file, (err) -> delete slowFilesObject[file.id] or file.id return complete(err) # Return subTasks.run() return collectionToRender # Plugin Event docpad.emitSerial 'renderBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Async tasks = docpad.createTaskGroup("renderFiles: renderCollection: renderBefore").done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'renderAfter', {collection}, (err) -> # Check return next(err) if err # Log docpad.log 'debug', util.format(locale.renderedFiles, collection.length) # Forward return next() # Queue the initial render initialCollection = collection.findAll('referencesOthers':false) subsequentCollection = null tasks.addTask "rendering the initial collection", (complete) -> renderCollection initialCollection, {renderPass:1}, (err) -> return complete(err) if err subsequentCollection = collection.findAll('referencesOthers':true) renderCollection(subsequentCollection, {renderPass:2}, complete) # Queue the subsequent renders if renderPasses > 1 [3..renderPasses].forEach (renderPass) -> tasks.addTask "rendering the subsequent collection index #{renderPass}", (complete) -> renderCollection(subsequentCollection, {renderPass}, complete) # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'renderFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ ###* # Write rendered files to the DocPad out directory. # The writeBefore and writeAfter events are emitted here. # @private # @method writeFiles # @param {Object} [opts={}] # @param {Function} next # @param {Error} next.err ### writeFiles: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) {collection,templateData} = opts docpad = @ config = @getConfig() locale = @getLocale() slowFilesObject = {} # Log docpad.log 'debug', util.format(locale.writingFiles, collection.length) # Plugin Event docpad.emitSerial 'writeBefore', {collection,templateData}, (err) -> # Prepare return next(err) if err # Completion callback tasks = docpad.createTaskGroup("writeFiles", concurrency:0).done (err) -> # Kill the timer docpad.timer('slowfiles') # Check return next(err) if err # After docpad.emitSerial 'writeAfter', {collection}, (err) -> # Check return next(err) if err # docpad.log 'debug', util.format(locale.wroteFiles, collection.length) return next() # Add write tasks collection.forEach (file,index) -> filePath = file.getFilePath() tasks.addTask "writing the file: #{filePath}", (complete) -> # Prepare slowFilesObject[file.id] = file.get('relativePath') # Create sub tasks fileTasks = docpad.createTaskGroup("tasks for file write: #{filePath}", concurrency:0).done (err) -> delete slowFilesObject[file.id] return complete(err) # Write out if file.get('write') isnt false and file.get('outPath') fileTasks.addTask "write out", (complete) -> file.action('write', complete) # Write source if file.get('writeSource') is true and file.get('fullPath') fileTasks.addTask "write source", (complete) -> file.action('writeSource', complete) # Run sub tasks fileTasks.run() # Setup the timer docpad.timer 'slowfiles', 'interval', config.slowFilesDelay, -> slowFilesArray = (value or key for own key,value of slowFilesObject) docpad.log('info', util.format(locale.slowFiles, 'writeFiles')+' \n'+slowFilesArray.join('\n')) # Run tasks tasks.run() # Chain @ # --------------------------------- # Generate # Generate Helpers ###* # Has DocPad's generation process started? # @private # @property {Boolean} generateStarted ### generateStarted: null ###* # Has DocPad's generation process ended? # @private # @property {Boolean} generateEnded ### generateEnded: null ###* # Is DocPad currently generating? # @private # @property {Boolean} generating ### generating: false ###* # Has DocPad done at least one generation? # True once the first generation has occured. # @private # @property {Object} generated ### generated: false ###* # Set off DocPad's generation process. # The generated, populateCollectionsBefore, populateCollections, populateCollections # generateBefore and generateAfter events are emitted here # @method generate # @param {Object} opts # @param {Function} next # @param {Error} next.err ### generate: (opts, next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = docpad.getConfig() locale = docpad.getLocale() database = docpad.getDatabase() # Check return next() if opts.collection?.length is 0 # Update generating flag lastGenerateStarted = docpad.generateStarted docpad.generateStarted = new Date() docpad.generateEnded = null docpad.generating = true # Grab the template data we will use for rendering opts.templateData = docpad.getTemplateData(opts.templateData or {}) # How many render passes will we require? # Can be over-written by API calls opts.renderPasses or= config.renderPasses # Destroy Regenerate Timer docpad.timer('regenerate') # Check plugin count docpad.log('notice', locale.renderNoPlugins) unless docpad.hasPlugins() # Log docpad.log('info', locale.renderGenerating) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratingNotification} # Tasks tasks = @createTaskGroup("generate tasks").done (err) -> # Update generating flag docpad.generating = false docpad.generateEnded = new Date() # Create Regenerate Timer if config.regenerateEvery docpad.timer 'regenerate', 'timeout', config.regenerateEvery, -> docpad.log('info', locale.renderInterval) docpad.action('generate', config.regenerateEveryOptions) # Error? return next(err) if err # Log success message seconds = (docpad.generateEnded - docpad.generateStarted) / 1000 howMany = "#{opts.collection?.length or 0}/#{database.length}" docpad.log 'info', util.format(locale.renderGenerated, howMany, seconds) docpad.notify (new Date()).toLocaleTimeString(), {title: locale.renderGeneratedNotification} # Generated if opts.initial is true docpad.generated = true return docpad.emitSerial('generated', opts, next) # Safety check if generated is false but initial was false too # https://github.com/bevry/docpad/issues/811 else if docpad.generated is false return next( new Errlop('DocPad is in an invalid state, please report this. Reference 3360') ) else return next() # Extract functions from tasks for simplicity # when dealing with nested tasks/groups addGroup = tasks.addGroup.bind(tasks) addTask = tasks.addTask.bind(tasks) # Setup a clean database addTask 'Reset our collections', (complete) -> # Skip if we are not a reset generation, or an initial generation (generated is false) return complete() unless opts.reset is true or docpad.generated is false return docpad.resetCollections(opts, complete) # Figure out the options # This is here as resetCollections could change our state # https://github.com/bevry/docpad/issues/811 addTask 'Figure out options', -> # Mode: Initial # Shall we do some basic initial checks # Set to the opts.reset value if specified, or whether are the initial generation opts.initial ?= !(docpad.generated) # Mode: Reset # Shall we reset the database # Set to true if we are the initial generation opts.reset ?= opts.initial # Mode: Populate # Shall we fetch in new data? # Set to the opts.reset value if specified, or the opts.initial value opts.populate ?= opts.reset # Mode: Reload # Shall we rescan the file system for changes? # Set to the opts.reset value if specified, or the opts.initial value opts.reload ?= opts.reset # Mode: Partial # Shall we perform a partial generation (false) or a completion generation (true)? # Set to false if we are the initial generation opts.partial ?= !(opts.reset) # Log our opts docpad.log( 'debug' 'Generate options:' pick(opts, ['initial', 'reset', 'populate', 'reload', 'partial', 'renderPasses']) ) # Check directory structure addTask 'check source directory exists', (complete) -> # Skip if we are not the initial generation return complete() unless opts.initial is true # Continue if we are the initial generation sourcePath = docpad.getPath('source') unless sourcePath err = new Errlop(util.format(locale.renderNonexistant, docpad.getPath(false, 'source'))) return complete(err) # Forward return complete() # Check directory structure addTask 'ensure out directory exists', (complete) -> outPath = docpad.getPath(false, 'out') return safefs.ensurePath(outPath, complete) addGroup 'fetch data to render', (addGroup, addTask) -> # Fetch new data # If we are a populate generation (by default an initial generation) if opts.populate is true # This will pull in new data from plugins addTask 'populateCollectionsBefore', (complete) -> docpad.emitSerial('populateCollectionsBefore', opts, complete) # Rescan the file system # If we are a reload generation (by default an initial generation) # This is useful when the database is out of sync with the source files # For instance, someone shut down docpad, and made some changes, then ran docpad again # See https://github.com/bevry/docpad/issues/705#issuecomment-29243666 for details if opts.reload is true addGroup 'import data from file system', (addGroup, addTask) -> # Documents docpad.getPath('documents').forEach (documentsPath) -> addTask 'import documents', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: documentsPath next: complete }) # Files docpad.getPath('files').forEach (filesPath) -> addTask 'import files', (complete) -> docpad.parseDirectory({ modelType: 'file' collection: database path: filesPath next: complete }) # Layouts docpad.getPath('layouts').forEach (layoutsPath) -> addTask 'import layouts', (complete) -> docpad.parseDirectory({ modelType: 'document' collection: database path: layoutsPath next: complete }) # This will pull in new data from plugins addTask 'populateCollections', (complete) -> docpad.emitSerial('populateCollections', opts, complete) addGroup 'determine files to render', (addGroup, addTask) -> # Perform a complete regeneration if opts.partial is false # Use Entire Collection addTask 'Add all database models to render queue', -> opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').models) # Perform a partial regeneration # If we are not a reset generation (by default any non-initial generation) else # Use Partial Collection addTask 'Add only changed models to render queue', -> changedQuery = $or: # Get changed files mtime: $gte: lastGenerateStarted # Get new files $and: wtime: null write: true opts.collection ?= new FilesCollection().add(docpad.getCollection('generate').findAll(changedQuery).models) addTask 'generateBefore', (complete) -> # If we have nothing to generate if opts.collection.length is 0 # then there is no need to execute further tasks tasks.clear() complete() # Otherwise continue down the task loop else docpad.emitSerial('generateBefore', opts, complete) addTask 'prepare files', (complete) -> # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Add anything that references other documents (e.g. partials, listing, etc) # This could eventually be way better standalones = opts.collection.pluck('standalone') allStandalone = standalones.indexOf(false) is -1 if allStandalone is false opts.collection.add(docpad.getCollection('referencesOthers').models) # Deeply/recursively add the layout children addLayoutChildren = (collection) -> collection.forEach (file) -> if file.get('isLayout') is true # Find layoutChildrenQuery = layoutRelativePath: file.get('relativePath') layoutChildrenCollection = docpad.getCollection('hasLayout').findAll(layoutChildrenQuery) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Layout children to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') write: model.get('write') } for model in layoutChildrenCollection.models ), '\n', layoutChildrenQuery # Recurse addLayoutChildren(layoutChildrenCollection) # Add opts.collection.add(layoutChildrenCollection.models) addLayoutChildren(opts.collection) # Filter out ignored, and no-render no-write files opts.collection.reset opts.collection.reject (file) -> return (file.get('render') is false and file.get('write') is false) # Log the files to generate if we are in debug mode docpad.log 'debug', 'Files to generate at', (lastGenerateStarted), '\n', ( { id: model.id path: model.getFilePath() mtime: model.get('mtime') wtime: model.get('wtime') ignored: model.get('ignored') write: model.get('write') } for model in opts.collection.models ) # Forward return complete() addGroup 'process file', (addGroup, addTask) -> addTask 'contextualizeFiles', {args:[opts]}, docpad.contextualizeFiles.bind(docpad) addTask 'renderFiles', {args:[opts]}, docpad.renderFiles.bind(docpad) addTask 'writeFiles', {args:[opts]}, docpad.writeFiles.bind(docpad) addTask 'generateAfter', (complete) -> docpad.emitSerial('generateAfter', opts, complete) # Run tasks.run() # Chain @ # --------------------------------- # Render ###* # Load a document # @private # @method loadDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Load # @TODO: don't load if already loaded document.action('load contextualize', opts, next) # Chain @ ###* # Load and render a document # @method loadAndRenderDocument # @param {Object} document # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.document ### loadAndRenderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ # Load docpad.loadDocument document, opts, (err) -> return next(err) if err # Render docpad.renderDocument(document, opts, next) # Chain @ ###* # Render a document # @method renderDocument # @param {Object} document # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### renderDocument: (document,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) # Render clone = document.clone().action 'render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render a document at a file path # next(err,result) # @method renderPath # @param {String} path # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderPath: (path,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ fullPath: path }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ ###* # Render the passed content data as a # document. Required option, filename # (opts.filename) # next(err,result) # @method renderData # @param {String} content # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered document ### renderData: (content,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) attributes = extendr.extend({ filename: opts.filename data: content }, opts.attributes or {}) # Handle document = @createDocument(attributes) @loadAndRenderDocument(document, opts, next) # Chain @ # Render Text # Doesn't extract meta information, or render layouts # TODO: Why not? Why not just have renderData? ###* # Render the passed text data as a # document. Required option, filename # (opts.filename) # next(err,result) # @private # @method renderText # @param {String} text # @param {Object} opts # @param {Function} next # @param {Error} next.err # @param {Object} next.result the rendered content # @param {Object} next.document the rendered document model ### renderText: (text,opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) opts.actions ?= ['renderExtensions', 'renderDocument'] attributes = extendr.extend({ filename: opts.filename data: text body: text content: text }, opts.attributes or {}) # Handle document = @createDocument(attributes) # Render clone = document.clone().action 'normalize contextualize render', opts, (err) -> result = clone.getOutContent() return next(err, result, document) # Chain @ ###* # Render action # @method render # @param {Object} opts # @param {Object} next # @param {Error} next.err # @param {Object} next.result # @param {Object} next.document ### render: (opts,next) -> # Prepare docpad = @ locale = @getLocale() config = @getConfig() [opts,next] = extractOptsAndCallback(opts,next) opts.stdin ?= false # Completion unless opts.output complete = next else complete = (err, result, document) -> # Forward return next(err) if err # Output if opts.output is true process.stdout.write(result) else if opts.output return safefs.writeFile opts.output, result, (err) -> return next(err, result, document) # Forward return next(null, result, document) # Render if opts.stdin docpad.renderStdin(opts, complete) else if opts.document docpad.renderDocument(opts.document, opts, complete) else if opts.data docpad.renderData(opts.data, opts, complete) else if opts.text docpad.renderText(opts.text, opts, complete) else path = opts.path or opts.fullPath or opts.filename or null if path docpad.renderPath(path, opts, complete) else err = new Errlop(locale.renderInvalidOptions) return complete(err) # Chain @ renderStdin: (opts, next) -> # Prepare docpad = @ [opts,next] = extractOptsAndCallback(opts,next) data = '' # Read stdin = process.stdin stdin.resume() stdin.setEncoding('utf8') stdin.on 'data', (_data) -> docpad.timer('render') data += _data.toString() process.stdin.on 'end', -> docpad.timer('render') docpad.renderData(data, opts, next) # Chain @ # --------------------------------- # Watch ###* # Array of file watchers # @private # @property {Array} watchers ### watchers: null ###* # Destructor. Destroy the watchers used # by DocPad # @private # @method destroyWatchers ### destroyWatchers: -> # Prepare docpad = @ # Check if docpad.watchers # Close each of them for watcher in docpad.watchers watcher.close() # Reset the array docpad.watchers = [] # Chain @ ###* # Start up file watchers used by DocPad # @private # @method watch # @param {Object} opts # @param {Function} next # @param {Error} next.err ### watch: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() database = @getDatabase() @watchers ?= [] # Restart our watchers restartWatchers = (next) -> # Close our watchers docpad.destroyWatchers() # Start a group tasks = docpad.createTaskGroup("watch tasks", concurrency:0).done(next) # Watch reload paths reloadPaths = union(docpad.getPath('reloads'), docpad.getPath('configs')) tasks.addTask "watch reload paths", (complete) -> docpad.watchdirs( reloadPaths, { 'log': docpad.log 'error': docpad.error 'change': -> docpad.log 'info', util.format(locale.watchReloadChange, new Date().toLocaleTimeString()) docpad.action 'load', (err) -> return docpad.fatal(err) if err performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the reload paths has failed:\n"+docpad.inspect(reloadPaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch regenerate paths regeneratePaths = docpad.getPath('regenerates') tasks.addTask "watch regenerate paths", (complete) -> docpad.watchdirs( regeneratePaths, { 'log': docpad.log 'error': docpad.error 'change': -> performGenerate(reset:true) }, (err,_watchers) -> if err docpad.warn("Watching the regenerate paths has failed:\n"+docpad.inspect(regeneratePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Watch the source sourcePaths = docpad.getPath('sources') tasks.addTask "watch the source path", (complete) -> docpad.watchdirs( sourcePaths, { 'log': docpad.log 'error': docpad.error 'change': changeHandler }, (err,_watchers) -> if err docpad.warn("Watching the source paths has failed:\n"+docpad.inspect(sourcePaths), err) return complete() for watcher in _watchers docpad.watchers.push(watcher) return complete() ) # Run tasks.run() # Chain @ # Timer queueRegeneration = -> docpad.timer('regeneration', 'timeout', config.regenerateDelay, performGenerate) # Generate performGenerate = (opts={}) -> # Q: Should we also pass over the collection? # A: No, doing the mtime query in generate is more robust # Log docpad.log util.format(locale.watchRegenerating, new Date().toLocaleTimeString()) # Afterwards, re-render anything that should always re-render docpad.action 'generate', opts, (err) -> docpad.error(err) if err docpad.log util.format(locale.watchRegenerated, new Date().toLocaleTimeString()) # Change event handler changeHandler = (changeType,filePath,fileCurrentStat,filePreviousStat) -> # Prepare fileEitherStat = (fileCurrentStat or filePreviousStat) # For some reason neither of the stats may exist, this will cause errors as this is an invalid state # as we depend on at least one stat existing, otherwise, what on earth is going on? # Whatever the case, this should be fixed within watchr, not docpad # as watchr should not be giving us invalid data # https://github.com/bevry/docpad/issues/792 unless fileEitherStat err = new Errlop(""" DocPad has encountered an invalid state while detecting changes for your files. So the DocPad team can fix this right away, please provide any information you can to: https://github.com/bevry/docpad/issues/792 """) return docpad.error(err) # Log the change docpad.log 'info', util.format(locale.watchChange, new Date().toLocaleTimeString()), changeType, filePath # Check if we are a file we don't care about # This check should not be needed with v2.3.3 of watchr # however we've still got it here as it may still be an issue isIgnored = docpad.isIgnoredPath(filePath) if isIgnored docpad.log 'debug', util.format(locale.watchIgnoredChange, new Date().toLocaleTimeString()), filePath return # Don't care if we are a directory isDirectory = fileEitherStat.isDirectory() if isDirectory docpad.log 'debug', util.format(locale.watchDirectoryChange, new Date().toLocaleTimeString()), filePath return # Override the stat's mtime to now # This is because renames will not update the mtime fileCurrentStat?.mtime = new Date() # Create the file object file = docpad.addModel({fullPath:filePath, stat:fileCurrentStat}) file.setStat(fileCurrentStat) if changeType is 'update' # File was deleted, delete the rendered file, and remove it from the database if changeType is 'delete' database.remove(file) file.action 'delete', (err) -> return docpad.error(err) if err queueRegeneration() # File is new or was changed, update it's mtime by setting the stat else if changeType in ['create', 'update'] file.action 'load', (err) -> return docpad.error(err) if err queueRegeneration() # Watch docpad.log(locale.watchStart) restartWatchers (err) -> return next(err) if err docpad.log(locale.watchStarted) return next() # Chain @ # --------------------------------- # Run Action ###* # Run an action # @method run # @param {Object} opts # @param {Function} next # @param {Error} next.err ### run: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts, next) docpad = @ locale = @getLocale() config = @getConfig() # Prepare run = (next) -> docpad.emitSerial 'runBefore', (err) -> return next(err) if err balUtil.flow( object: docpad action: 'generate watch' args: [opts] next: (err) -> docpad.emitSerial('runAfter', next) ) # Check if have the correct structure, if so let's proceed with DocPad sourcePath = @getPath('source') return run(next) if sourcePath # We don't have the correct structure # Check if we are running on an empty directory rootPath = @getPath('root') safefs.readdir rootPath, (err,files) -> return next(err) if err # Check if our directory is empty if files.length # It isn't empty, display a warning docpad.warn util.format(locale.invalidProject, rootPath) return next() else docpad.init opts, (err) -> # Check return next(err) if err # Keep in global? return run(next) if opts.global is true or docpad.getConfig().global is true # Log docpad.log('notice', locale.startLocal) # Destroy our DocPad instance so we can boot the local one docpad.destroy (err) -> # Check return next(err) if err # Forward onto the local DocPad Instance now that it has been installed return docpadUtil.startLocalDocPadExecutable(next) # Chain @ ###* # Info action # @private # @method info # @param {Object} opts # @param {Function} next ### info: (opts, next) -> [opts,next] = extractOptsAndCallback(opts,next) console.log @inspect @getConfig() next?() @ # --------------------------------- # Project ###* # Initialize the project install process. # @private # @method initInstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### initInstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Exists? packagePath = @getPath(false, 'package') safefs.exists packagePath, (exists) -> # Check return next() if exists # Write data = JSON.stringify({ name: 'no-skeleton.docpad' version: '0.1.0' description: 'New DocPad project without using a skeleton' dependencies: docpad: '~'+docpad.getVersion() scripts: start: 'docpad run' test: 'docpad generate' }, null, ' ') safefs.writeFile(packagePath, data, next) # Chain @ ###* # Uninstall a plugin. # @private # @method uninstall # @param {Object} opts # @param {Function} next # @param {Error} next.err ### uninstall: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("uninstall tasks").done(next) # Uninstall a plugin if opts.plugin tasks.addTask "uninstall the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin docpad.uninstallNodeModule(plugins, complete) # Re-load configuration tasks.addTask "re-load configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Install a plugin # @private # @method install # @param {Object} opts # @param {Function} next # @param {Error} next.err ### install: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("install tasks").done(next) tasks.addTask "init the installation", (complete) -> docpad.initInstall(opts, complete) # Install a plugin if opts.plugin tasks.addTask "install the plugin: #{opts.plugin}", (complete) -> plugins = for plugin in opts.plugin.split(/[,\s]+/) plugin = "docpad-plugin-#{plugin}" if plugin.indexOf('docpad-plugin-') isnt 0 plugin += '@'+docpad.pluginVersion if plugin.indexOf('@') is -1 plugin docpad.installNodeModule(plugins, complete) tasks.addTask "re-initialize the website's modules", (complete) -> docpad.initNodeModules(complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-load the configuration", (complete) -> docpad.load(complete) # Run tasks.run() # Chain @ ###* # Update global NPM and DocPad # @private # @method upgrade # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### upgrade: (opts,next) -> # Update Global NPM and DocPad @installNodeModule('npm docpad@6', {global: true}, next) # Chain @ ###* # Update the local DocPad and plugin dependencies # @private # @method update # @param {Object} opts # @param {Object} next # @param {Error} next.err ### update: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() # Tasks tasks = @createTaskGroup("update tasks").done(next) tasks.addTask "init the install", (complete) -> docpad.initInstall(opts, complete) # Update the local docpad and plugin dependencies # Grouped together to avoid npm dependency shortcuts that can cause missing dependencies # But don't update git/http/https dependencies, those are special for some reason # > https://github.com/bevry/docpad/pull/701 dependencies = [] eachr docpad.websitePackageConfig.dependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false or /// :// ///.test(version) is true dependencies.push(name+'@'+docpad.pluginVersion) if dependencies.length isnt 0 tasks.addTask "update plugins that are dependencies", (complete) -> docpad.installNodeModule('docpad@6 '+dependencies, complete) # Update the plugin dev dependencies devDependencies = [] eachr docpad.websitePackageConfig.devDependencies, (version,name) -> return if /^docpad-plugin-/.test(name) is false devDependencies.push(name+'@'+docpad.pluginVersion) if devDependencies.length isnt 0 tasks.addTask "update plugins that are dev dependencies", (complete) -> docpad.installNodeModule(devDependencies, {save: '--save-dev'}, complete) tasks.addTask "fix node package versions", (complete) -> docpad.fixNodePackageVersions(complete) tasks.addTask "re-initialize the rest of the website's modules", (complete) -> docpad.initNodeModules(complete) # Run tasks.run() # Chain @ ###* # DocPad cleanup tasks. # @private # @method clean # @param {Object} opts # @param {Object} next # @param {Error} next.err # @return {Object} description ### clean: (opts,next) -> # Prepare [opts,next] = extractOptsAndCallback(opts,next) docpad = @ config = @getConfig() locale = @getLocale() paths = [] # Log docpad.log('info', locale.cleanStarted) # Tasks tasks = @createTaskGroup("clean tasks", concurrency:0).done (err) -> # Error? return next(err) if err # Log message = util.format( locale.cleanFinish, paths.length ) if paths.length message += ': ' if paths.length isnt 1 message += '\n' message += paths.join('\n') docpad.log('info', message) # Forward return next() tasks.addTask 'reset the collections', (complete) -> docpad.resetCollections(opts, complete) # Delete out path # but only if our outPath is not a parent of our rootPath tasks.addTask 'delete out path', (complete) -> rootPath = docpad.getPath('root') outPath = docpad.getPath('out') # Only remove outpath if it does not contain our root path if outPath and pathUtil.relative(outPath, rootPath).startsWith('..') paths.push(outPath) rimraf(outPath, complete) else complete() # Run tasks tasks.run() # Chain @ ###* # Initialize the directory for DocPad # @private # @method init # @param {Function} next # @param {Error} next.err ### init: (opts,next) -> # Prepare docpad = @ config = @getConfig() rootPath = @getPath(false, 'root') # Tasks tasks = @createTaskGroup("init tasks").done(next) tasks.addTask "ensure the path we are writing to exists", (complete) -> safefs.ensurePath(rootPath, complete) tasks.addTask "ensure src path exists", (complete) -> safefs.ensurePath(docpad.getPath(false, 'source'), complete) tasks.addGroup "initialize the website directory files", -> @setConfig(concurrency:0) # README @addTask "README.md", (complete) -> readmePath = docpad.getPath(false, 'root', 'README.md') data = """ # Your [DocPad](https://docpad.bevry.me) Project ## License Copyright &copy; #{(new Date()).getFullYear()}+ All rights reserved. """ safefs.writeFile(readmePath, data, complete) # Config @addTask "docpad.coffee configuration file", (complete) -> configPath = docpad.getPath(false, 'root', 'docpad.js') data = """ // DocPad Configuration File // https://docpad.bevry.me/config // Define the DocPad Configuration const docpadConfig = { // ... } // Export the DocPad Configuration module.exports = docpadConfig """ safefs.writeFile(configPath, data, complete) # Documents @addTask "documents directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'document'), complete) # Layouts @addTask "layouts directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'layout'), complete) # Files @addTask "files directory", (complete) -> safefs.ensurePath(docpad.getPath(false, 'file'), complete) # Run tasks.run() # Chain @ # --------------------------------- # Export module.exports = DocPad
[ { "context": "###\n Copyright (c) 2016, Mollie B.V.\n All rights reserved.\n\n Redistribution and use", "end": 36, "score": 0.9481950998306274, "start": 26, "tag": "NAME", "value": "Mollie B.V" }, { "context": "source.org/licenses/bsd-license.php\n @author Mollie B.V. <info@mollie.nl>\n @copyright Mollie B.V.\n @l", "end": 1465, "score": 0.9350435137748718, "start": 1455, "tag": "NAME", "value": "Mollie B.V" }, { "context": "enses/bsd-license.php\n @author Mollie B.V. <info@mollie.nl>\n @copyright Mollie B.V.\n @link https:", "end": 1482, "score": 0.9999225735664368, "start": 1468, "tag": "EMAIL", "value": "info@mollie.nl" } ]
src/lib/mollie/api/client.coffee
veselinoskih/mollie-test
0
### Copyright (c) 2016, Mollie B.V. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @license Berkeley Software Distribution License (BSD-License 2) http://www.opensource.org/licenses/bsd-license.php @author Mollie B.V. <info@mollie.nl> @copyright Mollie B.V. @link https://www.mollie.nl ### url = require("url"); fs = require("fs"); https = require("https"); Payments = require("./resource/payments"); PaymentsRefunds = require("./resource/payments/refunds"); Methods = require("./resource/methods"); Issuers = require("./resource/issuers"); Customers = require("./resource/customers"); CustomersPayments = require("./resource/customers/payments"); CustomersMandates = require("./resource/customers/mandates"); CustomersSubscriptions = require("./resource/customers/subscriptions"); module.exports = class Client this.version = "1.3.5"; constructor: () -> this.config = { endpoint: "https://api.mollie.nl", version: "v1", key: "", }; this.payments = new Payments(this); this.payments_refunds = new PaymentsRefunds(this); this.methods = new Methods(this); this.issuers = new Issuers(this); this.customers = new Customers(this); this.customers_payments = new CustomersPayments(this); this.customers_mandates = new CustomersMandates(this); this.customers_subscriptions = new CustomersSubscriptions(this); setApiEndpoint: (endpoint) -> this.config.endpoint = endpoint; setApiKey: (key) -> this.config.key = key; callRest: (method, resource, id, data, callback) -> id = id || ''; parsedUrl = url.parse("#{@config.endpoint}/#{@config.version}/#{resource}/#{id}"); parsedUrl.method = method; parsedUrl.rejectUnauthorized = true; parsedUrl.cert = fs.readFileSync(__dirname + "/cacert.pem"); parsedUrl.headers = { Authorization: "Bearer #{@config.key}", Accept: "application/json", 'User-Agent': "Mollie/#{@constructor.version} Node/#{process.version}" }; request = https.request(parsedUrl); request.on("response", (response) -> body = ""; response.on("data", (data) -> body += data.toString(); ); response.on("end", -> callback(JSON.parse(body)) ); ); request.write(JSON.stringify(data)); request.end();
81997
### Copyright (c) 2016, <NAME>. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @license Berkeley Software Distribution License (BSD-License 2) http://www.opensource.org/licenses/bsd-license.php @author <NAME>. <<EMAIL>> @copyright Mollie B.V. @link https://www.mollie.nl ### url = require("url"); fs = require("fs"); https = require("https"); Payments = require("./resource/payments"); PaymentsRefunds = require("./resource/payments/refunds"); Methods = require("./resource/methods"); Issuers = require("./resource/issuers"); Customers = require("./resource/customers"); CustomersPayments = require("./resource/customers/payments"); CustomersMandates = require("./resource/customers/mandates"); CustomersSubscriptions = require("./resource/customers/subscriptions"); module.exports = class Client this.version = "1.3.5"; constructor: () -> this.config = { endpoint: "https://api.mollie.nl", version: "v1", key: "", }; this.payments = new Payments(this); this.payments_refunds = new PaymentsRefunds(this); this.methods = new Methods(this); this.issuers = new Issuers(this); this.customers = new Customers(this); this.customers_payments = new CustomersPayments(this); this.customers_mandates = new CustomersMandates(this); this.customers_subscriptions = new CustomersSubscriptions(this); setApiEndpoint: (endpoint) -> this.config.endpoint = endpoint; setApiKey: (key) -> this.config.key = key; callRest: (method, resource, id, data, callback) -> id = id || ''; parsedUrl = url.parse("#{@config.endpoint}/#{@config.version}/#{resource}/#{id}"); parsedUrl.method = method; parsedUrl.rejectUnauthorized = true; parsedUrl.cert = fs.readFileSync(__dirname + "/cacert.pem"); parsedUrl.headers = { Authorization: "Bearer #{@config.key}", Accept: "application/json", 'User-Agent': "Mollie/#{@constructor.version} Node/#{process.version}" }; request = https.request(parsedUrl); request.on("response", (response) -> body = ""; response.on("data", (data) -> body += data.toString(); ); response.on("end", -> callback(JSON.parse(body)) ); ); request.write(JSON.stringify(data)); request.end();
true
### Copyright (c) 2016, PI:NAME:<NAME>END_PI. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. @license Berkeley Software Distribution License (BSD-License 2) http://www.opensource.org/licenses/bsd-license.php @author PI:NAME:<NAME>END_PI. <PI:EMAIL:<EMAIL>END_PI> @copyright Mollie B.V. @link https://www.mollie.nl ### url = require("url"); fs = require("fs"); https = require("https"); Payments = require("./resource/payments"); PaymentsRefunds = require("./resource/payments/refunds"); Methods = require("./resource/methods"); Issuers = require("./resource/issuers"); Customers = require("./resource/customers"); CustomersPayments = require("./resource/customers/payments"); CustomersMandates = require("./resource/customers/mandates"); CustomersSubscriptions = require("./resource/customers/subscriptions"); module.exports = class Client this.version = "1.3.5"; constructor: () -> this.config = { endpoint: "https://api.mollie.nl", version: "v1", key: "", }; this.payments = new Payments(this); this.payments_refunds = new PaymentsRefunds(this); this.methods = new Methods(this); this.issuers = new Issuers(this); this.customers = new Customers(this); this.customers_payments = new CustomersPayments(this); this.customers_mandates = new CustomersMandates(this); this.customers_subscriptions = new CustomersSubscriptions(this); setApiEndpoint: (endpoint) -> this.config.endpoint = endpoint; setApiKey: (key) -> this.config.key = key; callRest: (method, resource, id, data, callback) -> id = id || ''; parsedUrl = url.parse("#{@config.endpoint}/#{@config.version}/#{resource}/#{id}"); parsedUrl.method = method; parsedUrl.rejectUnauthorized = true; parsedUrl.cert = fs.readFileSync(__dirname + "/cacert.pem"); parsedUrl.headers = { Authorization: "Bearer #{@config.key}", Accept: "application/json", 'User-Agent': "Mollie/#{@constructor.version} Node/#{process.version}" }; request = https.request(parsedUrl); request.on("response", (response) -> body = ""; response.on("data", (data) -> body += data.toString(); ); response.on("end", -> callback(JSON.parse(body)) ); ); request.write(JSON.stringify(data)); request.end();
[ { "context": "rt '/rpc'\n\n# Set the application title\napp.title 'Ask Craig'\n\n# Hide the footer\nhide app.footer\n\n# This", "end": 845, "score": 0.649749755859375, "start": 842, "tag": "NAME", "value": "Ask" }, { "context": "rpc'\n\n# Set the application title\napp.title 'Ask Craig'\n\n# Hide the footer\nhide app.footer\n\n# This is a ", "end": 851, "score": 0.5048059225082397, "start": 847, "tag": "NAME", "value": "raig" } ]
07-final-app/app-ask-craig-master/web/app.coffee
h2oai/qcon2015
20
# # This is the source code for the user interface. # # The HTML, stylesheet and necessary javascript files are automatically added # by the fluid compiler. # # You can install the fluid compiler using: # npm install fluid-lang -g # # The `fluid` compiler command looks something like this: # fluid --compile app.coffee \ # --include-js lib/thrift/lib/js/src/thrift.js \ # --include-js gen-js/web_types.js \ # --include-js gen-js/Web.js # # See this app's package.json for more tasks. # # Create a ref to the app server via the bundled Apache Thrift # XHR/JSON RPC client. # Also, export it to the window so that we can run RPC calls # from the in-browser Fluid REPL. window.server = server = new App.WebClient new Thrift.TJSONProtocol new Thrift.TXHRTransport '/rpc' # Set the application title app.title 'Ask Craig' # Hide the footer hide app.footer # This is a function that creates the UI for a list of jobs. createJobListing = (jobs) -> # A job listing is a block of jobs, each of which is a card. block jobs.map (job) -> card # The card displays the title and category. items: [ body2 job.title caption "Category: #{job.category}" ] # The card has a menu with an Edit command . menu: menu [ command 'Edit', -> alert 'not implemented' ] # Allow the card to expand to available width, and collapse to # minimum height. style: width: 'auto' minHeight: 'auto' # This is a function that fetches latest jobs from the server refreshJobListings = -> server.listJobs 0, 25, (jobs) -> # Fill the job listing view with jobs, if available. if jobs then set jobListingView, createJobListing jobs # This is a function that creates a view to add/edit a job posting. createJobView = -> # The job title field is a text area. jobTitleField = textarea title: 'Job Description' # The job category field is a text field. jobCategoryField = textfield 'NA', title: 'Category' # Tells the app server to save the new job posting. createJob = -> # A new job is composed of the values from our two fields. job = new App.Job title: get jobTitleField category: get jobCategoryField # Create the job... server.createJob job, -> # ... clear the title field set jobTitleField, '' # ... and go back to our list of jobs. showJobListingView() # The form itself is a card containing our two fields. self = card title: 'Add a new job posting' items: [ block jobTitleField block jobCategoryField ] buttons: [ # The post button creates a job and saves the economy ftw. button 'Post', color: 'accent', createJob # The dismiss button simply goes back to our list of jobs. button 'Dismiss', showJobListingView ] # Expand the form's width to fit the screen. style: width: 'auto' # This function prefills the job category, given a title. prefillJobCategory = (jobTitle) -> # Ask the server for the predicted category... server.predictJobCategory jobTitle, (category) -> # ... then update the job category field. set jobCategoryField, category # Whenever the job title changes, prefill the job category, # (but do this once in 500ms to go easy on the server). bind jobTitleField, _.throttle prefillJobCategory, 500 self # Shows the job listings. showJobListingView = -> hide jobView show jobListingView show buttonContainer refreshJobListings() # Shows the job view. showJobView = -> hide jobListingView hide buttonContainer show jobView # Create a job listing view (an empty block). jobListingView = block() # Create a job view. jobView = createJobView() # Create a FAB (a floating action button). addJobButton = button 'add', type: 'floating', color: 'primary' # Put the button in a block positioned to the bottom right, # on top of everything else. buttonContainer = block addJobButton, style: position: 'absolute' right: '10px' bottom: '10px' zIndex: 100 # Show the job view when the button is pressed. bind addJobButton, showJobView # Set the contents of the active page . set activePage, [ jobListingView, buttonContainer, jobView ] # Show the job listing as our initial view. showJobListingView()
48594
# # This is the source code for the user interface. # # The HTML, stylesheet and necessary javascript files are automatically added # by the fluid compiler. # # You can install the fluid compiler using: # npm install fluid-lang -g # # The `fluid` compiler command looks something like this: # fluid --compile app.coffee \ # --include-js lib/thrift/lib/js/src/thrift.js \ # --include-js gen-js/web_types.js \ # --include-js gen-js/Web.js # # See this app's package.json for more tasks. # # Create a ref to the app server via the bundled Apache Thrift # XHR/JSON RPC client. # Also, export it to the window so that we can run RPC calls # from the in-browser Fluid REPL. window.server = server = new App.WebClient new Thrift.TJSONProtocol new Thrift.TXHRTransport '/rpc' # Set the application title app.title '<NAME> C<NAME>' # Hide the footer hide app.footer # This is a function that creates the UI for a list of jobs. createJobListing = (jobs) -> # A job listing is a block of jobs, each of which is a card. block jobs.map (job) -> card # The card displays the title and category. items: [ body2 job.title caption "Category: #{job.category}" ] # The card has a menu with an Edit command . menu: menu [ command 'Edit', -> alert 'not implemented' ] # Allow the card to expand to available width, and collapse to # minimum height. style: width: 'auto' minHeight: 'auto' # This is a function that fetches latest jobs from the server refreshJobListings = -> server.listJobs 0, 25, (jobs) -> # Fill the job listing view with jobs, if available. if jobs then set jobListingView, createJobListing jobs # This is a function that creates a view to add/edit a job posting. createJobView = -> # The job title field is a text area. jobTitleField = textarea title: 'Job Description' # The job category field is a text field. jobCategoryField = textfield 'NA', title: 'Category' # Tells the app server to save the new job posting. createJob = -> # A new job is composed of the values from our two fields. job = new App.Job title: get jobTitleField category: get jobCategoryField # Create the job... server.createJob job, -> # ... clear the title field set jobTitleField, '' # ... and go back to our list of jobs. showJobListingView() # The form itself is a card containing our two fields. self = card title: 'Add a new job posting' items: [ block jobTitleField block jobCategoryField ] buttons: [ # The post button creates a job and saves the economy ftw. button 'Post', color: 'accent', createJob # The dismiss button simply goes back to our list of jobs. button 'Dismiss', showJobListingView ] # Expand the form's width to fit the screen. style: width: 'auto' # This function prefills the job category, given a title. prefillJobCategory = (jobTitle) -> # Ask the server for the predicted category... server.predictJobCategory jobTitle, (category) -> # ... then update the job category field. set jobCategoryField, category # Whenever the job title changes, prefill the job category, # (but do this once in 500ms to go easy on the server). bind jobTitleField, _.throttle prefillJobCategory, 500 self # Shows the job listings. showJobListingView = -> hide jobView show jobListingView show buttonContainer refreshJobListings() # Shows the job view. showJobView = -> hide jobListingView hide buttonContainer show jobView # Create a job listing view (an empty block). jobListingView = block() # Create a job view. jobView = createJobView() # Create a FAB (a floating action button). addJobButton = button 'add', type: 'floating', color: 'primary' # Put the button in a block positioned to the bottom right, # on top of everything else. buttonContainer = block addJobButton, style: position: 'absolute' right: '10px' bottom: '10px' zIndex: 100 # Show the job view when the button is pressed. bind addJobButton, showJobView # Set the contents of the active page . set activePage, [ jobListingView, buttonContainer, jobView ] # Show the job listing as our initial view. showJobListingView()
true
# # This is the source code for the user interface. # # The HTML, stylesheet and necessary javascript files are automatically added # by the fluid compiler. # # You can install the fluid compiler using: # npm install fluid-lang -g # # The `fluid` compiler command looks something like this: # fluid --compile app.coffee \ # --include-js lib/thrift/lib/js/src/thrift.js \ # --include-js gen-js/web_types.js \ # --include-js gen-js/Web.js # # See this app's package.json for more tasks. # # Create a ref to the app server via the bundled Apache Thrift # XHR/JSON RPC client. # Also, export it to the window so that we can run RPC calls # from the in-browser Fluid REPL. window.server = server = new App.WebClient new Thrift.TJSONProtocol new Thrift.TXHRTransport '/rpc' # Set the application title app.title 'PI:NAME:<NAME>END_PI CPI:NAME:<NAME>END_PI' # Hide the footer hide app.footer # This is a function that creates the UI for a list of jobs. createJobListing = (jobs) -> # A job listing is a block of jobs, each of which is a card. block jobs.map (job) -> card # The card displays the title and category. items: [ body2 job.title caption "Category: #{job.category}" ] # The card has a menu with an Edit command . menu: menu [ command 'Edit', -> alert 'not implemented' ] # Allow the card to expand to available width, and collapse to # minimum height. style: width: 'auto' minHeight: 'auto' # This is a function that fetches latest jobs from the server refreshJobListings = -> server.listJobs 0, 25, (jobs) -> # Fill the job listing view with jobs, if available. if jobs then set jobListingView, createJobListing jobs # This is a function that creates a view to add/edit a job posting. createJobView = -> # The job title field is a text area. jobTitleField = textarea title: 'Job Description' # The job category field is a text field. jobCategoryField = textfield 'NA', title: 'Category' # Tells the app server to save the new job posting. createJob = -> # A new job is composed of the values from our two fields. job = new App.Job title: get jobTitleField category: get jobCategoryField # Create the job... server.createJob job, -> # ... clear the title field set jobTitleField, '' # ... and go back to our list of jobs. showJobListingView() # The form itself is a card containing our two fields. self = card title: 'Add a new job posting' items: [ block jobTitleField block jobCategoryField ] buttons: [ # The post button creates a job and saves the economy ftw. button 'Post', color: 'accent', createJob # The dismiss button simply goes back to our list of jobs. button 'Dismiss', showJobListingView ] # Expand the form's width to fit the screen. style: width: 'auto' # This function prefills the job category, given a title. prefillJobCategory = (jobTitle) -> # Ask the server for the predicted category... server.predictJobCategory jobTitle, (category) -> # ... then update the job category field. set jobCategoryField, category # Whenever the job title changes, prefill the job category, # (but do this once in 500ms to go easy on the server). bind jobTitleField, _.throttle prefillJobCategory, 500 self # Shows the job listings. showJobListingView = -> hide jobView show jobListingView show buttonContainer refreshJobListings() # Shows the job view. showJobView = -> hide jobListingView hide buttonContainer show jobView # Create a job listing view (an empty block). jobListingView = block() # Create a job view. jobView = createJobView() # Create a FAB (a floating action button). addJobButton = button 'add', type: 'floating', color: 'primary' # Put the button in a block positioned to the bottom right, # on top of everything else. buttonContainer = block addJobButton, style: position: 'absolute' right: '10px' bottom: '10px' zIndex: 100 # Show the job view when the button is pressed. bind addJobButton, showJobView # Set the contents of the active page . set activePage, [ jobListingView, buttonContainer, jobView ] # Show the job listing as our initial view. showJobListingView()
[ { "context": " jid: config.thing\n password: config.password\n host: config.host\n port: c", "end": 875, "score": 0.9988792538642883, "start": 860, "tag": "PASSWORD", "value": "config.password" }, { "context": " jid: config.owner\n password: config.password\n host: config.host\n ", "end": 1261, "score": 0.9986627697944641, "start": 1246, "tag": "PASSWORD", "value": "config.password" }, { "context": "2'/>\n <str name='KEY' value='ABC'/>\n </register>\n <", "end": 3683, "score": 0.9976156949996948, "start": 3680, "tag": "KEY", "value": "ABC" }, { "context": "0'/>\n <str name='KEY' value='ABC'/>\n </register>\n <", "end": 4883, "score": 0.9784474968910217, "start": 4880, "tag": "KEY", "value": "ABC" } ]
test/004-search-ranges.coffee
TNO-IoT/testing-xep-0347
0
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # This set test some basic functions for registration, claim, # search, update, disown and unregister functions. # ltx = require('node-xmpp-core').ltx Client = require 'node-xmpp-client' bunyan = require 'bunyan' shortId = require 'shortid' assert = require 'assert' chai = require 'chai' Q = require 'q' config = require './helpers/config' log = bunyan.createLogger name: '004-search-ranges' level: 'trace' # global config thingConn = undefined ownerConn = undefined chai.should() assert = chai.assert describe 'Search ranges of meta-data to find a Thing', -> this.timeout 10000 before () -> defer = Q.defer() log.trace 'Connecting to XMPP server' thingConn = new Client jid: config.thing password: config.password host: config.host port: config.port reconnect: false thingConn.on 'online', () -> log.trace 'Thing is now online.' thingConn.send '<presence/>' thingConn.once 'stanza', (stanza) -> ownerConn = new Client jid: config.owner password: config.password host: config.host port: config.port reconnect: false ownerConn.on 'online', () -> log.trace 'Owner is now online.' defer.resolve() thingConn.on 'error', (err) -> log.warn err defer.reject() return defer.promise after () -> defer = Q.defer() log.trace 'Unsubscribing from presence!' thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>" ready = () -> thingConn.end() defer.resolve() setTimeout ready, 100 ownerConn.end() return defer.promise describe 'subscribe to the presence of the registry', -> it 'sends the presence subscribtion', (done) -> log.trace 'Sending presence subscription' message = "<presence type='subscribe' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'presence' stanza.attrs.type.should.equal 'subscribe' stanza.attrs.from.should.equal config.registry answer = "<presence type='subscribed' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ answer }" thingConn.send answer done() describe 'register the first thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.se'/> <str name='MODEL' value='B'/> <num name='V' value='1.2'/> <str name='KEY' value='ABC'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'register the second thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.com'/> <str name='MODEL' value='C'/> <num name='V' value='2.0'/> <str name='KEY' value='ABC'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'when someone searches with a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C' maxIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() describe 'when someone searches outside of a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='C' max='E' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='0' max='B'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.0' max='2.0'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.2' max='2.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches outside of a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='2.0' max='3.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='0' max='1.2'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a string mask', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.*' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'can find 2 things with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc#' wildcard='#'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.se' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() it 'only finds 1 thing with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='*.ktc.com' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'unregister the first thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'unregister the second thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done()
97000
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # This set test some basic functions for registration, claim, # search, update, disown and unregister functions. # ltx = require('node-xmpp-core').ltx Client = require 'node-xmpp-client' bunyan = require 'bunyan' shortId = require 'shortid' assert = require 'assert' chai = require 'chai' Q = require 'q' config = require './helpers/config' log = bunyan.createLogger name: '004-search-ranges' level: 'trace' # global config thingConn = undefined ownerConn = undefined chai.should() assert = chai.assert describe 'Search ranges of meta-data to find a Thing', -> this.timeout 10000 before () -> defer = Q.defer() log.trace 'Connecting to XMPP server' thingConn = new Client jid: config.thing password: <PASSWORD> host: config.host port: config.port reconnect: false thingConn.on 'online', () -> log.trace 'Thing is now online.' thingConn.send '<presence/>' thingConn.once 'stanza', (stanza) -> ownerConn = new Client jid: config.owner password: <PASSWORD> host: config.host port: config.port reconnect: false ownerConn.on 'online', () -> log.trace 'Owner is now online.' defer.resolve() thingConn.on 'error', (err) -> log.warn err defer.reject() return defer.promise after () -> defer = Q.defer() log.trace 'Unsubscribing from presence!' thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>" ready = () -> thingConn.end() defer.resolve() setTimeout ready, 100 ownerConn.end() return defer.promise describe 'subscribe to the presence of the registry', -> it 'sends the presence subscribtion', (done) -> log.trace 'Sending presence subscription' message = "<presence type='subscribe' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'presence' stanza.attrs.type.should.equal 'subscribe' stanza.attrs.from.should.equal config.registry answer = "<presence type='subscribed' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ answer }" thingConn.send answer done() describe 'register the first thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.se'/> <str name='MODEL' value='B'/> <num name='V' value='1.2'/> <str name='KEY' value='<KEY>'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'register the second thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.com'/> <str name='MODEL' value='C'/> <num name='V' value='2.0'/> <str name='KEY' value='<KEY>'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'when someone searches with a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C' maxIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() describe 'when someone searches outside of a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='C' max='E' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='0' max='B'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.0' max='2.0'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.2' max='2.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches outside of a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='2.0' max='3.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='0' max='1.2'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a string mask', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.*' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'can find 2 things with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc#' wildcard='#'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.se' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() it 'only finds 1 thing with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='*.ktc.com' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'unregister the first thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'unregister the second thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done()
true
# Tests if the server component complies to # https://xmpp.org/extensions/xep-0347.html # # This set test some basic functions for registration, claim, # search, update, disown and unregister functions. # ltx = require('node-xmpp-core').ltx Client = require 'node-xmpp-client' bunyan = require 'bunyan' shortId = require 'shortid' assert = require 'assert' chai = require 'chai' Q = require 'q' config = require './helpers/config' log = bunyan.createLogger name: '004-search-ranges' level: 'trace' # global config thingConn = undefined ownerConn = undefined chai.should() assert = chai.assert describe 'Search ranges of meta-data to find a Thing', -> this.timeout 10000 before () -> defer = Q.defer() log.trace 'Connecting to XMPP server' thingConn = new Client jid: config.thing password: PI:PASSWORD:<PASSWORD>END_PI host: config.host port: config.port reconnect: false thingConn.on 'online', () -> log.trace 'Thing is now online.' thingConn.send '<presence/>' thingConn.once 'stanza', (stanza) -> ownerConn = new Client jid: config.owner password: PI:PASSWORD:<PASSWORD>END_PI host: config.host port: config.port reconnect: false ownerConn.on 'online', () -> log.trace 'Owner is now online.' defer.resolve() thingConn.on 'error', (err) -> log.warn err defer.reject() return defer.promise after () -> defer = Q.defer() log.trace 'Unsubscribing from presence!' thingConn.send "<presence type='unsubscribe' to='#{ config.registry }'/>" ready = () -> thingConn.end() defer.resolve() setTimeout ready, 100 ownerConn.end() return defer.promise describe 'subscribe to the presence of the registry', -> it 'sends the presence subscribtion', (done) -> log.trace 'Sending presence subscription' message = "<presence type='subscribe' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'presence' stanza.attrs.type.should.equal 'subscribe' stanza.attrs.from.should.equal config.registry answer = "<presence type='subscribed' to='#{ config.registry }' id='#{ shortId.generate() }'/>" log.info "Sending message: #{ answer }" thingConn.send answer done() describe 'register the first thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.se'/> <str name='MODEL' value='B'/> <num name='V' value='1.2'/> <str name='KEY' value='PI:KEY:<KEY>END_PI'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'register the second thing in the registry', -> it 'sends registration message and receives a confirmation', (done) -> log.trace 'Sending register message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <register xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2' selfOwned='true'> <str name='SN' value='394872348732948723'/> <str name='MAN' value='www.ktc.com'/> <str name='MODEL' value='C'/> <num name='V' value='2.0'/> <str name='KEY' value='PI:KEY:<KEY>END_PI'/> </register> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'when someone searches with a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strRange name='MODEL' min='A' max='C' maxIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() describe 'when someone searches outside of a string range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='C' max='E' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strNRange name='MODEL' min='0' max='B'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.0' max='2.0'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numRange name='V' min='1.2' max='2.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches outside of a number range', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='2.0' max='3.0' minIncluded='false'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <numNRange name='V' min='0' max='1.2'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'when someone searches with a string mask', -> it 'can find 2 things', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.*' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'can find 2 things with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc#' wildcard='#'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 2 found.children[0].name.should.equal 'thing' found.children[0].attrs.jid.should.equal config.thing done() it 'only finds 1 thing', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='www.ktc.se' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '1' done() it 'only finds 1 thing with another wildcard', (done) -> message = "<iq type='get' to='#{ config.registry }' id='#{ shortId.generate() }'> <search xmlns='urn:xmpp:iot:discovery' offset='0' maxCount='20'> <strMask name='MAN' value='*.ktc.com' wildcard='*'/> </search> </iq>" log.info "Sending message: #{ message }" ownerConn.send message ownerConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry assert.lengthOf stanza.children, 1 stanza.children[0].name.should.equal 'found' found = stanza.children[0] assert.lengthOf found.children, 1 found.children[0].attrs.nodeId.should.equal '2' done() describe 'unregister the first thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='1'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done() describe 'unregister the second thing from the registry', -> it 'sends the unregister message and receives a confirmation', (done) -> log.trace 'Sending unregister message' message = "<iq type='set' to='#{ config.registry }' id='#{ shortId.generate() }'> <unregister xmlns='urn:xmpp:iot:discovery' sourceId='testing' nodeId='2'/> </iq>" log.info "Sending message: #{ message }" thingConn.send message thingConn.once 'stanza', (stanza) -> log.info "Received message: #{ stanza.toString() }" stanza.name.should.equal 'iq' stanza.attrs.type.should.equal 'result' stanza.attrs.from.should.equal config.registry done()
[ { "context": "t.com/projects/javascript-sprintf\n\n# Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com>\n# All rights re", "end": 513, "score": 0.999866783618927, "start": 493, "tag": "NAME", "value": "Alexandru Marasteanu" }, { "context": "ICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL,", "end": 1591, "score": 0.9998213648796082, "start": 1571, "tag": "NAME", "value": "Alexandru Marasteanu" }, { "context": "intf = printf\n@vprintf = vprintf\n\n# Copyright 2010 Tim Down.\n#\n# Licensed under the Apache License, Version 2", "end": 6519, "score": 0.999218761920929, "start": 6511, "tag": "NAME", "value": "Tim Down" } ]
src/utils.coffee
pyrocat101/LogoScript
4
mixinKeywords = ['extended', 'included'] class @Mixins @extends: (obj) -> for key, value of obj when key not in mixinKeywords @[key] = value obj.extended?.apply this this @include: (obj) -> for key, value of obj when key not in mixinKeywords # Assign properties to the prototype @::[key] = value obj.included?.apply this this # sprintf() for JavaScript 0.7-beta1 # http://www.diveintojavascript.com/projects/javascript-sprintf # Copyright (c) Alexandru Marasteanu <alexaholic [at) gmail (dot] com> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of sprintf() for JavaScript nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Alexandru Marasteanu BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sprintf = `(function() { function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } function str_repeat(input, multiplier) { for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} return output.join(''); } var str_format = function() { if (!str_format.cache.hasOwnProperty(arguments[0])) { str_format.cache[arguments[0]] = str_format.parse(arguments[0]); } return str_format.format.call(null, str_format.cache[arguments[0]], arguments); }; str_format.format = function(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]); if (node_type === 'string') { output.push(parse_tree[i]); } else if (node_type === 'array') { match = parse_tree[i]; // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor]; for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); } arg = arg[match[2][k]]; } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]]; } else { // positional argument (implicit) arg = argv[cursor++]; } if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); } switch (match[8]) { case 'b': arg = arg.toString(2); break; case 'c': arg = String.fromCharCode(arg); break; case 'd': arg = parseInt(arg, 10); break; case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; case 'o': arg = arg.toString(8); break; case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; case 'u': arg = Math.abs(arg); break; case 'x': arg = arg.toString(16); break; case 'X': arg = arg.toString(16).toUpperCase(); break; } arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; pad_length = match[6] - String(arg).length; pad = match[6] ? str_repeat(pad_character, pad_length) : ''; output.push(match[5] ? arg + pad : pad + arg); } } return output.join(''); }; str_format.cache = {}; str_format.parse = function(fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; while (_fmt) { if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { parse_tree.push(match[0]); } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { parse_tree.push('%'); } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1; var field_list = [], replacement_field = match[2], field_match = []; if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else { throw('[sprintf] huh?'); } } } else { throw('[sprintf] huh?'); } match[2] = field_list; } else { arg_names |= 2; } if (arg_names === 3) { throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); } parse_tree.push(match); } else { throw('[sprintf] huh?'); } _fmt = _fmt.substring(match[0].length); } return parse_tree; }; return str_format; })();` vsprintf = `function(fmt, argv) { argv.unshift(fmt); return sprintf.apply(null, argv); }` printf = (args...) -> console.log @sprintf.apply(null, args) vprintf = (fmt, argv) -> console.log @vsprintf.call(null, fmt, argv) @sprintf = sprintf @vsprintf = vsprintf @printf = printf @vprintf = vprintf # Copyright 2010 Tim Down. # # 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. Hashtable = `(function() { var FUNCTION = "function"; var arrayRemoveAt = (typeof Array.prototype.splice == FUNCTION) ? function(arr, idx) { arr.splice(idx, 1); } : function(arr, idx) { var itemsAfterDeleted, i, len; if (idx === arr.length - 1) { arr.length = idx; } else { itemsAfterDeleted = arr.slice(idx + 1); arr.length = idx; for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) { arr[idx + i] = itemsAfterDeleted[i]; } } }; function hashObject(obj) { var hashCode; if (typeof obj == "string") { return obj; } else if (typeof obj.hashCode == FUNCTION) { // Check the hashCode method really has returned a string hashCode = obj.hashCode(); return (typeof hashCode == "string") ? hashCode : hashObject(hashCode); } else if (typeof obj.toString == FUNCTION) { return obj.toString(); } else { try { return String(obj); } catch (ex) { // For host objects (such as ActiveObjects in IE) that have no toString() method and throw an error when // passed to String() return Object.prototype.toString.call(obj); } } } function equals_fixedValueHasEquals(fixedValue, variableValue) { return fixedValue.equals(variableValue); } function equals_fixedValueNoEquals(fixedValue, variableValue) { return (typeof variableValue.equals == FUNCTION) ? variableValue.equals(fixedValue) : (fixedValue === variableValue); } function createKeyValCheck(kvStr) { return function(kv) { if (kv === null) { throw new Error("null is not a valid " + kvStr); } else if (typeof kv == "undefined") { throw new Error(kvStr + " must not be undefined"); } }; } var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value"); /*----------------------------------------------------------------------------------------------------------------*/ function Bucket(hash, firstKey, firstValue, equalityFunction) { this[0] = hash; this.entries = []; this.addEntry(firstKey, firstValue); if (equalityFunction !== null) { this.getEqualityFunction = function() { return equalityFunction; }; } } var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2; function createBucketSearcher(mode) { return function(key) { var i = this.entries.length, entry, equals = this.getEqualityFunction(key); while (i--) { entry = this.entries[i]; if ( equals(key, entry[0]) ) { switch (mode) { case EXISTENCE: return true; case ENTRY: return entry; case ENTRY_INDEX_AND_VALUE: return [ i, entry[1] ]; } } } return false; }; } function createBucketLister(entryProperty) { return function(aggregatedArr) { var startIndex = aggregatedArr.length; for (var i = 0, len = this.entries.length; i < len; ++i) { aggregatedArr[startIndex + i] = this.entries[i][entryProperty]; } }; } Bucket.prototype = { getEqualityFunction: function(searchValue) { return (typeof searchValue.equals == FUNCTION) ? equals_fixedValueHasEquals : equals_fixedValueNoEquals; }, getEntryForKey: createBucketSearcher(ENTRY), getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE), removeEntryForKey: function(key) { var result = this.getEntryAndIndexForKey(key); if (result) { arrayRemoveAt(this.entries, result[0]); return result[1]; } return null; }, addEntry: function(key, value) { this.entries[this.entries.length] = [key, value]; }, keys: createBucketLister(0), values: createBucketLister(1), getEntries: function(entries) { var startIndex = entries.length; for (var i = 0, len = this.entries.length; i < len; ++i) { // Clone the entry stored in the bucket before adding to array entries[startIndex + i] = this.entries[i].slice(0); } }, containsKey: createBucketSearcher(EXISTENCE), containsValue: function(value) { var i = this.entries.length; while (i--) { if ( value === this.entries[i][1] ) { return true; } } return false; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Supporting functions for searching hashtable buckets function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; } function getBucketForHash(bucketsByHash, hash) { var bucket = bucketsByHash[hash]; // Check that this is a genuine bucket and not something inherited from the bucketsByHash's prototype return ( bucket && (bucket instanceof Bucket) ) ? bucket : null; } /*----------------------------------------------------------------------------------------------------------------*/ function Hashtable(hashingFunctionParam, equalityFunctionParam) { var that = this; var buckets = []; var bucketsByHash = {}; var hashingFunction = (typeof hashingFunctionParam == FUNCTION) ? hashingFunctionParam : hashObject; var equalityFunction = (typeof equalityFunctionParam == FUNCTION) ? equalityFunctionParam : null; this.put = function(key, value) { checkKey(key); checkValue(value); var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null; // Check if a bucket exists for the bucket key bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it already contains this key bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so replace old value and we're done. oldValue = bucketEntry[1]; bucketEntry[1] = value; } else { // The bucket does not contain an entry for this key, so add one bucket.addEntry(key, value); } } else { // No bucket exists for the key, so create one and put our key/value mapping in bucket = new Bucket(hash, key, value, equalityFunction); buckets[buckets.length] = bucket; bucketsByHash[hash] = bucket; } return oldValue; }; this.get = function(key) { checkKey(key); var hash = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it contains this key var bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so return the value. return bucketEntry[1]; } } return null; }; this.containsKey = function(key) { checkKey(key); var bucketKey = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, bucketKey); return bucket ? bucket.containsKey(key) : false; }; this.containsValue = function(value) { checkValue(value); var i = buckets.length; while (i--) { if (buckets[i].containsValue(value)) { return true; } } return false; }; this.clear = function() { buckets.length = 0; bucketsByHash = {}; }; this.isEmpty = function() { return !buckets.length; }; var createBucketAggregator = function(bucketFuncName) { return function() { var aggregated = [], i = buckets.length; while (i--) { buckets[i][bucketFuncName](aggregated); } return aggregated; }; }; this.keys = createBucketAggregator("keys"); this.values = createBucketAggregator("values"); this.entries = createBucketAggregator("getEntries"); this.remove = function(key) { checkKey(key); var hash = hashingFunction(key), bucketIndex, oldValue = null; // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Remove entry from this bucket for this key oldValue = bucket.removeEntryForKey(key); if (oldValue !== null) { // Entry was removed, so check if bucket is empty if (!bucket.entries.length) { // Bucket is empty, so remove it from the bucket collections bucketIndex = searchBuckets(buckets, hash); arrayRemoveAt(buckets, bucketIndex); delete bucketsByHash[hash]; } } } return oldValue; }; this.size = function() { var total = 0, i = buckets.length; while (i--) { total += buckets[i].entries.length; } return total; }; this.each = function(callback) { var entries = that.entries(), i = entries.length, entry; while (i--) { entry = entries[i]; callback(entry[0], entry[1]); } }; this.putAll = function(hashtable, conflictCallback) { var entries = hashtable.entries(); var entry, key, value, thisValue, i = entries.length; var hasConflictCallback = (typeof conflictCallback == FUNCTION); while (i--) { entry = entries[i]; key = entry[0]; value = entry[1]; // Check for a conflict. The default behaviour is to overwrite the value for an existing key if ( hasConflictCallback && (thisValue = that.get(key)) ) { value = conflictCallback(key, thisValue, value); } that.put(key, value); } }; this.clone = function() { var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam); clone.putAll(that); return clone; }; } return Hashtable; })();` HashSet = `function (hashingFunction, equalityFunction) { var hashTable = new Hashtable(hashingFunction, equalityFunction); this.add = function(o) { hashTable.put(o, true); }; this.addAll = function(arr) { var i = arr.length; while (i--) { hashTable.put(arr[i], true); } }; this.values = function() { return hashTable.keys(); }; this.remove = function(o) { return hashTable.remove(o) ? o : null; }; this.contains = function(o) { return hashTable.containsKey(o); }; this.clear = function() { hashTable.clear(); }; this.size = function() { return hashTable.size(); }; this.isEmpty = function() { return hashTable.isEmpty(); }; this.clone = function() { var h = new HashSet(hashingFunction, equalityFunction); h.addAll(hashTable.keys()); return h; }; this.intersection = function(hashSet) { var intersection = new HashSet(hashingFunction, equalityFunction); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (hashTable.containsKey(val)) { intersection.add(val); } } return intersection; }; this.union = function(hashSet) { var union = this.clone(); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (!hashTable.containsKey(val)) { union.add(val); } } return union; }; this.isSubsetOf = function(hashSet) { var values = hashTable.keys(), i = values.length; while (i--) { if (!hashSet.contains(values[i])) { return false; } } return true; }; }` @HashSet = HashSet @Hashtable = Hashtable
223467
mixinKeywords = ['extended', 'included'] class @Mixins @extends: (obj) -> for key, value of obj when key not in mixinKeywords @[key] = value obj.extended?.apply this this @include: (obj) -> for key, value of obj when key not in mixinKeywords # Assign properties to the prototype @::[key] = value obj.included?.apply this this # sprintf() for JavaScript 0.7-beta1 # http://www.diveintojavascript.com/projects/javascript-sprintf # Copyright (c) <NAME> <alexaholic [at) gmail (dot] com> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of sprintf() for JavaScript nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <NAME> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sprintf = `(function() { function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } function str_repeat(input, multiplier) { for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} return output.join(''); } var str_format = function() { if (!str_format.cache.hasOwnProperty(arguments[0])) { str_format.cache[arguments[0]] = str_format.parse(arguments[0]); } return str_format.format.call(null, str_format.cache[arguments[0]], arguments); }; str_format.format = function(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]); if (node_type === 'string') { output.push(parse_tree[i]); } else if (node_type === 'array') { match = parse_tree[i]; // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor]; for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); } arg = arg[match[2][k]]; } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]]; } else { // positional argument (implicit) arg = argv[cursor++]; } if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); } switch (match[8]) { case 'b': arg = arg.toString(2); break; case 'c': arg = String.fromCharCode(arg); break; case 'd': arg = parseInt(arg, 10); break; case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; case 'o': arg = arg.toString(8); break; case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; case 'u': arg = Math.abs(arg); break; case 'x': arg = arg.toString(16); break; case 'X': arg = arg.toString(16).toUpperCase(); break; } arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; pad_length = match[6] - String(arg).length; pad = match[6] ? str_repeat(pad_character, pad_length) : ''; output.push(match[5] ? arg + pad : pad + arg); } } return output.join(''); }; str_format.cache = {}; str_format.parse = function(fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; while (_fmt) { if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { parse_tree.push(match[0]); } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { parse_tree.push('%'); } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1; var field_list = [], replacement_field = match[2], field_match = []; if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else { throw('[sprintf] huh?'); } } } else { throw('[sprintf] huh?'); } match[2] = field_list; } else { arg_names |= 2; } if (arg_names === 3) { throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); } parse_tree.push(match); } else { throw('[sprintf] huh?'); } _fmt = _fmt.substring(match[0].length); } return parse_tree; }; return str_format; })();` vsprintf = `function(fmt, argv) { argv.unshift(fmt); return sprintf.apply(null, argv); }` printf = (args...) -> console.log @sprintf.apply(null, args) vprintf = (fmt, argv) -> console.log @vsprintf.call(null, fmt, argv) @sprintf = sprintf @vsprintf = vsprintf @printf = printf @vprintf = vprintf # Copyright 2010 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Hashtable = `(function() { var FUNCTION = "function"; var arrayRemoveAt = (typeof Array.prototype.splice == FUNCTION) ? function(arr, idx) { arr.splice(idx, 1); } : function(arr, idx) { var itemsAfterDeleted, i, len; if (idx === arr.length - 1) { arr.length = idx; } else { itemsAfterDeleted = arr.slice(idx + 1); arr.length = idx; for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) { arr[idx + i] = itemsAfterDeleted[i]; } } }; function hashObject(obj) { var hashCode; if (typeof obj == "string") { return obj; } else if (typeof obj.hashCode == FUNCTION) { // Check the hashCode method really has returned a string hashCode = obj.hashCode(); return (typeof hashCode == "string") ? hashCode : hashObject(hashCode); } else if (typeof obj.toString == FUNCTION) { return obj.toString(); } else { try { return String(obj); } catch (ex) { // For host objects (such as ActiveObjects in IE) that have no toString() method and throw an error when // passed to String() return Object.prototype.toString.call(obj); } } } function equals_fixedValueHasEquals(fixedValue, variableValue) { return fixedValue.equals(variableValue); } function equals_fixedValueNoEquals(fixedValue, variableValue) { return (typeof variableValue.equals == FUNCTION) ? variableValue.equals(fixedValue) : (fixedValue === variableValue); } function createKeyValCheck(kvStr) { return function(kv) { if (kv === null) { throw new Error("null is not a valid " + kvStr); } else if (typeof kv == "undefined") { throw new Error(kvStr + " must not be undefined"); } }; } var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value"); /*----------------------------------------------------------------------------------------------------------------*/ function Bucket(hash, firstKey, firstValue, equalityFunction) { this[0] = hash; this.entries = []; this.addEntry(firstKey, firstValue); if (equalityFunction !== null) { this.getEqualityFunction = function() { return equalityFunction; }; } } var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2; function createBucketSearcher(mode) { return function(key) { var i = this.entries.length, entry, equals = this.getEqualityFunction(key); while (i--) { entry = this.entries[i]; if ( equals(key, entry[0]) ) { switch (mode) { case EXISTENCE: return true; case ENTRY: return entry; case ENTRY_INDEX_AND_VALUE: return [ i, entry[1] ]; } } } return false; }; } function createBucketLister(entryProperty) { return function(aggregatedArr) { var startIndex = aggregatedArr.length; for (var i = 0, len = this.entries.length; i < len; ++i) { aggregatedArr[startIndex + i] = this.entries[i][entryProperty]; } }; } Bucket.prototype = { getEqualityFunction: function(searchValue) { return (typeof searchValue.equals == FUNCTION) ? equals_fixedValueHasEquals : equals_fixedValueNoEquals; }, getEntryForKey: createBucketSearcher(ENTRY), getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE), removeEntryForKey: function(key) { var result = this.getEntryAndIndexForKey(key); if (result) { arrayRemoveAt(this.entries, result[0]); return result[1]; } return null; }, addEntry: function(key, value) { this.entries[this.entries.length] = [key, value]; }, keys: createBucketLister(0), values: createBucketLister(1), getEntries: function(entries) { var startIndex = entries.length; for (var i = 0, len = this.entries.length; i < len; ++i) { // Clone the entry stored in the bucket before adding to array entries[startIndex + i] = this.entries[i].slice(0); } }, containsKey: createBucketSearcher(EXISTENCE), containsValue: function(value) { var i = this.entries.length; while (i--) { if ( value === this.entries[i][1] ) { return true; } } return false; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Supporting functions for searching hashtable buckets function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; } function getBucketForHash(bucketsByHash, hash) { var bucket = bucketsByHash[hash]; // Check that this is a genuine bucket and not something inherited from the bucketsByHash's prototype return ( bucket && (bucket instanceof Bucket) ) ? bucket : null; } /*----------------------------------------------------------------------------------------------------------------*/ function Hashtable(hashingFunctionParam, equalityFunctionParam) { var that = this; var buckets = []; var bucketsByHash = {}; var hashingFunction = (typeof hashingFunctionParam == FUNCTION) ? hashingFunctionParam : hashObject; var equalityFunction = (typeof equalityFunctionParam == FUNCTION) ? equalityFunctionParam : null; this.put = function(key, value) { checkKey(key); checkValue(value); var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null; // Check if a bucket exists for the bucket key bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it already contains this key bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so replace old value and we're done. oldValue = bucketEntry[1]; bucketEntry[1] = value; } else { // The bucket does not contain an entry for this key, so add one bucket.addEntry(key, value); } } else { // No bucket exists for the key, so create one and put our key/value mapping in bucket = new Bucket(hash, key, value, equalityFunction); buckets[buckets.length] = bucket; bucketsByHash[hash] = bucket; } return oldValue; }; this.get = function(key) { checkKey(key); var hash = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it contains this key var bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so return the value. return bucketEntry[1]; } } return null; }; this.containsKey = function(key) { checkKey(key); var bucketKey = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, bucketKey); return bucket ? bucket.containsKey(key) : false; }; this.containsValue = function(value) { checkValue(value); var i = buckets.length; while (i--) { if (buckets[i].containsValue(value)) { return true; } } return false; }; this.clear = function() { buckets.length = 0; bucketsByHash = {}; }; this.isEmpty = function() { return !buckets.length; }; var createBucketAggregator = function(bucketFuncName) { return function() { var aggregated = [], i = buckets.length; while (i--) { buckets[i][bucketFuncName](aggregated); } return aggregated; }; }; this.keys = createBucketAggregator("keys"); this.values = createBucketAggregator("values"); this.entries = createBucketAggregator("getEntries"); this.remove = function(key) { checkKey(key); var hash = hashingFunction(key), bucketIndex, oldValue = null; // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Remove entry from this bucket for this key oldValue = bucket.removeEntryForKey(key); if (oldValue !== null) { // Entry was removed, so check if bucket is empty if (!bucket.entries.length) { // Bucket is empty, so remove it from the bucket collections bucketIndex = searchBuckets(buckets, hash); arrayRemoveAt(buckets, bucketIndex); delete bucketsByHash[hash]; } } } return oldValue; }; this.size = function() { var total = 0, i = buckets.length; while (i--) { total += buckets[i].entries.length; } return total; }; this.each = function(callback) { var entries = that.entries(), i = entries.length, entry; while (i--) { entry = entries[i]; callback(entry[0], entry[1]); } }; this.putAll = function(hashtable, conflictCallback) { var entries = hashtable.entries(); var entry, key, value, thisValue, i = entries.length; var hasConflictCallback = (typeof conflictCallback == FUNCTION); while (i--) { entry = entries[i]; key = entry[0]; value = entry[1]; // Check for a conflict. The default behaviour is to overwrite the value for an existing key if ( hasConflictCallback && (thisValue = that.get(key)) ) { value = conflictCallback(key, thisValue, value); } that.put(key, value); } }; this.clone = function() { var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam); clone.putAll(that); return clone; }; } return Hashtable; })();` HashSet = `function (hashingFunction, equalityFunction) { var hashTable = new Hashtable(hashingFunction, equalityFunction); this.add = function(o) { hashTable.put(o, true); }; this.addAll = function(arr) { var i = arr.length; while (i--) { hashTable.put(arr[i], true); } }; this.values = function() { return hashTable.keys(); }; this.remove = function(o) { return hashTable.remove(o) ? o : null; }; this.contains = function(o) { return hashTable.containsKey(o); }; this.clear = function() { hashTable.clear(); }; this.size = function() { return hashTable.size(); }; this.isEmpty = function() { return hashTable.isEmpty(); }; this.clone = function() { var h = new HashSet(hashingFunction, equalityFunction); h.addAll(hashTable.keys()); return h; }; this.intersection = function(hashSet) { var intersection = new HashSet(hashingFunction, equalityFunction); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (hashTable.containsKey(val)) { intersection.add(val); } } return intersection; }; this.union = function(hashSet) { var union = this.clone(); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (!hashTable.containsKey(val)) { union.add(val); } } return union; }; this.isSubsetOf = function(hashSet) { var values = hashTable.keys(), i = values.length; while (i--) { if (!hashSet.contains(values[i])) { return false; } } return true; }; }` @HashSet = HashSet @Hashtable = Hashtable
true
mixinKeywords = ['extended', 'included'] class @Mixins @extends: (obj) -> for key, value of obj when key not in mixinKeywords @[key] = value obj.extended?.apply this this @include: (obj) -> for key, value of obj when key not in mixinKeywords # Assign properties to the prototype @::[key] = value obj.included?.apply this this # sprintf() for JavaScript 0.7-beta1 # http://www.diveintojavascript.com/projects/javascript-sprintf # Copyright (c) PI:NAME:<NAME>END_PI <alexaholic [at) gmail (dot] com> # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of sprintf() for JavaScript nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL PI:NAME:<NAME>END_PI BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. sprintf = `(function() { function get_type(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } function str_repeat(input, multiplier) { for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */} return output.join(''); } var str_format = function() { if (!str_format.cache.hasOwnProperty(arguments[0])) { str_format.cache[arguments[0]] = str_format.parse(arguments[0]); } return str_format.format.call(null, str_format.cache[arguments[0]], arguments); }; str_format.format = function(parse_tree, argv) { var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length; for (i = 0; i < tree_length; i++) { node_type = get_type(parse_tree[i]); if (node_type === 'string') { output.push(parse_tree[i]); } else if (node_type === 'array') { match = parse_tree[i]; // convenience purposes only if (match[2]) { // keyword argument arg = argv[cursor]; for (k = 0; k < match[2].length; k++) { if (!arg.hasOwnProperty(match[2][k])) { throw(sprintf('[sprintf] property "%s" does not exist', match[2][k])); } arg = arg[match[2][k]]; } } else if (match[1]) { // positional argument (explicit) arg = argv[match[1]]; } else { // positional argument (implicit) arg = argv[cursor++]; } if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) { throw(sprintf('[sprintf] expecting number but found %s', get_type(arg))); } switch (match[8]) { case 'b': arg = arg.toString(2); break; case 'c': arg = String.fromCharCode(arg); break; case 'd': arg = parseInt(arg, 10); break; case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break; case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break; case 'o': arg = arg.toString(8); break; case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break; case 'u': arg = Math.abs(arg); break; case 'x': arg = arg.toString(16); break; case 'X': arg = arg.toString(16).toUpperCase(); break; } arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg); pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' '; pad_length = match[6] - String(arg).length; pad = match[6] ? str_repeat(pad_character, pad_length) : ''; output.push(match[5] ? arg + pad : pad + arg); } } return output.join(''); }; str_format.cache = {}; str_format.parse = function(fmt) { var _fmt = fmt, match = [], parse_tree = [], arg_names = 0; while (_fmt) { if ((match = /^[^\x25]+/.exec(_fmt)) !== null) { parse_tree.push(match[0]); } else if ((match = /^\x25{2}/.exec(_fmt)) !== null) { parse_tree.push('%'); } else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) { if (match[2]) { arg_names |= 1; var field_list = [], replacement_field = match[2], field_match = []; if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') { if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) { field_list.push(field_match[1]); } else { throw('[sprintf] huh?'); } } } else { throw('[sprintf] huh?'); } match[2] = field_list; } else { arg_names |= 2; } if (arg_names === 3) { throw('[sprintf] mixing positional and named placeholders is not (yet) supported'); } parse_tree.push(match); } else { throw('[sprintf] huh?'); } _fmt = _fmt.substring(match[0].length); } return parse_tree; }; return str_format; })();` vsprintf = `function(fmt, argv) { argv.unshift(fmt); return sprintf.apply(null, argv); }` printf = (args...) -> console.log @sprintf.apply(null, args) vprintf = (fmt, argv) -> console.log @vsprintf.call(null, fmt, argv) @sprintf = sprintf @vsprintf = vsprintf @printf = printf @vprintf = vprintf # Copyright 2010 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. Hashtable = `(function() { var FUNCTION = "function"; var arrayRemoveAt = (typeof Array.prototype.splice == FUNCTION) ? function(arr, idx) { arr.splice(idx, 1); } : function(arr, idx) { var itemsAfterDeleted, i, len; if (idx === arr.length - 1) { arr.length = idx; } else { itemsAfterDeleted = arr.slice(idx + 1); arr.length = idx; for (i = 0, len = itemsAfterDeleted.length; i < len; ++i) { arr[idx + i] = itemsAfterDeleted[i]; } } }; function hashObject(obj) { var hashCode; if (typeof obj == "string") { return obj; } else if (typeof obj.hashCode == FUNCTION) { // Check the hashCode method really has returned a string hashCode = obj.hashCode(); return (typeof hashCode == "string") ? hashCode : hashObject(hashCode); } else if (typeof obj.toString == FUNCTION) { return obj.toString(); } else { try { return String(obj); } catch (ex) { // For host objects (such as ActiveObjects in IE) that have no toString() method and throw an error when // passed to String() return Object.prototype.toString.call(obj); } } } function equals_fixedValueHasEquals(fixedValue, variableValue) { return fixedValue.equals(variableValue); } function equals_fixedValueNoEquals(fixedValue, variableValue) { return (typeof variableValue.equals == FUNCTION) ? variableValue.equals(fixedValue) : (fixedValue === variableValue); } function createKeyValCheck(kvStr) { return function(kv) { if (kv === null) { throw new Error("null is not a valid " + kvStr); } else if (typeof kv == "undefined") { throw new Error(kvStr + " must not be undefined"); } }; } var checkKey = createKeyValCheck("key"), checkValue = createKeyValCheck("value"); /*----------------------------------------------------------------------------------------------------------------*/ function Bucket(hash, firstKey, firstValue, equalityFunction) { this[0] = hash; this.entries = []; this.addEntry(firstKey, firstValue); if (equalityFunction !== null) { this.getEqualityFunction = function() { return equalityFunction; }; } } var EXISTENCE = 0, ENTRY = 1, ENTRY_INDEX_AND_VALUE = 2; function createBucketSearcher(mode) { return function(key) { var i = this.entries.length, entry, equals = this.getEqualityFunction(key); while (i--) { entry = this.entries[i]; if ( equals(key, entry[0]) ) { switch (mode) { case EXISTENCE: return true; case ENTRY: return entry; case ENTRY_INDEX_AND_VALUE: return [ i, entry[1] ]; } } } return false; }; } function createBucketLister(entryProperty) { return function(aggregatedArr) { var startIndex = aggregatedArr.length; for (var i = 0, len = this.entries.length; i < len; ++i) { aggregatedArr[startIndex + i] = this.entries[i][entryProperty]; } }; } Bucket.prototype = { getEqualityFunction: function(searchValue) { return (typeof searchValue.equals == FUNCTION) ? equals_fixedValueHasEquals : equals_fixedValueNoEquals; }, getEntryForKey: createBucketSearcher(ENTRY), getEntryAndIndexForKey: createBucketSearcher(ENTRY_INDEX_AND_VALUE), removeEntryForKey: function(key) { var result = this.getEntryAndIndexForKey(key); if (result) { arrayRemoveAt(this.entries, result[0]); return result[1]; } return null; }, addEntry: function(key, value) { this.entries[this.entries.length] = [key, value]; }, keys: createBucketLister(0), values: createBucketLister(1), getEntries: function(entries) { var startIndex = entries.length; for (var i = 0, len = this.entries.length; i < len; ++i) { // Clone the entry stored in the bucket before adding to array entries[startIndex + i] = this.entries[i].slice(0); } }, containsKey: createBucketSearcher(EXISTENCE), containsValue: function(value) { var i = this.entries.length; while (i--) { if ( value === this.entries[i][1] ) { return true; } } return false; } }; /*----------------------------------------------------------------------------------------------------------------*/ // Supporting functions for searching hashtable buckets function searchBuckets(buckets, hash) { var i = buckets.length, bucket; while (i--) { bucket = buckets[i]; if (hash === bucket[0]) { return i; } } return null; } function getBucketForHash(bucketsByHash, hash) { var bucket = bucketsByHash[hash]; // Check that this is a genuine bucket and not something inherited from the bucketsByHash's prototype return ( bucket && (bucket instanceof Bucket) ) ? bucket : null; } /*----------------------------------------------------------------------------------------------------------------*/ function Hashtable(hashingFunctionParam, equalityFunctionParam) { var that = this; var buckets = []; var bucketsByHash = {}; var hashingFunction = (typeof hashingFunctionParam == FUNCTION) ? hashingFunctionParam : hashObject; var equalityFunction = (typeof equalityFunctionParam == FUNCTION) ? equalityFunctionParam : null; this.put = function(key, value) { checkKey(key); checkValue(value); var hash = hashingFunction(key), bucket, bucketEntry, oldValue = null; // Check if a bucket exists for the bucket key bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it already contains this key bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so replace old value and we're done. oldValue = bucketEntry[1]; bucketEntry[1] = value; } else { // The bucket does not contain an entry for this key, so add one bucket.addEntry(key, value); } } else { // No bucket exists for the key, so create one and put our key/value mapping in bucket = new Bucket(hash, key, value, equalityFunction); buckets[buckets.length] = bucket; bucketsByHash[hash] = bucket; } return oldValue; }; this.get = function(key) { checkKey(key); var hash = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Check this bucket to see if it contains this key var bucketEntry = bucket.getEntryForKey(key); if (bucketEntry) { // This bucket entry is the current mapping of key to value, so return the value. return bucketEntry[1]; } } return null; }; this.containsKey = function(key) { checkKey(key); var bucketKey = hashingFunction(key); // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, bucketKey); return bucket ? bucket.containsKey(key) : false; }; this.containsValue = function(value) { checkValue(value); var i = buckets.length; while (i--) { if (buckets[i].containsValue(value)) { return true; } } return false; }; this.clear = function() { buckets.length = 0; bucketsByHash = {}; }; this.isEmpty = function() { return !buckets.length; }; var createBucketAggregator = function(bucketFuncName) { return function() { var aggregated = [], i = buckets.length; while (i--) { buckets[i][bucketFuncName](aggregated); } return aggregated; }; }; this.keys = createBucketAggregator("keys"); this.values = createBucketAggregator("values"); this.entries = createBucketAggregator("getEntries"); this.remove = function(key) { checkKey(key); var hash = hashingFunction(key), bucketIndex, oldValue = null; // Check if a bucket exists for the bucket key var bucket = getBucketForHash(bucketsByHash, hash); if (bucket) { // Remove entry from this bucket for this key oldValue = bucket.removeEntryForKey(key); if (oldValue !== null) { // Entry was removed, so check if bucket is empty if (!bucket.entries.length) { // Bucket is empty, so remove it from the bucket collections bucketIndex = searchBuckets(buckets, hash); arrayRemoveAt(buckets, bucketIndex); delete bucketsByHash[hash]; } } } return oldValue; }; this.size = function() { var total = 0, i = buckets.length; while (i--) { total += buckets[i].entries.length; } return total; }; this.each = function(callback) { var entries = that.entries(), i = entries.length, entry; while (i--) { entry = entries[i]; callback(entry[0], entry[1]); } }; this.putAll = function(hashtable, conflictCallback) { var entries = hashtable.entries(); var entry, key, value, thisValue, i = entries.length; var hasConflictCallback = (typeof conflictCallback == FUNCTION); while (i--) { entry = entries[i]; key = entry[0]; value = entry[1]; // Check for a conflict. The default behaviour is to overwrite the value for an existing key if ( hasConflictCallback && (thisValue = that.get(key)) ) { value = conflictCallback(key, thisValue, value); } that.put(key, value); } }; this.clone = function() { var clone = new Hashtable(hashingFunctionParam, equalityFunctionParam); clone.putAll(that); return clone; }; } return Hashtable; })();` HashSet = `function (hashingFunction, equalityFunction) { var hashTable = new Hashtable(hashingFunction, equalityFunction); this.add = function(o) { hashTable.put(o, true); }; this.addAll = function(arr) { var i = arr.length; while (i--) { hashTable.put(arr[i], true); } }; this.values = function() { return hashTable.keys(); }; this.remove = function(o) { return hashTable.remove(o) ? o : null; }; this.contains = function(o) { return hashTable.containsKey(o); }; this.clear = function() { hashTable.clear(); }; this.size = function() { return hashTable.size(); }; this.isEmpty = function() { return hashTable.isEmpty(); }; this.clone = function() { var h = new HashSet(hashingFunction, equalityFunction); h.addAll(hashTable.keys()); return h; }; this.intersection = function(hashSet) { var intersection = new HashSet(hashingFunction, equalityFunction); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (hashTable.containsKey(val)) { intersection.add(val); } } return intersection; }; this.union = function(hashSet) { var union = this.clone(); var values = hashSet.values(), i = values.length, val; while (i--) { val = values[i]; if (!hashTable.containsKey(val)) { union.add(val); } } return union; }; this.isSubsetOf = function(hashSet) { var values = hashTable.keys(), i = values.length; while (i--) { if (!hashSet.contains(values[i])) { return false; } } return true; }; }` @HashSet = HashSet @Hashtable = Hashtable
[ { "context": "user.status = 'ACTIVE'\n user.password = req.body.password\n user.save ( err ) ->\n if err", "end": 494, "score": 0.9987166523933411, "start": 477, "tag": "PASSWORD", "value": "req.body.password" } ]
src/routes/system/passwd.coffee
rabrux/api-boilerplate
0
module.exports = ( router, schemas ) -> router.put '/passwd', ( req, res ) -> if !req.body or !req.body.key or !req.body.password return res.status( 400 ).send 'INVALID_DATA' schemas.User.findOne { key: req.body.key }, ( err, user ) -> if err then throw err if !user return res.status( 400 ).send 'INVALID_RECOVERY_HASH' else if user.status == 'RECOVERY_PASSWORD' user.status = 'ACTIVE' user.password = req.body.password user.save ( err ) -> if err then throw err return res.send 'SUCCESSFULLY_CHANGE_PASSWORD' else return res.status( 400 ).send 'PROCESS_UNINITIALIZED'
12790
module.exports = ( router, schemas ) -> router.put '/passwd', ( req, res ) -> if !req.body or !req.body.key or !req.body.password return res.status( 400 ).send 'INVALID_DATA' schemas.User.findOne { key: req.body.key }, ( err, user ) -> if err then throw err if !user return res.status( 400 ).send 'INVALID_RECOVERY_HASH' else if user.status == 'RECOVERY_PASSWORD' user.status = 'ACTIVE' user.password = <PASSWORD> user.save ( err ) -> if err then throw err return res.send 'SUCCESSFULLY_CHANGE_PASSWORD' else return res.status( 400 ).send 'PROCESS_UNINITIALIZED'
true
module.exports = ( router, schemas ) -> router.put '/passwd', ( req, res ) -> if !req.body or !req.body.key or !req.body.password return res.status( 400 ).send 'INVALID_DATA' schemas.User.findOne { key: req.body.key }, ( err, user ) -> if err then throw err if !user return res.status( 400 ).send 'INVALID_RECOVERY_HASH' else if user.status == 'RECOVERY_PASSWORD' user.status = 'ACTIVE' user.password = PI:PASSWORD:<PASSWORD>END_PI user.save ( err ) -> if err then throw err return res.send 'SUCCESSFULLY_CHANGE_PASSWORD' else return res.status( 400 ).send 'PROCESS_UNINITIALIZED'
[ { "context": ".stringEndsWith(key, 'Notify')\n key = Util.sliceStringBefore(key, \"Notify\")\n type = MztObje", "end": 5345, "score": 0.5607743263244629, "start": 5340, "tag": "KEY", "value": "slice" } ]
src/mozart/object.coffee
creativeprogramming/mozart
1
Util = require './util' {Events} = require './events' exports.MztObject = class MztObject # Internal Constants MODULEKEYWORDS = ['extended', 'included'] # Class Constants @NOTIFY: 2 @OBSERVE: 1 @SYNC: 0 # Class Methods @include: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @[key] = value obj.extended?.apply(@) this @extend: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @::[key] = value obj.included?.apply(@) this @create: (options) -> inst = new this() inst[k] = v for k, v of options inst._bindings = {} inst._bindings.notify = {} inst._bindings.observe = {} inst._bindings.stored = {} inst._createDeclaredBinds() inst._createLookups() inst.init?() inst # Instance Methods constructor: -> @_mozartId = Util.getId() toString: -> "obj-#{@_mozartId}" get: (key) -> if Util.isFunction(@[key]) @[key].call(@) else @[key] set: (key, value) -> oldValue = @[key] if oldValue isnt value # Binding Transfer: This deserves some explanation. # Take a look at the 'Bindings on targets that change' spec in object-spec.coffee # Essentially for this to work, when a property is set, if the old value is an # MztObject then we need to strip all bindings from it and store them on *this* # object. If the new value is also a MztObject, we need to apply those stored # bindings to the new object. if oldValue instanceof Mozart.MztObject @_bindings.stored[key] = { notify: oldValue._stripNotifyBindings(true) observe: oldValue._stripObserveBindings(true) } if @_bindings.stored[key].notify == {} and @_bindings.stored[key].observe == {} delete @_bindings.stored[key] # If the new value is explicitly null, and there are stored bindings for this # property, we should iterate them and set all targets to null. This means # where a binding 'a' is on 'x.y' and 'x' is now null, a should be set to null. if @_bindings.stored[key]? and @_bindings.stored[key].notify? and value == null for nv, bindings of @_bindings.stored[key].notify for binding in bindings binding.target.set(binding.attr, null) if value instanceof Mozart.MztObject and @_bindings.stored[key]? value._addNotifyBindings(@_bindings.stored[key].notify) unless @_bindings.stored[key].notify == {} value._addObserveBindings(@_bindings.stored[key].observe) unless @_bindings.stored[key].observe == {} delete @_bindings.stored[key] @[key] = value @_doNotifyBinding(key) @publish('change') @publish('change:'+key) bind: (args...) -> console.warn "'bind' will be depreciated in Mozart 0.2.0. Please use 'subscribe'." if console? @subscribe(args...) subscribe: (args...) -> Events.subscribe(@_mozartId, args...) @ one: (args...) -> console.warn "'one' will be depreciated in Mozart 0.2.0. Please use 'subscribeOnce'." if console? @subscribeOnce(args...) subscribeOnce: (args...) -> Events.subscribeOnce(@_mozartId, args...) @ publish: (args...) -> console.warn "'publish' will be depreciated in Mozart 0.2.0. Please use 'publish'." if console? @publish(args...) publish: (args...) -> Events.publish(@_mozartId, args...) @ unbind: (args...) -> console.warn "'unbind' will be depreciated in Mozart 0.2.0. Please use 'unsubscribe'." if console? @unsubscribe(args...) unsubscribe: (args...) -> Events.unsubscribe(@_mozartId, args...) @ release: -> return if @released @_removeAllBindings() @unsubscribe() for own k,v of @ @[k] = undefined delete @[k] @released = true # Private Methods _stripNotifyBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.notify bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.NOTIFY) bindings _addNotifyBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.NOTIFY, binding.transferable) _stripObserveBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.observe bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.OBSERVE) bindings _addObserveBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.OBSERVE, binding.transferable) _createDeclaredBinds: -> for key, v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Binding") key = Util.sliceStringBefore(key, "Binding") type = MztObject.SYNC if Util.stringEndsWith(key, 'Observe') key = Util.sliceStringBefore(key, "Observe") type = MztObject.OBSERVE else if Util.stringEndsWith(key, 'Notify') key = Util.sliceStringBefore(key, "Notify") type = MztObject.NOTIFY [path, attr] = Util.parsePath(v) if path? obj = Util._getPath(@,path) else obj = @ @_createBinding(key, obj, attr, type, Util.isAbsolutePath(v)) _hasNotifyBinding: (property, target, targetProperty, type) -> return false unless @_bindings.notify[property]? for binding in @_bindings.notify[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _hasObserveBinding: (property, target, targetProperty, type) -> return false unless @_bindings.observe[property]? for binding in @_bindings.observe[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _createBinding: (property, target, targetProperty, type, transferable) -> switch type when MztObject.NOTIFY return if @_hasNotifyBinding(property, target, targetProperty, type) @_bindings.notify[property] ?= [] @_bindings.notify[property].push({attr:targetProperty, target: target, transferable: transferable}) if target instanceof MztObject target._createBinding(targetProperty, @, property, MztObject.OBSERVE, transferable) @_doNotifyBinding(property) when MztObject.OBSERVE return if @_hasObserveBinding(property, target, targetProperty, type) unless target instanceof MztObject Util.warn "Binding #{property}ObserveBinding on",@,": target",target,"is not a MztObject" return @_bindings.observe[property] ?= [] @_bindings.observe[property].push({attr:targetProperty, target: target, transferable: transferable}) target._createBinding(targetProperty, @, property, MztObject.NOTIFY, transferable) when MztObject.SYNC @_createBinding(property, target, targetProperty, MztObject.OBSERVE, transferable) @_createBinding(property, target, targetProperty, MztObject.NOTIFY, transferable) _removeBinding: (property, target, targetProperty, type) -> switch type when MztObject.NOTIFY return unless @_hasNotifyBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.notify[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.notify[property] = bindingset else delete @_bindings.notify[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.OBSERVE) when MztObject.OBSERVE return unless @_hasObserveBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.observe[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.observe[property] = bindingset else delete @_bindings.observe[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.NOTIFY) when MztObject.SYNC @_removeBinding(property, target, targetProperty, MztObject.NOTIFY) @_removeBinding(property, target, targetProperty, MztObject.OBSERVE) _removeAllBindings: -> @_stripObserveBindings(false) @_stripNotifyBindings(false) _doNotifyBinding: (key) -> bindings = @_bindings.notify[key] return unless bindings? for binding in bindings if binding? if Util.isFunction(binding.target.set) binding.target.set(binding.attr, @get(key)) else binding.target[binding.attr] = @get(key) _createLookups: -> for key,v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Lookup") key = Util.sliceStringBefore(key, "Lookup") @[key] = Util._getPath(v)
211971
Util = require './util' {Events} = require './events' exports.MztObject = class MztObject # Internal Constants MODULEKEYWORDS = ['extended', 'included'] # Class Constants @NOTIFY: 2 @OBSERVE: 1 @SYNC: 0 # Class Methods @include: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @[key] = value obj.extended?.apply(@) this @extend: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @::[key] = value obj.included?.apply(@) this @create: (options) -> inst = new this() inst[k] = v for k, v of options inst._bindings = {} inst._bindings.notify = {} inst._bindings.observe = {} inst._bindings.stored = {} inst._createDeclaredBinds() inst._createLookups() inst.init?() inst # Instance Methods constructor: -> @_mozartId = Util.getId() toString: -> "obj-#{@_mozartId}" get: (key) -> if Util.isFunction(@[key]) @[key].call(@) else @[key] set: (key, value) -> oldValue = @[key] if oldValue isnt value # Binding Transfer: This deserves some explanation. # Take a look at the 'Bindings on targets that change' spec in object-spec.coffee # Essentially for this to work, when a property is set, if the old value is an # MztObject then we need to strip all bindings from it and store them on *this* # object. If the new value is also a MztObject, we need to apply those stored # bindings to the new object. if oldValue instanceof Mozart.MztObject @_bindings.stored[key] = { notify: oldValue._stripNotifyBindings(true) observe: oldValue._stripObserveBindings(true) } if @_bindings.stored[key].notify == {} and @_bindings.stored[key].observe == {} delete @_bindings.stored[key] # If the new value is explicitly null, and there are stored bindings for this # property, we should iterate them and set all targets to null. This means # where a binding 'a' is on 'x.y' and 'x' is now null, a should be set to null. if @_bindings.stored[key]? and @_bindings.stored[key].notify? and value == null for nv, bindings of @_bindings.stored[key].notify for binding in bindings binding.target.set(binding.attr, null) if value instanceof Mozart.MztObject and @_bindings.stored[key]? value._addNotifyBindings(@_bindings.stored[key].notify) unless @_bindings.stored[key].notify == {} value._addObserveBindings(@_bindings.stored[key].observe) unless @_bindings.stored[key].observe == {} delete @_bindings.stored[key] @[key] = value @_doNotifyBinding(key) @publish('change') @publish('change:'+key) bind: (args...) -> console.warn "'bind' will be depreciated in Mozart 0.2.0. Please use 'subscribe'." if console? @subscribe(args...) subscribe: (args...) -> Events.subscribe(@_mozartId, args...) @ one: (args...) -> console.warn "'one' will be depreciated in Mozart 0.2.0. Please use 'subscribeOnce'." if console? @subscribeOnce(args...) subscribeOnce: (args...) -> Events.subscribeOnce(@_mozartId, args...) @ publish: (args...) -> console.warn "'publish' will be depreciated in Mozart 0.2.0. Please use 'publish'." if console? @publish(args...) publish: (args...) -> Events.publish(@_mozartId, args...) @ unbind: (args...) -> console.warn "'unbind' will be depreciated in Mozart 0.2.0. Please use 'unsubscribe'." if console? @unsubscribe(args...) unsubscribe: (args...) -> Events.unsubscribe(@_mozartId, args...) @ release: -> return if @released @_removeAllBindings() @unsubscribe() for own k,v of @ @[k] = undefined delete @[k] @released = true # Private Methods _stripNotifyBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.notify bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.NOTIFY) bindings _addNotifyBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.NOTIFY, binding.transferable) _stripObserveBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.observe bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.OBSERVE) bindings _addObserveBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.OBSERVE, binding.transferable) _createDeclaredBinds: -> for key, v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Binding") key = Util.sliceStringBefore(key, "Binding") type = MztObject.SYNC if Util.stringEndsWith(key, 'Observe') key = Util.sliceStringBefore(key, "Observe") type = MztObject.OBSERVE else if Util.stringEndsWith(key, 'Notify') key = Util.<KEY>StringBefore(key, "Notify") type = MztObject.NOTIFY [path, attr] = Util.parsePath(v) if path? obj = Util._getPath(@,path) else obj = @ @_createBinding(key, obj, attr, type, Util.isAbsolutePath(v)) _hasNotifyBinding: (property, target, targetProperty, type) -> return false unless @_bindings.notify[property]? for binding in @_bindings.notify[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _hasObserveBinding: (property, target, targetProperty, type) -> return false unless @_bindings.observe[property]? for binding in @_bindings.observe[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _createBinding: (property, target, targetProperty, type, transferable) -> switch type when MztObject.NOTIFY return if @_hasNotifyBinding(property, target, targetProperty, type) @_bindings.notify[property] ?= [] @_bindings.notify[property].push({attr:targetProperty, target: target, transferable: transferable}) if target instanceof MztObject target._createBinding(targetProperty, @, property, MztObject.OBSERVE, transferable) @_doNotifyBinding(property) when MztObject.OBSERVE return if @_hasObserveBinding(property, target, targetProperty, type) unless target instanceof MztObject Util.warn "Binding #{property}ObserveBinding on",@,": target",target,"is not a MztObject" return @_bindings.observe[property] ?= [] @_bindings.observe[property].push({attr:targetProperty, target: target, transferable: transferable}) target._createBinding(targetProperty, @, property, MztObject.NOTIFY, transferable) when MztObject.SYNC @_createBinding(property, target, targetProperty, MztObject.OBSERVE, transferable) @_createBinding(property, target, targetProperty, MztObject.NOTIFY, transferable) _removeBinding: (property, target, targetProperty, type) -> switch type when MztObject.NOTIFY return unless @_hasNotifyBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.notify[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.notify[property] = bindingset else delete @_bindings.notify[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.OBSERVE) when MztObject.OBSERVE return unless @_hasObserveBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.observe[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.observe[property] = bindingset else delete @_bindings.observe[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.NOTIFY) when MztObject.SYNC @_removeBinding(property, target, targetProperty, MztObject.NOTIFY) @_removeBinding(property, target, targetProperty, MztObject.OBSERVE) _removeAllBindings: -> @_stripObserveBindings(false) @_stripNotifyBindings(false) _doNotifyBinding: (key) -> bindings = @_bindings.notify[key] return unless bindings? for binding in bindings if binding? if Util.isFunction(binding.target.set) binding.target.set(binding.attr, @get(key)) else binding.target[binding.attr] = @get(key) _createLookups: -> for key,v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Lookup") key = Util.sliceStringBefore(key, "Lookup") @[key] = Util._getPath(v)
true
Util = require './util' {Events} = require './events' exports.MztObject = class MztObject # Internal Constants MODULEKEYWORDS = ['extended', 'included'] # Class Constants @NOTIFY: 2 @OBSERVE: 1 @SYNC: 0 # Class Methods @include: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @[key] = value obj.extended?.apply(@) this @extend: (obj) -> for key, value of obj when key not in MODULEKEYWORDS @::[key] = value obj.included?.apply(@) this @create: (options) -> inst = new this() inst[k] = v for k, v of options inst._bindings = {} inst._bindings.notify = {} inst._bindings.observe = {} inst._bindings.stored = {} inst._createDeclaredBinds() inst._createLookups() inst.init?() inst # Instance Methods constructor: -> @_mozartId = Util.getId() toString: -> "obj-#{@_mozartId}" get: (key) -> if Util.isFunction(@[key]) @[key].call(@) else @[key] set: (key, value) -> oldValue = @[key] if oldValue isnt value # Binding Transfer: This deserves some explanation. # Take a look at the 'Bindings on targets that change' spec in object-spec.coffee # Essentially for this to work, when a property is set, if the old value is an # MztObject then we need to strip all bindings from it and store them on *this* # object. If the new value is also a MztObject, we need to apply those stored # bindings to the new object. if oldValue instanceof Mozart.MztObject @_bindings.stored[key] = { notify: oldValue._stripNotifyBindings(true) observe: oldValue._stripObserveBindings(true) } if @_bindings.stored[key].notify == {} and @_bindings.stored[key].observe == {} delete @_bindings.stored[key] # If the new value is explicitly null, and there are stored bindings for this # property, we should iterate them and set all targets to null. This means # where a binding 'a' is on 'x.y' and 'x' is now null, a should be set to null. if @_bindings.stored[key]? and @_bindings.stored[key].notify? and value == null for nv, bindings of @_bindings.stored[key].notify for binding in bindings binding.target.set(binding.attr, null) if value instanceof Mozart.MztObject and @_bindings.stored[key]? value._addNotifyBindings(@_bindings.stored[key].notify) unless @_bindings.stored[key].notify == {} value._addObserveBindings(@_bindings.stored[key].observe) unless @_bindings.stored[key].observe == {} delete @_bindings.stored[key] @[key] = value @_doNotifyBinding(key) @publish('change') @publish('change:'+key) bind: (args...) -> console.warn "'bind' will be depreciated in Mozart 0.2.0. Please use 'subscribe'." if console? @subscribe(args...) subscribe: (args...) -> Events.subscribe(@_mozartId, args...) @ one: (args...) -> console.warn "'one' will be depreciated in Mozart 0.2.0. Please use 'subscribeOnce'." if console? @subscribeOnce(args...) subscribeOnce: (args...) -> Events.subscribeOnce(@_mozartId, args...) @ publish: (args...) -> console.warn "'publish' will be depreciated in Mozart 0.2.0. Please use 'publish'." if console? @publish(args...) publish: (args...) -> Events.publish(@_mozartId, args...) @ unbind: (args...) -> console.warn "'unbind' will be depreciated in Mozart 0.2.0. Please use 'unsubscribe'." if console? @unsubscribe(args...) unsubscribe: (args...) -> Events.unsubscribe(@_mozartId, args...) @ release: -> return if @released @_removeAllBindings() @unsubscribe() for own k,v of @ @[k] = undefined delete @[k] @released = true # Private Methods _stripNotifyBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.notify bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.NOTIFY) bindings _addNotifyBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.NOTIFY, binding.transferable) _stripObserveBindings: (transferOnly = false) -> bindings = {} for key, cbindings of @_bindings.observe bindings[key] = [] for binding in cbindings when (!transferOnly or binding.transferable) bindings[key].push binding @_removeBinding(key, binding.target, binding.attr, MztObject.OBSERVE) bindings _addObserveBindings: (bindingset) -> for key, bindings of bindingset for binding in bindings @_createBinding(key, binding.target, binding.attr, MztObject.OBSERVE, binding.transferable) _createDeclaredBinds: -> for key, v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Binding") key = Util.sliceStringBefore(key, "Binding") type = MztObject.SYNC if Util.stringEndsWith(key, 'Observe') key = Util.sliceStringBefore(key, "Observe") type = MztObject.OBSERVE else if Util.stringEndsWith(key, 'Notify') key = Util.PI:KEY:<KEY>END_PIStringBefore(key, "Notify") type = MztObject.NOTIFY [path, attr] = Util.parsePath(v) if path? obj = Util._getPath(@,path) else obj = @ @_createBinding(key, obj, attr, type, Util.isAbsolutePath(v)) _hasNotifyBinding: (property, target, targetProperty, type) -> return false unless @_bindings.notify[property]? for binding in @_bindings.notify[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _hasObserveBinding: (property, target, targetProperty, type) -> return false unless @_bindings.observe[property]? for binding in @_bindings.observe[property] return true if binding.attr==targetProperty and binding.target._mozartId==target._mozartId return false _createBinding: (property, target, targetProperty, type, transferable) -> switch type when MztObject.NOTIFY return if @_hasNotifyBinding(property, target, targetProperty, type) @_bindings.notify[property] ?= [] @_bindings.notify[property].push({attr:targetProperty, target: target, transferable: transferable}) if target instanceof MztObject target._createBinding(targetProperty, @, property, MztObject.OBSERVE, transferable) @_doNotifyBinding(property) when MztObject.OBSERVE return if @_hasObserveBinding(property, target, targetProperty, type) unless target instanceof MztObject Util.warn "Binding #{property}ObserveBinding on",@,": target",target,"is not a MztObject" return @_bindings.observe[property] ?= [] @_bindings.observe[property].push({attr:targetProperty, target: target, transferable: transferable}) target._createBinding(targetProperty, @, property, MztObject.NOTIFY, transferable) when MztObject.SYNC @_createBinding(property, target, targetProperty, MztObject.OBSERVE, transferable) @_createBinding(property, target, targetProperty, MztObject.NOTIFY, transferable) _removeBinding: (property, target, targetProperty, type) -> switch type when MztObject.NOTIFY return unless @_hasNotifyBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.notify[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.notify[property] = bindingset else delete @_bindings.notify[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.OBSERVE) when MztObject.OBSERVE return unless @_hasObserveBinding(property, target, targetProperty) bindingset = [] for binding in @_bindings.observe[property] bindingset.push binding unless binding.attr==targetProperty and binding.target._mozartId==target._mozartId unless bindingset.length == 0 @_bindings.observe[property] = bindingset else delete @_bindings.observe[property] if target instanceof MztObject target._removeBinding(targetProperty, @, property, MztObject.NOTIFY) when MztObject.SYNC @_removeBinding(property, target, targetProperty, MztObject.NOTIFY) @_removeBinding(property, target, targetProperty, MztObject.OBSERVE) _removeAllBindings: -> @_stripObserveBindings(false) @_stripNotifyBindings(false) _doNotifyBinding: (key) -> bindings = @_bindings.notify[key] return unless bindings? for binding in bindings if binding? if Util.isFunction(binding.target.set) binding.target.set(binding.attr, @get(key)) else binding.target[binding.attr] = @get(key) _createLookups: -> for key,v of @ when !Util.isFunction(@[key]) and Util.stringEndsWith(key, "Lookup") key = Util.sliceStringBefore(key, "Lookup") @[key] = Util._getPath(v)
[ { "context": "view Custom reporters for gulp-scsslint\n * @author J-Sek\n###\n\n###\n * Emit error formatted for Visual Studi", "end": 72, "score": 0.9849093556404114, "start": 67, "tag": "NAME", "value": "J-Sek" } ]
index.coffee
jsek/gulp-scss-lint-visualstudio
1
### * @fileoverview Custom reporters for gulp-scsslint * @author J-Sek ### ### * Emit error formatted for Visual Studio on first error * Note: Intentially ignore warnings * Usage: Inline - intended for 'customReportField' ### extend = require('util')._extend getReporter = (opts = {}) -> opts = extend opts print = (file, stream) -> if (opts.errorsOnly and file.scsslint.errors > 0) or file.scsslint.issues > 0 for issue in file.scsslint.issues if (opts.errorsOnly and issue.severity isnt 'error') then continue place = "(#{issue.line},#{issue.column})" message = "#{file.path}#{place}: ScssLint #{issue.severity}: (#{issue.linter}) #{issue.reason}" process.stderr.write(message+'\n') unless opts.printAll process.exit 1 return print module.exports = getReporter
33828
### * @fileoverview Custom reporters for gulp-scsslint * @author <NAME> ### ### * Emit error formatted for Visual Studio on first error * Note: Intentially ignore warnings * Usage: Inline - intended for 'customReportField' ### extend = require('util')._extend getReporter = (opts = {}) -> opts = extend opts print = (file, stream) -> if (opts.errorsOnly and file.scsslint.errors > 0) or file.scsslint.issues > 0 for issue in file.scsslint.issues if (opts.errorsOnly and issue.severity isnt 'error') then continue place = "(#{issue.line},#{issue.column})" message = "#{file.path}#{place}: ScssLint #{issue.severity}: (#{issue.linter}) #{issue.reason}" process.stderr.write(message+'\n') unless opts.printAll process.exit 1 return print module.exports = getReporter
true
### * @fileoverview Custom reporters for gulp-scsslint * @author PI:NAME:<NAME>END_PI ### ### * Emit error formatted for Visual Studio on first error * Note: Intentially ignore warnings * Usage: Inline - intended for 'customReportField' ### extend = require('util')._extend getReporter = (opts = {}) -> opts = extend opts print = (file, stream) -> if (opts.errorsOnly and file.scsslint.errors > 0) or file.scsslint.issues > 0 for issue in file.scsslint.issues if (opts.errorsOnly and issue.severity isnt 'error') then continue place = "(#{issue.line},#{issue.column})" message = "#{file.path}#{place}: ScssLint #{issue.severity}: (#{issue.linter}) #{issue.reason}" process.stderr.write(message+'\n') unless opts.printAll process.exit 1 return print module.exports = getReporter
[ { "context": "length.should.equal 1\n h1.text().should.equal 'Pablo Picasso, MADONNA PAINTING — Auction Result'\n\n it 'has a ", "end": 1652, "score": 0.9991316795349121, "start": 1639, "tag": "NAME", "value": "Pablo Picasso" }, { "context": "h2').text().should.equal 'More auction results for Pablo Picasso'\n $results.find('tbody > tr').length.should.eq", "end": 2224, "score": 0.9520797729492188, "start": 2211, "tag": "NAME", "value": "Pablo Picasso" } ]
src/desktop/components/auction_lots/test/templates/detail.test.coffee
jo-rs/force
0
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' benv = require 'benv' { fabricate } = require '@artsy/antigravity' { resolve } = require 'path' Artist = require '../../../../models/artist' AuctionLot = require '../../../../models/auction_lot' AuctionLots = require '../../../../collections/auction_lots' Artworks = require '../../../../collections/artworks' CurrentUser = require '../../../../models/current_user' render = (templateName) -> filename = path.resolve __dirname, "../../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Detail auction lots template', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') @lot = new AuctionLot fabricate 'auction_result' @artist = new Artist fabricate 'artist', published_artworks_count: 2, forsale_artworks_count: 1 @artworks = new Artworks [fabricate 'artwork'] @auctionLots = new AuctionLots _.times(3, -> new AuctionLot fabricate 'auction_result'), state: totalRecords: 1 benv.render resolve(__dirname, '../../templates/detail.jade'), { sd: {} lot: @lot artist: @artist artworks: @artworks auctionLots: @auctionLots asset: (->) }, => @$template = $('body') @template = @$template.html() done() after -> benv.teardown() it 'has a single h1 tag describing the artist and title', -> (h1 = @$template.find('h1')).length.should.equal 1 h1.text().should.equal 'Pablo Picasso, MADONNA PAINTING — Auction Result' it 'has a link to the lot on the external auction site', -> @$template.find('.ard-external').text().should.containEql 'Visit the lot on lempertz-online.de' it 'has an h3 tag describing the artist available/reference works', -> @$template.find('h3.ara-available-works-count').text().should.equal '1 available work & 1 reference work' it 'displays more auction results', -> $results = @$template.find('.auction-result-more-results') $results.find('h2').text().should.equal 'More auction results for Pablo Picasso' $results.find('tbody > tr').length.should.equal 3
161630
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' benv = require 'benv' { fabricate } = require '@artsy/antigravity' { resolve } = require 'path' Artist = require '../../../../models/artist' AuctionLot = require '../../../../models/auction_lot' AuctionLots = require '../../../../collections/auction_lots' Artworks = require '../../../../collections/artworks' CurrentUser = require '../../../../models/current_user' render = (templateName) -> filename = path.resolve __dirname, "../../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Detail auction lots template', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') @lot = new AuctionLot fabricate 'auction_result' @artist = new Artist fabricate 'artist', published_artworks_count: 2, forsale_artworks_count: 1 @artworks = new Artworks [fabricate 'artwork'] @auctionLots = new AuctionLots _.times(3, -> new AuctionLot fabricate 'auction_result'), state: totalRecords: 1 benv.render resolve(__dirname, '../../templates/detail.jade'), { sd: {} lot: @lot artist: @artist artworks: @artworks auctionLots: @auctionLots asset: (->) }, => @$template = $('body') @template = @$template.html() done() after -> benv.teardown() it 'has a single h1 tag describing the artist and title', -> (h1 = @$template.find('h1')).length.should.equal 1 h1.text().should.equal '<NAME>, MADONNA PAINTING — Auction Result' it 'has a link to the lot on the external auction site', -> @$template.find('.ard-external').text().should.containEql 'Visit the lot on lempertz-online.de' it 'has an h3 tag describing the artist available/reference works', -> @$template.find('h3.ara-available-works-count').text().should.equal '1 available work & 1 reference work' it 'displays more auction results', -> $results = @$template.find('.auction-result-more-results') $results.find('h2').text().should.equal 'More auction results for <NAME>' $results.find('tbody > tr').length.should.equal 3
true
_ = require 'underscore' jade = require 'jade' path = require 'path' fs = require 'fs' Backbone = require 'backbone' benv = require 'benv' { fabricate } = require '@artsy/antigravity' { resolve } = require 'path' Artist = require '../../../../models/artist' AuctionLot = require '../../../../models/auction_lot' AuctionLots = require '../../../../collections/auction_lots' Artworks = require '../../../../collections/artworks' CurrentUser = require '../../../../models/current_user' render = (templateName) -> filename = path.resolve __dirname, "../../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'Detail auction lots template', -> before (done) -> benv.setup => benv.expose $: benv.require('jquery'), jQuery: benv.require('jquery') @lot = new AuctionLot fabricate 'auction_result' @artist = new Artist fabricate 'artist', published_artworks_count: 2, forsale_artworks_count: 1 @artworks = new Artworks [fabricate 'artwork'] @auctionLots = new AuctionLots _.times(3, -> new AuctionLot fabricate 'auction_result'), state: totalRecords: 1 benv.render resolve(__dirname, '../../templates/detail.jade'), { sd: {} lot: @lot artist: @artist artworks: @artworks auctionLots: @auctionLots asset: (->) }, => @$template = $('body') @template = @$template.html() done() after -> benv.teardown() it 'has a single h1 tag describing the artist and title', -> (h1 = @$template.find('h1')).length.should.equal 1 h1.text().should.equal 'PI:NAME:<NAME>END_PI, MADONNA PAINTING — Auction Result' it 'has a link to the lot on the external auction site', -> @$template.find('.ard-external').text().should.containEql 'Visit the lot on lempertz-online.de' it 'has an h3 tag describing the artist available/reference works', -> @$template.find('h3.ara-available-works-count').text().should.equal '1 available work & 1 reference work' it 'displays more auction results', -> $results = @$template.find('.auction-result-more-results') $results.find('h2').text().should.equal 'More auction results for PI:NAME:<NAME>END_PI' $results.find('tbody > tr').length.should.equal 3
[ { "context": ": (name) -> @internal = name\n obj = new Cls 'Felix'\n (-> obj.setName '1234567890').should.not.t", "end": 2098, "score": 0.9994363188743591, "start": 2093, "tag": "NAME", "value": "Felix" }, { "context": "ame: -> @new.name() == @name\n obj = new Cls 'Felix'\n (-> obj.setName 'Peter').should.throw dbc.", "end": 2752, "score": 0.9989804029464722, "start": 2747, "tag": "NAME", "value": "Felix" }, { "context": " obj = new Cls 'Felix'\n (-> obj.setName 'Peter').should.throw dbc.ContractException, \\\n \"", "end": 2782, "score": 0.9990947246551514, "start": 2777, "tag": "NAME", "value": "Peter" } ]
test/coffee-dbc.coffee
felixrabe/coffee-dbc
1
should = require('chai').should() dbc = require '../src/coffee-dbc' describe 'Design By Contract', -> describe '#class', -> it 'should return a class', -> Cls = dbc.class -> new Cls it 'should allow for a constructor', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) it 'should not allow direct access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) should.not.exist obj.x describe 'Queries', -> it 'should be possible', -> Cls = dbc.class -> queries: x: -> 24 obj = new Cls obj.x().should.equal 24 it 'should have access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> queries: x: -> @x * 2 new Cls(5).x().should.equal 10 it 'should not mutate object state', -> Cls = dbc.class -> constructor: (@x = 0) -> queries: x: -> @x++ (-> new Cls(2).x()).should.throw dbc.ContractException, \ "Object state was mutated by query 'x'" describe 'Commands', -> it 'should be possible and have access to instance variables', -> Cls = dbc.class -> constructor: -> @internal = 0 queries: x: -> @internal commands: addToX: (x) -> do: (x) -> @internal += x obj = new Cls obj.x().should.equal 0 obj.addToX(33) obj.x().should.equal 33 obj.addToX(15) obj.x().should.equal 48 it 'should be forced to return undefined', -> Cls = dbc.class -> commands: justChangeSomething: -> do: -> return 'a value' should.not.exist new Cls().justChangeSomething() it 'should allow for preconditions ("require")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> require: nameIsNotLongerThan10Characters: -> @name.length <= 10 do: (name) -> @internal = name obj = new Cls 'Felix' (-> obj.setName '1234567890').should.not.throw Error (-> obj.setName '12345678901').should.throw dbc.ContractException, \ "Contract 'setName.require.nameIsNotLongerThan10Characters' was broken" obj.name().should.not.equal '12345678901' obj.name().should.equal '1234567890' it 'should allow for postconditions ("ensure")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> do: (name) -> @internal_ = name ensure: actuallySetsName: -> @new.name() == @name obj = new Cls 'Felix' (-> obj.setName 'Peter').should.throw dbc.ContractException, \ "Contract 'setName.ensure.actuallySetsName' was broken" it 'should provide the previous state in postconditions', -> Cls = dbc.class -> constructor: (@_x) -> queries: x: -> @_x commands: incrementByOne: -> do: -> @_x += 1 ensure: incrementsXByOne: -> # typeof @old.x != 'undefined' @new.x() == @old.x() + 1 obj = new Cls(0) (-> obj.incrementByOne()).should.not.throw Error describe 'Class Invariant', -> it 'should be checked after construction', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' (-> new Cls 5).should.throw dbc.ContractException, \ "Contract 'invariant.nameIsAString' was broken" (-> new Cls 5).should.not.throw \ "Contract 'nameIsAString' was broken" it 'should check for correct values', -> Cls = dbc.class -> constructor: (@internal) -> queries: x: -> @internal invariant: xIsSmallerThan12: -> @new.x() < 12 (-> new Cls 5).should.not.throw Error (-> new Cls 15).should.throw Error (-> new Cls 15).should.throw dbc.ContractException it 'should be checked after every command call', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' commands: setName: (name) -> do: (name) -> @internal = name obj = null (-> new Cls).should.throw dbc.ContractException (-> new Cls 5).should.throw dbc.ContractException (-> obj = new Cls 'Heinz').should.not.throw dbc.ContractException (-> obj.setName 5).should.throw dbc.ContractException, /nameIsAString/ describe '#getFnArgNames', -> it 'should get the list of argument names', -> should.not.exist dbc.getFnArgNames -> (dbc.getFnArgNames (alabama) ->).should.deep.equal ['alabama'] (dbc.getFnArgNames (a, b, c = 5) ->).should.deep.equal ['a', 'b', 'c'] should.not.exist dbc.getFnArgNames (a, b, c...) -> # CoffeeScript uses arguments here describe 'Time Of Day Example', -> it 'reduced example 1 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 0 queries: hour: -> @hour commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h coffeeTime = new TimeOfDay(); (-> coffeeTime.setHour 23).should.not.throw Error (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'reduced example 2 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 5 queries: hour: -> @hour minute: -> @minute commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 5 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'full example should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 2 @minute = 3 @second = 4 queries: hour: -> @hour minute: -> @minute second: -> @second commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() secondUnchanged: -> @new.second() == @old.second() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() secondUnchanged: -> @new.second() == @old.second() setSecond: (s) -> require: validM: -> 0 <= @s and @s <= 59 do: (s) -> @second = s ensure: secondSet: -> @new.second() == @s hourUnchanged: -> @new.hour() == @old.hour() minuteUnchanged: -> @new.minute() == @old.minute() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 2 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException coffeeTime.minute().should.equal 3 (-> coffeeTime.setMinute 59).should.not.throw Error coffeeTime.minute().should.equal 59 (-> coffeeTime.setMinute 60).should.throw dbc.ContractException coffeeTime.second().should.equal 4 (-> coffeeTime.setSecond 59).should.not.throw Error coffeeTime.second().should.equal 59 (-> coffeeTime.setSecond 60).should.throw dbc.ContractException
149564
should = require('chai').should() dbc = require '../src/coffee-dbc' describe 'Design By Contract', -> describe '#class', -> it 'should return a class', -> Cls = dbc.class -> new Cls it 'should allow for a constructor', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) it 'should not allow direct access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) should.not.exist obj.x describe 'Queries', -> it 'should be possible', -> Cls = dbc.class -> queries: x: -> 24 obj = new Cls obj.x().should.equal 24 it 'should have access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> queries: x: -> @x * 2 new Cls(5).x().should.equal 10 it 'should not mutate object state', -> Cls = dbc.class -> constructor: (@x = 0) -> queries: x: -> @x++ (-> new Cls(2).x()).should.throw dbc.ContractException, \ "Object state was mutated by query 'x'" describe 'Commands', -> it 'should be possible and have access to instance variables', -> Cls = dbc.class -> constructor: -> @internal = 0 queries: x: -> @internal commands: addToX: (x) -> do: (x) -> @internal += x obj = new Cls obj.x().should.equal 0 obj.addToX(33) obj.x().should.equal 33 obj.addToX(15) obj.x().should.equal 48 it 'should be forced to return undefined', -> Cls = dbc.class -> commands: justChangeSomething: -> do: -> return 'a value' should.not.exist new Cls().justChangeSomething() it 'should allow for preconditions ("require")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> require: nameIsNotLongerThan10Characters: -> @name.length <= 10 do: (name) -> @internal = name obj = new Cls '<NAME>' (-> obj.setName '1234567890').should.not.throw Error (-> obj.setName '12345678901').should.throw dbc.ContractException, \ "Contract 'setName.require.nameIsNotLongerThan10Characters' was broken" obj.name().should.not.equal '12345678901' obj.name().should.equal '1234567890' it 'should allow for postconditions ("ensure")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> do: (name) -> @internal_ = name ensure: actuallySetsName: -> @new.name() == @name obj = new Cls '<NAME>' (-> obj.setName '<NAME>').should.throw dbc.ContractException, \ "Contract 'setName.ensure.actuallySetsName' was broken" it 'should provide the previous state in postconditions', -> Cls = dbc.class -> constructor: (@_x) -> queries: x: -> @_x commands: incrementByOne: -> do: -> @_x += 1 ensure: incrementsXByOne: -> # typeof @old.x != 'undefined' @new.x() == @old.x() + 1 obj = new Cls(0) (-> obj.incrementByOne()).should.not.throw Error describe 'Class Invariant', -> it 'should be checked after construction', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' (-> new Cls 5).should.throw dbc.ContractException, \ "Contract 'invariant.nameIsAString' was broken" (-> new Cls 5).should.not.throw \ "Contract 'nameIsAString' was broken" it 'should check for correct values', -> Cls = dbc.class -> constructor: (@internal) -> queries: x: -> @internal invariant: xIsSmallerThan12: -> @new.x() < 12 (-> new Cls 5).should.not.throw Error (-> new Cls 15).should.throw Error (-> new Cls 15).should.throw dbc.ContractException it 'should be checked after every command call', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' commands: setName: (name) -> do: (name) -> @internal = name obj = null (-> new Cls).should.throw dbc.ContractException (-> new Cls 5).should.throw dbc.ContractException (-> obj = new Cls 'Heinz').should.not.throw dbc.ContractException (-> obj.setName 5).should.throw dbc.ContractException, /nameIsAString/ describe '#getFnArgNames', -> it 'should get the list of argument names', -> should.not.exist dbc.getFnArgNames -> (dbc.getFnArgNames (alabama) ->).should.deep.equal ['alabama'] (dbc.getFnArgNames (a, b, c = 5) ->).should.deep.equal ['a', 'b', 'c'] should.not.exist dbc.getFnArgNames (a, b, c...) -> # CoffeeScript uses arguments here describe 'Time Of Day Example', -> it 'reduced example 1 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 0 queries: hour: -> @hour commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h coffeeTime = new TimeOfDay(); (-> coffeeTime.setHour 23).should.not.throw Error (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'reduced example 2 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 5 queries: hour: -> @hour minute: -> @minute commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 5 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'full example should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 2 @minute = 3 @second = 4 queries: hour: -> @hour minute: -> @minute second: -> @second commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() secondUnchanged: -> @new.second() == @old.second() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() secondUnchanged: -> @new.second() == @old.second() setSecond: (s) -> require: validM: -> 0 <= @s and @s <= 59 do: (s) -> @second = s ensure: secondSet: -> @new.second() == @s hourUnchanged: -> @new.hour() == @old.hour() minuteUnchanged: -> @new.minute() == @old.minute() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 2 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException coffeeTime.minute().should.equal 3 (-> coffeeTime.setMinute 59).should.not.throw Error coffeeTime.minute().should.equal 59 (-> coffeeTime.setMinute 60).should.throw dbc.ContractException coffeeTime.second().should.equal 4 (-> coffeeTime.setSecond 59).should.not.throw Error coffeeTime.second().should.equal 59 (-> coffeeTime.setSecond 60).should.throw dbc.ContractException
true
should = require('chai').should() dbc = require '../src/coffee-dbc' describe 'Design By Contract', -> describe '#class', -> it 'should return a class', -> Cls = dbc.class -> new Cls it 'should allow for a constructor', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) it 'should not allow direct access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> obj = new Cls(24) should.not.exist obj.x describe 'Queries', -> it 'should be possible', -> Cls = dbc.class -> queries: x: -> 24 obj = new Cls obj.x().should.equal 24 it 'should have access to instance variables', -> Cls = dbc.class -> constructor: (@x) -> queries: x: -> @x * 2 new Cls(5).x().should.equal 10 it 'should not mutate object state', -> Cls = dbc.class -> constructor: (@x = 0) -> queries: x: -> @x++ (-> new Cls(2).x()).should.throw dbc.ContractException, \ "Object state was mutated by query 'x'" describe 'Commands', -> it 'should be possible and have access to instance variables', -> Cls = dbc.class -> constructor: -> @internal = 0 queries: x: -> @internal commands: addToX: (x) -> do: (x) -> @internal += x obj = new Cls obj.x().should.equal 0 obj.addToX(33) obj.x().should.equal 33 obj.addToX(15) obj.x().should.equal 48 it 'should be forced to return undefined', -> Cls = dbc.class -> commands: justChangeSomething: -> do: -> return 'a value' should.not.exist new Cls().justChangeSomething() it 'should allow for preconditions ("require")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> require: nameIsNotLongerThan10Characters: -> @name.length <= 10 do: (name) -> @internal = name obj = new Cls 'PI:NAME:<NAME>END_PI' (-> obj.setName '1234567890').should.not.throw Error (-> obj.setName '12345678901').should.throw dbc.ContractException, \ "Contract 'setName.require.nameIsNotLongerThan10Characters' was broken" obj.name().should.not.equal '12345678901' obj.name().should.equal '1234567890' it 'should allow for postconditions ("ensure")', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal commands: setName: (name) -> do: (name) -> @internal_ = name ensure: actuallySetsName: -> @new.name() == @name obj = new Cls 'PI:NAME:<NAME>END_PI' (-> obj.setName 'PI:NAME:<NAME>END_PI').should.throw dbc.ContractException, \ "Contract 'setName.ensure.actuallySetsName' was broken" it 'should provide the previous state in postconditions', -> Cls = dbc.class -> constructor: (@_x) -> queries: x: -> @_x commands: incrementByOne: -> do: -> @_x += 1 ensure: incrementsXByOne: -> # typeof @old.x != 'undefined' @new.x() == @old.x() + 1 obj = new Cls(0) (-> obj.incrementByOne()).should.not.throw Error describe 'Class Invariant', -> it 'should be checked after construction', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' (-> new Cls 5).should.throw dbc.ContractException, \ "Contract 'invariant.nameIsAString' was broken" (-> new Cls 5).should.not.throw \ "Contract 'nameIsAString' was broken" it 'should check for correct values', -> Cls = dbc.class -> constructor: (@internal) -> queries: x: -> @internal invariant: xIsSmallerThan12: -> @new.x() < 12 (-> new Cls 5).should.not.throw Error (-> new Cls 15).should.throw Error (-> new Cls 15).should.throw dbc.ContractException it 'should be checked after every command call', -> Cls = dbc.class -> constructor: (@internal) -> queries: name: -> @internal invariant: nameIsAString: -> typeof @new.name() == 'string' commands: setName: (name) -> do: (name) -> @internal = name obj = null (-> new Cls).should.throw dbc.ContractException (-> new Cls 5).should.throw dbc.ContractException (-> obj = new Cls 'Heinz').should.not.throw dbc.ContractException (-> obj.setName 5).should.throw dbc.ContractException, /nameIsAString/ describe '#getFnArgNames', -> it 'should get the list of argument names', -> should.not.exist dbc.getFnArgNames -> (dbc.getFnArgNames (alabama) ->).should.deep.equal ['alabama'] (dbc.getFnArgNames (a, b, c = 5) ->).should.deep.equal ['a', 'b', 'c'] should.not.exist dbc.getFnArgNames (a, b, c...) -> # CoffeeScript uses arguments here describe 'Time Of Day Example', -> it 'reduced example 1 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 0 queries: hour: -> @hour commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h coffeeTime = new TimeOfDay(); (-> coffeeTime.setHour 23).should.not.throw Error (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'reduced example 2 should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 5 queries: hour: -> @hour minute: -> @minute commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 5 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException it 'full example should work', -> TimeOfDay = dbc.class -> constructor: -> @hour = 2 @minute = 3 @second = 4 queries: hour: -> @hour minute: -> @minute second: -> @second commands: setHour: (h) -> require: validH: -> 0 <= @h <= 23 do: (h) -> @hour = h ensure: hourSet: -> @new.hour() == @h minuteUnchanged: -> @new.minute() == @old.minute() secondUnchanged: -> @new.second() == @old.second() setMinute: (m) -> require: validM: -> 0 <= @m and @m <= 59 do: (m) -> @minute = m ensure: minuteSet: -> @new.minute() == @m hourUnchanged: -> @new.hour() == @old.hour() secondUnchanged: -> @new.second() == @old.second() setSecond: (s) -> require: validM: -> 0 <= @s and @s <= 59 do: (s) -> @second = s ensure: secondSet: -> @new.second() == @s hourUnchanged: -> @new.hour() == @old.hour() minuteUnchanged: -> @new.minute() == @old.minute() coffeeTime = new TimeOfDay(); coffeeTime.hour().should.equal 2 (-> coffeeTime.setHour 23).should.not.throw Error coffeeTime.hour().should.equal 23 (-> coffeeTime.setHour 24).should.throw dbc.ContractException coffeeTime.minute().should.equal 3 (-> coffeeTime.setMinute 59).should.not.throw Error coffeeTime.minute().should.equal 59 (-> coffeeTime.setMinute 60).should.throw dbc.ContractException coffeeTime.second().should.equal 4 (-> coffeeTime.setSecond 59).should.not.throw Error coffeeTime.second().should.equal 59 (-> coffeeTime.setSecond 60).should.throw dbc.ContractException
[ { "context": " {{{/}}}\n '''\n model.set 'myMessage', 'Heyo'\n expect(view.get 'test').to.equal 'say \"<!--$", "end": 2582, "score": 0.7444685101509094, "start": 2578, "tag": "NAME", "value": "Heyo" }, { "context": "age}}}></div>\n '''\n model.set 'myMessage', 'Heyo'\n expect(view.get 'test').to.equal 'say \"<div ", "end": 2901, "score": 0.8456413149833679, "start": 2897, "tag": "NAME", "value": "Heyo" } ]
test/View.components.mocha.coffee
rajiv20/derby
0
{expect, calls} = require 'racer/test/util' {DetachedModel: Model} = require './mocks' View = require '../lib/View.server' describe 'App HTML components', -> view = model = null beforeEach (done) -> view = new View model = new Model view._init model, false, done it 'supports void components', -> view.make 'test', 'say "<app:test2>"' view.make 'test2', 'hi' expect(view.get 'test').to.equal 'say "hi"' it 'supports literal attributes', -> view.make 'test', 'say "<app:test2 message="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'macro attributes are case-insensitive', -> view.make 'test', 'say "<app:test2 messAGE="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if messAGE}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'supports boolean and numerical attributes', -> view.make 'test', '<app:test2 show="true"> / <app:test2 num="-4.5"> / <app:test2 show="false">' view.make 'test2', ''' {{{#if show}}} Hi {{{else if equal(num, -4.5)}}} Got it {{{else}}} Nada {{{/}}} ''' expect(view.get 'test').to.equal 'Hi / Got it / Nada' it 'supports variable attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Yo"' expect(view.get 'test', myMessage: 'Heyo').to.equal 'say "Heyo"' it 'supports variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#with message}}} {{text}} {{{/}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports dot syntax for properties of variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{message.text}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports bound attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' model.set 'myMessage', 'Heyo' expect(view.get 'test').to.equal 'say "<!--$0--><!--$1-->Heyo<!--$$1--><!--$$0-->"' it 'supports bound attributes as element attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' <div title={{{message}}}></div> ''' model.set 'myMessage', 'Heyo' expect(view.get 'test').to.equal 'say "<div id=$0 title=Heyo></div>"' it 'supports nonvoid components', -> view.make 'test', '<ul><app:test2><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li></ul>' it 'supports content sections', -> view.make 'test', '<ul><app:test2><@section><i>Heyo</i></@section><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li><li>{{{section}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li><li><i>Heyo</i></li></ul>'
129180
{expect, calls} = require 'racer/test/util' {DetachedModel: Model} = require './mocks' View = require '../lib/View.server' describe 'App HTML components', -> view = model = null beforeEach (done) -> view = new View model = new Model view._init model, false, done it 'supports void components', -> view.make 'test', 'say "<app:test2>"' view.make 'test2', 'hi' expect(view.get 'test').to.equal 'say "hi"' it 'supports literal attributes', -> view.make 'test', 'say "<app:test2 message="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'macro attributes are case-insensitive', -> view.make 'test', 'say "<app:test2 messAGE="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if messAGE}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'supports boolean and numerical attributes', -> view.make 'test', '<app:test2 show="true"> / <app:test2 num="-4.5"> / <app:test2 show="false">' view.make 'test2', ''' {{{#if show}}} Hi {{{else if equal(num, -4.5)}}} Got it {{{else}}} Nada {{{/}}} ''' expect(view.get 'test').to.equal 'Hi / Got it / Nada' it 'supports variable attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Yo"' expect(view.get 'test', myMessage: 'Heyo').to.equal 'say "Heyo"' it 'supports variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#with message}}} {{text}} {{{/}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports dot syntax for properties of variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{message.text}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports bound attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' model.set 'myMessage', '<NAME>' expect(view.get 'test').to.equal 'say "<!--$0--><!--$1-->Heyo<!--$$1--><!--$$0-->"' it 'supports bound attributes as element attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' <div title={{{message}}}></div> ''' model.set 'myMessage', '<NAME>' expect(view.get 'test').to.equal 'say "<div id=$0 title=Heyo></div>"' it 'supports nonvoid components', -> view.make 'test', '<ul><app:test2><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li></ul>' it 'supports content sections', -> view.make 'test', '<ul><app:test2><@section><i>Heyo</i></@section><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li><li>{{{section}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li><li><i>Heyo</i></li></ul>'
true
{expect, calls} = require 'racer/test/util' {DetachedModel: Model} = require './mocks' View = require '../lib/View.server' describe 'App HTML components', -> view = model = null beforeEach (done) -> view = new View model = new Model view._init model, false, done it 'supports void components', -> view.make 'test', 'say "<app:test2>"' view.make 'test2', 'hi' expect(view.get 'test').to.equal 'say "hi"' it 'supports literal attributes', -> view.make 'test', 'say "<app:test2 message="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'macro attributes are case-insensitive', -> view.make 'test', 'say "<app:test2 messAGE="Howdy">" or "<app:test2>"' view.make 'test2', ''' {{{#if messAGE}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Howdy" or "Yo"' it 'supports boolean and numerical attributes', -> view.make 'test', '<app:test2 show="true"> / <app:test2 num="-4.5"> / <app:test2 show="false">' view.make 'test2', ''' {{{#if show}}} Hi {{{else if equal(num, -4.5)}}} Got it {{{else}}} Nada {{{/}}} ''' expect(view.get 'test').to.equal 'Hi / Got it / Nada' it 'supports variable attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' expect(view.get 'test').to.equal 'say "Yo"' expect(view.get 'test', myMessage: 'Heyo').to.equal 'say "Heyo"' it 'supports variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{#with message}}} {{text}} {{{/}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports dot syntax for properties of variable object attributes', -> view.make 'test', 'say "<app:test2 message="{{myMessage}}">"' view.make 'test2', ''' {{{message.text}}} ''' expect(view.get 'test', myMessage: {text: 'Heyo'}).to.equal 'say "Heyo"' it 'supports bound attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' {{{#if message}}} {{{message}}} {{{else}}} Yo {{{/}}} ''' model.set 'myMessage', 'PI:NAME:<NAME>END_PI' expect(view.get 'test').to.equal 'say "<!--$0--><!--$1-->Heyo<!--$$1--><!--$$0-->"' it 'supports bound attributes as element attributes', -> view.make 'test', 'say "<app:test2 message="{myMessage}">"' view.make 'test2', ''' <div title={{{message}}}></div> ''' model.set 'myMessage', 'PI:NAME:<NAME>END_PI' expect(view.get 'test').to.equal 'say "<div id=$0 title=Heyo></div>"' it 'supports nonvoid components', -> view.make 'test', '<ul><app:test2><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li></ul>' it 'supports content sections', -> view.make 'test', '<ul><app:test2><@section><i>Heyo</i></@section><b>Hi!</b></app:test2></ul>' view.make 'test2', '<li>{{{content}}}</li><li>{{{section}}}</li>', {nonvoid: null} expect(view.get 'test').to.equal '<ul><li><b>Hi!</b></li><li><i>Heyo</i></li></ul>'
[ { "context": "nt Twitter/Weibo @ mentions\n\n Copyright (c) 2012 chord.luo@gmail.com\n\n Permission is hereby granted, free of charge,", "end": 84, "score": 0.9999133348464966, "start": 65, "tag": "EMAIL", "value": "chord.luo@gmail.com" } ]
coffee/jquery.caret.coffee
NARKOZ/At.js
3
### Implement Twitter/Weibo @ mentions Copyright (c) 2012 chord.luo@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### ### 本插件操作 textarea 或者 input 内的插入符 只实现了获得插入符在文本框中的位置,我设置 插入符的位置. ### (($) -> getCaretPos = (inputor) -> if document.selection #IE # reference: http://tinyurl.com/86pyc4s ### #assume we select "HATE" in the inputor such as textarea -> { }. * start end-point. * / * < I really [HATE] IE > between the brackets is the selection range. * \ * end end-point. ### range = document.selection.createRange() pos = 0 # selection should in the inputor. if range and range.parentElement() is inputor normalizedValue = inputor.value.replace /\r\n/g, "\n" ### SOMETIME !!! "/r/n" is counted as two char. one line is two, two will be four. balalala. so we have to using the normalized one's length.; ### len = normalizedValue.length ### <[ I really HATE IE ]>: the whole content in the inputor will be the textInputRange. ### textInputRange = inputor.createTextRange() ### _here must be the position of bookmark. / <[ I really [HATE] IE ]> [---------->[ ] : this is what moveToBookmark do. < I really [[HATE] IE ]> : here is result. \ two brackets in should be in line. ### textInputRange.moveToBookmark range.getBookmark() endRange = inputor.createTextRange() ### [--------------------->[] : if set false all end-point goto end. < I really [[HATE] IE []]> ### endRange.collapse false ### ___VS____ / \ < I really [[HATE] IE []]> \_endRange end-point. " > -1" mean the start end-point will be the same or right to the end end-point * simplelly, all in the end. #### if textInputRange.compareEndPoints("StartToEnd", endRange) > -1 #TextRange object will miss "\r\n". So, we count it ourself. start = end = len else ### I really |HATE] IE ]> <-| I really[ [HATE] IE ]> <-[ I reall[y [HATE] IE ]> will return how many unit have moved. ### start = -textInputRange.moveStart "character", -len end = -textInputRange.moveEnd "character", -len else start = inputor.selectionStart return start setCaretPos = (inputor, pos) -> if document.selection #IE range = inputor.createTextRange() range.move "character", pos range.select() else inputor.setSelectionRange pos, pos $.fn.caretPos = (pos) -> inputor = this[0] inputor.focus() if pos setCaretPos(inputor, pos) else getCaretPos(inputor) )(window.jQuery)
84991
### Implement Twitter/Weibo @ mentions Copyright (c) 2012 <EMAIL> 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. ### ### 本插件操作 textarea 或者 input 内的插入符 只实现了获得插入符在文本框中的位置,我设置 插入符的位置. ### (($) -> getCaretPos = (inputor) -> if document.selection #IE # reference: http://tinyurl.com/86pyc4s ### #assume we select "HATE" in the inputor such as textarea -> { }. * start end-point. * / * < I really [HATE] IE > between the brackets is the selection range. * \ * end end-point. ### range = document.selection.createRange() pos = 0 # selection should in the inputor. if range and range.parentElement() is inputor normalizedValue = inputor.value.replace /\r\n/g, "\n" ### SOMETIME !!! "/r/n" is counted as two char. one line is two, two will be four. balalala. so we have to using the normalized one's length.; ### len = normalizedValue.length ### <[ I really HATE IE ]>: the whole content in the inputor will be the textInputRange. ### textInputRange = inputor.createTextRange() ### _here must be the position of bookmark. / <[ I really [HATE] IE ]> [---------->[ ] : this is what moveToBookmark do. < I really [[HATE] IE ]> : here is result. \ two brackets in should be in line. ### textInputRange.moveToBookmark range.getBookmark() endRange = inputor.createTextRange() ### [--------------------->[] : if set false all end-point goto end. < I really [[HATE] IE []]> ### endRange.collapse false ### ___VS____ / \ < I really [[HATE] IE []]> \_endRange end-point. " > -1" mean the start end-point will be the same or right to the end end-point * simplelly, all in the end. #### if textInputRange.compareEndPoints("StartToEnd", endRange) > -1 #TextRange object will miss "\r\n". So, we count it ourself. start = end = len else ### I really |HATE] IE ]> <-| I really[ [HATE] IE ]> <-[ I reall[y [HATE] IE ]> will return how many unit have moved. ### start = -textInputRange.moveStart "character", -len end = -textInputRange.moveEnd "character", -len else start = inputor.selectionStart return start setCaretPos = (inputor, pos) -> if document.selection #IE range = inputor.createTextRange() range.move "character", pos range.select() else inputor.setSelectionRange pos, pos $.fn.caretPos = (pos) -> inputor = this[0] inputor.focus() if pos setCaretPos(inputor, pos) else getCaretPos(inputor) )(window.jQuery)
true
### Implement Twitter/Weibo @ mentions Copyright (c) 2012 PI:EMAIL:<EMAIL>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. ### ### 本插件操作 textarea 或者 input 内的插入符 只实现了获得插入符在文本框中的位置,我设置 插入符的位置. ### (($) -> getCaretPos = (inputor) -> if document.selection #IE # reference: http://tinyurl.com/86pyc4s ### #assume we select "HATE" in the inputor such as textarea -> { }. * start end-point. * / * < I really [HATE] IE > between the brackets is the selection range. * \ * end end-point. ### range = document.selection.createRange() pos = 0 # selection should in the inputor. if range and range.parentElement() is inputor normalizedValue = inputor.value.replace /\r\n/g, "\n" ### SOMETIME !!! "/r/n" is counted as two char. one line is two, two will be four. balalala. so we have to using the normalized one's length.; ### len = normalizedValue.length ### <[ I really HATE IE ]>: the whole content in the inputor will be the textInputRange. ### textInputRange = inputor.createTextRange() ### _here must be the position of bookmark. / <[ I really [HATE] IE ]> [---------->[ ] : this is what moveToBookmark do. < I really [[HATE] IE ]> : here is result. \ two brackets in should be in line. ### textInputRange.moveToBookmark range.getBookmark() endRange = inputor.createTextRange() ### [--------------------->[] : if set false all end-point goto end. < I really [[HATE] IE []]> ### endRange.collapse false ### ___VS____ / \ < I really [[HATE] IE []]> \_endRange end-point. " > -1" mean the start end-point will be the same or right to the end end-point * simplelly, all in the end. #### if textInputRange.compareEndPoints("StartToEnd", endRange) > -1 #TextRange object will miss "\r\n". So, we count it ourself. start = end = len else ### I really |HATE] IE ]> <-| I really[ [HATE] IE ]> <-[ I reall[y [HATE] IE ]> will return how many unit have moved. ### start = -textInputRange.moveStart "character", -len end = -textInputRange.moveEnd "character", -len else start = inputor.selectionStart return start setCaretPos = (inputor, pos) -> if document.selection #IE range = inputor.createTextRange() range.move "character", pos range.select() else inputor.setSelectionRange pos, pos $.fn.caretPos = (pos) -> inputor = this[0] inputor.focus() if pos setCaretPos(inputor, pos) else getCaretPos(inputor) )(window.jQuery)
[ { "context": "###\nCopyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(", "end": 36, "score": 0.9998359084129333, "start": 24, "tag": "NAME", "value": "Bill Burdick" }, { "context": ", Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure\n\n(licensed with ZLIB license)\n\nThis softw", "end": 75, "score": 0.9992289543151855, "start": 72, "tag": "USERNAME", "value": "zot" } ]
METEOR-OLD/private/build/gen.coffee
zot/Leisure
58
### Copyright (C) 2013, Bill Burdick, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { simpyCons, resolve, lazy, verboseMsg, nsLog, } = root = (module ? {}).exports = require '15-base' rz = resolve lz = lazy lc = Leisure_call { nameSub, getLitVal, getRefName, getLambdaVar, getLambdaBody, getApplyFunc, getApplyArg, getAnnoName, getAnnoData, getAnnoBody, getLetName, getLetValue, getLetBody, Leisure_lit, Leisure_ref, Leisure_lambda, Leisure_apply, Leisure_let, Leisure_anno, setType, setDataType, cons, Nil, define, functionInfo, getPos, isNil, } = require '16-ast' { makeSyncMonad, runMonad, _true, _false, left, right, booleanFor, newConsFrom, } = require '17-runtime' _ = (Leisure.require ? require) 'lodash.min' consFrom = newConsFrom sm = if sourceMap? then sourceMap else (if module? then require else Leisure.require)("source-map") { SourceNode, SourceMapConsumer, } = sm.sourceMap ? sm varNameSub = (n)-> "L_#{nameSub n}" useArity = true #useArity = false collectArgs = (args, result)-> for i in args if Array.isArray i then collectArgs i, result else result.push i result locateAst = (ast)-> [line, col] = pos = getPos(ast).toArray() [line,col] check = (bool, arg)-> if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack checkChild = (child)-> if Array.isArray child for c in child checkChild c else check (typeof child == 'string') || (child instanceof SourceNode), c currentFile = 'NEVERGIVENFILE.lsr' currentFuncName = undefined withFile = (file, name, block)-> oldFileName = currentFile oldFuncName = currentFuncName currentFile = file currentFuncName = name try block() finally currentFile = oldFileName currentFuncName = oldFuncName sn = (ast, str...)-> #(collectArgs str, []).join('') #[file, line, col] = getPos(ast).toArray() [line, offset] = locateAst ast #console.log "SN #{line} #{offset}" check typeof line == 'number', 'line' check typeof offset == 'number', 'offset' checkChild str if line < 1 then line = 1 if currentFile == 'NEVERGIVENFILE.lsr' then console.log new Error("SN CALLED WITHOUT FILE").stack if currentFuncName? #console.log "USING NAME: #{currentFuncName}" new SourceNode(line, offset, currentFile, str, currentFuncName) else new SourceNode(line, offset, currentFile, str) #else new SourceNode(line, offset, currentFile, str) genNode = (ast)-> genUniq ast, Nil, [Nil, 0] gen = (ast)-> genMap(ast).toStringWithSourceMap(file: currentFile).code genSource = (source, ast)-> #console.log "SOURCE: #{source}\nAST: #{ast}" funcname = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName' then getAnnoData ast else null #withFile "data:text/plain;base64,#{btoa source}", funcname, -> withFile "dynamic code with source", funcname, -> sm = genNode(ast).prepend("\n").toStringWithSourceMap file: "dynamic code with source" map = JSON.parse sm.map.toString() map.sourcesContent = [source] code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;utf-8;base64,#{btoa JSON.stringify map}\n" #code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;base64,#{btoa JSON.stringify map}\n" #console.log "CODE: #{code}" #console.log "MAP: #{JSON.stringify map}" code genMap = (ast)-> #console.log "GEN AST: #{ast}" #file = getPos(ast).head().replace /\.lsr$/, '.js.map' hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename' filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr' nameAst = if hasFile then getAnnoBody ast else null #funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else null funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else currentFuncName #console.log "File: #{filename}, func: #{funcname}, nameast: #{nameAst instanceof Leisure_anno}" #if funcname then verboseMsg 'gen', "compiling ast: #{funcname}" #sub = withFile filename, funcname, -> genNode(ast) sub = withFile filename, null, -> genNode(ast) [line, offset] = locateAst ast if funcname then new SourceNode line, offset, filename, sub, funcname else sub findName = (name)-> for i in [root.nameSpacePath.length - 1 .. 0] if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i] if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace else null location = (ast)-> [line, col] = locateAst ast "#{line}:#{col}" genRefName = (ref, uniq, names)-> name = getRefName ref #if isNil (val = names.find (el)-> el == name) then console.log("GLOBAL: #{name}, val = #{val}") #else console.log("LOCAL: #{name}, val = #{val}") #if isNil (val = names.find (el)-> el == name) then "#{currentNameSpace}#{name}" if isNil (val = names.find (el)-> el == name) ns = findName nameSub name if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}" else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}" varNameSub name else uniqName name, uniq genUniq = (ast, names, uniq, count)-> switch ast.constructor when Leisure_lit then sn ast, JSON.stringify getLitVal ast when Leisure_ref then sn ast, "resolve(", (genRefName ast, uniq, names), ")" when Leisure_lambda then genLambda ast, names, uniq, count ? 0 when Leisure_apply if useArity then genArifiedApply ast, names, uniq, arity else sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" when Leisure_let then sn ast, "(function(){\n", (genLets ast, names, uniq), "})()" when Leisure_anno name = getAnnoName ast data = getAnnoData ast if name == 'arity' && useArity && data > 1 genArifiedLambda (getAnnoBody ast), names, uniq, data else genned = genUniq (getAnnoBody ast), names, uniq switch name when 'type' then sn ast, "setType(", (genned), ", '", data, "')" when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')" when 'define' [funcName, arity, src] = data.toArray() sn ast, "define('", funcName, "', (function(){return ", genned, "}), ", arity, ", ", JSON.stringify(src), ")" when 'leisureName' #console.log "DEFINE #{getAnnoData ast} = #{getApplyArg getAnnoBody ast}" genned else genned else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}" # this is a no-op, now define 'newGen', (makeSyncMonad (env, cont)-> console.log "CALL TO OBSOLETE NEWGEN" cont _true), null, null, null, 'parser' genArifiedApply = (ast, names, uniq)-> args = [] func = ast while dumpAnno(func) instanceof Leisure_apply args.push getApplyArg dumpAnno func func = getApplyFunc dumpAnno func args.reverse() info = functionInfo[getRefName func] if dumpAnno(func) instanceof Leisure_ref && info?.newArity && (arity = info?.arity) && arity <= args.length argCode = [] argCode.push ast argCode.push genUniq func, names, uniq argCode.push '(' for i in [0...arity] if i > 0 then argCode.push ', ' argCode.push sn args[i], genApplyArg args[i], names, uniq argCode.push ')' for i in [arity...args.length] by 1 argCode.push '(', (sn args[i], genApplyArg args[i], names, uniq), ')' sn argCode... else ast = dumpAnno ast sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" genLambda = (ast, names, uniq, count)-> name = getLambdaVar ast u = addUniq name, names, uniq n = cons name, names addLambdaProperties ast, sn ast, "function(", (uniqName name, u), "){return ", (genUniq (getLambdaBody ast), n, u, 1), "}" getLambdaArgs = (ast)-> args = [] while ast instanceof Leisure_lambda args.push getLambdaVar ast ast = getLambdaBody ast [args, ast] genArifiedLambda = (ast, names, uniq, arity)-> if arity < 2 then genLambda ast, names, uniq, 0 else args = getNArgs(arity, ast).toArray() argList = _.map(args, ((x)-> 'L_' + x)).join ', ' mainFunc = sn ast, """ (function(#{argList}) { return arguments.callee.length != arguments.length ? Leisure_primCall(arguments.callee, 0, arguments) : """, genUniq(getNthLambdaBody(ast, arity), names, uniq), ";\n})" result = addLambdaProperties ast, (sn ast, mainFunc) annoAst = ast while annoAst instanceof Leisure_anno name = getAnnoName annoAst data = getAnnoData annoAst switch name when 'type' then result = sn ast, "setType(", result, ", '", data, "')" when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')" annoAst = getAnnoBody annoAst result getNthLambdaBody = (ast, n)-> if n == 0 then ast else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1 else throw new Error "Expected lambda but got #{ast}" strRepeat = (string, n)-> result = string for i in [1...n] result += string result (window ? global ? {}).curryCall = curryCall = (args, func)-> f = func args[0] for i in [1...args.length] f = f args[i] f getNArgs = (n, ast)-> d = dumpAnno ast if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d specialAnnotations = ['type', 'dataType', 'define'] arrayify = (cons)-> if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray() else cons getLambdaProperties = (body, props)-> if body instanceof Leisure_anno if !_.contains specialAnnotations, getAnnoName(body) if !props then props = {} value = getAnnoData body props[getAnnoName body] = arrayify value getLambdaProperties getAnnoBody(body), props props addLambdaProperties = (ast, def, extras)-> props = getLambdaProperties getLambdaBody ast if props || extras p = {} if props then _.merge p, props if extras then _.merge p, extras sn ast, "setLambdaProperties(", def, ", ", (JSON.stringify p), ")" else def lcons = (a, b)-> rz(L_cons)(lz a)(lz b) parseErr = (a, b)-> rz(L_parseErr)(a)(b) lconsFrom = (array)-> if array instanceof Array p = rz L_nil for el in array.reverse() p = lcons lconsFrom(el), p p else array assocListProps = null getAssocListProps = -> if !assocListProps assocListProps = lcons lcons('assoc', 'true'), rz(L_nil) assocListProps.properties = assocListProps assocListProps lacons = (key, value, list)-> alist = lcons lcons(key, value), list alist.properties = getAssocListProps() alist (window ? global).setLambdaProperties = (def, props)-> p = rz L_nil for k, v of props p = lacons k, lconsFrom(v), p def.properties = p def lazify = (ast, func)-> sn ast, "function(){return ", func, "}" dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast genApplyArg = (arg, names, uniq)-> d = dumpAnno arg if d instanceof Leisure_apply then lazify d, genUniq arg, names, uniq else if d instanceof Leisure_ref then genRefName d, uniq, names else if d instanceof Leisure_lit then sn arg, JSON.stringify getLitVal d else if d instanceof Leisure_let then sn arg, "function(){return", (genUniq arg, names, uniq), ";}" else if d instanceof Leisure_lambda then sn arg, "lazy(", (genUniq arg, names, uniq), ")" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLetAssign = (arg, names, uniq)-> if dumpAnno(arg) instanceof Leisure_let then sn arg, "function(){", (genLets arg, names, uniq), "}" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLets = (ast, names, uniq)-> bindings = letList ast, [] letNames = _.foldl bindings, ((n, l)-> cons (getLetName l), n), names [letUniq, decs, assigns] = _.foldl bindings, ((result, l)-> [u, code, assigns] = result newU = addUniq (getLetName l), letNames, u letName = uniqName (getLetName l), newU [newU, (cons (sn ast, letName + ' = ', genLetAssign(getLetValue(l), letNames, u)), code), (cons letName, assigns)]), [uniq, Nil, Nil] sn ast, " var ", assigns.reverse().join(', '), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (genUniq (getLastLetBody ast), letNames, letUniq) addUniq = (name, names, uniq)-> if (names.find (el)-> el == name) != Nil [overrides, num] = uniq [(cons (cons name, "#{name}_#{num}"), overrides), num + 1] else uniq uniqName = (name, uniq)-> [uniq] = uniq kv = uniq.find ((el)-> el.head() == name), uniq varNameSub (if kv != Nil then kv.tail() else name) letList = (ast, buf)-> if ast instanceof Leisure_let buf.push ast letList getLetBody(ast), buf else buf getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast define 'runAst', ((code)->(ast)-> jsCode = null try jsCode = gen rz ast eval "(#{jsCode})" catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") msg = "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: " console.log msg + ast() + "\n" + err.stack parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' define 'genAst', ((ast)-> jsCode = null try gen rz ast catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' root.gen = gen root.genMap = genMap root.genSource = genSource root.genNode = genNode root.sourceNode = sn root.withFile = withFile root.curryCall = curryCall #root.useNameSpace = useNameSpace #root.pushNameSpace = pushNameSpace #root.getNameSpacePath = getNameSpacePath #root.clearNameSpacePath = clearNameSpacePath #root.saveNameSpace = saveNameSpace #root.restoreNameSpace = restoreNameSpace root.SourceNode = SourceNode root.SourceMapConsumer = SourceMapConsumer
20909
### Copyright (C) 2013, <NAME>, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { simpyCons, resolve, lazy, verboseMsg, nsLog, } = root = (module ? {}).exports = require '15-base' rz = resolve lz = lazy lc = Leisure_call { nameSub, getLitVal, getRefName, getLambdaVar, getLambdaBody, getApplyFunc, getApplyArg, getAnnoName, getAnnoData, getAnnoBody, getLetName, getLetValue, getLetBody, Leisure_lit, Leisure_ref, Leisure_lambda, Leisure_apply, Leisure_let, Leisure_anno, setType, setDataType, cons, Nil, define, functionInfo, getPos, isNil, } = require '16-ast' { makeSyncMonad, runMonad, _true, _false, left, right, booleanFor, newConsFrom, } = require '17-runtime' _ = (Leisure.require ? require) 'lodash.min' consFrom = newConsFrom sm = if sourceMap? then sourceMap else (if module? then require else Leisure.require)("source-map") { SourceNode, SourceMapConsumer, } = sm.sourceMap ? sm varNameSub = (n)-> "L_#{nameSub n}" useArity = true #useArity = false collectArgs = (args, result)-> for i in args if Array.isArray i then collectArgs i, result else result.push i result locateAst = (ast)-> [line, col] = pos = getPos(ast).toArray() [line,col] check = (bool, arg)-> if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack checkChild = (child)-> if Array.isArray child for c in child checkChild c else check (typeof child == 'string') || (child instanceof SourceNode), c currentFile = 'NEVERGIVENFILE.lsr' currentFuncName = undefined withFile = (file, name, block)-> oldFileName = currentFile oldFuncName = currentFuncName currentFile = file currentFuncName = name try block() finally currentFile = oldFileName currentFuncName = oldFuncName sn = (ast, str...)-> #(collectArgs str, []).join('') #[file, line, col] = getPos(ast).toArray() [line, offset] = locateAst ast #console.log "SN #{line} #{offset}" check typeof line == 'number', 'line' check typeof offset == 'number', 'offset' checkChild str if line < 1 then line = 1 if currentFile == 'NEVERGIVENFILE.lsr' then console.log new Error("SN CALLED WITHOUT FILE").stack if currentFuncName? #console.log "USING NAME: #{currentFuncName}" new SourceNode(line, offset, currentFile, str, currentFuncName) else new SourceNode(line, offset, currentFile, str) #else new SourceNode(line, offset, currentFile, str) genNode = (ast)-> genUniq ast, Nil, [Nil, 0] gen = (ast)-> genMap(ast).toStringWithSourceMap(file: currentFile).code genSource = (source, ast)-> #console.log "SOURCE: #{source}\nAST: #{ast}" funcname = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName' then getAnnoData ast else null #withFile "data:text/plain;base64,#{btoa source}", funcname, -> withFile "dynamic code with source", funcname, -> sm = genNode(ast).prepend("\n").toStringWithSourceMap file: "dynamic code with source" map = JSON.parse sm.map.toString() map.sourcesContent = [source] code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;utf-8;base64,#{btoa JSON.stringify map}\n" #code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;base64,#{btoa JSON.stringify map}\n" #console.log "CODE: #{code}" #console.log "MAP: #{JSON.stringify map}" code genMap = (ast)-> #console.log "GEN AST: #{ast}" #file = getPos(ast).head().replace /\.lsr$/, '.js.map' hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename' filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr' nameAst = if hasFile then getAnnoBody ast else null #funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else null funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else currentFuncName #console.log "File: #{filename}, func: #{funcname}, nameast: #{nameAst instanceof Leisure_anno}" #if funcname then verboseMsg 'gen', "compiling ast: #{funcname}" #sub = withFile filename, funcname, -> genNode(ast) sub = withFile filename, null, -> genNode(ast) [line, offset] = locateAst ast if funcname then new SourceNode line, offset, filename, sub, funcname else sub findName = (name)-> for i in [root.nameSpacePath.length - 1 .. 0] if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i] if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace else null location = (ast)-> [line, col] = locateAst ast "#{line}:#{col}" genRefName = (ref, uniq, names)-> name = getRefName ref #if isNil (val = names.find (el)-> el == name) then console.log("GLOBAL: #{name}, val = #{val}") #else console.log("LOCAL: #{name}, val = #{val}") #if isNil (val = names.find (el)-> el == name) then "#{currentNameSpace}#{name}" if isNil (val = names.find (el)-> el == name) ns = findName nameSub name if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}" else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}" varNameSub name else uniqName name, uniq genUniq = (ast, names, uniq, count)-> switch ast.constructor when Leisure_lit then sn ast, JSON.stringify getLitVal ast when Leisure_ref then sn ast, "resolve(", (genRefName ast, uniq, names), ")" when Leisure_lambda then genLambda ast, names, uniq, count ? 0 when Leisure_apply if useArity then genArifiedApply ast, names, uniq, arity else sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" when Leisure_let then sn ast, "(function(){\n", (genLets ast, names, uniq), "})()" when Leisure_anno name = getAnnoName ast data = getAnnoData ast if name == 'arity' && useArity && data > 1 genArifiedLambda (getAnnoBody ast), names, uniq, data else genned = genUniq (getAnnoBody ast), names, uniq switch name when 'type' then sn ast, "setType(", (genned), ", '", data, "')" when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')" when 'define' [funcName, arity, src] = data.toArray() sn ast, "define('", funcName, "', (function(){return ", genned, "}), ", arity, ", ", JSON.stringify(src), ")" when 'leisureName' #console.log "DEFINE #{getAnnoData ast} = #{getApplyArg getAnnoBody ast}" genned else genned else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}" # this is a no-op, now define 'newGen', (makeSyncMonad (env, cont)-> console.log "CALL TO OBSOLETE NEWGEN" cont _true), null, null, null, 'parser' genArifiedApply = (ast, names, uniq)-> args = [] func = ast while dumpAnno(func) instanceof Leisure_apply args.push getApplyArg dumpAnno func func = getApplyFunc dumpAnno func args.reverse() info = functionInfo[getRefName func] if dumpAnno(func) instanceof Leisure_ref && info?.newArity && (arity = info?.arity) && arity <= args.length argCode = [] argCode.push ast argCode.push genUniq func, names, uniq argCode.push '(' for i in [0...arity] if i > 0 then argCode.push ', ' argCode.push sn args[i], genApplyArg args[i], names, uniq argCode.push ')' for i in [arity...args.length] by 1 argCode.push '(', (sn args[i], genApplyArg args[i], names, uniq), ')' sn argCode... else ast = dumpAnno ast sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" genLambda = (ast, names, uniq, count)-> name = getLambdaVar ast u = addUniq name, names, uniq n = cons name, names addLambdaProperties ast, sn ast, "function(", (uniqName name, u), "){return ", (genUniq (getLambdaBody ast), n, u, 1), "}" getLambdaArgs = (ast)-> args = [] while ast instanceof Leisure_lambda args.push getLambdaVar ast ast = getLambdaBody ast [args, ast] genArifiedLambda = (ast, names, uniq, arity)-> if arity < 2 then genLambda ast, names, uniq, 0 else args = getNArgs(arity, ast).toArray() argList = _.map(args, ((x)-> 'L_' + x)).join ', ' mainFunc = sn ast, """ (function(#{argList}) { return arguments.callee.length != arguments.length ? Leisure_primCall(arguments.callee, 0, arguments) : """, genUniq(getNthLambdaBody(ast, arity), names, uniq), ";\n})" result = addLambdaProperties ast, (sn ast, mainFunc) annoAst = ast while annoAst instanceof Leisure_anno name = getAnnoName annoAst data = getAnnoData annoAst switch name when 'type' then result = sn ast, "setType(", result, ", '", data, "')" when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')" annoAst = getAnnoBody annoAst result getNthLambdaBody = (ast, n)-> if n == 0 then ast else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1 else throw new Error "Expected lambda but got #{ast}" strRepeat = (string, n)-> result = string for i in [1...n] result += string result (window ? global ? {}).curryCall = curryCall = (args, func)-> f = func args[0] for i in [1...args.length] f = f args[i] f getNArgs = (n, ast)-> d = dumpAnno ast if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d specialAnnotations = ['type', 'dataType', 'define'] arrayify = (cons)-> if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray() else cons getLambdaProperties = (body, props)-> if body instanceof Leisure_anno if !_.contains specialAnnotations, getAnnoName(body) if !props then props = {} value = getAnnoData body props[getAnnoName body] = arrayify value getLambdaProperties getAnnoBody(body), props props addLambdaProperties = (ast, def, extras)-> props = getLambdaProperties getLambdaBody ast if props || extras p = {} if props then _.merge p, props if extras then _.merge p, extras sn ast, "setLambdaProperties(", def, ", ", (JSON.stringify p), ")" else def lcons = (a, b)-> rz(L_cons)(lz a)(lz b) parseErr = (a, b)-> rz(L_parseErr)(a)(b) lconsFrom = (array)-> if array instanceof Array p = rz L_nil for el in array.reverse() p = lcons lconsFrom(el), p p else array assocListProps = null getAssocListProps = -> if !assocListProps assocListProps = lcons lcons('assoc', 'true'), rz(L_nil) assocListProps.properties = assocListProps assocListProps lacons = (key, value, list)-> alist = lcons lcons(key, value), list alist.properties = getAssocListProps() alist (window ? global).setLambdaProperties = (def, props)-> p = rz L_nil for k, v of props p = lacons k, lconsFrom(v), p def.properties = p def lazify = (ast, func)-> sn ast, "function(){return ", func, "}" dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast genApplyArg = (arg, names, uniq)-> d = dumpAnno arg if d instanceof Leisure_apply then lazify d, genUniq arg, names, uniq else if d instanceof Leisure_ref then genRefName d, uniq, names else if d instanceof Leisure_lit then sn arg, JSON.stringify getLitVal d else if d instanceof Leisure_let then sn arg, "function(){return", (genUniq arg, names, uniq), ";}" else if d instanceof Leisure_lambda then sn arg, "lazy(", (genUniq arg, names, uniq), ")" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLetAssign = (arg, names, uniq)-> if dumpAnno(arg) instanceof Leisure_let then sn arg, "function(){", (genLets arg, names, uniq), "}" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLets = (ast, names, uniq)-> bindings = letList ast, [] letNames = _.foldl bindings, ((n, l)-> cons (getLetName l), n), names [letUniq, decs, assigns] = _.foldl bindings, ((result, l)-> [u, code, assigns] = result newU = addUniq (getLetName l), letNames, u letName = uniqName (getLetName l), newU [newU, (cons (sn ast, letName + ' = ', genLetAssign(getLetValue(l), letNames, u)), code), (cons letName, assigns)]), [uniq, Nil, Nil] sn ast, " var ", assigns.reverse().join(', '), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (genUniq (getLastLetBody ast), letNames, letUniq) addUniq = (name, names, uniq)-> if (names.find (el)-> el == name) != Nil [overrides, num] = uniq [(cons (cons name, "#{name}_#{num}"), overrides), num + 1] else uniq uniqName = (name, uniq)-> [uniq] = uniq kv = uniq.find ((el)-> el.head() == name), uniq varNameSub (if kv != Nil then kv.tail() else name) letList = (ast, buf)-> if ast instanceof Leisure_let buf.push ast letList getLetBody(ast), buf else buf getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast define 'runAst', ((code)->(ast)-> jsCode = null try jsCode = gen rz ast eval "(#{jsCode})" catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") msg = "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: " console.log msg + ast() + "\n" + err.stack parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' define 'genAst', ((ast)-> jsCode = null try gen rz ast catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' root.gen = gen root.genMap = genMap root.genSource = genSource root.genNode = genNode root.sourceNode = sn root.withFile = withFile root.curryCall = curryCall #root.useNameSpace = useNameSpace #root.pushNameSpace = pushNameSpace #root.getNameSpacePath = getNameSpacePath #root.clearNameSpacePath = clearNameSpacePath #root.saveNameSpace = saveNameSpace #root.restoreNameSpace = restoreNameSpace root.SourceNode = SourceNode root.SourceMapConsumer = SourceMapConsumer
true
### Copyright (C) 2013, PI:NAME:<NAME>END_PI, Tiny Concepts: https://github.com/zot/Leisure (licensed with ZLIB license) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ### { simpyCons, resolve, lazy, verboseMsg, nsLog, } = root = (module ? {}).exports = require '15-base' rz = resolve lz = lazy lc = Leisure_call { nameSub, getLitVal, getRefName, getLambdaVar, getLambdaBody, getApplyFunc, getApplyArg, getAnnoName, getAnnoData, getAnnoBody, getLetName, getLetValue, getLetBody, Leisure_lit, Leisure_ref, Leisure_lambda, Leisure_apply, Leisure_let, Leisure_anno, setType, setDataType, cons, Nil, define, functionInfo, getPos, isNil, } = require '16-ast' { makeSyncMonad, runMonad, _true, _false, left, right, booleanFor, newConsFrom, } = require '17-runtime' _ = (Leisure.require ? require) 'lodash.min' consFrom = newConsFrom sm = if sourceMap? then sourceMap else (if module? then require else Leisure.require)("source-map") { SourceNode, SourceMapConsumer, } = sm.sourceMap ? sm varNameSub = (n)-> "L_#{nameSub n}" useArity = true #useArity = false collectArgs = (args, result)-> for i in args if Array.isArray i then collectArgs i, result else result.push i result locateAst = (ast)-> [line, col] = pos = getPos(ast).toArray() [line,col] check = (bool, arg)-> if !bool then console.log new Error("Bad sourcemap arg: #{arg}").stack checkChild = (child)-> if Array.isArray child for c in child checkChild c else check (typeof child == 'string') || (child instanceof SourceNode), c currentFile = 'NEVERGIVENFILE.lsr' currentFuncName = undefined withFile = (file, name, block)-> oldFileName = currentFile oldFuncName = currentFuncName currentFile = file currentFuncName = name try block() finally currentFile = oldFileName currentFuncName = oldFuncName sn = (ast, str...)-> #(collectArgs str, []).join('') #[file, line, col] = getPos(ast).toArray() [line, offset] = locateAst ast #console.log "SN #{line} #{offset}" check typeof line == 'number', 'line' check typeof offset == 'number', 'offset' checkChild str if line < 1 then line = 1 if currentFile == 'NEVERGIVENFILE.lsr' then console.log new Error("SN CALLED WITHOUT FILE").stack if currentFuncName? #console.log "USING NAME: #{currentFuncName}" new SourceNode(line, offset, currentFile, str, currentFuncName) else new SourceNode(line, offset, currentFile, str) #else new SourceNode(line, offset, currentFile, str) genNode = (ast)-> genUniq ast, Nil, [Nil, 0] gen = (ast)-> genMap(ast).toStringWithSourceMap(file: currentFile).code genSource = (source, ast)-> #console.log "SOURCE: #{source}\nAST: #{ast}" funcname = if ast instanceof Leisure_anno && getAnnoName(ast) == 'leisureName' then getAnnoData ast else null #withFile "data:text/plain;base64,#{btoa source}", funcname, -> withFile "dynamic code with source", funcname, -> sm = genNode(ast).prepend("\n").toStringWithSourceMap file: "dynamic code with source" map = JSON.parse sm.map.toString() map.sourcesContent = [source] code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;utf-8;base64,#{btoa JSON.stringify map}\n" #code = "(#{sm.code})\n//# sourceMappingURL=data:application/json;base64,#{btoa JSON.stringify map}\n" #console.log "CODE: #{code}" #console.log "MAP: #{JSON.stringify map}" code genMap = (ast)-> #console.log "GEN AST: #{ast}" #file = getPos(ast).head().replace /\.lsr$/, '.js.map' hasFile = ast instanceof Leisure_anno && getAnnoName(ast) == 'filename' filename = if hasFile then getAnnoData ast else 'GENFORUNKNOWNFILE.lsr' nameAst = if hasFile then getAnnoBody ast else null #funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else null funcname = if nameAst instanceof Leisure_anno && getAnnoName(nameAst) == 'leisureName' then getAnnoData nameAst else currentFuncName #console.log "File: #{filename}, func: #{funcname}, nameast: #{nameAst instanceof Leisure_anno}" #if funcname then verboseMsg 'gen', "compiling ast: #{funcname}" #sub = withFile filename, funcname, -> genNode(ast) sub = withFile filename, null, -> genNode(ast) [line, offset] = locateAst ast if funcname then new SourceNode line, offset, filename, sub, funcname else sub findName = (name)-> for i in [root.nameSpacePath.length - 1 .. 0] if LeisureNameSpaces[root.nameSpacePath[i]]?[name] then return root.nameSpacePath[i] if root.currentNameSpace && LeisureNameSpaces[root.currentNameSpace][name] then root.currentNameSpace else null location = (ast)-> [line, col] = locateAst ast "#{line}:#{col}" genRefName = (ref, uniq, names)-> name = getRefName ref #if isNil (val = names.find (el)-> el == name) then console.log("GLOBAL: #{name}, val = #{val}") #else console.log("LOCAL: #{name}, val = #{val}") #if isNil (val = names.find (el)-> el == name) then "#{currentNameSpace}#{name}" if isNil (val = names.find (el)-> el == name) ns = findName nameSub name if ns == root.currentNameSpace then nsLog "LOCAL NAME: #{name} FOR #{root.currentNameSpace} #{location ref}" else if !ns then nsLog "GUESSING LOCAL NAME #{name} FOR #{root.currentNameSpace} #{location ref}" varNameSub name else uniqName name, uniq genUniq = (ast, names, uniq, count)-> switch ast.constructor when Leisure_lit then sn ast, JSON.stringify getLitVal ast when Leisure_ref then sn ast, "resolve(", (genRefName ast, uniq, names), ")" when Leisure_lambda then genLambda ast, names, uniq, count ? 0 when Leisure_apply if useArity then genArifiedApply ast, names, uniq, arity else sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" when Leisure_let then sn ast, "(function(){\n", (genLets ast, names, uniq), "})()" when Leisure_anno name = getAnnoName ast data = getAnnoData ast if name == 'arity' && useArity && data > 1 genArifiedLambda (getAnnoBody ast), names, uniq, data else genned = genUniq (getAnnoBody ast), names, uniq switch name when 'type' then sn ast, "setType(", (genned), ", '", data, "')" when 'dataType' then sn ast, "setDataType(", genned, ", '", data, "')" when 'define' [funcName, arity, src] = data.toArray() sn ast, "define('", funcName, "', (function(){return ", genned, "}), ", arity, ", ", JSON.stringify(src), ")" when 'leisureName' #console.log "DEFINE #{getAnnoData ast} = #{getApplyArg getAnnoBody ast}" genned else genned else "CANNOT GENERATE CODE FOR UNKNOWN AST TYPE: #{ast}, #{ast.constructor} #{Leisure_lambda}" # this is a no-op, now define 'newGen', (makeSyncMonad (env, cont)-> console.log "CALL TO OBSOLETE NEWGEN" cont _true), null, null, null, 'parser' genArifiedApply = (ast, names, uniq)-> args = [] func = ast while dumpAnno(func) instanceof Leisure_apply args.push getApplyArg dumpAnno func func = getApplyFunc dumpAnno func args.reverse() info = functionInfo[getRefName func] if dumpAnno(func) instanceof Leisure_ref && info?.newArity && (arity = info?.arity) && arity <= args.length argCode = [] argCode.push ast argCode.push genUniq func, names, uniq argCode.push '(' for i in [0...arity] if i > 0 then argCode.push ', ' argCode.push sn args[i], genApplyArg args[i], names, uniq argCode.push ')' for i in [arity...args.length] by 1 argCode.push '(', (sn args[i], genApplyArg args[i], names, uniq), ')' sn argCode... else ast = dumpAnno ast sn ast, (genUniq (getApplyFunc ast), names, uniq), "(", (genApplyArg (getApplyArg ast), names, uniq), ")" genLambda = (ast, names, uniq, count)-> name = getLambdaVar ast u = addUniq name, names, uniq n = cons name, names addLambdaProperties ast, sn ast, "function(", (uniqName name, u), "){return ", (genUniq (getLambdaBody ast), n, u, 1), "}" getLambdaArgs = (ast)-> args = [] while ast instanceof Leisure_lambda args.push getLambdaVar ast ast = getLambdaBody ast [args, ast] genArifiedLambda = (ast, names, uniq, arity)-> if arity < 2 then genLambda ast, names, uniq, 0 else args = getNArgs(arity, ast).toArray() argList = _.map(args, ((x)-> 'L_' + x)).join ', ' mainFunc = sn ast, """ (function(#{argList}) { return arguments.callee.length != arguments.length ? Leisure_primCall(arguments.callee, 0, arguments) : """, genUniq(getNthLambdaBody(ast, arity), names, uniq), ";\n})" result = addLambdaProperties ast, (sn ast, mainFunc) annoAst = ast while annoAst instanceof Leisure_anno name = getAnnoName annoAst data = getAnnoData annoAst switch name when 'type' then result = sn ast, "setType(", result, ", '", data, "')" when 'dataType' then result = sn ast, "setDataType(", result, ", '", data, "')" annoAst = getAnnoBody annoAst result getNthLambdaBody = (ast, n)-> if n == 0 then ast else if (d = dumpAnno ast) instanceof Leisure_lambda then getNthLambdaBody getLambdaBody(d), n - 1 else throw new Error "Expected lambda but got #{ast}" strRepeat = (string, n)-> result = string for i in [1...n] result += string result (window ? global ? {}).curryCall = curryCall = (args, func)-> f = func args[0] for i in [1...args.length] f = f args[i] f getNArgs = (n, ast)-> d = dumpAnno ast if !n then Nil else cons (getLambdaVar d), getNArgs n - 1, getLambdaBody d specialAnnotations = ['type', 'dataType', 'define'] arrayify = (cons)-> if cons instanceof Leisure_cons then cons.map((el)-> arrayify el).toArray() else cons getLambdaProperties = (body, props)-> if body instanceof Leisure_anno if !_.contains specialAnnotations, getAnnoName(body) if !props then props = {} value = getAnnoData body props[getAnnoName body] = arrayify value getLambdaProperties getAnnoBody(body), props props addLambdaProperties = (ast, def, extras)-> props = getLambdaProperties getLambdaBody ast if props || extras p = {} if props then _.merge p, props if extras then _.merge p, extras sn ast, "setLambdaProperties(", def, ", ", (JSON.stringify p), ")" else def lcons = (a, b)-> rz(L_cons)(lz a)(lz b) parseErr = (a, b)-> rz(L_parseErr)(a)(b) lconsFrom = (array)-> if array instanceof Array p = rz L_nil for el in array.reverse() p = lcons lconsFrom(el), p p else array assocListProps = null getAssocListProps = -> if !assocListProps assocListProps = lcons lcons('assoc', 'true'), rz(L_nil) assocListProps.properties = assocListProps assocListProps lacons = (key, value, list)-> alist = lcons lcons(key, value), list alist.properties = getAssocListProps() alist (window ? global).setLambdaProperties = (def, props)-> p = rz L_nil for k, v of props p = lacons k, lconsFrom(v), p def.properties = p def lazify = (ast, func)-> sn ast, "function(){return ", func, "}" dumpAnno = (ast)-> if ast instanceof Leisure_anno then dumpAnno getAnnoBody ast else ast genApplyArg = (arg, names, uniq)-> d = dumpAnno arg if d instanceof Leisure_apply then lazify d, genUniq arg, names, uniq else if d instanceof Leisure_ref then genRefName d, uniq, names else if d instanceof Leisure_lit then sn arg, JSON.stringify getLitVal d else if d instanceof Leisure_let then sn arg, "function(){return", (genUniq arg, names, uniq), ";}" else if d instanceof Leisure_lambda then sn arg, "lazy(", (genUniq arg, names, uniq), ")" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLetAssign = (arg, names, uniq)-> if dumpAnno(arg) instanceof Leisure_let then sn arg, "function(){", (genLets arg, names, uniq), "}" else sn arg, "function(){return ", (genUniq arg, names, uniq), "}" genLets = (ast, names, uniq)-> bindings = letList ast, [] letNames = _.foldl bindings, ((n, l)-> cons (getLetName l), n), names [letUniq, decs, assigns] = _.foldl bindings, ((result, l)-> [u, code, assigns] = result newU = addUniq (getLetName l), letNames, u letName = uniqName (getLetName l), newU [newU, (cons (sn ast, letName + ' = ', genLetAssign(getLetValue(l), letNames, u)), code), (cons letName, assigns)]), [uniq, Nil, Nil] sn ast, " var ", assigns.reverse().join(', '), ";\n ", decs.reverse().intersperse(';\n ').toArray(), ";\n\n return ", (genUniq (getLastLetBody ast), letNames, letUniq) addUniq = (name, names, uniq)-> if (names.find (el)-> el == name) != Nil [overrides, num] = uniq [(cons (cons name, "#{name}_#{num}"), overrides), num + 1] else uniq uniqName = (name, uniq)-> [uniq] = uniq kv = uniq.find ((el)-> el.head() == name), uniq varNameSub (if kv != Nil then kv.tail() else name) letList = (ast, buf)-> if ast instanceof Leisure_let buf.push ast letList getLetBody(ast), buf else buf getLastLetBody = (ast)-> if ast instanceof Leisure_let then getLastLetBody getLetBody ast else ast define 'runAst', ((code)->(ast)-> jsCode = null try jsCode = gen rz ast eval "(#{jsCode})" catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") msg = "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: " console.log msg + ast() + "\n" + err.stack parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' define 'genAst', ((ast)-> jsCode = null try gen rz ast catch err codeMsg = (if jsCode then "CODE: \n#{jsCode}\n" else "") parseErr (lz "\n\nParse error: " + err.toString() + "\n#{codeMsg}AST: "), (ast)), null, null, null, 'parser' root.gen = gen root.genMap = genMap root.genSource = genSource root.genNode = genNode root.sourceNode = sn root.withFile = withFile root.curryCall = curryCall #root.useNameSpace = useNameSpace #root.pushNameSpace = pushNameSpace #root.getNameSpacePath = getNameSpacePath #root.clearNameSpacePath = clearNameSpacePath #root.saveNameSpace = saveNameSpace #root.restoreNameSpace = restoreNameSpace root.SourceNode = SourceNode root.SourceMapConsumer = SourceMapConsumer
[ { "context": "oqueen'\n 'Nidoran?'\n 'Nidorino'\n 'Nidoking'\n 'Clefairy'\n 'Clefable'\n 'Vulpix'\n 'Ninetales'\n 'Jigglyp", "end": 6930, "score": 0.6961014270782471, "start": 6922, "tag": "NAME", "value": "Clefairy" }, { "context": "aras'\n 'Parasect'\n 'Venonat'\n 'Venomoth'\n 'Diglett'\n 'Dugtrio'\n 'Meowth'\n 'Persian'\n 'Psyduck'\n ", "end": 7114, "score": 0.6498677730560303, "start": 7110, "tag": "NAME", "value": "lett" }, { "context": "arasect'\n 'Venonat'\n 'Venomoth'\n 'Diglett'\n 'Dugtrio'\n 'Meowth'\n 'Persian'\n 'Psyduck'\n 'Golduck'\n", "end": 7125, "score": 0.5717806816101074, "start": 7120, "tag": "NAME", "value": "ugtri" }, { "context": " 'Dugtrio'\n 'Meowth'\n 'Persian'\n 'Psyduck'\n 'Golduck'\n 'Mankey'\n 'Primeape'\n 'Growlithe'\n 'Arcanin", "end": 7173, "score": 0.6641345024108887, "start": 7166, "tag": "NAME", "value": "Golduck" }, { "context": " 'Meowth'\n 'Persian'\n 'Psyduck'\n 'Golduck'\n 'Mankey'\n 'Primeape'\n 'Growlithe'\n 'Arcanine'\n 'Poliw", "end": 7184, "score": 0.7290549874305725, "start": 7178, "tag": "NAME", "value": "Mankey" }, { "context": "rsian'\n 'Psyduck'\n 'Golduck'\n 'Mankey'\n 'Primeape'\n 'Growlithe'\n 'Arcanine'\n 'Poliwag'\n 'Poliwh", "end": 7197, "score": 0.6429497599601746, "start": 7194, "tag": "NAME", "value": "ape" }, { "context": "anine'\n 'Poliwag'\n 'Poliwhirl'\n 'Poliwrath'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n", "end": 7273, "score": 0.7396267056465149, "start": 7269, "tag": "NAME", "value": "Abra" }, { "context": "'Poliwag'\n 'Poliwhirl'\n 'Poliwrath'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Mac", "end": 7279, "score": 0.6352477669715881, "start": 7278, "tag": "NAME", "value": "K" }, { "context": "'Poliwhirl'\n 'Poliwrath'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bell", "end": 7292, "score": 0.7228744029998779, "start": 7290, "tag": "NAME", "value": "Al" }, { "context": "hirl'\n 'Poliwrath'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout", "end": 7298, "score": 0.5914648771286011, "start": 7296, "tag": "NAME", "value": "am" }, { "context": " 'Poliwrath'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout'\n 'Weepin", "end": 7309, "score": 0.8277644515037537, "start": 7303, "tag": "NAME", "value": "Machop" }, { "context": "'\n 'Abra'\n 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout'\n 'Weepinbell'\n 'Vic", "end": 7321, "score": 0.7686574459075928, "start": 7314, "tag": "NAME", "value": "Machoke" }, { "context": " 'Kadabra'\n 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout'\n 'Weepinbell'\n 'Victreebel'\n '", "end": 7333, "score": 0.871661365032196, "start": 7326, "tag": "NAME", "value": "Machamp" }, { "context": " 'Alakazam'\n 'Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout'\n 'Weepinbell'\n 'Victreebel'\n 'Tentacool'\n 'T", "end": 7348, "score": 0.8842466473579407, "start": 7338, "tag": "NAME", "value": "Bellsprout" }, { "context": "Machop'\n 'Machoke'\n 'Machamp'\n 'Bellsprout'\n 'Weepinbell'\n 'Victreebel'\n 'Tentacool'\n 'Tentacruel'\n 'G", "end": 7363, "score": 0.89726722240448, "start": 7353, "tag": "NAME", "value": "Weepinbell" }, { "context": "oke'\n 'Machamp'\n 'Bellsprout'\n 'Weepinbell'\n 'Victreebel'\n 'Tentacool'\n 'Tentacruel'\n 'Geodude'\n 'Grav", "end": 7378, "score": 0.9271998405456543, "start": 7368, "tag": "NAME", "value": "Victreebel" }, { "context": "'\n 'Bellsprout'\n 'Weepinbell'\n 'Victreebel'\n 'Tentacool'\n 'Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem", "end": 7392, "score": 0.8930816054344177, "start": 7383, "tag": "NAME", "value": "Tentacool" }, { "context": "t'\n 'Weepinbell'\n 'Victreebel'\n 'Tentacool'\n 'Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n ", "end": 7407, "score": 0.8876533508300781, "start": 7397, "tag": "NAME", "value": "Tentacruel" }, { "context": "l'\n 'Victreebel'\n 'Tentacool'\n 'Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n ", "end": 7419, "score": 0.8903715014457703, "start": 7412, "tag": "NAME", "value": "Geodude" }, { "context": "ebel'\n 'Tentacool'\n 'Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n ", "end": 7432, "score": 0.8760409355163574, "start": 7424, "tag": "NAME", "value": "Graveler" }, { "context": "acool'\n 'Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'", "end": 7442, "score": 0.942960262298584, "start": 7437, "tag": "NAME", "value": "Golem" }, { "context": "Tentacruel'\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemi", "end": 7453, "score": 0.9423993229866028, "start": 7447, "tag": "NAME", "value": "Ponyta" }, { "context": "\n 'Geodude'\n 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magnet", "end": 7466, "score": 0.8819301128387451, "start": 7458, "tag": "NAME", "value": "Rapidash" }, { "context": " 'Graveler'\n 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magneton'\n 'Farfet", "end": 7479, "score": 0.6517707109451294, "start": 7471, "tag": "NAME", "value": "Slowpoke" }, { "context": " 'Golem'\n 'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Do", "end": 7491, "score": 0.7121381759643555, "start": 7484, "tag": "NAME", "value": "Slowbro" }, { "context": "'Ponyta'\n 'Rapidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio", "end": 7505, "score": 0.8563702702522278, "start": 7496, "tag": "NAME", "value": "Magnemite" }, { "context": "pidash'\n 'Slowpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n ", "end": 7518, "score": 0.8821592926979065, "start": 7510, "tag": "NAME", "value": "Magneton" }, { "context": "owpoke'\n 'Slowbro'\n 'Magnemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Gri", "end": 7534, "score": 0.8391914367675781, "start": 7523, "tag": "NAME", "value": "Farfetch\\'d" }, { "context": "ro'\n 'Magnemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Mu", "end": 7544, "score": 0.9165643453598022, "start": 7539, "tag": "NAME", "value": "Doduo" }, { "context": "nemite'\n 'Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shell", "end": 7555, "score": 0.9009240865707397, "start": 7549, "tag": "NAME", "value": "Dodrio" }, { "context": "Magneton'\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'C", "end": 7564, "score": 0.8011195659637451, "start": 7560, "tag": "NAME", "value": "Seel" }, { "context": "\n 'Farfetch\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n '", "end": 7576, "score": 0.8166794180870056, "start": 7569, "tag": "NAME", "value": "Dewgong" }, { "context": "\\'d'\n 'Doduo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n '", "end": 7587, "score": 0.9527945518493652, "start": 7581, "tag": "NAME", "value": "Grimer" }, { "context": "uo'\n 'Dodrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'", "end": 7595, "score": 0.9061375856399536, "start": 7592, "tag": "NAME", "value": "Muk" }, { "context": "odrio'\n 'Seel'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n ", "end": 7608, "score": 0.8613756895065308, "start": 7600, "tag": "NAME", "value": "Shellder" }, { "context": "l'\n 'Dewgong'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Dr", "end": 7621, "score": 0.8417479395866394, "start": 7613, "tag": "NAME", "value": "Cloyster" }, { "context": "'\n 'Grimer'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'H", "end": 7632, "score": 0.9054705500602722, "start": 7626, "tag": "NAME", "value": "Gastly" }, { "context": "'\n 'Muk'\n 'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Kra", "end": 7644, "score": 0.8972692489624023, "start": 7637, "tag": "NAME", "value": "Haunter" }, { "context": "'Shellder'\n 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kin", "end": 7655, "score": 0.8322224617004395, "start": 7649, "tag": "NAME", "value": "Gengar" }, { "context": " 'Cloyster'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n '", "end": 7664, "score": 0.8528482913970947, "start": 7660, "tag": "NAME", "value": "Onix" }, { "context": "er'\n 'Gastly'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n '", "end": 7676, "score": 0.9062992334365845, "start": 7669, "tag": "NAME", "value": "Drowzee" }, { "context": "y'\n 'Haunter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'", "end": 7686, "score": 0.8296215534210205, "start": 7681, "tag": "NAME", "value": "Hypno" }, { "context": "ter'\n 'Gengar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcu", "end": 7697, "score": 0.8217708468437195, "start": 7691, "tag": "NAME", "value": "Krabby" }, { "context": "gar'\n 'Onix'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcute'\n 'Exegg", "end": 7709, "score": 0.8598529100418091, "start": 7702, "tag": "NAME", "value": "Kingler" }, { "context": "'\n 'Drowzee'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cub", "end": 7721, "score": 0.8640655875205994, "start": 7714, "tag": "NAME", "value": "Voltorb" }, { "context": "'\n 'Hypno'\n 'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowa", "end": 7735, "score": 0.7871196866035461, "start": 7726, "tag": "NAME", "value": "Electrode" }, { "context": "'Krabby'\n 'Kingler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmo", "end": 7746, "score": 0.6184105277061462, "start": 7740, "tag": "NAME", "value": "Exeggc" }, { "context": "ngler'\n 'Voltorb'\n 'Electrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitm", "end": 7759, "score": 0.5335118770599365, "start": 7754, "tag": "NAME", "value": "Exegg" }, { "context": "orb'\n 'Electrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lick", "end": 7774, "score": 0.6909509897232056, "start": 7768, "tag": "NAME", "value": "Cubone" }, { "context": "ctrode'\n 'Exeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lickitung'\n 'Ko", "end": 7786, "score": 0.8109526634216309, "start": 7779, "tag": "NAME", "value": "Marowak" }, { "context": "xeggcute'\n 'Exeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lickitung'\n 'Koffing'\n 'Weez", "end": 7800, "score": 0.8573024868965149, "start": 7791, "tag": "NAME", "value": "Hitmonlee" }, { "context": "xeggutor'\n 'Cubone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn", "end": 7815, "score": 0.8340556025505066, "start": 7805, "tag": "NAME", "value": "Hitmonchan" }, { "context": "bone'\n 'Marowak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n ", "end": 7829, "score": 0.8183403015136719, "start": 7820, "tag": "NAME", "value": "Lickitung" }, { "context": "ak'\n 'Hitmonlee'\n 'Hitmonchan'\n 'Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n ", "end": 7841, "score": 0.7238526344299316, "start": 7834, "tag": "NAME", "value": "Koffing" }, { "context": "lee'\n 'Hitmonchan'\n 'Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n 'Tangela'\n ", "end": 7853, "score": 0.62043297290802, "start": 7847, "tag": "NAME", "value": "eezing" }, { "context": "onchan'\n 'Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n 'Tangela'\n 'Kangaskhan", "end": 7865, "score": 0.656956672668457, "start": 7859, "tag": "NAME", "value": "hyhorn" }, { "context": "Lickitung'\n 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n 'Tangela'\n 'Kangaskhan'\n 'Horsea", "end": 7876, "score": 0.8623648285865784, "start": 7870, "tag": "NAME", "value": "Rhydon" }, { "context": " 'Koffing'\n 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n 'Tangela'\n 'Kangaskhan'\n 'Horsea'\n 'Seadra'", "end": 7888, "score": 0.9171103239059448, "start": 7881, "tag": "NAME", "value": "Chansey" }, { "context": " 'Weezing'\n 'Rhyhorn'\n 'Rhydon'\n 'Chansey'\n 'Tangela'\n 'Kangaskhan'\n 'Horsea'\n 'Seadra'\n 'Goldeen'", "end": 7900, "score": 0.657691478729248, "start": 7893, "tag": "NAME", "value": "Tangela" }, { "context": "Rhydon'\n 'Chansey'\n 'Tangela'\n 'Kangaskhan'\n 'Horsea'\n 'Seadra'\n 'Goldeen'\n 'Seaking'\n 'Staryu'\n ", "end": 7925, "score": 0.5376801490783691, "start": 7920, "tag": "NAME", "value": "Horse" }, { "context": "Chansey'\n 'Tangela'\n 'Kangaskhan'\n 'Horsea'\n 'Seadra'\n 'Goldeen'\n 'Seaking'\n 'Staryu'\n 'Starmi", "end": 7933, "score": 0.5761272311210632, "start": 7931, "tag": "NAME", "value": "Se" }, { "context": "'Tangela'\n 'Kangaskhan'\n 'Horsea'\n 'Seadra'\n 'Goldeen'\n 'Seaking'\n 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n", "end": 7949, "score": 0.6584426164627075, "start": 7942, "tag": "NAME", "value": "Goldeen" }, { "context": "\n 'Horsea'\n 'Seadra'\n 'Goldeen'\n 'Seaking'\n 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n ", "end": 7972, "score": 0.9880749583244324, "start": 7966, "tag": "NAME", "value": "Staryu" }, { "context": "\n 'Seadra'\n 'Goldeen'\n 'Seaking'\n 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'", "end": 7984, "score": 0.9910209774971008, "start": 7977, "tag": "NAME", "value": "Starmie" }, { "context": "Goldeen'\n 'Seaking'\n 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n ", "end": 7997, "score": 0.8738679885864258, "start": 7993, "tag": "NAME", "value": "Mime" }, { "context": " 'Seaking'\n 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n ", "end": 8009, "score": 0.9864440560340881, "start": 8002, "tag": "NAME", "value": "Scyther" }, { "context": " 'Staryu'\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n", "end": 8018, "score": 0.9654995799064636, "start": 8014, "tag": "NAME", "value": "Jynx" }, { "context": "\n 'Starmie'\n 'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n ", "end": 8033, "score": 0.9329864978790283, "start": 8023, "tag": "NAME", "value": "Electabuzz" }, { "context": "'Mr. Mime'\n 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n", "end": 8044, "score": 0.9921508431434631, "start": 8038, "tag": "NAME", "value": "Magmar" }, { "context": " 'Scyther'\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n", "end": 8055, "score": 0.9795892834663391, "start": 8049, "tag": "NAME", "value": "Pinsir" }, { "context": "\n 'Jynx'\n 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n ", "end": 8066, "score": 0.95440274477005, "start": 8060, "tag": "NAME", "value": "Tauros" }, { "context": " 'Electabuzz'\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'V", "end": 8079, "score": 0.9410631060600281, "start": 8071, "tag": "NAME", "value": "Magikarp" }, { "context": "\n 'Magmar'\n 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'J", "end": 8092, "score": 0.9733583927154541, "start": 8084, "tag": "NAME", "value": "Gyarados" }, { "context": " 'Pinsir'\n 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n '", "end": 8103, "score": 0.9853453636169434, "start": 8097, "tag": "NAME", "value": "Lapras" }, { "context": " 'Tauros'\n 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n ", "end": 8113, "score": 0.9636257290840149, "start": 8108, "tag": "NAME", "value": "Ditto" }, { "context": " 'Magikarp'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'", "end": 8123, "score": 0.9597445130348206, "start": 8118, "tag": "NAME", "value": "Eevee" }, { "context": "p'\n 'Gyarados'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n", "end": 8136, "score": 0.9410736560821533, "start": 8128, "tag": "NAME", "value": "Vaporeon" }, { "context": "s'\n 'Lapras'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n", "end": 8148, "score": 0.9298315048217773, "start": 8141, "tag": "NAME", "value": "Jolteon" }, { "context": "'\n 'Ditto'\n 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n ", "end": 8160, "score": 0.9482946395874023, "start": 8153, "tag": "NAME", "value": "Flareon" }, { "context": " 'Eevee'\n 'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n 'Kabutops'\n", "end": 8172, "score": 0.9591829180717468, "start": 8165, "tag": "NAME", "value": "Porygon" }, { "context": "'Vaporeon'\n 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n 'Kabutops'\n 'Aerodacty", "end": 8184, "score": 0.8435039520263672, "start": 8177, "tag": "NAME", "value": "Omanyte" }, { "context": " 'Jolteon'\n 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n 'Kabutops'\n 'Aerodactyl'\n 'Snorla", "end": 8196, "score": 0.970902144908905, "start": 8189, "tag": "NAME", "value": "Omastar" }, { "context": " 'Flareon'\n 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n 'Kabutops'\n 'Aerodactyl'\n 'Snorlax'\n 'Artic", "end": 8207, "score": 0.8865202069282532, "start": 8201, "tag": "NAME", "value": "Kabuto" }, { "context": " 'Porygon'\n 'Omanyte'\n 'Omastar'\n 'Kabuto'\n 'Kabutops'\n 'Aerodactyl'\n 'Snorlax'\n 'Articuno'\n 'Zapdo", "end": 8220, "score": 0.7054051160812378, "start": 8212, "tag": "NAME", "value": "Kabutops" }, { "context": "mastar'\n 'Kabuto'\n 'Kabutops'\n 'Aerodactyl'\n 'Snorlax'\n 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n", "end": 8247, "score": 0.7342672348022461, "start": 8240, "tag": "NAME", "value": "Snorlax" }, { "context": "abuto'\n 'Kabutops'\n 'Aerodactyl'\n 'Snorlax'\n 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'", "end": 8260, "score": 0.9565730094909668, "start": 8252, "tag": "NAME", "value": "Articuno" }, { "context": "utops'\n 'Aerodactyl'\n 'Snorlax'\n 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'\n 'Dragoni", "end": 8271, "score": 0.9498242735862732, "start": 8265, "tag": "NAME", "value": "Zapdos" }, { "context": "erodactyl'\n 'Snorlax'\n 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtw", "end": 8283, "score": 0.9804284572601318, "start": 8276, "tag": "NAME", "value": "Moltres" }, { "context": " 'Snorlax'\n 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n ", "end": 8295, "score": 0.9633702635765076, "start": 8288, "tag": "NAME", "value": "Dratini" }, { "context": " 'Articuno'\n 'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n ", "end": 8309, "score": 0.7481233477592468, "start": 8300, "tag": "NAME", "value": "Dragonair" }, { "context": "'Zapdos'\n 'Moltres'\n 'Dratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n 'Bayleef'\n '", "end": 8323, "score": 0.7178564071655273, "start": 8314, "tag": "NAME", "value": "Dragonite" }, { "context": "ltres'\n 'Dratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n 'Bayleef'\n 'Meganium'\n ", "end": 8334, "score": 0.8388989567756653, "start": 8328, "tag": "NAME", "value": "Mewtwo" }, { "context": "ratini'\n 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n 'Bayleef'\n 'Meganium'\n 'Cyndaq", "end": 8342, "score": 0.7613115310668945, "start": 8339, "tag": "NAME", "value": "Mew" }, { "context": " 'Dragonair'\n 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n 'Bayleef'\n 'Meganium'\n 'Cyndaquil'\n 'Quilav", "end": 8356, "score": 0.852044403553009, "start": 8347, "tag": "NAME", "value": "Chikorita" }, { "context": " 'Dragonite'\n 'Mewtwo'\n 'Mew'\n 'Chikorita'\n 'Bayleef'\n 'Meganium'\n 'Cyndaquil'\n 'Quilava'\n 'Typhlo", "end": 8368, "score": 0.6033356785774231, "start": 8361, "tag": "NAME", "value": "Bayleef" }, { "context": "w'\n 'Chikorita'\n 'Bayleef'\n 'Meganium'\n 'Cyndaquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croco", "end": 8395, "score": 0.5454245209693909, "start": 8391, "tag": "NAME", "value": "quil" }, { "context": "korita'\n 'Bayleef'\n 'Meganium'\n 'Cyndaquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Fera", "end": 8407, "score": 0.7252340316772461, "start": 8400, "tag": "NAME", "value": "Quilava" }, { "context": "ayleef'\n 'Meganium'\n 'Cyndaquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sent", "end": 8422, "score": 0.6944719552993774, "start": 8412, "tag": "NAME", "value": "Typhlosion" }, { "context": "nium'\n 'Cyndaquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n '", "end": 8430, "score": 0.5976770520210266, "start": 8427, "tag": "NAME", "value": "Tot" }, { "context": "\n 'Cyndaquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furre", "end": 8435, "score": 0.5222494602203369, "start": 8432, "tag": "NAME", "value": "ile" }, { "context": "aquil'\n 'Quilava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoo", "end": 8448, "score": 0.8576782941818237, "start": 8440, "tag": "NAME", "value": "Croconaw" }, { "context": "lava'\n 'Typhlosion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n", "end": 8463, "score": 0.9063094258308411, "start": 8453, "tag": "NAME", "value": "Feraligatr" }, { "context": "sion'\n 'Totodile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n ", "end": 8475, "score": 0.9243195056915283, "start": 8468, "tag": "NAME", "value": "Sentret" }, { "context": "odile'\n 'Croconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n ", "end": 8486, "score": 0.8705649375915527, "start": 8480, "tag": "NAME", "value": "Furret" }, { "context": "roconaw'\n 'Feraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n ", "end": 8499, "score": 0.8513843417167664, "start": 8491, "tag": "NAME", "value": "Hoothoot" }, { "context": "eraligatr'\n 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n ", "end": 8511, "score": 0.6611242890357971, "start": 8504, "tag": "NAME", "value": "Noctowl" }, { "context": " 'Sentret'\n 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n ", "end": 8522, "score": 0.7967106699943542, "start": 8516, "tag": "NAME", "value": "Ledyba" }, { "context": " 'Furret'\n 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'", "end": 8533, "score": 0.7509244680404663, "start": 8527, "tag": "NAME", "value": "Ledian" }, { "context": " 'Hoothoot'\n 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n", "end": 8546, "score": 0.7316246032714844, "start": 8538, "tag": "NAME", "value": "Spinarak" }, { "context": " 'Noctowl'\n 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n ", "end": 8558, "score": 0.7958256602287292, "start": 8551, "tag": "NAME", "value": "Ariados" }, { "context": " 'Ledyba'\n 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n ", "end": 8569, "score": 0.6764048933982849, "start": 8563, "tag": "NAME", "value": "Crobat" }, { "context": " 'Ledian'\n 'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n ", "end": 8582, "score": 0.5711851716041565, "start": 8574, "tag": "NAME", "value": "Chinchou" }, { "context": "'Spinarak'\n 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n ", "end": 8594, "score": 0.6909819841384888, "start": 8587, "tag": "NAME", "value": "Lanturn" }, { "context": " 'Ariados'\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n", "end": 8604, "score": 0.774897038936615, "start": 8599, "tag": "NAME", "value": "Pichu" }, { "context": "\n 'Crobat'\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n ", "end": 8615, "score": 0.9188945293426514, "start": 8609, "tag": "NAME", "value": "Cleffa" }, { "context": "\n 'Chinchou'\n 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mare", "end": 8629, "score": 0.7751855850219727, "start": 8620, "tag": "NAME", "value": "Igglybuff" }, { "context": " 'Lanturn'\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaa", "end": 8640, "score": 0.7793161273002625, "start": 8634, "tag": "NAME", "value": "Togepi" }, { "context": "\n 'Pichu'\n 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Amph", "end": 8652, "score": 0.8026799559593201, "start": 8645, "tag": "NAME", "value": "Togetic" }, { "context": " 'Cleffa'\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n '", "end": 8661, "score": 0.9245221614837646, "start": 8657, "tag": "NAME", "value": "Natu" }, { "context": "\n 'Igglybuff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom", "end": 8670, "score": 0.8952707052230835, "start": 8666, "tag": "NAME", "value": "Xatu" }, { "context": "buff'\n 'Togepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill", "end": 8681, "score": 0.9244118332862854, "start": 8675, "tag": "NAME", "value": "Mareep" }, { "context": "gepi'\n 'Togetic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill'\n 'Azumari", "end": 8693, "score": 0.7078761458396912, "start": 8686, "tag": "NAME", "value": "Flaaffy" }, { "context": "etic'\n 'Natu'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowo", "end": 8706, "score": 0.7082852721214294, "start": 8698, "tag": "NAME", "value": "Ampharos" }, { "context": "'\n 'Xatu'\n 'Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Polito", "end": 8720, "score": 0.6324620842933655, "start": 8711, "tag": "NAME", "value": "Bellossom" }, { "context": "Mareep'\n 'Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hopp", "end": 8731, "score": 0.9536712169647217, "start": 8725, "tag": "NAME", "value": "Marill" }, { "context": "Flaaffy'\n 'Ampharos'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploo", "end": 8745, "score": 0.9140451550483704, "start": 8736, "tag": "NAME", "value": "Azumarill" }, { "context": "pharos'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploom'\n '", "end": 8751, "score": 0.6964876651763916, "start": 8750, "tag": "NAME", "value": "S" }, { "context": "ros'\n 'Bellossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff", "end": 8759, "score": 0.6326627135276794, "start": 8753, "tag": "NAME", "value": "owoodo" }, { "context": "lossom'\n 'Marill'\n 'Azumarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n ", "end": 8772, "score": 0.5503700375556946, "start": 8764, "tag": "NAME", "value": "Politoed" }, { "context": "umarill'\n 'Sudowoodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n", "end": 8796, "score": 0.6121806502342224, "start": 8788, "tag": "NAME", "value": "Skiploom" }, { "context": "oodo'\n 'Politoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n '", "end": 8809, "score": 0.5937454104423523, "start": 8805, "tag": "NAME", "value": "luff" }, { "context": "Politoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper", "end": 8815, "score": 0.6840804815292358, "start": 8814, "tag": "NAME", "value": "A" }, { "context": "itoed'\n 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n ", "end": 8819, "score": 0.5913294553756714, "start": 8817, "tag": "NAME", "value": "om" }, { "context": " 'Hoppip'\n 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n ", "end": 8831, "score": 0.651438295841217, "start": 8824, "tag": "NAME", "value": "Sunkern" }, { "context": " 'Skiploom'\n 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n 'Espeon'\n '", "end": 8844, "score": 0.6655277609825134, "start": 8836, "tag": "NAME", "value": "Sunflora" }, { "context": " 'Jumpluff'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n ", "end": 8854, "score": 0.8499746322631836, "start": 8849, "tag": "NAME", "value": "Yanma" }, { "context": "'\n 'Aipom'\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n 'Murkrow'\n", "end": 8865, "score": 0.9326043128967285, "start": 8859, "tag": "NAME", "value": "Wooper" }, { "context": "\n 'Sunkern'\n 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n", "end": 8878, "score": 0.8713488578796387, "start": 8870, "tag": "NAME", "value": "Quagsire" }, { "context": " 'Sunflora'\n 'Yanma'\n 'Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n 'Misdreav", "end": 8889, "score": 0.5682456493377686, "start": 8883, "tag": "NAME", "value": "Espeon" }, { "context": " 'Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n 'Misdreavus'\n 'Unown'\n 'W", "end": 8907, "score": 0.8015241026878357, "start": 8906, "tag": "NAME", "value": "M" }, { "context": "Wooper'\n 'Quagsire'\n 'Espeon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n 'Misdreavus'\n 'Unown'\n 'Wobbuff", "end": 8913, "score": 0.70375657081604, "start": 8909, "tag": "NAME", "value": "krow" }, { "context": " 'Espeon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n 'Misdreavus'\n 'Unown'\n 'Wobbuffet'\n 'Girafarig'\n '", "end": 8934, "score": 0.6639020442962646, "start": 8931, "tag": "NAME", "value": "Mis" }, { "context": "peon'\n 'Umbreon'\n 'Murkrow'\n 'Slowking'\n 'Misdreavus'\n 'Unown'\n 'Wobbuffet'\n 'Girafarig'\n 'Pineco'", "end": 8941, "score": 0.5654296278953552, "start": 8935, "tag": "NAME", "value": "reavus" }, { "context": "owking'\n 'Misdreavus'\n 'Unown'\n 'Wobbuffet'\n 'Girafarig'\n 'Pineco'\n 'Forretress'\n 'Dunsparce'\n 'Gliga", "end": 8979, "score": 0.7755916118621826, "start": 8970, "tag": "NAME", "value": "Girafarig" }, { "context": "dreavus'\n 'Unown'\n 'Wobbuffet'\n 'Girafarig'\n 'Pineco'\n 'Forretress'\n 'Dunsparce'\n 'Gligar'\n 'Steel", "end": 8990, "score": 0.9459584355354309, "start": 8984, "tag": "NAME", "value": "Pineco" }, { "context": "'Unown'\n 'Wobbuffet'\n 'Girafarig'\n 'Pineco'\n 'Forretress'\n 'Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull", "end": 9005, "score": 0.9031742215156555, "start": 8995, "tag": "NAME", "value": "Forretress" }, { "context": "uffet'\n 'Girafarig'\n 'Pineco'\n 'Forretress'\n 'Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'", "end": 9019, "score": 0.9228775501251221, "start": 9010, "tag": "NAME", "value": "Dunsparce" }, { "context": "farig'\n 'Pineco'\n 'Forretress'\n 'Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfis", "end": 9030, "score": 0.8880407810211182, "start": 9024, "tag": "NAME", "value": "Gligar" }, { "context": "ineco'\n 'Forretress'\n 'Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor", "end": 9042, "score": 0.9672297835350037, "start": 9035, "tag": "NAME", "value": "Steelix" }, { "context": "rretress'\n 'Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'", "end": 9055, "score": 0.8312155604362488, "start": 9047, "tag": "NAME", "value": "Snubbull" }, { "context": "Dunsparce'\n 'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross", "end": 9068, "score": 0.6993440389633179, "start": 9060, "tag": "NAME", "value": "Granbull" }, { "context": "'Gligar'\n 'Steelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'", "end": 9081, "score": 0.8225154280662537, "start": 9073, "tag": "NAME", "value": "Qwilfish" }, { "context": "teelix'\n 'Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiur", "end": 9092, "score": 0.8805274963378906, "start": 9086, "tag": "NAME", "value": "Scizor" }, { "context": "Snubbull'\n 'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiursa'\n 'Ursar", "end": 9104, "score": 0.830327570438385, "start": 9097, "tag": "NAME", "value": "Shuckle" }, { "context": "'Granbull'\n 'Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma", "end": 9118, "score": 0.9363610744476318, "start": 9109, "tag": "NAME", "value": "Heracross" }, { "context": "Qwilfish'\n 'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcarg", "end": 9130, "score": 0.9169880747795105, "start": 9123, "tag": "NAME", "value": "Sneasel" }, { "context": "'Scizor'\n 'Shuckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n", "end": 9144, "score": 0.9574934244155884, "start": 9135, "tag": "NAME", "value": "Teddiursa" }, { "context": "uckle'\n 'Heracross'\n 'Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'", "end": 9157, "score": 0.8810836672782898, "start": 9149, "tag": "NAME", "value": "Ursaring" }, { "context": "across'\n 'Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola", "end": 9168, "score": 0.9113866686820984, "start": 9162, "tag": "NAME", "value": "Slugma" }, { "context": "Sneasel'\n 'Teddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid", "end": 9181, "score": 0.8899312019348145, "start": 9173, "tag": "NAME", "value": "Magcargo" }, { "context": "eddiursa'\n 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid'\n 'Octill", "end": 9192, "score": 0.8582919239997864, "start": 9186, "tag": "NAME", "value": "Swinub" }, { "context": " 'Ursaring'\n 'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid'\n 'Octillery'\n 'Delibi", "end": 9206, "score": 0.8402720093727112, "start": 9197, "tag": "NAME", "value": "Piloswine" }, { "context": "'Slugma'\n 'Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid'\n 'Octillery'\n 'Delibird'\n 'Manti", "end": 9218, "score": 0.9240685105323792, "start": 9211, "tag": "NAME", "value": "Corsola" }, { "context": "Magcargo'\n 'Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid'\n 'Octillery'\n 'Delibird'\n 'Mantine'\n 'Skarmo", "end": 9231, "score": 0.9021496772766113, "start": 9223, "tag": "NAME", "value": "Remoraid" }, { "context": "Swinub'\n 'Piloswine'\n 'Corsola'\n 'Remoraid'\n 'Octillery'\n 'Delibird'\n 'Mantine'\n 'Skarmory'\n 'Houndou", "end": 9245, "score": 0.8623176217079163, "start": 9236, "tag": "NAME", "value": "Octillery" }, { "context": "oswine'\n 'Corsola'\n 'Remoraid'\n 'Octillery'\n 'Delibird'\n 'Mantine'\n 'Skarmory'\n 'Houndour'\n 'Houndoo", "end": 9258, "score": 0.8132762908935547, "start": 9250, "tag": "NAME", "value": "Delibird" }, { "context": "rsola'\n 'Remoraid'\n 'Octillery'\n 'Delibird'\n 'Mantine'\n 'Skarmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdr", "end": 9270, "score": 0.8676244616508484, "start": 9263, "tag": "NAME", "value": "Mantine" }, { "context": "moraid'\n 'Octillery'\n 'Delibird'\n 'Mantine'\n 'Skarmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'", "end": 9283, "score": 0.9250988960266113, "start": 9275, "tag": "NAME", "value": "Skarmory" }, { "context": "tillery'\n 'Delibird'\n 'Mantine'\n 'Skarmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n", "end": 9296, "score": 0.8642538189888, "start": 9288, "tag": "NAME", "value": "Houndour" }, { "context": "elibird'\n 'Mantine'\n 'Skarmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n", "end": 9309, "score": 0.8193864226341248, "start": 9301, "tag": "NAME", "value": "Houndoom" }, { "context": "antine'\n 'Skarmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'", "end": 9321, "score": 0.8991711139678955, "start": 9314, "tag": "NAME", "value": "Kingdra" }, { "context": "karmory'\n 'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargl", "end": 9332, "score": 0.9439011216163635, "start": 9326, "tag": "NAME", "value": "Phanpy" }, { "context": "'Houndour'\n 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogu", "end": 9344, "score": 0.9773578643798828, "start": 9337, "tag": "NAME", "value": "Donphan" }, { "context": " 'Houndoom'\n 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmont", "end": 9357, "score": 0.8774349689483643, "start": 9349, "tag": "NAME", "value": "Porygon2" }, { "context": " 'Kingdra'\n 'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smooch", "end": 9370, "score": 0.915835440158844, "start": 9362, "tag": "NAME", "value": "Stantler" }, { "context": "'Phanpy'\n 'Donphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid", "end": 9383, "score": 0.8761852979660034, "start": 9375, "tag": "NAME", "value": "Smeargle" }, { "context": "onphan'\n 'Porygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n", "end": 9395, "score": 0.8498608469963074, "start": 9388, "tag": "NAME", "value": "Tyrogue" }, { "context": "orygon2'\n 'Stantler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n ", "end": 9409, "score": 0.865940272808075, "start": 9400, "tag": "NAME", "value": "Hitmontop" }, { "context": "antler'\n 'Smeargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n '", "end": 9422, "score": 0.8487157821655273, "start": 9414, "tag": "NAME", "value": "Smoochum" }, { "context": "eargle'\n 'Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n '", "end": 9433, "score": 0.8158103227615356, "start": 9427, "tag": "NAME", "value": "Elekid" }, { "context": "Tyrogue'\n 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n '", "end": 9443, "score": 0.952674150466919, "start": 9438, "tag": "NAME", "value": "Magby" }, { "context": " 'Hitmontop'\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n '", "end": 9455, "score": 0.9522952437400818, "start": 9448, "tag": "NAME", "value": "Miltank" }, { "context": "\n 'Smoochum'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n ", "end": 9467, "score": 0.8822470307350159, "start": 9460, "tag": "NAME", "value": "Blissey" }, { "context": "'\n 'Elekid'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n ", "end": 9478, "score": 0.8032450675964355, "start": 9472, "tag": "NAME", "value": "Raikou" }, { "context": "'\n 'Magby'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranita", "end": 9488, "score": 0.6831348538398743, "start": 9483, "tag": "NAME", "value": "Entei" }, { "context": "'\n 'Miltank'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'", "end": 9500, "score": 0.8157814145088196, "start": 9493, "tag": "NAME", "value": "Suicune" }, { "context": "'\n 'Blissey'\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'\n 'Ho-Oh'\n ", "end": 9513, "score": 0.8677200675010681, "start": 9505, "tag": "NAME", "value": "Larvitar" }, { "context": "\n 'Raikou'\n 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'\n 'Ho-Oh'\n 'Celebi'\n '", "end": 9525, "score": 0.7479837536811829, "start": 9518, "tag": "NAME", "value": "Pupitar" }, { "context": " 'Entei'\n 'Suicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'\n 'Ho-Oh'\n 'Celebi'\n '? (glitch Poké", "end": 9539, "score": 0.8107987642288208, "start": 9530, "tag": "NAME", "value": "Tyranitar" }, { "context": "uicune'\n 'Larvitar'\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'\n 'Ho-Oh'\n 'Celebi'\n '? (glitch Pokémon)'\n '?", "end": 9549, "score": 0.8034098744392395, "start": 9544, "tag": "NAME", "value": "Lugia" }, { "context": "\n 'Pupitar'\n 'Tyranitar'\n 'Lugia'\n 'Ho-Oh'\n 'Celebi'\n '? (glitch Pokémon)'\n '? (glitch Pokémon)'\n ", "end": 9570, "score": 0.6529583930969238, "start": 9564, "tag": "NAME", "value": "Celebi" }, { "context": "\n '? (glitch Pokémon)'\n '? (glitch Pokémon)'\n 'Treecko'\n 'Grovyle'\n 'Sceptile'\n 'Torchic'\n 'Combuske", "end": 10157, "score": 0.9699097871780396, "start": 10150, "tag": "NAME", "value": "Treecko" }, { "context": "h Pokémon)'\n '? (glitch Pokémon)'\n 'Treecko'\n 'Grovyle'\n 'Sceptile'\n 'Torchic'\n 'Combusken'\n 'Blazik", "end": 10169, "score": 0.9747325778007507, "start": 10162, "tag": "NAME", "value": "Grovyle" }, { "context": " '? (glitch Pokémon)'\n 'Treecko'\n 'Grovyle'\n 'Sceptile'\n 'Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip", "end": 10182, "score": 0.9446861743927002, "start": 10174, "tag": "NAME", "value": "Sceptile" }, { "context": "Pokémon)'\n 'Treecko'\n 'Grovyle'\n 'Sceptile'\n 'Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshto", "end": 10194, "score": 0.9548331499099731, "start": 10187, "tag": "NAME", "value": "Torchic" }, { "context": "'Treecko'\n 'Grovyle'\n 'Sceptile'\n 'Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swamper", "end": 10208, "score": 0.9476842880249023, "start": 10199, "tag": "NAME", "value": "Combusken" }, { "context": "rovyle'\n 'Sceptile'\n 'Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochye", "end": 10221, "score": 0.9608256816864014, "start": 10213, "tag": "NAME", "value": "Blaziken" }, { "context": "eptile'\n 'Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochyena'\n 'Migh", "end": 10232, "score": 0.9637256264686584, "start": 10226, "tag": "NAME", "value": "Mudkip" }, { "context": "Torchic'\n 'Combusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochyena'\n 'Mightyena'\n 'Zigz", "end": 10246, "score": 0.9704222679138184, "start": 10237, "tag": "NAME", "value": "Marshtomp" }, { "context": "mbusken'\n 'Blaziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Lin", "end": 10259, "score": 0.9778583645820618, "start": 10251, "tag": "NAME", "value": "Swampert" }, { "context": "laziken'\n 'Mudkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmp", "end": 10273, "score": 0.9764434695243835, "start": 10264, "tag": "NAME", "value": "Poochyena" }, { "context": "dkip'\n 'Marshtomp'\n 'Swampert'\n 'Poochyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon", "end": 10287, "score": 0.9869371056556702, "start": 10278, "tag": "NAME", "value": "Mightyena" }, { "context": "tomp'\n 'Swampert'\n 'Poochyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly", "end": 10301, "score": 0.9822599291801453, "start": 10292, "tag": "NAME", "value": "Zigzagoon" }, { "context": "ert'\n 'Poochyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon", "end": 10313, "score": 0.9804353713989258, "start": 10306, "tag": "NAME", "value": "Linoone" }, { "context": "hyena'\n 'Mightyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'", "end": 10325, "score": 0.9657291769981384, "start": 10318, "tag": "NAME", "value": "Wurmple" }, { "context": "ghtyena'\n 'Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n ", "end": 10337, "score": 0.9659830927848816, "start": 10330, "tag": "NAME", "value": "Silcoon" }, { "context": "Zigzagoon'\n 'Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'L", "end": 10351, "score": 0.9223474860191345, "start": 10342, "tag": "NAME", "value": "Beautifly" }, { "context": "Linoone'\n 'Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n '", "end": 10363, "score": 0.954833447933197, "start": 10356, "tag": "NAME", "value": "Cascoon" }, { "context": "Wurmple'\n 'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n '", "end": 10374, "score": 0.9755721688270569, "start": 10368, "tag": "NAME", "value": "Dustox" }, { "context": "'Silcoon'\n 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n ", "end": 10384, "score": 0.9551401138305664, "start": 10379, "tag": "NAME", "value": "Lotad" }, { "context": " 'Beautifly'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n", "end": 10395, "score": 0.9145923852920532, "start": 10389, "tag": "NAME", "value": "Lombre" }, { "context": "y'\n 'Cascoon'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n ", "end": 10408, "score": 0.9056626558303833, "start": 10400, "tag": "NAME", "value": "Ludicolo" }, { "context": "'\n 'Dustox'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n", "end": 10419, "score": 0.9063431620597839, "start": 10413, "tag": "NAME", "value": "Seedot" }, { "context": "'\n 'Lotad'\n 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'", "end": 10431, "score": 0.9455404877662659, "start": 10424, "tag": "NAME", "value": "Nuzleaf" }, { "context": " 'Lombre'\n 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'", "end": 10443, "score": 0.9667901992797852, "start": 10436, "tag": "NAME", "value": "Shiftry" }, { "context": " 'Ludicolo'\n 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'", "end": 10455, "score": 0.9537754058837891, "start": 10448, "tag": "NAME", "value": "Nincada" }, { "context": " 'Seedot'\n 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomis", "end": 10467, "score": 0.9517423510551453, "start": 10460, "tag": "NAME", "value": "Ninjask" }, { "context": " 'Nuzleaf'\n 'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom", "end": 10480, "score": 0.9726130962371826, "start": 10472, "tag": "NAME", "value": "Shedinja" }, { "context": "'Shiftry'\n 'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'", "end": 10492, "score": 0.9675204753875732, "start": 10485, "tag": "NAME", "value": "Taillow" }, { "context": "'Nincada'\n 'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'", "end": 10504, "score": 0.9628938436508179, "start": 10497, "tag": "NAME", "value": "Swellow" }, { "context": "'Ninjask'\n 'Shedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n", "end": 10518, "score": 0.9558286666870117, "start": 10509, "tag": "NAME", "value": "Shroomish" }, { "context": "hedinja'\n 'Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n", "end": 10530, "score": 0.9322370290756226, "start": 10523, "tag": "NAME", "value": "Breloom" }, { "context": "Taillow'\n 'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n 'Masquera", "end": 10541, "score": 0.9485079646110535, "start": 10535, "tag": "NAME", "value": "Spinda" }, { "context": "'Swellow'\n 'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n 'Masquerain'\n 'Wailm", "end": 10553, "score": 0.9775862097740173, "start": 10546, "tag": "NAME", "value": "Wingull" }, { "context": "'Shroomish'\n 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailor", "end": 10566, "score": 0.9811620116233826, "start": 10558, "tag": "NAME", "value": "Pelipper" }, { "context": " 'Breloom'\n 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty", "end": 10578, "score": 0.9669089317321777, "start": 10571, "tag": "NAME", "value": "Surskit" }, { "context": " 'Spinda'\n 'Wingull'\n 'Pelipper'\n 'Surskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n", "end": 10593, "score": 0.9675362706184387, "start": 10583, "tag": "NAME", "value": "Masquerain" }, { "context": "ngull'\n 'Pelipper'\n 'Surskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n", "end": 10605, "score": 0.9638432860374451, "start": 10598, "tag": "NAME", "value": "Wailmer" }, { "context": "lipper'\n 'Surskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n ", "end": 10617, "score": 0.9661412239074707, "start": 10610, "tag": "NAME", "value": "Wailord" }, { "context": "urskit'\n 'Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n", "end": 10628, "score": 0.9695908427238464, "start": 10622, "tag": "NAME", "value": "Skitty" }, { "context": "Masquerain'\n 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n", "end": 10641, "score": 0.9519538879394531, "start": 10633, "tag": "NAME", "value": "Delcatty" }, { "context": " 'Wailmer'\n 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n", "end": 10653, "score": 0.973271369934082, "start": 10646, "tag": "NAME", "value": "Kecleon" }, { "context": " 'Wailord'\n 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'", "end": 10664, "score": 0.9722380638122559, "start": 10658, "tag": "NAME", "value": "Baltoy" }, { "context": " 'Skitty'\n 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach", "end": 10676, "score": 0.981248140335083, "start": 10669, "tag": "NAME", "value": "Claydol" }, { "context": " 'Delcatty'\n 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash", "end": 10689, "score": 0.9709144234657288, "start": 10681, "tag": "NAME", "value": "Nosepass" }, { "context": " 'Kecleon'\n 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc", "end": 10701, "score": 0.9570545554161072, "start": 10694, "tag": "NAME", "value": "Torkoal" }, { "context": " 'Baltoy'\n 'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphis", "end": 10713, "score": 0.9410154819488525, "start": 10706, "tag": "NAME", "value": "Sableye" }, { "context": "'Claydol'\n 'Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdau", "end": 10726, "score": 0.9389012455940247, "start": 10718, "tag": "NAME", "value": "Barboach" }, { "context": "Nosepass'\n 'Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas", "end": 10739, "score": 0.9611079096794128, "start": 10731, "tag": "NAME", "value": "Whiscash" }, { "context": "Torkoal'\n 'Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic", "end": 10751, "score": 0.9258150458335876, "start": 10744, "tag": "NAME", "value": "Luvdisc" }, { "context": "Sableye'\n 'Barboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha", "end": 10764, "score": 0.9441566467285156, "start": 10756, "tag": "NAME", "value": "Corphish" }, { "context": "arboach'\n 'Whiscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'", "end": 10778, "score": 0.9431345462799072, "start": 10769, "tag": "NAME", "value": "Crawdaunt" }, { "context": "iscash'\n 'Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinc", "end": 10789, "score": 0.9108407497406006, "start": 10783, "tag": "NAME", "value": "Feebas" }, { "context": "Luvdisc'\n 'Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrav", "end": 10801, "score": 0.9799501895904541, "start": 10794, "tag": "NAME", "value": "Milotic" }, { "context": "Corphish'\n 'Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'", "end": 10814, "score": 0.976876974105835, "start": 10806, "tag": "NAME", "value": "Carvanha" }, { "context": "Crawdaunt'\n 'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'", "end": 10827, "score": 0.9672518372535706, "start": 10819, "tag": "NAME", "value": "Sharpedo" }, { "context": "'Feebas'\n 'Milotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'", "end": 10840, "score": 0.9442668557167053, "start": 10832, "tag": "NAME", "value": "Trapinch" }, { "context": "ilotic'\n 'Carvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrik", "end": 10852, "score": 0.9790465235710144, "start": 10845, "tag": "NAME", "value": "Vibrava" }, { "context": "arvanha'\n 'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrike'\n 'Manec", "end": 10863, "score": 0.9779810905456543, "start": 10857, "tag": "NAME", "value": "Flygon" }, { "context": "'Sharpedo'\n 'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrike'\n 'Manectric'\n 'Nume", "end": 10876, "score": 0.9742884635925293, "start": 10868, "tag": "NAME", "value": "Makuhita" }, { "context": "'Trapinch'\n 'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrike'\n 'Manectric'\n 'Numel'\n 'Camerup", "end": 10889, "score": 0.9654335379600525, "start": 10881, "tag": "NAME", "value": "Hariyama" }, { "context": "'Vibrava'\n 'Flygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrike'\n 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n", "end": 10903, "score": 0.9589142799377441, "start": 10894, "tag": "NAME", "value": "Electrike" }, { "context": "lygon'\n 'Makuhita'\n 'Hariyama'\n 'Electrike'\n 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n '", "end": 10917, "score": 0.9787740707397461, "start": 10908, "tag": "NAME", "value": "Manectric" }, { "context": "hita'\n 'Hariyama'\n 'Electrike'\n 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n ", "end": 10927, "score": 0.9643399715423584, "start": 10922, "tag": "NAME", "value": "Numel" }, { "context": "ariyama'\n 'Electrike'\n 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n '", "end": 10940, "score": 0.9658235907554626, "start": 10932, "tag": "NAME", "value": "Camerupt" }, { "context": "lectrike'\n 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n ", "end": 10951, "score": 0.9250629544258118, "start": 10945, "tag": "NAME", "value": "Spheal" }, { "context": " 'Manectric'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n", "end": 10962, "score": 0.8397764563560486, "start": 10956, "tag": "NAME", "value": "Sealeo" }, { "context": "'\n 'Numel'\n 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n ", "end": 10974, "score": 0.9505080580711365, "start": 10967, "tag": "NAME", "value": "Walrein" }, { "context": " 'Camerupt'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'", "end": 10985, "score": 0.9517467021942139, "start": 10979, "tag": "NAME", "value": "Cacnea" }, { "context": "'\n 'Spheal'\n 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n", "end": 10998, "score": 0.9201410412788391, "start": 10990, "tag": "NAME", "value": "Cacturne" }, { "context": " 'Sealeo'\n 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n", "end": 11010, "score": 0.9368950724601746, "start": 11003, "tag": "NAME", "value": "Snorunt" }, { "context": " 'Walrein'\n 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n", "end": 11021, "score": 0.9648265242576599, "start": 11015, "tag": "NAME", "value": "Glalie" }, { "context": " 'Cacnea'\n 'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n ", "end": 11034, "score": 0.9695507287979126, "start": 11026, "tag": "NAME", "value": "Lunatone" }, { "context": "'Cacturne'\n 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n ", "end": 11046, "score": 0.9370161294937134, "start": 11039, "tag": "NAME", "value": "Solrock" }, { "context": " 'Snorunt'\n 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'M", "end": 11058, "score": 0.9420528411865234, "start": 11051, "tag": "NAME", "value": "Azurill" }, { "context": " 'Glalie'\n 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'M", "end": 11069, "score": 0.8644009828567505, "start": 11063, "tag": "NAME", "value": "Spoink" }, { "context": " 'Lunatone'\n 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n '", "end": 11081, "score": 0.9404945969581604, "start": 11074, "tag": "NAME", "value": "Grumpig" }, { "context": " 'Solrock'\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n ", "end": 11092, "score": 0.8038802742958069, "start": 11086, "tag": "NAME", "value": "Plusle" }, { "context": "\n 'Azurill'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n", "end": 11102, "score": 0.8718634843826294, "start": 11097, "tag": "NAME", "value": "Minun" }, { "context": "l'\n 'Spoink'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'", "end": 11113, "score": 0.9164156317710876, "start": 11107, "tag": "NAME", "value": "Mawile" }, { "context": "k'\n 'Grumpig'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n ", "end": 11126, "score": 0.9211012721061707, "start": 11118, "tag": "NAME", "value": "Meditite" }, { "context": "'\n 'Plusle'\n 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n ", "end": 11139, "score": 0.9462661743164062, "start": 11131, "tag": "NAME", "value": "Medicham" }, { "context": " 'Minun'\n 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n", "end": 11150, "score": 0.8991220593452454, "start": 11144, "tag": "NAME", "value": "Swablu" }, { "context": " 'Mawile'\n 'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n", "end": 11162, "score": 0.8700377345085144, "start": 11155, "tag": "NAME", "value": "Altaria" }, { "context": "'Meditite'\n 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'", "end": 11173, "score": 0.9467584490776062, "start": 11167, "tag": "NAME", "value": "Wynaut" }, { "context": " 'Medicham'\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth", "end": 11185, "score": 0.9643967151641846, "start": 11178, "tag": "NAME", "value": "Duskull" }, { "context": "\n 'Swablu'\n 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'", "end": 11198, "score": 0.8298416137695312, "start": 11190, "tag": "NAME", "value": "Dusclops" }, { "context": " 'Altaria'\n 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n", "end": 11210, "score": 0.8828644156455994, "start": 11203, "tag": "NAME", "value": "Roselia" }, { "context": " 'Wynaut'\n 'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n ", "end": 11222, "score": 0.7045118808746338, "start": 11215, "tag": "NAME", "value": "Slakoth" }, { "context": "'Duskull'\n 'Dusclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n ", "end": 11235, "score": 0.7020819187164307, "start": 11227, "tag": "NAME", "value": "Vigoroth" }, { "context": "sclops'\n 'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n ", "end": 11247, "score": 0.7029938697814941, "start": 11242, "tag": "NAME", "value": "aking" }, { "context": "'Roselia'\n 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n ", "end": 11258, "score": 0.764614999294281, "start": 11252, "tag": "NAME", "value": "Gulpin" }, { "context": " 'Slakoth'\n 'Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n", "end": 11269, "score": 0.7149232029914856, "start": 11263, "tag": "NAME", "value": "Swalot" }, { "context": "Vigoroth'\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'", "end": 11281, "score": 0.5852218866348267, "start": 11277, "tag": "NAME", "value": "pius" }, { "context": "\n 'Slaking'\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'", "end": 11293, "score": 0.5916213393211365, "start": 11286, "tag": "NAME", "value": "Whismur" }, { "context": "\n 'Gulpin'\n 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss", "end": 11305, "score": 0.8169319033622742, "start": 11298, "tag": "NAME", "value": "Loudred" }, { "context": " 'Swalot'\n 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n", "end": 11317, "score": 0.7250441312789917, "start": 11310, "tag": "NAME", "value": "Exploud" }, { "context": " 'Tropius'\n 'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n ", "end": 11330, "score": 0.7484080791473389, "start": 11322, "tag": "NAME", "value": "Clamperl" }, { "context": "'Whismur'\n 'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n 'Banette'\n ", "end": 11342, "score": 0.7174902558326721, "start": 11335, "tag": "NAME", "value": "Huntail" }, { "context": "'Loudred'\n 'Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n 'Banette'\n 'Seviper'\n ", "end": 11355, "score": 0.6538847088813782, "start": 11347, "tag": "NAME", "value": "Gorebyss" }, { "context": "Exploud'\n 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n 'Banette'\n 'Seviper'\n 'Zangoose'", "end": 11365, "score": 0.7427650690078735, "start": 11360, "tag": "NAME", "value": "Absol" }, { "context": " 'Clamperl'\n 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n 'Banette'\n 'Seviper'\n 'Zangoose'\n 'Relicant", "end": 11377, "score": 0.6539472937583923, "start": 11370, "tag": "NAME", "value": "Shuppet" }, { "context": " 'Huntail'\n 'Gorebyss'\n 'Absol'\n 'Shuppet'\n 'Banette'\n 'Seviper'\n 'Zangoose'\n 'Relicanth'\n 'Aron'\n", "end": 11389, "score": 0.5550680160522461, "start": 11382, "tag": "NAME", "value": "Banette" }, { "context": "anette'\n 'Seviper'\n 'Zangoose'\n 'Relicanth'\n 'Aron'\n 'Lairon'\n 'Aggron'\n 'Castform'\n 'Volbeat'\n ", "end": 11437, "score": 0.6942391395568848, "start": 11433, "tag": "NAME", "value": "Aron" }, { "context": " 'Seviper'\n 'Zangoose'\n 'Relicanth'\n 'Aron'\n 'Lairon'\n 'Aggron'\n 'Castform'\n 'Volbeat'\n 'Illumise'", "end": 11448, "score": 0.6216893792152405, "start": 11442, "tag": "NAME", "value": "Lairon" }, { "context": " 'Zangoose'\n 'Relicanth'\n 'Aron'\n 'Lairon'\n 'Aggron'\n 'Castform'\n 'Volbeat'\n 'Illumise'\n 'Lileep'", "end": 11459, "score": 0.706713855266571, "start": 11453, "tag": "NAME", "value": "Aggron" }, { "context": "'\n 'Relicanth'\n 'Aron'\n 'Lairon'\n 'Aggron'\n 'Castform'\n 'Volbeat'\n 'Illumise'\n 'Lileep'\n 'Cradily'\n", "end": 11472, "score": 0.6610782146453857, "start": 11464, "tag": "NAME", "value": "Castform" }, { "context": " 'Lairon'\n 'Aggron'\n 'Castform'\n 'Volbeat'\n 'Illumise'\n 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n ", "end": 11497, "score": 0.7121028304100037, "start": 11489, "tag": "NAME", "value": "Illumise" }, { "context": "'Aggron'\n 'Castform'\n 'Volbeat'\n 'Illumise'\n 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n ", "end": 11508, "score": 0.6850355267524719, "start": 11502, "tag": "NAME", "value": "Lileep" }, { "context": "'Castform'\n 'Volbeat'\n 'Illumise'\n 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n '", "end": 11520, "score": 0.9486129879951477, "start": 11513, "tag": "NAME", "value": "Cradily" }, { "context": " 'Volbeat'\n 'Illumise'\n 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n ", "end": 11532, "score": 0.9235536456108093, "start": 11525, "tag": "NAME", "value": "Anorith" }, { "context": " 'Illumise'\n 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n '", "end": 11544, "score": 0.9355068802833557, "start": 11537, "tag": "NAME", "value": "Armaldo" }, { "context": " 'Lileep'\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n ", "end": 11554, "score": 0.8510863780975342, "start": 11549, "tag": "NAME", "value": "Ralts" }, { "context": "\n 'Cradily'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence", "end": 11565, "score": 0.8651086688041687, "start": 11559, "tag": "NAME", "value": "Kirlia" }, { "context": "'\n 'Anorith'\n 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n ", "end": 11579, "score": 0.8974828124046326, "start": 11570, "tag": "NAME", "value": "Gardevoir" }, { "context": " 'Armaldo'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n", "end": 11589, "score": 0.9156702756881714, "start": 11584, "tag": "NAME", "value": "Bagon" }, { "context": "'\n 'Ralts'\n 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross", "end": 11601, "score": 0.9156115651130676, "start": 11594, "tag": "NAME", "value": "Shelgon" }, { "context": " 'Kirlia'\n 'Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'", "end": 11615, "score": 0.8254868388175964, "start": 11606, "tag": "NAME", "value": "Salamence" }, { "context": "Gardevoir'\n 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'", "end": 11626, "score": 0.7880157828330994, "start": 11620, "tag": "NAME", "value": "Beldum" }, { "context": " 'Bagon'\n 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'\n 'Registe", "end": 11637, "score": 0.7847813963890076, "start": 11631, "tag": "NAME", "value": "Metang" }, { "context": " 'Shelgon'\n 'Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'", "end": 11651, "score": 0.9087650775909424, "start": 11642, "tag": "NAME", "value": "Metagross" }, { "context": "Salamence'\n 'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n", "end": 11664, "score": 0.9188497066497803, "start": 11656, "tag": "NAME", "value": "Regirock" }, { "context": "'Beldum'\n 'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza", "end": 11675, "score": 0.8930420279502869, "start": 11669, "tag": "NAME", "value": "Regice" }, { "context": "'Metang'\n 'Metagross'\n 'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n ", "end": 11689, "score": 0.8441845774650574, "start": 11680, "tag": "NAME", "value": "Registeel" }, { "context": "tagross'\n 'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n ", "end": 11700, "score": 0.8847401142120361, "start": 11694, "tag": "NAME", "value": "Kyogre" }, { "context": "'Regirock'\n 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n ", "end": 11712, "score": 0.9426966309547424, "start": 11705, "tag": "NAME", "value": "Groudon" }, { "context": " 'Regice'\n 'Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n '", "end": 11725, "score": 0.967717170715332, "start": 11717, "tag": "NAME", "value": "Rayquaza" }, { "context": "Registeel'\n 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n ", "end": 11736, "score": 0.9469776153564453, "start": 11730, "tag": "NAME", "value": "Latias" }, { "context": " 'Kyogre'\n 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n 'Pokémon E", "end": 11747, "score": 0.9166501760482788, "start": 11741, "tag": "NAME", "value": "Latios" }, { "context": " 'Groudon'\n 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n 'Pokémon Egg'\n 'Unown", "end": 11759, "score": 0.9210710525512695, "start": 11752, "tag": "NAME", "value": "Jirachi" }, { "context": " 'Rayquaza'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n 'Pokémon Egg'\n 'Unown'\n 'Unown'", "end": 11770, "score": 0.8747686743736267, "start": 11764, "tag": "NAME", "value": "Deoxys" }, { "context": "'\n 'Latias'\n 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n 'Pokémon Egg'\n 'Unown'\n 'Unown'\n 'Unown'\n ", "end": 11783, "score": 0.8606101870536804, "start": 11775, "tag": "NAME", "value": "Chimecho" }, { "context": " 'Latios'\n 'Jirachi'\n 'Deoxys'\n 'Chimecho'\n 'Pokémon Egg'\n 'Unown'\n 'Unown'\n 'Unown'\n 'Unown'\n 'Unown", "end": 11799, "score": 0.8975661396980286, "start": 11788, "tag": "NAME", "value": "Pokémon Egg" } ]
lib/Pokemon.coffee
alvaro-cuesta/pokedit3
1
util = undefined PokemonString = require "#{__dirname}/String" Items = require "#{__dirname}/Items" {UInt8, UInt16LE, UInt32LE, Obj, ArrayOf, Slice, Filter, Wrap, Transform, Pass} = require "#{__dirname}/byte-spec" checksum = (buffer) -> sum = 0 (sum += buffer.readUInt16LE i) for i in [0...buffer.length] by 2 sum &= 0xFFFF sum G = growth: Obj [ {species: UInt16LE} {item: UInt16LE} {experience: UInt32LE} {ppBonus: UInt8} # TODO: BITS! {friendship: UInt8} {unknown0: UInt16LE} ] A = moves: Obj [ {moves: ArrayOf 4, UInt16LE} {pp: ArrayOf 4, UInt8} ] E = evCondition: Obj [ {hp: UInt8} {attack: UInt8} {defense: UInt8} {speed: UInt8} {spAttack: UInt8} {spDefense: UInt8} {coolness: UInt8} {beauty: UInt8} {cuteness: UInt8} {smartness: UInt8} {toughness: UInt8} {feel: UInt8} ] M = misc: Obj [ {pokerus: UInt8} {metLocation: UInt8} {origins: UInt16LE} # TODO: BITS! {ivs: UInt32LE} # TODO: BITS! {ribbons: UInt32LE} # TODO: WHAT? ] SPEC_POKEMON_DATA = [ Obj [G, A, E, M] Obj [G, A, M, E] Obj [G, E, A, M] Obj [G, E, M, A] Obj [G, M, A, E] Obj [G, M, E, A] Obj [A, G, E, M] Obj [A, G, M, E] Obj [A, E, G, M] Obj [A, E, M, G] Obj [A, M, G, E] Obj [A, M, E, G] Obj [E, G, A, M] Obj [E, G, M, A] Obj [E, A, G, M] Obj [E, A, M, G] Obj [E, M, G, A] Obj [E, M, A, G] Obj [M, G, A, E] Obj [M, G, E, A] Obj [M, A, G, E] Obj [M, A, E, G] Obj [M, E, G, A] Obj [M, E, A, G] ] POKEMON_DATA_LENGTH = 48 SpecPokemon = -> wrap = new Wrap() [ {personality: wrap.capture UInt32LE} {otId: wrap.capture UInt32LE} {nickname: PokemonString 10} {language: Transform UInt16LE, (l) -> l - 0x201} {otName: PokemonString 7} {mark: UInt8} # TODO: BITS! {checksum: UInt16LE} {unknown0: UInt16LE} {data: wrap.emit (c) -> [otId, personality] = [c.pop(), c.pop()] order = personality % 24 key = otId ^ personality Pass SPEC_POKEMON_DATA[order], Transform (Slice POKEMON_DATA_LENGTH), (v) -> data = new Buffer POKEMON_DATA_LENGTH for i in [0...POKEMON_DATA_LENGTH] by 4 data.writeInt32LE (key ^ v.readUInt32LE i), i data } ] SPEC_EXTENDED = [ {status: UInt32LE} # TODO: BITS! {level: UInt8} {pokerus: UInt8} {hp: UInt16LE} {maxHp: UInt16LE} {attack: UInt16LE} {defense: UInt16LE} {speed: UInt16LE} {spAttack: UInt16LE} {spDefense: UInt16LE} ] module.exports = (extended) -> Obj if extended SpecPokemon().concat SPEC_EXTENDED else SpecPokemon() module.exports.parseOLD = (buffer, extended) -> readChecksum = buffer.readUInt16LE 0x1C trainerId = buffer.readUInt32LE 0x04 personality = buffer.readUInt32LE 0x00 dataBuffer = new Buffer POKEMON_DATA_SIZE for i in [0...POKEMON_DATA_SIZE] by 4 dataBuffer.writeInt32LE (trainerId ^ personality ^ buffer.readUInt32LE i + 0x20), i expectedChecksum = checksum.pokemon dataBuffer return if readChecksum == 0 and trainerId == 0 and personality == 0 and expectedChecksum == 0 if readChecksum != expectedChecksum throw "Bad checksum #{readChecksum.toString 16} (expected #{expectedChecksum.toString 16})" marks = buffer.readUInt8 0x1B language = (buffer.readUInt16LE 0x12) - 0x0201 data = parseData dataBuffer, personality result = name: util.decodeString buffer, 0x08, 10 trainer: id: buffer.readUInt16LE 0x04 fullId: trainerId name: util.decodeString buffer, 0x14, 8 language: language personality: raw: personality data: data marks: circle: !!(marks & 1) square: !!(marks & 2) triangle: !!(marks & 4) heart: !!(marks & 8) # Extended stats (Pokémon is not in box) if extended result.level = buffer.readUInt8 0x54 status = buffer.readUInt32LE 0x50 result.status = sleep: (status & 0b111) or false poison: !!(status & 8) burn: !!(status & 16) freeze: !!(status & 32) paralysis: !!(status & 64) badPoison: !!(status & 128) result.remainingPokerus = buffer.readUInt8 0x55 result.stats = hp: buffer.readUInt16LE 0x56 hpMax: buffer.readUInt16LE 0x58 attack: buffer.readUInt16LE 0x5A defense: buffer.readUInt16LE 0x5C speed: buffer.readUInt16LE 0x5E spAttack: buffer.readUInt16LE 0x60 spDefense: buffer.readUInt16LE 0x62 result parseData = (buffer, personality, pokemonRSE) -> dataOrder = POKEMON_DATA_ORDER[personality % 24] species = buffer.readUInt16LE 0 + SUBSTRUCTURE_LENGTH * dataOrder[G] item = buffer.readUInt16LE 2 + SUBSTRUCTURE_LENGTH * dataOrder[G] bonuses = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[G] pokerus = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[M] result = growth: species: id: species name: SPECIES[species] item: id: item name: items.NAMES[item] experience: buffer.readUInt32LE 4 + SUBSTRUCTURE_LENGTH * dataOrder[G] friendship: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[G] moves: for i in [0..3] id = buffer.readUInt16LE 0 + i * 2 + SUBSTRUCTURE_LENGTH * dataOrder[A] id: id name: MOVES[id] pp: buffer.readUInt8 8 + i + SUBSTRUCTURE_LENGTH * dataOrder[A] bonus: (bonuses & (0b11 << (i * 2))) >>> (i * 2) ev: hp: buffer.readUInt8 0 + SUBSTRUCTURE_LENGTH * dataOrder[E] attack: buffer.readUInt8 1 + SUBSTRUCTURE_LENGTH * dataOrder[E] defense: buffer.readUInt8 2 + SUBSTRUCTURE_LENGTH * dataOrder[E] speed: buffer.readUInt8 3 + SUBSTRUCTURE_LENGTH * dataOrder[E] spAttack: buffer.readUInt8 4 + SUBSTRUCTURE_LENGTH * dataOrder[E] spDefense: buffer.readUInt8 5 + SUBSTRUCTURE_LENGTH * dataOrder[E] condition: coolness: buffer.readUInt8 6 + SUBSTRUCTURE_LENGTH * dataOrder[E] beauty: buffer.readUInt8 7 + SUBSTRUCTURE_LENGTH * dataOrder[E] cuteness: buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[E] smartness: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[E] toughness: buffer.readUInt8 10 + SUBSTRUCTURE_LENGTH * dataOrder[E] feel: buffer.readUInt8 11 + SUBSTRUCTURE_LENGTH * dataOrder[E] pokerus: remaining: pokerus & 0xF immune: (pokerus >>> 4) > 0 met: 0 origin: 0 iv: 0 ribbons: 0 module.exports.LANGUAGES = ['JP', 'EN', 'FR', 'IT', 'DE', undefined, 'ES'] module.exports.SPECIES = [ undefined 'Bulbasaur' 'Ivysaur' 'Venusaur' 'Charmander' 'Charmeleon' 'Charizard' 'Squirtle' 'Wartortle' 'Blastoise' 'Caterpie' 'Metapod' 'Butterfree' 'Weedle' 'Kakuna' 'Beedrill' 'Pidgey' 'Pidgeotto' 'Pidgeot' 'Rattata' 'Raticate' 'Spearow' 'Fearow' 'Ekans' 'Arbok' 'Pikachu' 'Raichu' 'Sandshrew' 'Sandslash' 'Nidoran?' 'Nidorina' 'Nidoqueen' 'Nidoran?' 'Nidorino' 'Nidoking' 'Clefairy' 'Clefable' 'Vulpix' 'Ninetales' 'Jigglypuff' 'Wigglytuff' 'Zubat' 'Golbat' 'Oddish' 'Gloom' 'Vileplume' 'Paras' 'Parasect' 'Venonat' 'Venomoth' 'Diglett' 'Dugtrio' 'Meowth' 'Persian' 'Psyduck' 'Golduck' 'Mankey' 'Primeape' 'Growlithe' 'Arcanine' 'Poliwag' 'Poliwhirl' 'Poliwrath' 'Abra' 'Kadabra' 'Alakazam' 'Machop' 'Machoke' 'Machamp' 'Bellsprout' 'Weepinbell' 'Victreebel' 'Tentacool' 'Tentacruel' 'Geodude' 'Graveler' 'Golem' 'Ponyta' 'Rapidash' 'Slowpoke' 'Slowbro' 'Magnemite' 'Magneton' 'Farfetch\'d' 'Doduo' 'Dodrio' 'Seel' 'Dewgong' 'Grimer' 'Muk' 'Shellder' 'Cloyster' 'Gastly' 'Haunter' 'Gengar' 'Onix' 'Drowzee' 'Hypno' 'Krabby' 'Kingler' 'Voltorb' 'Electrode' 'Exeggcute' 'Exeggutor' 'Cubone' 'Marowak' 'Hitmonlee' 'Hitmonchan' 'Lickitung' 'Koffing' 'Weezing' 'Rhyhorn' 'Rhydon' 'Chansey' 'Tangela' 'Kangaskhan' 'Horsea' 'Seadra' 'Goldeen' 'Seaking' 'Staryu' 'Starmie' 'Mr. Mime' 'Scyther' 'Jynx' 'Electabuzz' 'Magmar' 'Pinsir' 'Tauros' 'Magikarp' 'Gyarados' 'Lapras' 'Ditto' 'Eevee' 'Vaporeon' 'Jolteon' 'Flareon' 'Porygon' 'Omanyte' 'Omastar' 'Kabuto' 'Kabutops' 'Aerodactyl' 'Snorlax' 'Articuno' 'Zapdos' 'Moltres' 'Dratini' 'Dragonair' 'Dragonite' 'Mewtwo' 'Mew' 'Chikorita' 'Bayleef' 'Meganium' 'Cyndaquil' 'Quilava' 'Typhlosion' 'Totodile' 'Croconaw' 'Feraligatr' 'Sentret' 'Furret' 'Hoothoot' 'Noctowl' 'Ledyba' 'Ledian' 'Spinarak' 'Ariados' 'Crobat' 'Chinchou' 'Lanturn' 'Pichu' 'Cleffa' 'Igglybuff' 'Togepi' 'Togetic' 'Natu' 'Xatu' 'Mareep' 'Flaaffy' 'Ampharos' 'Bellossom' 'Marill' 'Azumarill' 'Sudowoodo' 'Politoed' 'Hoppip' 'Skiploom' 'Jumpluff' 'Aipom' 'Sunkern' 'Sunflora' 'Yanma' 'Wooper' 'Quagsire' 'Espeon' 'Umbreon' 'Murkrow' 'Slowking' 'Misdreavus' 'Unown' 'Wobbuffet' 'Girafarig' 'Pineco' 'Forretress' 'Dunsparce' 'Gligar' 'Steelix' 'Snubbull' 'Granbull' 'Qwilfish' 'Scizor' 'Shuckle' 'Heracross' 'Sneasel' 'Teddiursa' 'Ursaring' 'Slugma' 'Magcargo' 'Swinub' 'Piloswine' 'Corsola' 'Remoraid' 'Octillery' 'Delibird' 'Mantine' 'Skarmory' 'Houndour' 'Houndoom' 'Kingdra' 'Phanpy' 'Donphan' 'Porygon2' 'Stantler' 'Smeargle' 'Tyrogue' 'Hitmontop' 'Smoochum' 'Elekid' 'Magby' 'Miltank' 'Blissey' 'Raikou' 'Entei' 'Suicune' 'Larvitar' 'Pupitar' 'Tyranitar' 'Lugia' 'Ho-Oh' 'Celebi' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' 'Treecko' 'Grovyle' 'Sceptile' 'Torchic' 'Combusken' 'Blaziken' 'Mudkip' 'Marshtomp' 'Swampert' 'Poochyena' 'Mightyena' 'Zigzagoon' 'Linoone' 'Wurmple' 'Silcoon' 'Beautifly' 'Cascoon' 'Dustox' 'Lotad' 'Lombre' 'Ludicolo' 'Seedot' 'Nuzleaf' 'Shiftry' 'Nincada' 'Ninjask' 'Shedinja' 'Taillow' 'Swellow' 'Shroomish' 'Breloom' 'Spinda' 'Wingull' 'Pelipper' 'Surskit' 'Masquerain' 'Wailmer' 'Wailord' 'Skitty' 'Delcatty' 'Kecleon' 'Baltoy' 'Claydol' 'Nosepass' 'Torkoal' 'Sableye' 'Barboach' 'Whiscash' 'Luvdisc' 'Corphish' 'Crawdaunt' 'Feebas' 'Milotic' 'Carvanha' 'Sharpedo' 'Trapinch' 'Vibrava' 'Flygon' 'Makuhita' 'Hariyama' 'Electrike' 'Manectric' 'Numel' 'Camerupt' 'Spheal' 'Sealeo' 'Walrein' 'Cacnea' 'Cacturne' 'Snorunt' 'Glalie' 'Lunatone' 'Solrock' 'Azurill' 'Spoink' 'Grumpig' 'Plusle' 'Minun' 'Mawile' 'Meditite' 'Medicham' 'Swablu' 'Altaria' 'Wynaut' 'Duskull' 'Dusclops' 'Roselia' 'Slakoth' 'Vigoroth' 'Slaking' 'Gulpin' 'Swalot' 'Tropius' 'Whismur' 'Loudred' 'Exploud' 'Clamperl' 'Huntail' 'Gorebyss' 'Absol' 'Shuppet' 'Banette' 'Seviper' 'Zangoose' 'Relicanth' 'Aron' 'Lairon' 'Aggron' 'Castform' 'Volbeat' 'Illumise' 'Lileep' 'Cradily' 'Anorith' 'Armaldo' 'Ralts' 'Kirlia' 'Gardevoir' 'Bagon' 'Shelgon' 'Salamence' 'Beldum' 'Metang' 'Metagross' 'Regirock' 'Regice' 'Registeel' 'Kyogre' 'Groudon' 'Rayquaza' 'Latias' 'Latios' 'Jirachi' 'Deoxys' 'Chimecho' 'Pokémon Egg' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' ] module.exports.MOVES = [ undefined 'Pound' 'Karate Chop' 'DoubleSlap' 'Comet Punch' 'Mega Punch' 'Pay Day' 'Fire Punch' 'Ice Punch' 'ThunderPunch' 'Scratch' 'ViceGrip' 'Guillotine' 'Razor Wind' 'Swords Dance' 'Cut' 'Gust' 'Wing Attack' 'Whirlwind' 'Fly' 'Bind' 'Slam' 'Vine Whip' 'Stomp' 'Double Kick' 'Mega Kick' 'Jump Kick' 'Rolling Kick' 'Sand-Attack' 'Headbutt' 'Horn Attack' 'Fury Attack' 'Horn Drill' 'Tackle' 'Body Slam' 'Wrap' 'Take Down' 'Thrash' 'Double-Edge' 'Tail Whip' 'Poison Sting' 'Twineedle' 'Pin Missile' 'Leer' 'Bite' 'Growl' 'Roar' 'Sing' 'Supersonic' 'SonicBoom' 'Disable' 'Acid' 'Ember' 'Flamethrower' 'Mist' 'Water Gun' 'Hydro Pump' 'Surf' 'Ice Beam' 'Blizzard' 'Psybeam' 'BubbleBeam' 'Aurora Beam' 'Hyper Beam' 'Peck' 'Drill Peck' 'Submission' 'Low Kick' 'Counter' 'Seismic Toss' 'Strength' 'Absorb' 'Mega Drain' 'Leech Seed' 'Growth' 'Razor Leaf' 'SolarBeam' 'PoisonPowder' 'Stun Spore' 'Sleep Powder' 'Petal Dance' 'String Shot' 'Dragon Rage' 'Fire Spin' 'ThunderShock' 'Thunderbolt' 'Thunder Wave' 'Thunder' 'Rock Throw' 'Earthquake' 'Fissure' 'Dig' 'Toxic' 'Confusion' 'Psychic' 'Hypnosis' 'Meditate' 'Agility' 'Quick Attack' 'Rage' 'Teleport' 'Night Shade' 'Mimic' 'Screech' 'Double Team' 'Recover' 'Harden' 'Minimize' 'SmokeScreen' 'Confuse Ray' 'Withdraw' 'Defense Curl' 'Barrier' 'Light Screen' 'Haze' 'Reflect' 'Focus Energy' 'Bide' 'Metronome' 'Mirror Move' 'Selfdestruct' 'Egg Bomb' 'Lick' 'Smog' 'Sludge' 'Bone Club' 'Fire Blast' 'Waterfall' 'Clamp' 'Swift' 'Skull Bash' 'Spike Cannon' 'Constrict' 'Amnesia' 'Kinesis' 'Softboiled' 'Hi Jump Kick' 'Glare' 'Dream Eater' 'Poison Gas' 'Barrage' 'Leech Life' 'Lovely Kiss' 'Sky Attack' 'Transform' 'Bubble' 'Dizzy Punch' 'Spore' 'Flash' 'Psywave' 'Splash' 'Acid Armor' 'Crabhammer' 'Explosion' 'Fury Swipes' 'Bonemerang' 'Rest' 'Rock Slide' 'Hyper Fang' 'Sharpen' 'Conversion' 'Tri Attack' 'Super Fang' 'Slash' 'Substitute' 'Struggle' 'Sketch' 'Triple Kick' 'Thief' 'Spider Web' 'Mind Reader' 'Nightmare' 'Flame Wheel' 'Snore' 'Curse' 'Flail' 'Conversion 2' 'Aeroblast' 'Cotton Spore' 'Reversal' 'Spite' 'Powder Snow' 'Protect' 'Mach Punch' 'Scary Face' 'Faint Attack' 'Sweet Kiss' 'Belly Drum' 'Sludge Bomb' 'Mud-Slap' 'Octazooka' 'Spikes' 'Zap Cannon' 'Foresight' 'Destiny Bond' 'Perish Song' 'Icy Wind' 'Detect' 'Bone Rush' 'Lock-On' 'Outrage' 'Sandstorm' 'Giga Drain' 'Endure' 'Charm' 'Rollout' 'False Swipe' 'Swagger' 'Milk Drink' 'Spark' 'Fury Cutter' 'Steel Wing' 'Mean Look' 'Attract' 'Sleep Talk' 'Heal Bell' 'Return' 'Present' 'Frustration' 'Safeguard' 'Pain Split' 'Sacred Fire' 'Magnitude' 'DynamicPunch' 'Megahorn' 'DragonBreath' 'Baton Pass' 'Encore' 'Pursuit' 'Rapid Spin' 'Sweet Scent' 'Iron Tail' 'Metal Claw' 'Vital Throw' 'Morning Sun' 'Synthesis' 'Moonlight' 'Hidden Power' 'Cross Chop' 'Twister' 'Rain Dance' 'Sunny Day' 'Crunch' 'Mirror Coat' 'Psych Up' 'ExtremeSpeed' 'AncientPower' 'Shadow Ball' 'Future Sight' 'Rock Smash' 'Whirlpool' 'Beat Up' 'Fake Out' 'Uproar' 'Stockpile' 'Spit Up' 'Swallow' 'Heat Wave' 'Hail' 'Torment' 'Flatter' 'Will-O-Wisp' 'Memento' 'Facade' 'Focus Punch' 'SmellingSalt' 'Follow Me' 'Nature Power' 'Charge' 'Taunt' 'Helping Hand' 'Trick' 'Role Play' 'Wish' 'Assist' 'Ingrain' 'Superpower' 'Magic Coat' 'Recycle' 'Revenge' 'Brick Break' 'Yawn' 'Knock Off' 'Endeavor' 'Eruption' 'Skill Swap' 'Imprison' 'Refresh' 'Grudge' 'Snatch' 'Secret Power' 'Dive' 'Arm Thrust' 'Camouflage' 'Tail Glow' 'Luster Purge' 'Mist Ball' 'FeatherDance' 'Teeter Dance' 'Blaze Kick' 'Mud Sport' 'Ice Ball' 'Needle Arm' 'Slack Off' 'Hyper Voice' 'Poison Fang' 'Crush Claw' 'Blast Burn' 'Hydro Cannon' 'Meteor Mash' 'Astonish' 'Weather Ball' 'Aromatherapy' 'Fake Tears' 'Air Cutter' 'Overheat' 'Odor Sleuth' 'Rock Tomb' 'Silver Wind' 'Metal Sound' 'GrassWhistle' 'Tickle' 'Cosmic Power' 'Water Spout' 'Signal Beam' 'Shadow Punch' 'Extrasensory' 'Sky Uppercut' 'Sand Tomb' 'Sheer Cold' 'Muddy Water' 'Bullet Seed' 'Aerial Ace' 'Icicle Spear' 'Iron Defense' 'Block' 'Howl' 'Dragon Claw' 'Frenzy Plant' 'Bulk Up' 'Bounce' 'Mud Shot' 'Poison Tail' 'Covet' 'Volt Tackle' 'Magical Leaf' 'Water Sport' 'Calm Mind' 'Leaf Blade' 'Dragon Dance' 'Rock Blast' 'Shock Wave' 'Water Pulse' 'Doom Desire' 'Psycho Boost' ] module.exports.NATURES = [ 'Hardy (=)' 'Lonely (+Atk-Def)' 'Brave (+Atk-Spe)' 'Adamant (+Atk-SpA)' 'Naughty (+Atk-SpD)' 'Bold (+Def-Atk)' 'Docile (=)' 'Relaxed (+Def-Spe)' 'Impish (+Def-SpA)' 'Lax (+Def-SpD)' 'Timid (+Spe-Atk)' 'Hasty (+Spe-Def)' 'Serious (=)' 'Jolly (+Spe-SpA)' 'Naive (+Spe-SpD)' 'Modest (+SpA-Atk)' 'Mild (+SpA-Def)' 'Quiet (+SpA-Spe)' 'Bashful (=)' 'Rash (+SpA-SpD)' 'Calm (+SpD-Atk)' 'Gentle (+SpD-Def)' 'Sassy (+SpD-Spe)' 'Careful (-SpD-SpA)' 'Quirky (=)' ]
224005
util = undefined PokemonString = require "#{__dirname}/String" Items = require "#{__dirname}/Items" {UInt8, UInt16LE, UInt32LE, Obj, ArrayOf, Slice, Filter, Wrap, Transform, Pass} = require "#{__dirname}/byte-spec" checksum = (buffer) -> sum = 0 (sum += buffer.readUInt16LE i) for i in [0...buffer.length] by 2 sum &= 0xFFFF sum G = growth: Obj [ {species: UInt16LE} {item: UInt16LE} {experience: UInt32LE} {ppBonus: UInt8} # TODO: BITS! {friendship: UInt8} {unknown0: UInt16LE} ] A = moves: Obj [ {moves: ArrayOf 4, UInt16LE} {pp: ArrayOf 4, UInt8} ] E = evCondition: Obj [ {hp: UInt8} {attack: UInt8} {defense: UInt8} {speed: UInt8} {spAttack: UInt8} {spDefense: UInt8} {coolness: UInt8} {beauty: UInt8} {cuteness: UInt8} {smartness: UInt8} {toughness: UInt8} {feel: UInt8} ] M = misc: Obj [ {pokerus: UInt8} {metLocation: UInt8} {origins: UInt16LE} # TODO: BITS! {ivs: UInt32LE} # TODO: BITS! {ribbons: UInt32LE} # TODO: WHAT? ] SPEC_POKEMON_DATA = [ Obj [G, A, E, M] Obj [G, A, M, E] Obj [G, E, A, M] Obj [G, E, M, A] Obj [G, M, A, E] Obj [G, M, E, A] Obj [A, G, E, M] Obj [A, G, M, E] Obj [A, E, G, M] Obj [A, E, M, G] Obj [A, M, G, E] Obj [A, M, E, G] Obj [E, G, A, M] Obj [E, G, M, A] Obj [E, A, G, M] Obj [E, A, M, G] Obj [E, M, G, A] Obj [E, M, A, G] Obj [M, G, A, E] Obj [M, G, E, A] Obj [M, A, G, E] Obj [M, A, E, G] Obj [M, E, G, A] Obj [M, E, A, G] ] POKEMON_DATA_LENGTH = 48 SpecPokemon = -> wrap = new Wrap() [ {personality: wrap.capture UInt32LE} {otId: wrap.capture UInt32LE} {nickname: PokemonString 10} {language: Transform UInt16LE, (l) -> l - 0x201} {otName: PokemonString 7} {mark: UInt8} # TODO: BITS! {checksum: UInt16LE} {unknown0: UInt16LE} {data: wrap.emit (c) -> [otId, personality] = [c.pop(), c.pop()] order = personality % 24 key = otId ^ personality Pass SPEC_POKEMON_DATA[order], Transform (Slice POKEMON_DATA_LENGTH), (v) -> data = new Buffer POKEMON_DATA_LENGTH for i in [0...POKEMON_DATA_LENGTH] by 4 data.writeInt32LE (key ^ v.readUInt32LE i), i data } ] SPEC_EXTENDED = [ {status: UInt32LE} # TODO: BITS! {level: UInt8} {pokerus: UInt8} {hp: UInt16LE} {maxHp: UInt16LE} {attack: UInt16LE} {defense: UInt16LE} {speed: UInt16LE} {spAttack: UInt16LE} {spDefense: UInt16LE} ] module.exports = (extended) -> Obj if extended SpecPokemon().concat SPEC_EXTENDED else SpecPokemon() module.exports.parseOLD = (buffer, extended) -> readChecksum = buffer.readUInt16LE 0x1C trainerId = buffer.readUInt32LE 0x04 personality = buffer.readUInt32LE 0x00 dataBuffer = new Buffer POKEMON_DATA_SIZE for i in [0...POKEMON_DATA_SIZE] by 4 dataBuffer.writeInt32LE (trainerId ^ personality ^ buffer.readUInt32LE i + 0x20), i expectedChecksum = checksum.pokemon dataBuffer return if readChecksum == 0 and trainerId == 0 and personality == 0 and expectedChecksum == 0 if readChecksum != expectedChecksum throw "Bad checksum #{readChecksum.toString 16} (expected #{expectedChecksum.toString 16})" marks = buffer.readUInt8 0x1B language = (buffer.readUInt16LE 0x12) - 0x0201 data = parseData dataBuffer, personality result = name: util.decodeString buffer, 0x08, 10 trainer: id: buffer.readUInt16LE 0x04 fullId: trainerId name: util.decodeString buffer, 0x14, 8 language: language personality: raw: personality data: data marks: circle: !!(marks & 1) square: !!(marks & 2) triangle: !!(marks & 4) heart: !!(marks & 8) # Extended stats (Pokémon is not in box) if extended result.level = buffer.readUInt8 0x54 status = buffer.readUInt32LE 0x50 result.status = sleep: (status & 0b111) or false poison: !!(status & 8) burn: !!(status & 16) freeze: !!(status & 32) paralysis: !!(status & 64) badPoison: !!(status & 128) result.remainingPokerus = buffer.readUInt8 0x55 result.stats = hp: buffer.readUInt16LE 0x56 hpMax: buffer.readUInt16LE 0x58 attack: buffer.readUInt16LE 0x5A defense: buffer.readUInt16LE 0x5C speed: buffer.readUInt16LE 0x5E spAttack: buffer.readUInt16LE 0x60 spDefense: buffer.readUInt16LE 0x62 result parseData = (buffer, personality, pokemonRSE) -> dataOrder = POKEMON_DATA_ORDER[personality % 24] species = buffer.readUInt16LE 0 + SUBSTRUCTURE_LENGTH * dataOrder[G] item = buffer.readUInt16LE 2 + SUBSTRUCTURE_LENGTH * dataOrder[G] bonuses = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[G] pokerus = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[M] result = growth: species: id: species name: SPECIES[species] item: id: item name: items.NAMES[item] experience: buffer.readUInt32LE 4 + SUBSTRUCTURE_LENGTH * dataOrder[G] friendship: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[G] moves: for i in [0..3] id = buffer.readUInt16LE 0 + i * 2 + SUBSTRUCTURE_LENGTH * dataOrder[A] id: id name: MOVES[id] pp: buffer.readUInt8 8 + i + SUBSTRUCTURE_LENGTH * dataOrder[A] bonus: (bonuses & (0b11 << (i * 2))) >>> (i * 2) ev: hp: buffer.readUInt8 0 + SUBSTRUCTURE_LENGTH * dataOrder[E] attack: buffer.readUInt8 1 + SUBSTRUCTURE_LENGTH * dataOrder[E] defense: buffer.readUInt8 2 + SUBSTRUCTURE_LENGTH * dataOrder[E] speed: buffer.readUInt8 3 + SUBSTRUCTURE_LENGTH * dataOrder[E] spAttack: buffer.readUInt8 4 + SUBSTRUCTURE_LENGTH * dataOrder[E] spDefense: buffer.readUInt8 5 + SUBSTRUCTURE_LENGTH * dataOrder[E] condition: coolness: buffer.readUInt8 6 + SUBSTRUCTURE_LENGTH * dataOrder[E] beauty: buffer.readUInt8 7 + SUBSTRUCTURE_LENGTH * dataOrder[E] cuteness: buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[E] smartness: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[E] toughness: buffer.readUInt8 10 + SUBSTRUCTURE_LENGTH * dataOrder[E] feel: buffer.readUInt8 11 + SUBSTRUCTURE_LENGTH * dataOrder[E] pokerus: remaining: pokerus & 0xF immune: (pokerus >>> 4) > 0 met: 0 origin: 0 iv: 0 ribbons: 0 module.exports.LANGUAGES = ['JP', 'EN', 'FR', 'IT', 'DE', undefined, 'ES'] module.exports.SPECIES = [ undefined 'Bulbasaur' 'Ivysaur' 'Venusaur' 'Charmander' 'Charmeleon' 'Charizard' 'Squirtle' 'Wartortle' 'Blastoise' 'Caterpie' 'Metapod' 'Butterfree' 'Weedle' 'Kakuna' 'Beedrill' 'Pidgey' 'Pidgeotto' 'Pidgeot' 'Rattata' 'Raticate' 'Spearow' 'Fearow' 'Ekans' 'Arbok' 'Pikachu' 'Raichu' 'Sandshrew' 'Sandslash' 'Nidoran?' 'Nidorina' 'Nidoqueen' 'Nidoran?' 'Nidorino' 'Nidoking' '<NAME>' 'Clefable' 'Vulpix' 'Ninetales' 'Jigglypuff' 'Wigglytuff' 'Zubat' 'Golbat' 'Oddish' 'Gloom' 'Vileplume' 'Paras' 'Parasect' 'Venonat' 'Venomoth' 'Dig<NAME>' 'D<NAME>o' 'Meowth' 'Persian' 'Psyduck' '<NAME>' '<NAME>' 'Prime<NAME>' 'Growlithe' 'Arcanine' 'Poliwag' 'Poliwhirl' 'Poliwrath' '<NAME>' '<NAME>adabra' '<NAME>akaz<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>ute' '<NAME>utor' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'W<NAME>' 'R<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Kangaskhan' '<NAME>a' '<NAME>adra' '<NAME>' 'Seaking' '<NAME>' '<NAME>' 'Mr. <NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Aerodactyl' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Meganium' 'Cynda<NAME>' '<NAME>' '<NAME>' '<NAME>od<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>ud<NAME>' '<NAME>' 'Hoppip' '<NAME>' 'Jump<NAME>' '<NAME>ip<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Umbreon' '<NAME>ur<NAME>' 'Slowking' '<NAME>d<NAME>' 'Unown' 'Wobbuffet' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Ho-Oh' '<NAME>' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Sl<NAME>' '<NAME>' '<NAME>' 'Tro<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Seviper' 'Zangoose' 'Relicanth' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Volbeat' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' ] module.exports.MOVES = [ undefined 'Pound' 'Karate Chop' 'DoubleSlap' 'Comet Punch' 'Mega Punch' 'Pay Day' 'Fire Punch' 'Ice Punch' 'ThunderPunch' 'Scratch' 'ViceGrip' 'Guillotine' 'Razor Wind' 'Swords Dance' 'Cut' 'Gust' 'Wing Attack' 'Whirlwind' 'Fly' 'Bind' 'Slam' 'Vine Whip' 'Stomp' 'Double Kick' 'Mega Kick' 'Jump Kick' 'Rolling Kick' 'Sand-Attack' 'Headbutt' 'Horn Attack' 'Fury Attack' 'Horn Drill' 'Tackle' 'Body Slam' 'Wrap' 'Take Down' 'Thrash' 'Double-Edge' 'Tail Whip' 'Poison Sting' 'Twineedle' 'Pin Missile' 'Leer' 'Bite' 'Growl' 'Roar' 'Sing' 'Supersonic' 'SonicBoom' 'Disable' 'Acid' 'Ember' 'Flamethrower' 'Mist' 'Water Gun' 'Hydro Pump' 'Surf' 'Ice Beam' 'Blizzard' 'Psybeam' 'BubbleBeam' 'Aurora Beam' 'Hyper Beam' 'Peck' 'Drill Peck' 'Submission' 'Low Kick' 'Counter' 'Seismic Toss' 'Strength' 'Absorb' 'Mega Drain' 'Leech Seed' 'Growth' 'Razor Leaf' 'SolarBeam' 'PoisonPowder' 'Stun Spore' 'Sleep Powder' 'Petal Dance' 'String Shot' 'Dragon Rage' 'Fire Spin' 'ThunderShock' 'Thunderbolt' 'Thunder Wave' 'Thunder' 'Rock Throw' 'Earthquake' 'Fissure' 'Dig' 'Toxic' 'Confusion' 'Psychic' 'Hypnosis' 'Meditate' 'Agility' 'Quick Attack' 'Rage' 'Teleport' 'Night Shade' 'Mimic' 'Screech' 'Double Team' 'Recover' 'Harden' 'Minimize' 'SmokeScreen' 'Confuse Ray' 'Withdraw' 'Defense Curl' 'Barrier' 'Light Screen' 'Haze' 'Reflect' 'Focus Energy' 'Bide' 'Metronome' 'Mirror Move' 'Selfdestruct' 'Egg Bomb' 'Lick' 'Smog' 'Sludge' 'Bone Club' 'Fire Blast' 'Waterfall' 'Clamp' 'Swift' 'Skull Bash' 'Spike Cannon' 'Constrict' 'Amnesia' 'Kinesis' 'Softboiled' 'Hi Jump Kick' 'Glare' 'Dream Eater' 'Poison Gas' 'Barrage' 'Leech Life' 'Lovely Kiss' 'Sky Attack' 'Transform' 'Bubble' 'Dizzy Punch' 'Spore' 'Flash' 'Psywave' 'Splash' 'Acid Armor' 'Crabhammer' 'Explosion' 'Fury Swipes' 'Bonemerang' 'Rest' 'Rock Slide' 'Hyper Fang' 'Sharpen' 'Conversion' 'Tri Attack' 'Super Fang' 'Slash' 'Substitute' 'Struggle' 'Sketch' 'Triple Kick' 'Thief' 'Spider Web' 'Mind Reader' 'Nightmare' 'Flame Wheel' 'Snore' 'Curse' 'Flail' 'Conversion 2' 'Aeroblast' 'Cotton Spore' 'Reversal' 'Spite' 'Powder Snow' 'Protect' 'Mach Punch' 'Scary Face' 'Faint Attack' 'Sweet Kiss' 'Belly Drum' 'Sludge Bomb' 'Mud-Slap' 'Octazooka' 'Spikes' 'Zap Cannon' 'Foresight' 'Destiny Bond' 'Perish Song' 'Icy Wind' 'Detect' 'Bone Rush' 'Lock-On' 'Outrage' 'Sandstorm' 'Giga Drain' 'Endure' 'Charm' 'Rollout' 'False Swipe' 'Swagger' 'Milk Drink' 'Spark' 'Fury Cutter' 'Steel Wing' 'Mean Look' 'Attract' 'Sleep Talk' 'Heal Bell' 'Return' 'Present' 'Frustration' 'Safeguard' 'Pain Split' 'Sacred Fire' 'Magnitude' 'DynamicPunch' 'Megahorn' 'DragonBreath' 'Baton Pass' 'Encore' 'Pursuit' 'Rapid Spin' 'Sweet Scent' 'Iron Tail' 'Metal Claw' 'Vital Throw' 'Morning Sun' 'Synthesis' 'Moonlight' 'Hidden Power' 'Cross Chop' 'Twister' 'Rain Dance' 'Sunny Day' 'Crunch' 'Mirror Coat' 'Psych Up' 'ExtremeSpeed' 'AncientPower' 'Shadow Ball' 'Future Sight' 'Rock Smash' 'Whirlpool' 'Beat Up' 'Fake Out' 'Uproar' 'Stockpile' 'Spit Up' 'Swallow' 'Heat Wave' 'Hail' 'Torment' 'Flatter' 'Will-O-Wisp' 'Memento' 'Facade' 'Focus Punch' 'SmellingSalt' 'Follow Me' 'Nature Power' 'Charge' 'Taunt' 'Helping Hand' 'Trick' 'Role Play' 'Wish' 'Assist' 'Ingrain' 'Superpower' 'Magic Coat' 'Recycle' 'Revenge' 'Brick Break' 'Yawn' 'Knock Off' 'Endeavor' 'Eruption' 'Skill Swap' 'Imprison' 'Refresh' 'Grudge' 'Snatch' 'Secret Power' 'Dive' 'Arm Thrust' 'Camouflage' 'Tail Glow' 'Luster Purge' 'Mist Ball' 'FeatherDance' 'Teeter Dance' 'Blaze Kick' 'Mud Sport' 'Ice Ball' 'Needle Arm' 'Slack Off' 'Hyper Voice' 'Poison Fang' 'Crush Claw' 'Blast Burn' 'Hydro Cannon' 'Meteor Mash' 'Astonish' 'Weather Ball' 'Aromatherapy' 'Fake Tears' 'Air Cutter' 'Overheat' 'Odor Sleuth' 'Rock Tomb' 'Silver Wind' 'Metal Sound' 'GrassWhistle' 'Tickle' 'Cosmic Power' 'Water Spout' 'Signal Beam' 'Shadow Punch' 'Extrasensory' 'Sky Uppercut' 'Sand Tomb' 'Sheer Cold' 'Muddy Water' 'Bullet Seed' 'Aerial Ace' 'Icicle Spear' 'Iron Defense' 'Block' 'Howl' 'Dragon Claw' 'Frenzy Plant' 'Bulk Up' 'Bounce' 'Mud Shot' 'Poison Tail' 'Covet' 'Volt Tackle' 'Magical Leaf' 'Water Sport' 'Calm Mind' 'Leaf Blade' 'Dragon Dance' 'Rock Blast' 'Shock Wave' 'Water Pulse' 'Doom Desire' 'Psycho Boost' ] module.exports.NATURES = [ 'Hardy (=)' 'Lonely (+Atk-Def)' 'Brave (+Atk-Spe)' 'Adamant (+Atk-SpA)' 'Naughty (+Atk-SpD)' 'Bold (+Def-Atk)' 'Docile (=)' 'Relaxed (+Def-Spe)' 'Impish (+Def-SpA)' 'Lax (+Def-SpD)' 'Timid (+Spe-Atk)' 'Hasty (+Spe-Def)' 'Serious (=)' 'Jolly (+Spe-SpA)' 'Naive (+Spe-SpD)' 'Modest (+SpA-Atk)' 'Mild (+SpA-Def)' 'Quiet (+SpA-Spe)' 'Bashful (=)' 'Rash (+SpA-SpD)' 'Calm (+SpD-Atk)' 'Gentle (+SpD-Def)' 'Sassy (+SpD-Spe)' 'Careful (-SpD-SpA)' 'Quirky (=)' ]
true
util = undefined PokemonString = require "#{__dirname}/String" Items = require "#{__dirname}/Items" {UInt8, UInt16LE, UInt32LE, Obj, ArrayOf, Slice, Filter, Wrap, Transform, Pass} = require "#{__dirname}/byte-spec" checksum = (buffer) -> sum = 0 (sum += buffer.readUInt16LE i) for i in [0...buffer.length] by 2 sum &= 0xFFFF sum G = growth: Obj [ {species: UInt16LE} {item: UInt16LE} {experience: UInt32LE} {ppBonus: UInt8} # TODO: BITS! {friendship: UInt8} {unknown0: UInt16LE} ] A = moves: Obj [ {moves: ArrayOf 4, UInt16LE} {pp: ArrayOf 4, UInt8} ] E = evCondition: Obj [ {hp: UInt8} {attack: UInt8} {defense: UInt8} {speed: UInt8} {spAttack: UInt8} {spDefense: UInt8} {coolness: UInt8} {beauty: UInt8} {cuteness: UInt8} {smartness: UInt8} {toughness: UInt8} {feel: UInt8} ] M = misc: Obj [ {pokerus: UInt8} {metLocation: UInt8} {origins: UInt16LE} # TODO: BITS! {ivs: UInt32LE} # TODO: BITS! {ribbons: UInt32LE} # TODO: WHAT? ] SPEC_POKEMON_DATA = [ Obj [G, A, E, M] Obj [G, A, M, E] Obj [G, E, A, M] Obj [G, E, M, A] Obj [G, M, A, E] Obj [G, M, E, A] Obj [A, G, E, M] Obj [A, G, M, E] Obj [A, E, G, M] Obj [A, E, M, G] Obj [A, M, G, E] Obj [A, M, E, G] Obj [E, G, A, M] Obj [E, G, M, A] Obj [E, A, G, M] Obj [E, A, M, G] Obj [E, M, G, A] Obj [E, M, A, G] Obj [M, G, A, E] Obj [M, G, E, A] Obj [M, A, G, E] Obj [M, A, E, G] Obj [M, E, G, A] Obj [M, E, A, G] ] POKEMON_DATA_LENGTH = 48 SpecPokemon = -> wrap = new Wrap() [ {personality: wrap.capture UInt32LE} {otId: wrap.capture UInt32LE} {nickname: PokemonString 10} {language: Transform UInt16LE, (l) -> l - 0x201} {otName: PokemonString 7} {mark: UInt8} # TODO: BITS! {checksum: UInt16LE} {unknown0: UInt16LE} {data: wrap.emit (c) -> [otId, personality] = [c.pop(), c.pop()] order = personality % 24 key = otId ^ personality Pass SPEC_POKEMON_DATA[order], Transform (Slice POKEMON_DATA_LENGTH), (v) -> data = new Buffer POKEMON_DATA_LENGTH for i in [0...POKEMON_DATA_LENGTH] by 4 data.writeInt32LE (key ^ v.readUInt32LE i), i data } ] SPEC_EXTENDED = [ {status: UInt32LE} # TODO: BITS! {level: UInt8} {pokerus: UInt8} {hp: UInt16LE} {maxHp: UInt16LE} {attack: UInt16LE} {defense: UInt16LE} {speed: UInt16LE} {spAttack: UInt16LE} {spDefense: UInt16LE} ] module.exports = (extended) -> Obj if extended SpecPokemon().concat SPEC_EXTENDED else SpecPokemon() module.exports.parseOLD = (buffer, extended) -> readChecksum = buffer.readUInt16LE 0x1C trainerId = buffer.readUInt32LE 0x04 personality = buffer.readUInt32LE 0x00 dataBuffer = new Buffer POKEMON_DATA_SIZE for i in [0...POKEMON_DATA_SIZE] by 4 dataBuffer.writeInt32LE (trainerId ^ personality ^ buffer.readUInt32LE i + 0x20), i expectedChecksum = checksum.pokemon dataBuffer return if readChecksum == 0 and trainerId == 0 and personality == 0 and expectedChecksum == 0 if readChecksum != expectedChecksum throw "Bad checksum #{readChecksum.toString 16} (expected #{expectedChecksum.toString 16})" marks = buffer.readUInt8 0x1B language = (buffer.readUInt16LE 0x12) - 0x0201 data = parseData dataBuffer, personality result = name: util.decodeString buffer, 0x08, 10 trainer: id: buffer.readUInt16LE 0x04 fullId: trainerId name: util.decodeString buffer, 0x14, 8 language: language personality: raw: personality data: data marks: circle: !!(marks & 1) square: !!(marks & 2) triangle: !!(marks & 4) heart: !!(marks & 8) # Extended stats (Pokémon is not in box) if extended result.level = buffer.readUInt8 0x54 status = buffer.readUInt32LE 0x50 result.status = sleep: (status & 0b111) or false poison: !!(status & 8) burn: !!(status & 16) freeze: !!(status & 32) paralysis: !!(status & 64) badPoison: !!(status & 128) result.remainingPokerus = buffer.readUInt8 0x55 result.stats = hp: buffer.readUInt16LE 0x56 hpMax: buffer.readUInt16LE 0x58 attack: buffer.readUInt16LE 0x5A defense: buffer.readUInt16LE 0x5C speed: buffer.readUInt16LE 0x5E spAttack: buffer.readUInt16LE 0x60 spDefense: buffer.readUInt16LE 0x62 result parseData = (buffer, personality, pokemonRSE) -> dataOrder = POKEMON_DATA_ORDER[personality % 24] species = buffer.readUInt16LE 0 + SUBSTRUCTURE_LENGTH * dataOrder[G] item = buffer.readUInt16LE 2 + SUBSTRUCTURE_LENGTH * dataOrder[G] bonuses = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[G] pokerus = buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[M] result = growth: species: id: species name: SPECIES[species] item: id: item name: items.NAMES[item] experience: buffer.readUInt32LE 4 + SUBSTRUCTURE_LENGTH * dataOrder[G] friendship: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[G] moves: for i in [0..3] id = buffer.readUInt16LE 0 + i * 2 + SUBSTRUCTURE_LENGTH * dataOrder[A] id: id name: MOVES[id] pp: buffer.readUInt8 8 + i + SUBSTRUCTURE_LENGTH * dataOrder[A] bonus: (bonuses & (0b11 << (i * 2))) >>> (i * 2) ev: hp: buffer.readUInt8 0 + SUBSTRUCTURE_LENGTH * dataOrder[E] attack: buffer.readUInt8 1 + SUBSTRUCTURE_LENGTH * dataOrder[E] defense: buffer.readUInt8 2 + SUBSTRUCTURE_LENGTH * dataOrder[E] speed: buffer.readUInt8 3 + SUBSTRUCTURE_LENGTH * dataOrder[E] spAttack: buffer.readUInt8 4 + SUBSTRUCTURE_LENGTH * dataOrder[E] spDefense: buffer.readUInt8 5 + SUBSTRUCTURE_LENGTH * dataOrder[E] condition: coolness: buffer.readUInt8 6 + SUBSTRUCTURE_LENGTH * dataOrder[E] beauty: buffer.readUInt8 7 + SUBSTRUCTURE_LENGTH * dataOrder[E] cuteness: buffer.readUInt8 8 + SUBSTRUCTURE_LENGTH * dataOrder[E] smartness: buffer.readUInt8 9 + SUBSTRUCTURE_LENGTH * dataOrder[E] toughness: buffer.readUInt8 10 + SUBSTRUCTURE_LENGTH * dataOrder[E] feel: buffer.readUInt8 11 + SUBSTRUCTURE_LENGTH * dataOrder[E] pokerus: remaining: pokerus & 0xF immune: (pokerus >>> 4) > 0 met: 0 origin: 0 iv: 0 ribbons: 0 module.exports.LANGUAGES = ['JP', 'EN', 'FR', 'IT', 'DE', undefined, 'ES'] module.exports.SPECIES = [ undefined 'Bulbasaur' 'Ivysaur' 'Venusaur' 'Charmander' 'Charmeleon' 'Charizard' 'Squirtle' 'Wartortle' 'Blastoise' 'Caterpie' 'Metapod' 'Butterfree' 'Weedle' 'Kakuna' 'Beedrill' 'Pidgey' 'Pidgeotto' 'Pidgeot' 'Rattata' 'Raticate' 'Spearow' 'Fearow' 'Ekans' 'Arbok' 'Pikachu' 'Raichu' 'Sandshrew' 'Sandslash' 'Nidoran?' 'Nidorina' 'Nidoqueen' 'Nidoran?' 'Nidorino' 'Nidoking' 'PI:NAME:<NAME>END_PI' 'Clefable' 'Vulpix' 'Ninetales' 'Jigglypuff' 'Wigglytuff' 'Zubat' 'Golbat' 'Oddish' 'Gloom' 'Vileplume' 'Paras' 'Parasect' 'Venonat' 'Venomoth' 'DigPI:NAME:<NAME>END_PI' 'DPI:NAME:<NAME>END_PIo' 'Meowth' 'Persian' 'Psyduck' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PrimePI:NAME:<NAME>END_PI' 'Growlithe' 'Arcanine' 'Poliwag' 'Poliwhirl' 'Poliwrath' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PIadabra' 'PI:NAME:<NAME>END_PIakazPI: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' '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' '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' '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_PIute' 'PI:NAME:<NAME>END_PIutor' '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' 'WPI:NAME:<NAME>END_PI' 'RPI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Kangaskhan' 'PI:NAME:<NAME>END_PIa' 'PI:NAME:<NAME>END_PIadra' 'PI:NAME:<NAME>END_PI' 'Seaking' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Mr. 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' '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' 'Aerodactyl' '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' 'PI:NAME:<NAME>END_PI' 'Meganium' 'CyndaPI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PIodPI: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' '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' '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_PIudPI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Hoppip' 'PI:NAME:<NAME>END_PI' 'JumpPI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PIipPI: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' 'Umbreon' 'PI:NAME:<NAME>END_PIurPI:NAME:<NAME>END_PI' 'Slowking' 'PI:NAME:<NAME>END_PIdPI:NAME:<NAME>END_PI' 'Unown' 'Wobbuffet' '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' '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' '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' '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' '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' 'Ho-Oh' 'PI:NAME:<NAME>END_PI' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '? (glitch Pokémon)' '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' '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' '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' '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' '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' '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' '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' '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' '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' 'SlPI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'TroPI: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' 'Seviper' 'Zangoose' 'Relicanth' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Volbeat' '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' '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' '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' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' 'Unown' ] module.exports.MOVES = [ undefined 'Pound' 'Karate Chop' 'DoubleSlap' 'Comet Punch' 'Mega Punch' 'Pay Day' 'Fire Punch' 'Ice Punch' 'ThunderPunch' 'Scratch' 'ViceGrip' 'Guillotine' 'Razor Wind' 'Swords Dance' 'Cut' 'Gust' 'Wing Attack' 'Whirlwind' 'Fly' 'Bind' 'Slam' 'Vine Whip' 'Stomp' 'Double Kick' 'Mega Kick' 'Jump Kick' 'Rolling Kick' 'Sand-Attack' 'Headbutt' 'Horn Attack' 'Fury Attack' 'Horn Drill' 'Tackle' 'Body Slam' 'Wrap' 'Take Down' 'Thrash' 'Double-Edge' 'Tail Whip' 'Poison Sting' 'Twineedle' 'Pin Missile' 'Leer' 'Bite' 'Growl' 'Roar' 'Sing' 'Supersonic' 'SonicBoom' 'Disable' 'Acid' 'Ember' 'Flamethrower' 'Mist' 'Water Gun' 'Hydro Pump' 'Surf' 'Ice Beam' 'Blizzard' 'Psybeam' 'BubbleBeam' 'Aurora Beam' 'Hyper Beam' 'Peck' 'Drill Peck' 'Submission' 'Low Kick' 'Counter' 'Seismic Toss' 'Strength' 'Absorb' 'Mega Drain' 'Leech Seed' 'Growth' 'Razor Leaf' 'SolarBeam' 'PoisonPowder' 'Stun Spore' 'Sleep Powder' 'Petal Dance' 'String Shot' 'Dragon Rage' 'Fire Spin' 'ThunderShock' 'Thunderbolt' 'Thunder Wave' 'Thunder' 'Rock Throw' 'Earthquake' 'Fissure' 'Dig' 'Toxic' 'Confusion' 'Psychic' 'Hypnosis' 'Meditate' 'Agility' 'Quick Attack' 'Rage' 'Teleport' 'Night Shade' 'Mimic' 'Screech' 'Double Team' 'Recover' 'Harden' 'Minimize' 'SmokeScreen' 'Confuse Ray' 'Withdraw' 'Defense Curl' 'Barrier' 'Light Screen' 'Haze' 'Reflect' 'Focus Energy' 'Bide' 'Metronome' 'Mirror Move' 'Selfdestruct' 'Egg Bomb' 'Lick' 'Smog' 'Sludge' 'Bone Club' 'Fire Blast' 'Waterfall' 'Clamp' 'Swift' 'Skull Bash' 'Spike Cannon' 'Constrict' 'Amnesia' 'Kinesis' 'Softboiled' 'Hi Jump Kick' 'Glare' 'Dream Eater' 'Poison Gas' 'Barrage' 'Leech Life' 'Lovely Kiss' 'Sky Attack' 'Transform' 'Bubble' 'Dizzy Punch' 'Spore' 'Flash' 'Psywave' 'Splash' 'Acid Armor' 'Crabhammer' 'Explosion' 'Fury Swipes' 'Bonemerang' 'Rest' 'Rock Slide' 'Hyper Fang' 'Sharpen' 'Conversion' 'Tri Attack' 'Super Fang' 'Slash' 'Substitute' 'Struggle' 'Sketch' 'Triple Kick' 'Thief' 'Spider Web' 'Mind Reader' 'Nightmare' 'Flame Wheel' 'Snore' 'Curse' 'Flail' 'Conversion 2' 'Aeroblast' 'Cotton Spore' 'Reversal' 'Spite' 'Powder Snow' 'Protect' 'Mach Punch' 'Scary Face' 'Faint Attack' 'Sweet Kiss' 'Belly Drum' 'Sludge Bomb' 'Mud-Slap' 'Octazooka' 'Spikes' 'Zap Cannon' 'Foresight' 'Destiny Bond' 'Perish Song' 'Icy Wind' 'Detect' 'Bone Rush' 'Lock-On' 'Outrage' 'Sandstorm' 'Giga Drain' 'Endure' 'Charm' 'Rollout' 'False Swipe' 'Swagger' 'Milk Drink' 'Spark' 'Fury Cutter' 'Steel Wing' 'Mean Look' 'Attract' 'Sleep Talk' 'Heal Bell' 'Return' 'Present' 'Frustration' 'Safeguard' 'Pain Split' 'Sacred Fire' 'Magnitude' 'DynamicPunch' 'Megahorn' 'DragonBreath' 'Baton Pass' 'Encore' 'Pursuit' 'Rapid Spin' 'Sweet Scent' 'Iron Tail' 'Metal Claw' 'Vital Throw' 'Morning Sun' 'Synthesis' 'Moonlight' 'Hidden Power' 'Cross Chop' 'Twister' 'Rain Dance' 'Sunny Day' 'Crunch' 'Mirror Coat' 'Psych Up' 'ExtremeSpeed' 'AncientPower' 'Shadow Ball' 'Future Sight' 'Rock Smash' 'Whirlpool' 'Beat Up' 'Fake Out' 'Uproar' 'Stockpile' 'Spit Up' 'Swallow' 'Heat Wave' 'Hail' 'Torment' 'Flatter' 'Will-O-Wisp' 'Memento' 'Facade' 'Focus Punch' 'SmellingSalt' 'Follow Me' 'Nature Power' 'Charge' 'Taunt' 'Helping Hand' 'Trick' 'Role Play' 'Wish' 'Assist' 'Ingrain' 'Superpower' 'Magic Coat' 'Recycle' 'Revenge' 'Brick Break' 'Yawn' 'Knock Off' 'Endeavor' 'Eruption' 'Skill Swap' 'Imprison' 'Refresh' 'Grudge' 'Snatch' 'Secret Power' 'Dive' 'Arm Thrust' 'Camouflage' 'Tail Glow' 'Luster Purge' 'Mist Ball' 'FeatherDance' 'Teeter Dance' 'Blaze Kick' 'Mud Sport' 'Ice Ball' 'Needle Arm' 'Slack Off' 'Hyper Voice' 'Poison Fang' 'Crush Claw' 'Blast Burn' 'Hydro Cannon' 'Meteor Mash' 'Astonish' 'Weather Ball' 'Aromatherapy' 'Fake Tears' 'Air Cutter' 'Overheat' 'Odor Sleuth' 'Rock Tomb' 'Silver Wind' 'Metal Sound' 'GrassWhistle' 'Tickle' 'Cosmic Power' 'Water Spout' 'Signal Beam' 'Shadow Punch' 'Extrasensory' 'Sky Uppercut' 'Sand Tomb' 'Sheer Cold' 'Muddy Water' 'Bullet Seed' 'Aerial Ace' 'Icicle Spear' 'Iron Defense' 'Block' 'Howl' 'Dragon Claw' 'Frenzy Plant' 'Bulk Up' 'Bounce' 'Mud Shot' 'Poison Tail' 'Covet' 'Volt Tackle' 'Magical Leaf' 'Water Sport' 'Calm Mind' 'Leaf Blade' 'Dragon Dance' 'Rock Blast' 'Shock Wave' 'Water Pulse' 'Doom Desire' 'Psycho Boost' ] module.exports.NATURES = [ 'Hardy (=)' 'Lonely (+Atk-Def)' 'Brave (+Atk-Spe)' 'Adamant (+Atk-SpA)' 'Naughty (+Atk-SpD)' 'Bold (+Def-Atk)' 'Docile (=)' 'Relaxed (+Def-Spe)' 'Impish (+Def-SpA)' 'Lax (+Def-SpD)' 'Timid (+Spe-Atk)' 'Hasty (+Spe-Def)' 'Serious (=)' 'Jolly (+Spe-SpA)' 'Naive (+Spe-SpD)' 'Modest (+SpA-Atk)' 'Mild (+SpA-Def)' 'Quiet (+SpA-Spe)' 'Bashful (=)' 'Rash (+SpA-SpD)' 'Calm (+SpD-Atk)' 'Gentle (+SpD-Def)' 'Sassy (+SpD-Spe)' 'Careful (-SpD-SpA)' 'Quirky (=)' ]
[ { "context": " fakeText = helpers.getFakeText()\n\n email = \"kodingtestuser+#{username}@koding.com\"\n\n users.push { name, ", "end": 687, "score": 0.77383953332901, "start": 673, "tag": "EMAIL", "value": "kodingtestuser" }, { "context": "rs.getFakeText()\n\n email = \"kodingtestuser+#{username}@koding.com\"\n\n users.push { name, email, username, passw", "end": 710, "score": 0.9826880693435669, "start": 690, "tag": "EMAIL", "value": "username}@koding.com" }, { "context": "')[2]\n index = index + 1\n password = user.password\n username = user.username\n { 'email", "end": 2887, "score": 0.9992191791534424, "start": 2874, "tag": "PASSWORD", "value": "user.password" }, { "context": " password = user.password\n username = user.username\n { 'email': user.email, 'role': 'member', ", "end": 2920, "score": 0.9976801872253418, "start": 2907, "tag": "USERNAME", "value": "user.username" } ]
client/test/lib/utils/utils.coffee
lionheart1022/koding
0
fs = require 'fs' faker = require 'faker' tempDir = require 'os-tmpdir' formatter = require 'json-format' _ = require 'lodash' async = require 'async' module.exports = generateUsers: -> users = [] for [1..10] name = faker.Name.findName() username = faker.Helpers.slugify(faker.Internet.userName()).toLowerCase().replace(/\./g, '').replace(/_/g, '') username = username.substring(0, 7) + Date.now() password = @getPassword() teamSlug = name.toLowerCase().replace(/\s/g, '-').replace(/'/g, '').replace('.', '') helpers = require '../helpers/helpers' fakeText = helpers.getFakeText() email = "kodingtestuser+#{username}@koding.com" users.push { name, email, username, password, teamSlug, fakeText } fs.writeFileSync 'users.json', formatter users, 'utf-8' return users getPassword: -> password = faker.Helpers.slugify(faker.Internet.userName()) while password.length < 12 password = faker.Helpers.slugify(faker.Internet.userName()) return password getUser: (createNewUserData, index = 0) -> if createNewUserData users = @generateUsers() return if index is -1 then users else users[index] try usersFile = fs.readFileSync('users.json') users = JSON.parse(usersFile) return if index is -1 then users else users[index] catch users = @generateUsers() return if index is -1 then users else users[index] getHookFilePath: (type) -> hookDir = process.env.TEST_SUITE_HOOK_DIR { TEST_GROUP, TEST_SUITE } = process.env return "#{hookDir}/#{TEST_GROUP}_#{TEST_SUITE}_#{type}" registerSuiteHook: (type) -> fs.writeFileSync @getHookFilePath(type), '' suiteHookHasRun: (type) -> try fs.statSync @getHookFilePath type return yes catch return no getCollabLinkFilePath: -> return "#{tempDir()}/collabLink.txt" getMemberInvitationPath: -> return "#{tempDir()}/invitation.txt" beforeCollaborationSuite: -> @getUser() if process.env.__NIGHTWATCH_ENV_KEY is 'host_1' @registerSuiteHook 'before' unless @suiteHookHasRun 'before' afterEachCollaborationTest: (browser, done) -> queue = [ (next) -> browser.deleteCollabLink (result) -> next null, result (next) -> browser.deleteMemberInvitation (res) -> next null, res ] async.series queue, (err, result) -> done() unless err getInvitationData: -> targetUsers = [0..6].map (index) => @getUser no, index + 1 index = 0 invitations = targetUsers.map (user) -> if user firstName = if (index is 0 or index is 2) then '' else user.fakeText.split(' ')[0] lastName = if (index is 1 or index is 2) then '' else user.fakeText.split(' ')[2] index = index + 1 password = user.password username = user.username { 'email': user.email, 'role': 'member', firstName, lastName, password, username } host = @getUser() invitations.push host invitations = _.sortBy(_.sortBy(_.sortBy(invitations, 'firstName'), 'lastName'), 'email') index = invitations.indexOf host return { invitations, index }
82925
fs = require 'fs' faker = require 'faker' tempDir = require 'os-tmpdir' formatter = require 'json-format' _ = require 'lodash' async = require 'async' module.exports = generateUsers: -> users = [] for [1..10] name = faker.Name.findName() username = faker.Helpers.slugify(faker.Internet.userName()).toLowerCase().replace(/\./g, '').replace(/_/g, '') username = username.substring(0, 7) + Date.now() password = @getPassword() teamSlug = name.toLowerCase().replace(/\s/g, '-').replace(/'/g, '').replace('.', '') helpers = require '../helpers/helpers' fakeText = helpers.getFakeText() email = "<EMAIL>+#{<EMAIL>" users.push { name, email, username, password, teamSlug, fakeText } fs.writeFileSync 'users.json', formatter users, 'utf-8' return users getPassword: -> password = faker.Helpers.slugify(faker.Internet.userName()) while password.length < 12 password = faker.Helpers.slugify(faker.Internet.userName()) return password getUser: (createNewUserData, index = 0) -> if createNewUserData users = @generateUsers() return if index is -1 then users else users[index] try usersFile = fs.readFileSync('users.json') users = JSON.parse(usersFile) return if index is -1 then users else users[index] catch users = @generateUsers() return if index is -1 then users else users[index] getHookFilePath: (type) -> hookDir = process.env.TEST_SUITE_HOOK_DIR { TEST_GROUP, TEST_SUITE } = process.env return "#{hookDir}/#{TEST_GROUP}_#{TEST_SUITE}_#{type}" registerSuiteHook: (type) -> fs.writeFileSync @getHookFilePath(type), '' suiteHookHasRun: (type) -> try fs.statSync @getHookFilePath type return yes catch return no getCollabLinkFilePath: -> return "#{tempDir()}/collabLink.txt" getMemberInvitationPath: -> return "#{tempDir()}/invitation.txt" beforeCollaborationSuite: -> @getUser() if process.env.__NIGHTWATCH_ENV_KEY is 'host_1' @registerSuiteHook 'before' unless @suiteHookHasRun 'before' afterEachCollaborationTest: (browser, done) -> queue = [ (next) -> browser.deleteCollabLink (result) -> next null, result (next) -> browser.deleteMemberInvitation (res) -> next null, res ] async.series queue, (err, result) -> done() unless err getInvitationData: -> targetUsers = [0..6].map (index) => @getUser no, index + 1 index = 0 invitations = targetUsers.map (user) -> if user firstName = if (index is 0 or index is 2) then '' else user.fakeText.split(' ')[0] lastName = if (index is 1 or index is 2) then '' else user.fakeText.split(' ')[2] index = index + 1 password = <PASSWORD> username = user.username { 'email': user.email, 'role': 'member', firstName, lastName, password, username } host = @getUser() invitations.push host invitations = _.sortBy(_.sortBy(_.sortBy(invitations, 'firstName'), 'lastName'), 'email') index = invitations.indexOf host return { invitations, index }
true
fs = require 'fs' faker = require 'faker' tempDir = require 'os-tmpdir' formatter = require 'json-format' _ = require 'lodash' async = require 'async' module.exports = generateUsers: -> users = [] for [1..10] name = faker.Name.findName() username = faker.Helpers.slugify(faker.Internet.userName()).toLowerCase().replace(/\./g, '').replace(/_/g, '') username = username.substring(0, 7) + Date.now() password = @getPassword() teamSlug = name.toLowerCase().replace(/\s/g, '-').replace(/'/g, '').replace('.', '') helpers = require '../helpers/helpers' fakeText = helpers.getFakeText() email = "PI:EMAIL:<EMAIL>END_PI+#{PI:EMAIL:<EMAIL>END_PI" users.push { name, email, username, password, teamSlug, fakeText } fs.writeFileSync 'users.json', formatter users, 'utf-8' return users getPassword: -> password = faker.Helpers.slugify(faker.Internet.userName()) while password.length < 12 password = faker.Helpers.slugify(faker.Internet.userName()) return password getUser: (createNewUserData, index = 0) -> if createNewUserData users = @generateUsers() return if index is -1 then users else users[index] try usersFile = fs.readFileSync('users.json') users = JSON.parse(usersFile) return if index is -1 then users else users[index] catch users = @generateUsers() return if index is -1 then users else users[index] getHookFilePath: (type) -> hookDir = process.env.TEST_SUITE_HOOK_DIR { TEST_GROUP, TEST_SUITE } = process.env return "#{hookDir}/#{TEST_GROUP}_#{TEST_SUITE}_#{type}" registerSuiteHook: (type) -> fs.writeFileSync @getHookFilePath(type), '' suiteHookHasRun: (type) -> try fs.statSync @getHookFilePath type return yes catch return no getCollabLinkFilePath: -> return "#{tempDir()}/collabLink.txt" getMemberInvitationPath: -> return "#{tempDir()}/invitation.txt" beforeCollaborationSuite: -> @getUser() if process.env.__NIGHTWATCH_ENV_KEY is 'host_1' @registerSuiteHook 'before' unless @suiteHookHasRun 'before' afterEachCollaborationTest: (browser, done) -> queue = [ (next) -> browser.deleteCollabLink (result) -> next null, result (next) -> browser.deleteMemberInvitation (res) -> next null, res ] async.series queue, (err, result) -> done() unless err getInvitationData: -> targetUsers = [0..6].map (index) => @getUser no, index + 1 index = 0 invitations = targetUsers.map (user) -> if user firstName = if (index is 0 or index is 2) then '' else user.fakeText.split(' ')[0] lastName = if (index is 1 or index is 2) then '' else user.fakeText.split(' ')[2] index = index + 1 password = PI:PASSWORD:<PASSWORD>END_PI username = user.username { 'email': user.email, 'role': 'member', firstName, lastName, password, username } host = @getUser() invitations.push host invitations = _.sortBy(_.sortBy(_.sortBy(invitations, 'firstName'), 'lastName'), 'email') index = invitations.indexOf host return { invitations, index }
[ { "context": "# Wi-Fi Widget\n# Vidur Murali, 2017\n# \n\n# ------------------------------ CONFIG", "end": 29, "score": 0.9998757243156433, "start": 17, "tag": "NAME", "value": "Vidur Murali" } ]
wifi.widget/index.coffee
vyder/uebersicht-widgets
0
# Wi-Fi Widget # Vidur Murali, 2017 # # ------------------------------ CONFIG ------------------------------ # milliseconds refreshFrequency: 3 * 1000 # icon icon_img: "wifi.widget/glyphicons-74-wifi.svg" # ---------------------------- END CONFIG ---------------------------- command: "wifi.widget/wifi_status" render: (output) -> """ <span id="wifi_info"></span> <div id="wifi_icon"></div> """ # Runs once after the render afterRender: -> # Embed the SVG icon @get_icon (err, content) -> icon = $('#wifi_icon').hide() return if err parser = new DOMParser() format = "image/svg+xml" # Create svg element from content string svg = parser.parseFromString(content, format).documentElement # Clear existing content, and append the svg icon.show().html('').append svg get_icon: (callback) -> @run("cat #{@icon_img}", callback) update: (output) -> is_connected = (output.match(/disconnected/i) == null) # Add/remove 'disconnected' if network is not connected $('#wifi_icon').toggleClass('disconnected', !is_connected) # Slice to remove a random space that # shows up at the end of the output # message = '' message = output.slice(0, -1) if is_connected $('#wifi_info').text message style: """ bottom 206px right 10px font-family 'San Francisco Display' font-weight light font-size 14pt font-smooth always color #B7BCBE #wifi_info margin-right -7px #wifi_icon display inline-block width 30px margin-right -1px path fill #B7BCBE & > svg > g transform translate(3px,12px) &.disconnected margin-right -8px path fill #5A747F """
114958
# Wi-Fi Widget # <NAME>, 2017 # # ------------------------------ CONFIG ------------------------------ # milliseconds refreshFrequency: 3 * 1000 # icon icon_img: "wifi.widget/glyphicons-74-wifi.svg" # ---------------------------- END CONFIG ---------------------------- command: "wifi.widget/wifi_status" render: (output) -> """ <span id="wifi_info"></span> <div id="wifi_icon"></div> """ # Runs once after the render afterRender: -> # Embed the SVG icon @get_icon (err, content) -> icon = $('#wifi_icon').hide() return if err parser = new DOMParser() format = "image/svg+xml" # Create svg element from content string svg = parser.parseFromString(content, format).documentElement # Clear existing content, and append the svg icon.show().html('').append svg get_icon: (callback) -> @run("cat #{@icon_img}", callback) update: (output) -> is_connected = (output.match(/disconnected/i) == null) # Add/remove 'disconnected' if network is not connected $('#wifi_icon').toggleClass('disconnected', !is_connected) # Slice to remove a random space that # shows up at the end of the output # message = '' message = output.slice(0, -1) if is_connected $('#wifi_info').text message style: """ bottom 206px right 10px font-family 'San Francisco Display' font-weight light font-size 14pt font-smooth always color #B7BCBE #wifi_info margin-right -7px #wifi_icon display inline-block width 30px margin-right -1px path fill #B7BCBE & > svg > g transform translate(3px,12px) &.disconnected margin-right -8px path fill #5A747F """
true
# Wi-Fi Widget # PI:NAME:<NAME>END_PI, 2017 # # ------------------------------ CONFIG ------------------------------ # milliseconds refreshFrequency: 3 * 1000 # icon icon_img: "wifi.widget/glyphicons-74-wifi.svg" # ---------------------------- END CONFIG ---------------------------- command: "wifi.widget/wifi_status" render: (output) -> """ <span id="wifi_info"></span> <div id="wifi_icon"></div> """ # Runs once after the render afterRender: -> # Embed the SVG icon @get_icon (err, content) -> icon = $('#wifi_icon').hide() return if err parser = new DOMParser() format = "image/svg+xml" # Create svg element from content string svg = parser.parseFromString(content, format).documentElement # Clear existing content, and append the svg icon.show().html('').append svg get_icon: (callback) -> @run("cat #{@icon_img}", callback) update: (output) -> is_connected = (output.match(/disconnected/i) == null) # Add/remove 'disconnected' if network is not connected $('#wifi_icon').toggleClass('disconnected', !is_connected) # Slice to remove a random space that # shows up at the end of the output # message = '' message = output.slice(0, -1) if is_connected $('#wifi_info').text message style: """ bottom 206px right 10px font-family 'San Francisco Display' font-weight light font-size 14pt font-smooth always color #B7BCBE #wifi_info margin-right -7px #wifi_icon display inline-block width 30px margin-right -1px path fill #B7BCBE & > svg > g transform translate(3px,12px) &.disconnected margin-right -8px path fill #5A747F """
[ { "context": "Pending = Number.POSITIVE_INFINITY\n currentName = initialName\n for migration, i in @Meta.migrations\n if", "end": 11370, "score": 0.7900030016899109, "start": 11363, "tag": "NAME", "value": "initial" }, { "context": "hema = '1.0.0'\n currentSerial = 0\n currentName = initialName\n previousMigration = null\n for migration, i in ", "end": 13322, "score": 0.9363301992416382, "start": 13311, "tag": "NAME", "value": "initialName" } ]
server.coffee
peerlibrary/meteor-peerdb-migrations
4
import semver from 'semver' import util from 'util' globals = @ allMigrationDescriptors = [] try # Migration of migrations collection. new DirectCollection('migrations').renameCollection 'peerdb.migrations' catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" # Fields: # serial # migrationName # oldCollectionName # newCollectionName # oldVersion # newVersion # timestamp # migrated # all # # We use a lower case collection name to signal it is a system collection. globals.Document.Migrations = new Meteor.Collection 'peerdb.migrations' class globals.Document._Migration updateAll: (document, collection, currentSchema, intoSchema) -> @_updateAll = true forward: (document, collection, currentSchema, newSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: newSchema}, {multi: true} backward: (document, collection, currentSchema, oldSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: oldSchema}, {multi: true} class globals.Document.PatchMigration extends globals.Document._Migration class globals.Document.MinorMigration extends globals.Document._Migration class globals.Document.MajorMigration extends globals.Document._Migration class globals.Document.AddReferenceFieldsMigration extends globals.Document.MinorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveReferenceFieldsMigration extends globals.Document.MajorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddGeneratedFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.ModifyGeneratedFieldsMigration extends globals.Document.PatchMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveGeneratedFieldsMigration extends globals.Document.MajorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddOptionalFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields super document, collection, currentSchema, newSchema backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.AddRequiredFieldsMigration extends globals.Document.MinorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: newSchema for field, value of @fields if _.isFunction value update.$set[field] = value() else update.$set[field] = value count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RemoveFieldsMigration extends globals.Document.MajorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: oldSchema for field, value of @fields if _.isFunction value v = value() else v = value update.$set[field] = v unless _.isUndefined v count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RenameFieldsMigration extends globals.Document.MajorMigration # Fields is object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $set: _schema: newSchema $rename: {} for from, to of @fields update.$rename[from] = to count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $set: _schema: oldSchema $rename: {} for from, to of @fields # Reversed. update.$rename[to] = from count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document._RenameCollectionMigration extends globals.Document.MajorMigration constructor: (@oldName, @newName) -> super() @name = "Renaming collection from '#{@oldName}' to '#{@newName}'" _rename: (collection, to) -> try collection.renameCollection to catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" forward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @oldName @_rename collection, @newName collection.name = @newName # We renamed the collection, so let's update all documents to new schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts backward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @newName @_rename collection, @oldName collection.name = @oldName # We renamed the collection, so let's update all documents to old schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts globals.Document.addMigration = (migration) -> throw new Error "Migration is missing a name" unless migration.name throw new Error "Migration is not a migration instance" unless migration instanceof @_Migration throw new Error "Migration with the name '#{migration.name}' already exists" if migration.name in _.pluck @Meta.migrations, 'name' @Meta.migrations.push migration allMigrationDescriptors.push document: @ migration: migration globals.Document.renameCollectionMigration = (oldName, newName) -> @addMigration new @_RenameCollectionMigration oldName, newName globals.Document.migrateForward = (untilMigration) -> schemas = ['1.0.0'] currentSchema = '1.0.0' currentSerial = 0 initialName = @Meta.collection._name for migration in @Meta.migrations by -1 when migration instanceof @_RenameCollectionMigration throw new Error "Inconsistent document renaming, renaming from '#{migration.oldName}' to '#{migration.newName}', but current name is '#{initialName}' (new name and current name should match)" if migration.newName isnt initialName initialName = migration.oldName migrationsPending = Number.POSITIVE_INFINITY currentName = initialName for migration, i in @Meta.migrations if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName migrations = globals.Document.Migrations.find( serial: $gt: currentSerial oldCollectionName: $in: [currentName, newName] , sort: [ ['serial', 'asc'] ] ).fetch() if migrations[0] throw new Error "Unexpected migration recorded: #{util.inspect migrations[0], depth: 10}" if migrationsPending < Number.POSITIVE_INFINITY if migrations[0].migrationName is migration.name and migrations[0].oldCollectionName is currentName and migrations[0].newCollectionName is newName and migrations[0].oldVersion is currentSchema and migrations[0].newVersion is newSchema currentSerial = migrations[0].serial else throw new Error "Inconsistent migration recorded, expected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}', got: #{util.inspect migrations[0], depth: 10}" else if migrationsPending is Number.POSITIVE_INFINITY migrationsPending = i currentSchema = newSchema schemas.push currentSchema currentName = newName unknownSchema = _.pluck @Meta.collection.find( _schema: $nin: schemas $exists: true , fields: _id: 1 ).fetch(), '_id' throw new Error "Documents with unknown schema version: #{unknownSchema}" if unknownSchema.length updateAll = false currentSchema = '1.0.0' currentSerial = 0 currentName = initialName previousMigration = null for migration, i in @Meta.migrations if previousMigration is untilMigration break previousMigration = migration if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if i < migrationsPending and migration instanceof @_RenameCollectionMigration # We skip all already done rename migrations (but we run other old migrations again, just with the last known collection name). currentSchema = newSchema currentName = migration.newName continue if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName if globals.Document.migrationsDisabled # Migrations are disabled but we are still running # the code just to compute the latest schema version. currentSchema = newSchema currentName = newName continue migration._updateAll = false counts = migration.forward @, new DirectCollection(currentName), currentSchema, newSchema throw new Error "Invalid return value from migration: #{util.inspect counts}" unless 'migrated' of counts and 'all' of counts updateAll = true if counts.migrated and migration._updateAll if i < migrationsPending count = globals.Document.Migrations.update migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema , $inc: migrated: counts.migrated all: counts.all , # To catch any errors. multi: true throw new Error "Inconsistent migration record state, missing migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 1 else count = globals.Document.Migrations.find( migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema ).count() throw new Error "Inconsistent migration record state, unexpected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 0 globals.Document.Migrations.insert # Things should not be running in parallel here anyway, so we can get next serial in this way. serial: globals.Document.Migrations.findOne({}, {sort: [['serial', 'desc']]}).serial + 1 migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema migrated: counts.migrated all: counts.all timestamp: new Date() if migration instanceof @_RenameCollectionMigration Log.info "Renamed collection '#{currentName}' to '#{newName}'" Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all else Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) in '#{currentName}' collection (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all currentSchema = newSchema currentName = newName # We do not check for not migrated documents if migrations are disabled. unless globals.Document.migrationsDisabled # For all those documents which lack schema information we assume they have the last schema. @Meta.collection.update _schema: $exists: false , $set: _schema: currentSchema , multi: true @Meta.schema = currentSchema # Return if updateAll should be called. updateAll globals.Document.migrateBackward = (untilMigration) -> # TODO: Implement. throw new Error "Not implemented yet" globals.Document._setupMigrationsObserve = -> @Meta.collection.find( _schema: $exists: false , fields: _id: 1 _schema: 1 ).observeChanges added: globals.Document._observerCallback true, (id, fields) => # TODO: Check if schema is known and complain if not. # TODO: We could automatically migrate old documents if we know of newer schema. return if fields._schema @Meta.collection.update id, $set: _schema: @Meta.schema getReplacedDocument = (document) -> return document unless document.Meta._replaced for current in globals.Document.list parentMeta = current.Meta while parentMeta if parentMeta is document.Meta return current parentMeta = parentMeta.parent throw new Error "Cannot find a replaced document for '#{document.Meta._name}'." migrateAllForward = -> updateAll = false for migrationDescriptor in allMigrationDescriptors updateAll = getReplacedDocument(migrationDescriptor.document).migrateForward(migrationDescriptor.migration) or updateAll # We set initial schema value for all documents in server collections which do not have migrations. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server unless document.Meta.schema document.migrateForward(null) # Return if updateAll should be called. updateAll # TODO: What happens if this is called multiple times? We should make sure that for each document observers are made only once. setupMigrationsObserve = -> # Setup migrations' observe only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server document._setupMigrationsObserve() migrations = -> if not globals.Document.migrationsDisabled and globals.Document.Migrations.find({}, limit: 1).count() == 0 globals.Document.Migrations.insert serial: 1 migrationName: null oldCollectionName: null newCollectionName: null oldVersion: null newVersion: null timestamp: new Date() migrated: 0 all: 0 # Even with disabled migrations this computes the latest schema versions for every document. updateAll = migrateAllForward() # Check that everything has been migrated to the latest schema version. unless globals.Document.migrationsDisabled # Check only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server notMigrated = _.pluck document.Meta.collection.find( _schema: $ne: document.Meta.schema , fields: _id: 1 ).fetch(), '_id' throw new Error "Not all documents migrated to the latest schema version (#{document.Meta.schema}) for '#{document.Meta._name}': #{notMigrated}" if notMigrated.length unless globals.Document.instanceDisabled setupMigrationsObserve() # "updateAll" can be "true" only if migrations are not disabled. if updateAll Log.info "Migrations requested updating all references..." globals.Document.updateAll() globals.Document.migrationsDisabled = !!process.env.PEERDB_MIGRATIONS_DISABLED globals.Document.prepare -> Log.info "Skipped migrations" if globals.Document.migrationsDisabled # We still run the code to determine schema version and setup # observer to set schema version when inserting new documents, # but we then inside the code skip running migrations themselves. migrations() Document = globals.Document
203499
import semver from 'semver' import util from 'util' globals = @ allMigrationDescriptors = [] try # Migration of migrations collection. new DirectCollection('migrations').renameCollection 'peerdb.migrations' catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" # Fields: # serial # migrationName # oldCollectionName # newCollectionName # oldVersion # newVersion # timestamp # migrated # all # # We use a lower case collection name to signal it is a system collection. globals.Document.Migrations = new Meteor.Collection 'peerdb.migrations' class globals.Document._Migration updateAll: (document, collection, currentSchema, intoSchema) -> @_updateAll = true forward: (document, collection, currentSchema, newSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: newSchema}, {multi: true} backward: (document, collection, currentSchema, oldSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: oldSchema}, {multi: true} class globals.Document.PatchMigration extends globals.Document._Migration class globals.Document.MinorMigration extends globals.Document._Migration class globals.Document.MajorMigration extends globals.Document._Migration class globals.Document.AddReferenceFieldsMigration extends globals.Document.MinorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveReferenceFieldsMigration extends globals.Document.MajorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddGeneratedFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.ModifyGeneratedFieldsMigration extends globals.Document.PatchMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveGeneratedFieldsMigration extends globals.Document.MajorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddOptionalFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields super document, collection, currentSchema, newSchema backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.AddRequiredFieldsMigration extends globals.Document.MinorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: newSchema for field, value of @fields if _.isFunction value update.$set[field] = value() else update.$set[field] = value count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RemoveFieldsMigration extends globals.Document.MajorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: oldSchema for field, value of @fields if _.isFunction value v = value() else v = value update.$set[field] = v unless _.isUndefined v count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RenameFieldsMigration extends globals.Document.MajorMigration # Fields is object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $set: _schema: newSchema $rename: {} for from, to of @fields update.$rename[from] = to count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $set: _schema: oldSchema $rename: {} for from, to of @fields # Reversed. update.$rename[to] = from count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document._RenameCollectionMigration extends globals.Document.MajorMigration constructor: (@oldName, @newName) -> super() @name = "Renaming collection from '#{@oldName}' to '#{@newName}'" _rename: (collection, to) -> try collection.renameCollection to catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" forward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @oldName @_rename collection, @newName collection.name = @newName # We renamed the collection, so let's update all documents to new schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts backward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @newName @_rename collection, @oldName collection.name = @oldName # We renamed the collection, so let's update all documents to old schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts globals.Document.addMigration = (migration) -> throw new Error "Migration is missing a name" unless migration.name throw new Error "Migration is not a migration instance" unless migration instanceof @_Migration throw new Error "Migration with the name '#{migration.name}' already exists" if migration.name in _.pluck @Meta.migrations, 'name' @Meta.migrations.push migration allMigrationDescriptors.push document: @ migration: migration globals.Document.renameCollectionMigration = (oldName, newName) -> @addMigration new @_RenameCollectionMigration oldName, newName globals.Document.migrateForward = (untilMigration) -> schemas = ['1.0.0'] currentSchema = '1.0.0' currentSerial = 0 initialName = @Meta.collection._name for migration in @Meta.migrations by -1 when migration instanceof @_RenameCollectionMigration throw new Error "Inconsistent document renaming, renaming from '#{migration.oldName}' to '#{migration.newName}', but current name is '#{initialName}' (new name and current name should match)" if migration.newName isnt initialName initialName = migration.oldName migrationsPending = Number.POSITIVE_INFINITY currentName = <NAME>Name for migration, i in @Meta.migrations if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName migrations = globals.Document.Migrations.find( serial: $gt: currentSerial oldCollectionName: $in: [currentName, newName] , sort: [ ['serial', 'asc'] ] ).fetch() if migrations[0] throw new Error "Unexpected migration recorded: #{util.inspect migrations[0], depth: 10}" if migrationsPending < Number.POSITIVE_INFINITY if migrations[0].migrationName is migration.name and migrations[0].oldCollectionName is currentName and migrations[0].newCollectionName is newName and migrations[0].oldVersion is currentSchema and migrations[0].newVersion is newSchema currentSerial = migrations[0].serial else throw new Error "Inconsistent migration recorded, expected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}', got: #{util.inspect migrations[0], depth: 10}" else if migrationsPending is Number.POSITIVE_INFINITY migrationsPending = i currentSchema = newSchema schemas.push currentSchema currentName = newName unknownSchema = _.pluck @Meta.collection.find( _schema: $nin: schemas $exists: true , fields: _id: 1 ).fetch(), '_id' throw new Error "Documents with unknown schema version: #{unknownSchema}" if unknownSchema.length updateAll = false currentSchema = '1.0.0' currentSerial = 0 currentName = <NAME> previousMigration = null for migration, i in @Meta.migrations if previousMigration is untilMigration break previousMigration = migration if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if i < migrationsPending and migration instanceof @_RenameCollectionMigration # We skip all already done rename migrations (but we run other old migrations again, just with the last known collection name). currentSchema = newSchema currentName = migration.newName continue if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName if globals.Document.migrationsDisabled # Migrations are disabled but we are still running # the code just to compute the latest schema version. currentSchema = newSchema currentName = newName continue migration._updateAll = false counts = migration.forward @, new DirectCollection(currentName), currentSchema, newSchema throw new Error "Invalid return value from migration: #{util.inspect counts}" unless 'migrated' of counts and 'all' of counts updateAll = true if counts.migrated and migration._updateAll if i < migrationsPending count = globals.Document.Migrations.update migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema , $inc: migrated: counts.migrated all: counts.all , # To catch any errors. multi: true throw new Error "Inconsistent migration record state, missing migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 1 else count = globals.Document.Migrations.find( migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema ).count() throw new Error "Inconsistent migration record state, unexpected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 0 globals.Document.Migrations.insert # Things should not be running in parallel here anyway, so we can get next serial in this way. serial: globals.Document.Migrations.findOne({}, {sort: [['serial', 'desc']]}).serial + 1 migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema migrated: counts.migrated all: counts.all timestamp: new Date() if migration instanceof @_RenameCollectionMigration Log.info "Renamed collection '#{currentName}' to '#{newName}'" Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all else Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) in '#{currentName}' collection (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all currentSchema = newSchema currentName = newName # We do not check for not migrated documents if migrations are disabled. unless globals.Document.migrationsDisabled # For all those documents which lack schema information we assume they have the last schema. @Meta.collection.update _schema: $exists: false , $set: _schema: currentSchema , multi: true @Meta.schema = currentSchema # Return if updateAll should be called. updateAll globals.Document.migrateBackward = (untilMigration) -> # TODO: Implement. throw new Error "Not implemented yet" globals.Document._setupMigrationsObserve = -> @Meta.collection.find( _schema: $exists: false , fields: _id: 1 _schema: 1 ).observeChanges added: globals.Document._observerCallback true, (id, fields) => # TODO: Check if schema is known and complain if not. # TODO: We could automatically migrate old documents if we know of newer schema. return if fields._schema @Meta.collection.update id, $set: _schema: @Meta.schema getReplacedDocument = (document) -> return document unless document.Meta._replaced for current in globals.Document.list parentMeta = current.Meta while parentMeta if parentMeta is document.Meta return current parentMeta = parentMeta.parent throw new Error "Cannot find a replaced document for '#{document.Meta._name}'." migrateAllForward = -> updateAll = false for migrationDescriptor in allMigrationDescriptors updateAll = getReplacedDocument(migrationDescriptor.document).migrateForward(migrationDescriptor.migration) or updateAll # We set initial schema value for all documents in server collections which do not have migrations. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server unless document.Meta.schema document.migrateForward(null) # Return if updateAll should be called. updateAll # TODO: What happens if this is called multiple times? We should make sure that for each document observers are made only once. setupMigrationsObserve = -> # Setup migrations' observe only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server document._setupMigrationsObserve() migrations = -> if not globals.Document.migrationsDisabled and globals.Document.Migrations.find({}, limit: 1).count() == 0 globals.Document.Migrations.insert serial: 1 migrationName: null oldCollectionName: null newCollectionName: null oldVersion: null newVersion: null timestamp: new Date() migrated: 0 all: 0 # Even with disabled migrations this computes the latest schema versions for every document. updateAll = migrateAllForward() # Check that everything has been migrated to the latest schema version. unless globals.Document.migrationsDisabled # Check only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server notMigrated = _.pluck document.Meta.collection.find( _schema: $ne: document.Meta.schema , fields: _id: 1 ).fetch(), '_id' throw new Error "Not all documents migrated to the latest schema version (#{document.Meta.schema}) for '#{document.Meta._name}': #{notMigrated}" if notMigrated.length unless globals.Document.instanceDisabled setupMigrationsObserve() # "updateAll" can be "true" only if migrations are not disabled. if updateAll Log.info "Migrations requested updating all references..." globals.Document.updateAll() globals.Document.migrationsDisabled = !!process.env.PEERDB_MIGRATIONS_DISABLED globals.Document.prepare -> Log.info "Skipped migrations" if globals.Document.migrationsDisabled # We still run the code to determine schema version and setup # observer to set schema version when inserting new documents, # but we then inside the code skip running migrations themselves. migrations() Document = globals.Document
true
import semver from 'semver' import util from 'util' globals = @ allMigrationDescriptors = [] try # Migration of migrations collection. new DirectCollection('migrations').renameCollection 'peerdb.migrations' catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" # Fields: # serial # migrationName # oldCollectionName # newCollectionName # oldVersion # newVersion # timestamp # migrated # all # # We use a lower case collection name to signal it is a system collection. globals.Document.Migrations = new Meteor.Collection 'peerdb.migrations' class globals.Document._Migration updateAll: (document, collection, currentSchema, intoSchema) -> @_updateAll = true forward: (document, collection, currentSchema, newSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: newSchema}, {multi: true} backward: (document, collection, currentSchema, oldSchema) -> migrated: 0 all: collection.update {_schema: currentSchema}, {$set: _schema: oldSchema}, {multi: true} class globals.Document.PatchMigration extends globals.Document._Migration class globals.Document.MinorMigration extends globals.Document._Migration class globals.Document.MajorMigration extends globals.Document._Migration class globals.Document.AddReferenceFieldsMigration extends globals.Document.MinorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveReferenceFieldsMigration extends globals.Document.MajorMigration forward: (document, collection, currentSchema, newSchema) -> @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddGeneratedFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.ModifyGeneratedFieldsMigration extends globals.Document.PatchMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields @updateAll document, collection, currentSchema, newSchema counts = super document, collection, currentSchema, newSchema counts.migrated = counts.all counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.RemoveGeneratedFieldsMigration extends globals.Document.MajorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> assert @fields @updateAll document, collection, currentSchema, oldSchema counts = super document, collection, currentSchema, oldSchema counts.migrated = counts.all counts class globals.Document.AddOptionalFieldsMigration extends globals.Document.MinorMigration # Fields is an array. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> assert @fields super document, collection, currentSchema, newSchema backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field in @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.AddRequiredFieldsMigration extends globals.Document.MinorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: newSchema for field, value of @fields if _.isFunction value update.$set[field] = value() else update.$set[field] = value count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $unset: {} $set: _schema: oldSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RemoveFieldsMigration extends globals.Document.MajorMigration # Fields is an object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $unset: {} $set: _schema: newSchema for field, value of @fields update.$unset[field] = '' count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> selector = _schema: currentSchema for field, value of @fields selector[field] = $exists: false update = $set: _schema: oldSchema for field, value of @fields if _.isFunction value v = value() else v = value update.$set[field] = v unless _.isUndefined v count = collection.update selector, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document.RenameFieldsMigration extends globals.Document.MajorMigration # Fields is object. constructor: (fields) -> super() @fields = fields if fields forward: (document, collection, currentSchema, newSchema) -> update = $set: _schema: newSchema $rename: {} for from, to of @fields update.$rename[from] = to count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, newSchema counts.migrated += count counts.all += count counts backward: (document, collection, currentSchema, oldSchema) -> update = $set: _schema: oldSchema $rename: {} for from, to of @fields # Reversed. update.$rename[to] = from count = collection.update {_schema: currentSchema}, update, {multi: true} counts = super document, collection, currentSchema, oldSchema counts.migrated += count counts.all += count counts class globals.Document._RenameCollectionMigration extends globals.Document.MajorMigration constructor: (@oldName, @newName) -> super() @name = "Renaming collection from '#{@oldName}' to '#{@newName}'" _rename: (collection, to) -> try collection.renameCollection to catch error throw error unless /source namespace does not exist|Source collection .* does not exist/.test "#{error}" forward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @oldName @_rename collection, @newName collection.name = @newName # We renamed the collection, so let's update all documents to new schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts backward: (document, collection, currentSchema, newSchema) -> assert.equal collection.name, @newName @_rename collection, @oldName collection.name = @oldName # We renamed the collection, so let's update all documents to old schema version. counts = super document, collection, currentSchema, newSchema # We migrated everything. counts.migrated = counts.all counts globals.Document.addMigration = (migration) -> throw new Error "Migration is missing a name" unless migration.name throw new Error "Migration is not a migration instance" unless migration instanceof @_Migration throw new Error "Migration with the name '#{migration.name}' already exists" if migration.name in _.pluck @Meta.migrations, 'name' @Meta.migrations.push migration allMigrationDescriptors.push document: @ migration: migration globals.Document.renameCollectionMigration = (oldName, newName) -> @addMigration new @_RenameCollectionMigration oldName, newName globals.Document.migrateForward = (untilMigration) -> schemas = ['1.0.0'] currentSchema = '1.0.0' currentSerial = 0 initialName = @Meta.collection._name for migration in @Meta.migrations by -1 when migration instanceof @_RenameCollectionMigration throw new Error "Inconsistent document renaming, renaming from '#{migration.oldName}' to '#{migration.newName}', but current name is '#{initialName}' (new name and current name should match)" if migration.newName isnt initialName initialName = migration.oldName migrationsPending = Number.POSITIVE_INFINITY currentName = PI:NAME:<NAME>END_PIName for migration, i in @Meta.migrations if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName migrations = globals.Document.Migrations.find( serial: $gt: currentSerial oldCollectionName: $in: [currentName, newName] , sort: [ ['serial', 'asc'] ] ).fetch() if migrations[0] throw new Error "Unexpected migration recorded: #{util.inspect migrations[0], depth: 10}" if migrationsPending < Number.POSITIVE_INFINITY if migrations[0].migrationName is migration.name and migrations[0].oldCollectionName is currentName and migrations[0].newCollectionName is newName and migrations[0].oldVersion is currentSchema and migrations[0].newVersion is newSchema currentSerial = migrations[0].serial else throw new Error "Inconsistent migration recorded, expected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}', got: #{util.inspect migrations[0], depth: 10}" else if migrationsPending is Number.POSITIVE_INFINITY migrationsPending = i currentSchema = newSchema schemas.push currentSchema currentName = newName unknownSchema = _.pluck @Meta.collection.find( _schema: $nin: schemas $exists: true , fields: _id: 1 ).fetch(), '_id' throw new Error "Documents with unknown schema version: #{unknownSchema}" if unknownSchema.length updateAll = false currentSchema = '1.0.0' currentSerial = 0 currentName = PI:NAME:<NAME>END_PI previousMigration = null for migration, i in @Meta.migrations if previousMigration is untilMigration break previousMigration = migration if migration instanceof @PatchMigration newSchema = semver.inc currentSchema, 'patch' else if migration instanceof @MinorMigration newSchema = semver.inc currentSchema, 'minor' else if migration instanceof @MajorMigration newSchema = semver.inc currentSchema, 'major' if i < migrationsPending and migration instanceof @_RenameCollectionMigration # We skip all already done rename migrations (but we run other old migrations again, just with the last known collection name). currentSchema = newSchema currentName = migration.newName continue if migration instanceof @_RenameCollectionMigration newName = migration.newName else newName = currentName if globals.Document.migrationsDisabled # Migrations are disabled but we are still running # the code just to compute the latest schema version. currentSchema = newSchema currentName = newName continue migration._updateAll = false counts = migration.forward @, new DirectCollection(currentName), currentSchema, newSchema throw new Error "Invalid return value from migration: #{util.inspect counts}" unless 'migrated' of counts and 'all' of counts updateAll = true if counts.migrated and migration._updateAll if i < migrationsPending count = globals.Document.Migrations.update migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema , $inc: migrated: counts.migrated all: counts.all , # To catch any errors. multi: true throw new Error "Inconsistent migration record state, missing migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 1 else count = globals.Document.Migrations.find( migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema ).count() throw new Error "Inconsistent migration record state, unexpected migrationName='#{migration.name}', oldCollectionName='#{currentName}', newCollectionName='#{newName}', oldVersion='#{currentSchema}', newVersion='#{newSchema}'" unless count is 0 globals.Document.Migrations.insert # Things should not be running in parallel here anyway, so we can get next serial in this way. serial: globals.Document.Migrations.findOne({}, {sort: [['serial', 'desc']]}).serial + 1 migrationName: migration.name oldCollectionName: currentName newCollectionName: newName oldVersion: currentSchema newVersion: newSchema migrated: counts.migrated all: counts.all timestamp: new Date() if migration instanceof @_RenameCollectionMigration Log.info "Renamed collection '#{currentName}' to '#{newName}'" Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all else Log.info "Migrated #{counts.migrated}/#{counts.all} document(s) in '#{currentName}' collection (from #{currentSchema} to #{newSchema}): #{migration.name}" if counts.all currentSchema = newSchema currentName = newName # We do not check for not migrated documents if migrations are disabled. unless globals.Document.migrationsDisabled # For all those documents which lack schema information we assume they have the last schema. @Meta.collection.update _schema: $exists: false , $set: _schema: currentSchema , multi: true @Meta.schema = currentSchema # Return if updateAll should be called. updateAll globals.Document.migrateBackward = (untilMigration) -> # TODO: Implement. throw new Error "Not implemented yet" globals.Document._setupMigrationsObserve = -> @Meta.collection.find( _schema: $exists: false , fields: _id: 1 _schema: 1 ).observeChanges added: globals.Document._observerCallback true, (id, fields) => # TODO: Check if schema is known and complain if not. # TODO: We could automatically migrate old documents if we know of newer schema. return if fields._schema @Meta.collection.update id, $set: _schema: @Meta.schema getReplacedDocument = (document) -> return document unless document.Meta._replaced for current in globals.Document.list parentMeta = current.Meta while parentMeta if parentMeta is document.Meta return current parentMeta = parentMeta.parent throw new Error "Cannot find a replaced document for '#{document.Meta._name}'." migrateAllForward = -> updateAll = false for migrationDescriptor in allMigrationDescriptors updateAll = getReplacedDocument(migrationDescriptor.document).migrateForward(migrationDescriptor.migration) or updateAll # We set initial schema value for all documents in server collections which do not have migrations. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server unless document.Meta.schema document.migrateForward(null) # Return if updateAll should be called. updateAll # TODO: What happens if this is called multiple times? We should make sure that for each document observers are made only once. setupMigrationsObserve = -> # Setup migrations' observe only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server document._setupMigrationsObserve() migrations = -> if not globals.Document.migrationsDisabled and globals.Document.Migrations.find({}, limit: 1).count() == 0 globals.Document.Migrations.insert serial: 1 migrationName: null oldCollectionName: null newCollectionName: null oldVersion: null newVersion: null timestamp: new Date() migrated: 0 all: 0 # Even with disabled migrations this computes the latest schema versions for every document. updateAll = migrateAllForward() # Check that everything has been migrated to the latest schema version. unless globals.Document.migrationsDisabled # Check only for server collections. for document in globals.Document.list when document.Meta.collection._connection is Meteor.server notMigrated = _.pluck document.Meta.collection.find( _schema: $ne: document.Meta.schema , fields: _id: 1 ).fetch(), '_id' throw new Error "Not all documents migrated to the latest schema version (#{document.Meta.schema}) for '#{document.Meta._name}': #{notMigrated}" if notMigrated.length unless globals.Document.instanceDisabled setupMigrationsObserve() # "updateAll" can be "true" only if migrations are not disabled. if updateAll Log.info "Migrations requested updating all references..." globals.Document.updateAll() globals.Document.migrationsDisabled = !!process.env.PEERDB_MIGRATIONS_DISABLED globals.Document.prepare -> Log.info "Skipped migrations" if globals.Document.migrationsDisabled # We still run the code to determine schema version and setup # observer to set schema version when inserting new documents, # but we then inside the code skip running migrations themselves. migrations() Document = globals.Document
[ { "context": "###\n# \n# countUp.js\n# by @inorganik\n# v 0.0.5\n#\n# Example:\n# numAnim = new countUp \"S", "end": 35, "score": 0.9996728897094727, "start": 25, "tag": "USERNAME", "value": "@inorganik" }, { "context": "wsers without native support\n # by Opera engineer Erik Möller\n while x < vendors.length and not window.request", "end": 1224, "score": 0.9997380971908569, "start": 1213, "tag": "NAME", "value": "Erik Möller" }, { "context": "nimationFrame = (id) ->\n clearTimeout id\n\n # Robert Penner's easeOutExpo\n @easeOutExpo = (t, b, c, d) ->\n ", "end": 1961, "score": 0.9994555115699768, "start": 1948, "tag": "NAME", "value": "Robert Penner" }, { "context": "-Math.pow(2, -10 * t / d) + 1) + b\n # thanks to @lifthrasiir's \"exact easing\" commit\n c * (-Math.pow(2, -10", "end": 2104, "score": 0.999641478061676, "start": 2092, "tag": "USERNAME", "value": "@lifthrasiir" } ]
countUp.coffee
masonicboom/countUp.js
1
### # # countUp.js # by @inorganik # v 0.0.5 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### window.requestAnimationFrame = window.requestAnimationFrame or window.mozRequestAnimationFrame or window.webkitRequestAnimationFrame or window.msRequestAnimationFrame # target = id of Html element where counting occurs # startVal = the value you want to start at # endVal = the value you want to arrive at # decimals = number of decimal places in number, default 0 # duration = duration in seconds, default 2 countUp = (target, startVal, endVal, decimals, duration) -> lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = document.getElementById target startVal = Number startVal endVal = Number endVal @countDown = if (startVal > endVal) then true else false #toggle easing @useEasing = true decimals = Math.max(0, decimals or 0) @dec = Math.pow(10, decimals) @duration = duration * 1000 or 2000 @startTime = null @frameVal = startVal @.rAF = null # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer Erik Möller while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # Robert Penner's easeOutExpo @easeOutExpo = (t, b, c, d) -> # modified from: # c * (-Math.pow(2, -10 * t / d) + 1) + b # thanks to @lifthrasiir's "exact easing" commit c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null progress = timestamp - @startTime # to ease or not to ease is the question if @.useEasing if @.countDown i = @.easeOutExpo progress, 0, startVal - endVal, @.duration @.frameVal = startVal - i else @.frameVal = @.easeOutExpo(progress, startVal, endVal - startVal, @.duration) console.log @.frameVal else if @.countDown i = (startVal - endVal) * (progress / @.duration) @.frameVal = startVal - i else @.frameVal = startVal + (endVal - startVal) * (progress / @.duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < endVal) then endVal else @frameVal else @frameVal = if (@framVal > endVal) then endVal else @frameVal # formate and print value @doc.innerHTML = @addCommas @frameVal.toFixed(decimals) # weather to continue if progress < self.duration self.rAF = requestAnimationFrame self.count else self.callback() if self.callback? @start = () -> # make sure endVal is a number requestAnimationFrame @count unless isNaN(endVal) and isNan(startVal) isnt null else console.log('countUp error: startVal or endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> cancelAnimationFrame @rAF @doc.innerHTML = startVal @addCommas = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then "." + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') x1 + x2
215144
### # # countUp.js # by @inorganik # v 0.0.5 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### window.requestAnimationFrame = window.requestAnimationFrame or window.mozRequestAnimationFrame or window.webkitRequestAnimationFrame or window.msRequestAnimationFrame # target = id of Html element where counting occurs # startVal = the value you want to start at # endVal = the value you want to arrive at # decimals = number of decimal places in number, default 0 # duration = duration in seconds, default 2 countUp = (target, startVal, endVal, decimals, duration) -> lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = document.getElementById target startVal = Number startVal endVal = Number endVal @countDown = if (startVal > endVal) then true else false #toggle easing @useEasing = true decimals = Math.max(0, decimals or 0) @dec = Math.pow(10, decimals) @duration = duration * 1000 or 2000 @startTime = null @frameVal = startVal @.rAF = null # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer <NAME> while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # <NAME>'s easeOutExpo @easeOutExpo = (t, b, c, d) -> # modified from: # c * (-Math.pow(2, -10 * t / d) + 1) + b # thanks to @lifthrasiir's "exact easing" commit c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null progress = timestamp - @startTime # to ease or not to ease is the question if @.useEasing if @.countDown i = @.easeOutExpo progress, 0, startVal - endVal, @.duration @.frameVal = startVal - i else @.frameVal = @.easeOutExpo(progress, startVal, endVal - startVal, @.duration) console.log @.frameVal else if @.countDown i = (startVal - endVal) * (progress / @.duration) @.frameVal = startVal - i else @.frameVal = startVal + (endVal - startVal) * (progress / @.duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < endVal) then endVal else @frameVal else @frameVal = if (@framVal > endVal) then endVal else @frameVal # formate and print value @doc.innerHTML = @addCommas @frameVal.toFixed(decimals) # weather to continue if progress < self.duration self.rAF = requestAnimationFrame self.count else self.callback() if self.callback? @start = () -> # make sure endVal is a number requestAnimationFrame @count unless isNaN(endVal) and isNan(startVal) isnt null else console.log('countUp error: startVal or endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> cancelAnimationFrame @rAF @doc.innerHTML = startVal @addCommas = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then "." + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') x1 + x2
true
### # # countUp.js # by @inorganik # v 0.0.5 # # Example: # numAnim = new countUp "SomeElementYouWantToAnimate", 99.99, 2, 1.5 # numAnim.start() # ### window.requestAnimationFrame = window.requestAnimationFrame or window.mozRequestAnimationFrame or window.webkitRequestAnimationFrame or window.msRequestAnimationFrame # target = id of Html element where counting occurs # startVal = the value you want to start at # endVal = the value you want to arrive at # decimals = number of decimal places in number, default 0 # duration = duration in seconds, default 2 countUp = (target, startVal, endVal, decimals, duration) -> lastTime = 0 vendors = [ 'webkit' 'moz' 'ms' ] @doc = document.getElementById target startVal = Number startVal endVal = Number endVal @countDown = if (startVal > endVal) then true else false #toggle easing @useEasing = true decimals = Math.max(0, decimals or 0) @dec = Math.pow(10, decimals) @duration = duration * 1000 or 2000 @startTime = null @frameVal = startVal @.rAF = null # make sure requestAnimationFrame and cancelAnimationFrame are defined # polyfill for browsers without native support # by Opera engineer PI:NAME:<NAME>END_PI while x < vendors.length and not window.requestAnimationFrame window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'] window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'] unless window.requestAnimationFrame window.requestAnimationFrame = (callback, element) -> currTime = new Date().getTime() timeToCall = Math.max 0, 16 - (currTime - lastTime) id = window.setTimeout(-> callback currTime + timeToCall , timeToCall) lastTime = currTime + timeToCall id unless window.cancelAnimationFrame window.cancelAnimationFrame = (id) -> clearTimeout id # PI:NAME:<NAME>END_PI's easeOutExpo @easeOutExpo = (t, b, c, d) -> # modified from: # c * (-Math.pow(2, -10 * t / d) + 1) + b # thanks to @lifthrasiir's "exact easing" commit c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b @count = (timestamp) -> @startTime = timestamp if @startTime is null progress = timestamp - @startTime # to ease or not to ease is the question if @.useEasing if @.countDown i = @.easeOutExpo progress, 0, startVal - endVal, @.duration @.frameVal = startVal - i else @.frameVal = @.easeOutExpo(progress, startVal, endVal - startVal, @.duration) console.log @.frameVal else if @.countDown i = (startVal - endVal) * (progress / @.duration) @.frameVal = startVal - i else @.frameVal = startVal + (endVal - startVal) * (progress / @.duration) # decimal @frameVal = Math.round(@frameVal * @dec) / @dec # don't go past enVal since progress can exceed duration in last grame if @countDown @frameVal = if (@framVal < endVal) then endVal else @frameVal else @frameVal = if (@framVal > endVal) then endVal else @frameVal # formate and print value @doc.innerHTML = @addCommas @frameVal.toFixed(decimals) # weather to continue if progress < self.duration self.rAF = requestAnimationFrame self.count else self.callback() if self.callback? @start = () -> # make sure endVal is a number requestAnimationFrame @count unless isNaN(endVal) and isNan(startVal) isnt null else console.log('countUp error: startVal or endVal is not a number') @doc.innerHTML = '--' false @stop = () -> cancelAnimationFrame @rAF @reset = () -> cancelAnimationFrame @rAF @doc.innerHTML = startVal @addCommas = (nStr) -> nStr += '' x = nStr.split('.') x1 = x[0] x2 = if x.length > 1 then "." + x[1] else '' rgx = /(\d+)(\d{3})/ while rgx.test(x1) x1 = x1.replace(rgx, '$1' + ',' + '$2') x1 + x2
[ { "context": "id: null,\n error_id: \"Error\",\n pass: null,\n error_pass: \"Error\",\n complete: f", "end": 1784, "score": 0.9314895272254944, "start": 1780, "tag": "PASSWORD", "value": "null" }, { "context": "\"Error\",\n pass: null,\n error_pass: \"Error\",\n complete: false,\n loading: false", "end": 1812, "score": 0.9805926084518433, "start": 1807, "tag": "PASSWORD", "value": "Error" } ]
view/Login.cjsx
m-mitsuhide/amatelus
0
React = require "react" Redux = require 'redux' MUI = require 'material-ui' Style = require "./Style.cjsx" request = require "superagent" apiPath = require "../config.js" Loading = require "./Loading.cjsx" action = require "../action/Login_action.cjsx" Background = require '../view/Background.cjsx' TextField = MUI.TextField AppBar = MUI.AppBar Paper = MUI.Paper RaisedButton = MUI.RaisedButton store = Redux.createStore (state,action)-> if typeof state == 'undefined' state = { id: null, error_id: null, pass: null, error_pass: null, complete: false, loading: false } else if action.type == 'id' state = { id: action.value, error_id: null, pass: state.pass, error_pass: state.error_pass, loading: state.loading } if state.id == "" state.error_id = null else if !/^[0-9a-zA-Z]{5,15}$/.test state.id state.error_id = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'pass' state = { id: state.id, error_id: state.error_id, pass: action.value, error_pass: null, loading: state.loading } if state.pass == "" state.error_pass = null else if !/^[0-9a-zA-Z]{8,}$/.test state.pass state.error_pass = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'loading' state = { id: state.id, error_id: state.error_id, pass: state.pass, error_pass: state.error_pass, complete: state.complete, loading: true } else if action.type == 'loaded' if action.data.error state = { id: null, error_id: "Error", pass: null, error_pass: "Error", complete: false, loading: false } else action.onLogin action.data.name state class Login extends React.Component constructor:(props)-> super props @state = store.getState() store.subscribe ()=> @updateState() render:()-> <div> <Background /> <div id="Login"> <div className="paper"> <Paper zDepth={0}> <AppBar iconElementLeft={<span/>} title="Login" /> <div className="input-area"> <TextField errorText={@state.error_id} onInput={ (e)->store.dispatch( action.inputId( e.target.value ) ) } value={@state.id} hintText="alphanumeric from 5 to 15" floatingLabelText="id" /> <TextField type="password" errorText={@state.error_pass} onInput={ (e)->store.dispatch( action.inputPass( e.target.value ) ) } value={@state.pass} hintText="alphanumeric 8 or more" floatingLabelText="password" /> <div className="enter-btn"> <RaisedButton label="Enter" disabled={!@state.complete} primary={true} onClick={@submit}/> </div> </div> </Paper> <Loading visible={@state.loading}/> </div> <Style type="Login"/> </div> </div> submit: () => store.dispatch { type: "loading" } state = store.getState() request .post( apiPath.path.login ) .type('form') .send({ id: state.id, pass: state.pass }) .end(( err, req ) => if err console.log("network error") else store.dispatch { type: "loaded", data: JSON.parse(req.text), onLogin: @props.onLogin } ) updateState:()-> @setState store.getState() module.exports = Login;
84098
React = require "react" Redux = require 'redux' MUI = require 'material-ui' Style = require "./Style.cjsx" request = require "superagent" apiPath = require "../config.js" Loading = require "./Loading.cjsx" action = require "../action/Login_action.cjsx" Background = require '../view/Background.cjsx' TextField = MUI.TextField AppBar = MUI.AppBar Paper = MUI.Paper RaisedButton = MUI.RaisedButton store = Redux.createStore (state,action)-> if typeof state == 'undefined' state = { id: null, error_id: null, pass: null, error_pass: null, complete: false, loading: false } else if action.type == 'id' state = { id: action.value, error_id: null, pass: state.pass, error_pass: state.error_pass, loading: state.loading } if state.id == "" state.error_id = null else if !/^[0-9a-zA-Z]{5,15}$/.test state.id state.error_id = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'pass' state = { id: state.id, error_id: state.error_id, pass: action.value, error_pass: null, loading: state.loading } if state.pass == "" state.error_pass = null else if !/^[0-9a-zA-Z]{8,}$/.test state.pass state.error_pass = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'loading' state = { id: state.id, error_id: state.error_id, pass: state.pass, error_pass: state.error_pass, complete: state.complete, loading: true } else if action.type == 'loaded' if action.data.error state = { id: null, error_id: "Error", pass: <PASSWORD>, error_pass: "<PASSWORD>", complete: false, loading: false } else action.onLogin action.data.name state class Login extends React.Component constructor:(props)-> super props @state = store.getState() store.subscribe ()=> @updateState() render:()-> <div> <Background /> <div id="Login"> <div className="paper"> <Paper zDepth={0}> <AppBar iconElementLeft={<span/>} title="Login" /> <div className="input-area"> <TextField errorText={@state.error_id} onInput={ (e)->store.dispatch( action.inputId( e.target.value ) ) } value={@state.id} hintText="alphanumeric from 5 to 15" floatingLabelText="id" /> <TextField type="password" errorText={@state.error_pass} onInput={ (e)->store.dispatch( action.inputPass( e.target.value ) ) } value={@state.pass} hintText="alphanumeric 8 or more" floatingLabelText="password" /> <div className="enter-btn"> <RaisedButton label="Enter" disabled={!@state.complete} primary={true} onClick={@submit}/> </div> </div> </Paper> <Loading visible={@state.loading}/> </div> <Style type="Login"/> </div> </div> submit: () => store.dispatch { type: "loading" } state = store.getState() request .post( apiPath.path.login ) .type('form') .send({ id: state.id, pass: state.pass }) .end(( err, req ) => if err console.log("network error") else store.dispatch { type: "loaded", data: JSON.parse(req.text), onLogin: @props.onLogin } ) updateState:()-> @setState store.getState() module.exports = Login;
true
React = require "react" Redux = require 'redux' MUI = require 'material-ui' Style = require "./Style.cjsx" request = require "superagent" apiPath = require "../config.js" Loading = require "./Loading.cjsx" action = require "../action/Login_action.cjsx" Background = require '../view/Background.cjsx' TextField = MUI.TextField AppBar = MUI.AppBar Paper = MUI.Paper RaisedButton = MUI.RaisedButton store = Redux.createStore (state,action)-> if typeof state == 'undefined' state = { id: null, error_id: null, pass: null, error_pass: null, complete: false, loading: false } else if action.type == 'id' state = { id: action.value, error_id: null, pass: state.pass, error_pass: state.error_pass, loading: state.loading } if state.id == "" state.error_id = null else if !/^[0-9a-zA-Z]{5,15}$/.test state.id state.error_id = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'pass' state = { id: state.id, error_id: state.error_id, pass: action.value, error_pass: null, loading: state.loading } if state.pass == "" state.error_pass = null else if !/^[0-9a-zA-Z]{8,}$/.test state.pass state.error_pass = "Error" state.complete = state.id && state.pass && !state.error_id && !state.error_pass else if action.type == 'loading' state = { id: state.id, error_id: state.error_id, pass: state.pass, error_pass: state.error_pass, complete: state.complete, loading: true } else if action.type == 'loaded' if action.data.error state = { id: null, error_id: "Error", pass: PI:PASSWORD:<PASSWORD>END_PI, error_pass: "PI:PASSWORD:<PASSWORD>END_PI", complete: false, loading: false } else action.onLogin action.data.name state class Login extends React.Component constructor:(props)-> super props @state = store.getState() store.subscribe ()=> @updateState() render:()-> <div> <Background /> <div id="Login"> <div className="paper"> <Paper zDepth={0}> <AppBar iconElementLeft={<span/>} title="Login" /> <div className="input-area"> <TextField errorText={@state.error_id} onInput={ (e)->store.dispatch( action.inputId( e.target.value ) ) } value={@state.id} hintText="alphanumeric from 5 to 15" floatingLabelText="id" /> <TextField type="password" errorText={@state.error_pass} onInput={ (e)->store.dispatch( action.inputPass( e.target.value ) ) } value={@state.pass} hintText="alphanumeric 8 or more" floatingLabelText="password" /> <div className="enter-btn"> <RaisedButton label="Enter" disabled={!@state.complete} primary={true} onClick={@submit}/> </div> </div> </Paper> <Loading visible={@state.loading}/> </div> <Style type="Login"/> </div> </div> submit: () => store.dispatch { type: "loading" } state = store.getState() request .post( apiPath.path.login ) .type('form') .send({ id: state.id, pass: state.pass }) .end(( err, req ) => if err console.log("network error") else store.dispatch { type: "loaded", data: JSON.parse(req.text), onLogin: @props.onLogin } ) updateState:()-> @setState store.getState() module.exports = Login;
[ { "context": "403c-6b43-46be-9357-728d476f84c7'\n token: '1979780f49d488f41293f70ff1baec9be910cf9b'\n server: 'localhost'\n port: '6000'", "end": 4910, "score": 0.9748842716217041, "start": 4870, "tag": "KEY", "value": "1979780f49d488f41293f70ff1baec9be910cf9b" }, { "context": "9f8f80-4712-47be-a100-f0579836a9b9'\n token: 'cdbc4fa219d40088b3189b66af27e051a8fa358e'\n hostname: 'localhost'\n port: '3000'\n ", "end": 5698, "score": 0.9582610130310059, "start": 5658, "tag": "KEY", "value": "cdbc4fa219d40088b3189b66af27e051a8fa358e" } ]
command-message-blast.coffee
octoblu/meshblu-benchmark
0
_ = require 'lodash' commander = require 'commander' async = require 'async' uuid = require 'uuid' colors = require 'colors' MeshbluHttp = require 'meshblu-http' MeshbluConfig = require 'meshblu-config' debug = require('debug')('meshblu-benchmark:message-blast') MeshbluWebsocket = require 'meshblu-websocket' Benchmark = require 'simple-benchmark' class CommandMessageWebhook parseOptions: => commander .option '-c, --cycles [n]', 'number of cycles to run (defaults to 10)', @parseInt, 10 .option '-n, --number-of-messages [n]', 'Number of parallel messages per second (defaults to 1)', @parseInt, 1 .option '-t, --type [type]', 'Type of connection to use (defaults to http)', 'http' .parse process.argv {@numberOfMessages,@cycles,@type} = commander run: => @registeredDevices = [] @parseOptions() @elapsedTimes = [] @startTimes = {} @messages = [] @currentCycle = 0 console.log 'pid: ', process.pid @registerReceiverAndSenders (error, receiver, senders) => @die error if error? setInterval (=> @blast receiver, with: senders), 1000 averageTimeBetween: (times, begin, end) => differences = _.map times, (time) => time[end] - time[begin] _.sum(differences) / _.size(differences) blast: (receiver, {with: senders}) => return @printAverageAndDie() if @currentCycle >= @cycles @currentCycle += 1 # _.defer => debug 'blast', @currentCycle, @cycles async.each senders, (sender, done) => @message from: sender, to: receiver, done die: (error) => if 'Error' == typeof error console.error colors.red error.message else console.error colors.red arguments... process.exit 1 message: ({from: sender, to: receiver}, callback) => messageId = uuid.v1() message = devices: [receiver.uuid] topic: 'make peter happy' payload: messageId: messageId times: start: Date.now() @startTimes[messageId] = message.payload.times.start @["#{@type}Message"] from: sender, to: receiver, message httpMessage: ({from: sender, to: receiver}, message) => start = message.payload.times.start sender.message message #, => websocketMessage: ({from: sender, to: receiver}, message) => receiver.message message parseInt: (str) => parseInt str onMessage: (message) => endTime = Date.now() messageId = message?.payload?.messageId return unless messageId? @receivedMessages ?= {} @receivedMessages[messageId] ?= 0 @receivedMessages[messageId] += 1 startTime = @startTimes[messageId] delete @startTimes[messageId] # startTime = message.payload.startTime return unless startTime? elapsedTime = endTime - startTime @elapsedTimes.push elapsedTime message.payload.times.end = endTime @messages.push message.payload.times # debug "onMessage", elapsedTime: elapsedTime printAverageAndDie: => setTimeout => average = _.sum(@elapsedTimes) / _.size(@elapsedTimes) debug averageElapsedTime: average danglingMessages: _.size(_.keys(@startTimes)) successfulRoundTrips: _.size(@elapsedTimes) percentile90: @nthPercentile(90, @elapsedTimes) median: @nthPercentile(50, @elapsedTimes) averageRoutedToEnd: @averageTimeBetween @messages, 'routed', 'end' averageParseStartToEnd: @averageTimeBetween @messages, 'parseStart', 'end' async.each @registeredDevices, @unregister, => @registeredDevices = [] process.exit 0 , 2000 register: (callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.register {}, (error, device) => return callback error if error? @registeredDevices.push device callback null, device unregister: (device, callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.unregister device, callback registerReceiverAndSenders: (callback) => async.parallel { receiver: @registerReceiver senders: @registerSenders }, (error, results={}) => {receiver,senders} = results callback error, receiver, senders registerReceiver: (callback) => async.waterfall [ @register @subscribeToDevice ], callback registerSenders: (callback) => async.timesLimit @numberOfMessages, 50, @registerSender, callback registerSender: (i, callback) => @register (error, device) => meshbluConfig = new MeshbluConfig config = _.extend meshbluConfig.toJSON(), _.pick(device, 'uuid', 'token') # sender = new MeshbluWebsocket config # sender.connect (error) => # callback error, sender config = uuid: 'c780403c-6b43-46be-9357-728d476f84c7' token: '1979780f49d488f41293f70ff1baec9be910cf9b' server: 'localhost' port: '6000' protocol: 'http' sender = new MeshbluHttp config callback error, sender # callback error, config singleRun: (device, callback) => benchmark = new Benchmark label: 'message-webhook' async.parallel [ @listenForMessage async.apply @message, device ], (error) => return callback error if error? console.log benchmark.toString() callback(null, benchmark.elapsed()) subscribeToDevice: (device, callback) => meshbluConfig = new MeshbluConfig config = meshbluConfig.toJSON() # config.uuid = device.uuid # config.token = device.token config = uuid: '7a9f8f80-4712-47be-a100-f0579836a9b9' token: 'cdbc4fa219d40088b3189b66af27e051a8fa358e' hostname: 'localhost' port: '3000' protocol: 'http' conn = new MeshbluWebsocket config conn.connect (error) => return callback error if error? conn.on 'message', @onMessage # conn.uuid = device.uuid conn.uuid = config.uuid callback error, conn nthPercentile: (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] new CommandMessageWebhook().run()
111849
_ = require 'lodash' commander = require 'commander' async = require 'async' uuid = require 'uuid' colors = require 'colors' MeshbluHttp = require 'meshblu-http' MeshbluConfig = require 'meshblu-config' debug = require('debug')('meshblu-benchmark:message-blast') MeshbluWebsocket = require 'meshblu-websocket' Benchmark = require 'simple-benchmark' class CommandMessageWebhook parseOptions: => commander .option '-c, --cycles [n]', 'number of cycles to run (defaults to 10)', @parseInt, 10 .option '-n, --number-of-messages [n]', 'Number of parallel messages per second (defaults to 1)', @parseInt, 1 .option '-t, --type [type]', 'Type of connection to use (defaults to http)', 'http' .parse process.argv {@numberOfMessages,@cycles,@type} = commander run: => @registeredDevices = [] @parseOptions() @elapsedTimes = [] @startTimes = {} @messages = [] @currentCycle = 0 console.log 'pid: ', process.pid @registerReceiverAndSenders (error, receiver, senders) => @die error if error? setInterval (=> @blast receiver, with: senders), 1000 averageTimeBetween: (times, begin, end) => differences = _.map times, (time) => time[end] - time[begin] _.sum(differences) / _.size(differences) blast: (receiver, {with: senders}) => return @printAverageAndDie() if @currentCycle >= @cycles @currentCycle += 1 # _.defer => debug 'blast', @currentCycle, @cycles async.each senders, (sender, done) => @message from: sender, to: receiver, done die: (error) => if 'Error' == typeof error console.error colors.red error.message else console.error colors.red arguments... process.exit 1 message: ({from: sender, to: receiver}, callback) => messageId = uuid.v1() message = devices: [receiver.uuid] topic: 'make peter happy' payload: messageId: messageId times: start: Date.now() @startTimes[messageId] = message.payload.times.start @["#{@type}Message"] from: sender, to: receiver, message httpMessage: ({from: sender, to: receiver}, message) => start = message.payload.times.start sender.message message #, => websocketMessage: ({from: sender, to: receiver}, message) => receiver.message message parseInt: (str) => parseInt str onMessage: (message) => endTime = Date.now() messageId = message?.payload?.messageId return unless messageId? @receivedMessages ?= {} @receivedMessages[messageId] ?= 0 @receivedMessages[messageId] += 1 startTime = @startTimes[messageId] delete @startTimes[messageId] # startTime = message.payload.startTime return unless startTime? elapsedTime = endTime - startTime @elapsedTimes.push elapsedTime message.payload.times.end = endTime @messages.push message.payload.times # debug "onMessage", elapsedTime: elapsedTime printAverageAndDie: => setTimeout => average = _.sum(@elapsedTimes) / _.size(@elapsedTimes) debug averageElapsedTime: average danglingMessages: _.size(_.keys(@startTimes)) successfulRoundTrips: _.size(@elapsedTimes) percentile90: @nthPercentile(90, @elapsedTimes) median: @nthPercentile(50, @elapsedTimes) averageRoutedToEnd: @averageTimeBetween @messages, 'routed', 'end' averageParseStartToEnd: @averageTimeBetween @messages, 'parseStart', 'end' async.each @registeredDevices, @unregister, => @registeredDevices = [] process.exit 0 , 2000 register: (callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.register {}, (error, device) => return callback error if error? @registeredDevices.push device callback null, device unregister: (device, callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.unregister device, callback registerReceiverAndSenders: (callback) => async.parallel { receiver: @registerReceiver senders: @registerSenders }, (error, results={}) => {receiver,senders} = results callback error, receiver, senders registerReceiver: (callback) => async.waterfall [ @register @subscribeToDevice ], callback registerSenders: (callback) => async.timesLimit @numberOfMessages, 50, @registerSender, callback registerSender: (i, callback) => @register (error, device) => meshbluConfig = new MeshbluConfig config = _.extend meshbluConfig.toJSON(), _.pick(device, 'uuid', 'token') # sender = new MeshbluWebsocket config # sender.connect (error) => # callback error, sender config = uuid: 'c780403c-6b43-46be-9357-728d476f84c7' token: '<KEY>' server: 'localhost' port: '6000' protocol: 'http' sender = new MeshbluHttp config callback error, sender # callback error, config singleRun: (device, callback) => benchmark = new Benchmark label: 'message-webhook' async.parallel [ @listenForMessage async.apply @message, device ], (error) => return callback error if error? console.log benchmark.toString() callback(null, benchmark.elapsed()) subscribeToDevice: (device, callback) => meshbluConfig = new MeshbluConfig config = meshbluConfig.toJSON() # config.uuid = device.uuid # config.token = device.token config = uuid: '7a9f8f80-4712-47be-a100-f0579836a9b9' token: '<KEY>' hostname: 'localhost' port: '3000' protocol: 'http' conn = new MeshbluWebsocket config conn.connect (error) => return callback error if error? conn.on 'message', @onMessage # conn.uuid = device.uuid conn.uuid = config.uuid callback error, conn nthPercentile: (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] new CommandMessageWebhook().run()
true
_ = require 'lodash' commander = require 'commander' async = require 'async' uuid = require 'uuid' colors = require 'colors' MeshbluHttp = require 'meshblu-http' MeshbluConfig = require 'meshblu-config' debug = require('debug')('meshblu-benchmark:message-blast') MeshbluWebsocket = require 'meshblu-websocket' Benchmark = require 'simple-benchmark' class CommandMessageWebhook parseOptions: => commander .option '-c, --cycles [n]', 'number of cycles to run (defaults to 10)', @parseInt, 10 .option '-n, --number-of-messages [n]', 'Number of parallel messages per second (defaults to 1)', @parseInt, 1 .option '-t, --type [type]', 'Type of connection to use (defaults to http)', 'http' .parse process.argv {@numberOfMessages,@cycles,@type} = commander run: => @registeredDevices = [] @parseOptions() @elapsedTimes = [] @startTimes = {} @messages = [] @currentCycle = 0 console.log 'pid: ', process.pid @registerReceiverAndSenders (error, receiver, senders) => @die error if error? setInterval (=> @blast receiver, with: senders), 1000 averageTimeBetween: (times, begin, end) => differences = _.map times, (time) => time[end] - time[begin] _.sum(differences) / _.size(differences) blast: (receiver, {with: senders}) => return @printAverageAndDie() if @currentCycle >= @cycles @currentCycle += 1 # _.defer => debug 'blast', @currentCycle, @cycles async.each senders, (sender, done) => @message from: sender, to: receiver, done die: (error) => if 'Error' == typeof error console.error colors.red error.message else console.error colors.red arguments... process.exit 1 message: ({from: sender, to: receiver}, callback) => messageId = uuid.v1() message = devices: [receiver.uuid] topic: 'make peter happy' payload: messageId: messageId times: start: Date.now() @startTimes[messageId] = message.payload.times.start @["#{@type}Message"] from: sender, to: receiver, message httpMessage: ({from: sender, to: receiver}, message) => start = message.payload.times.start sender.message message #, => websocketMessage: ({from: sender, to: receiver}, message) => receiver.message message parseInt: (str) => parseInt str onMessage: (message) => endTime = Date.now() messageId = message?.payload?.messageId return unless messageId? @receivedMessages ?= {} @receivedMessages[messageId] ?= 0 @receivedMessages[messageId] += 1 startTime = @startTimes[messageId] delete @startTimes[messageId] # startTime = message.payload.startTime return unless startTime? elapsedTime = endTime - startTime @elapsedTimes.push elapsedTime message.payload.times.end = endTime @messages.push message.payload.times # debug "onMessage", elapsedTime: elapsedTime printAverageAndDie: => setTimeout => average = _.sum(@elapsedTimes) / _.size(@elapsedTimes) debug averageElapsedTime: average danglingMessages: _.size(_.keys(@startTimes)) successfulRoundTrips: _.size(@elapsedTimes) percentile90: @nthPercentile(90, @elapsedTimes) median: @nthPercentile(50, @elapsedTimes) averageRoutedToEnd: @averageTimeBetween @messages, 'routed', 'end' averageParseStartToEnd: @averageTimeBetween @messages, 'parseStart', 'end' async.each @registeredDevices, @unregister, => @registeredDevices = [] process.exit 0 , 2000 register: (callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.register {}, (error, device) => return callback error if error? @registeredDevices.push device callback null, device unregister: (device, callback) => meshbluConfig = new MeshbluConfig meshbluHttp = new MeshbluHttp meshbluConfig.toJSON() meshbluHttp.unregister device, callback registerReceiverAndSenders: (callback) => async.parallel { receiver: @registerReceiver senders: @registerSenders }, (error, results={}) => {receiver,senders} = results callback error, receiver, senders registerReceiver: (callback) => async.waterfall [ @register @subscribeToDevice ], callback registerSenders: (callback) => async.timesLimit @numberOfMessages, 50, @registerSender, callback registerSender: (i, callback) => @register (error, device) => meshbluConfig = new MeshbluConfig config = _.extend meshbluConfig.toJSON(), _.pick(device, 'uuid', 'token') # sender = new MeshbluWebsocket config # sender.connect (error) => # callback error, sender config = uuid: 'c780403c-6b43-46be-9357-728d476f84c7' token: 'PI:KEY:<KEY>END_PI' server: 'localhost' port: '6000' protocol: 'http' sender = new MeshbluHttp config callback error, sender # callback error, config singleRun: (device, callback) => benchmark = new Benchmark label: 'message-webhook' async.parallel [ @listenForMessage async.apply @message, device ], (error) => return callback error if error? console.log benchmark.toString() callback(null, benchmark.elapsed()) subscribeToDevice: (device, callback) => meshbluConfig = new MeshbluConfig config = meshbluConfig.toJSON() # config.uuid = device.uuid # config.token = device.token config = uuid: '7a9f8f80-4712-47be-a100-f0579836a9b9' token: 'PI:KEY:<KEY>END_PI' hostname: 'localhost' port: '3000' protocol: 'http' conn = new MeshbluWebsocket config conn.connect (error) => return callback error if error? conn.on 'message', @onMessage # conn.uuid = device.uuid conn.uuid = config.uuid callback error, conn nthPercentile: (percentile, array) => array = _.sortBy array index = (percentile / 100) * _.size(array) if Math.floor(index) == index return (array[index-1] + array[index]) / 2 return array[Math.floor index] new CommandMessageWebhook().run()
[ { "context": "ib/jquery.js'\nMove = require './../move.coffee'\n\n# Tim Huminski's favorite move. Does base damage of 0.5,\n# Never", "end": 77, "score": 0.9972984194755554, "start": 65, "tag": "NAME", "value": "Tim Huminski" } ]
src/js/moves/sandal.coffee
Huntrr/Battle-Resolution
0
$ = require 'lib/jquery.js' Move = require './../move.coffee' # Tim Huminski's favorite move. Does base damage of 0.5, # Never very effective module.exports = class Sandal extends Move constructor: () -> super 'THROW SANDAL' getDamage: () -> return 1 use: (cb) -> super() Thrown = require 'effects/thrown.coffee' if @user.has('THROWN 1 SANDAL') @user.removeStatus('THROWN 1 SANDAL') @user.addStatus(new Thrown(2)) @target.damage(@getDamage() * 2) @announce cb, @user.name + ' has thrown their other sandal! It\'s super effective!' else if @user.has('THROWN 2 SANDALS') @announce cb, 'But ' + @user.name + ' is out of sandals and has none to throw!' else @user.addStatus(new Thrown (1)) @target.damage(@getDamage()) @announce cb, @user.name + ' throws one flip flop at ' + @target.name
155344
$ = require 'lib/jquery.js' Move = require './../move.coffee' # <NAME>'s favorite move. Does base damage of 0.5, # Never very effective module.exports = class Sandal extends Move constructor: () -> super 'THROW SANDAL' getDamage: () -> return 1 use: (cb) -> super() Thrown = require 'effects/thrown.coffee' if @user.has('THROWN 1 SANDAL') @user.removeStatus('THROWN 1 SANDAL') @user.addStatus(new Thrown(2)) @target.damage(@getDamage() * 2) @announce cb, @user.name + ' has thrown their other sandal! It\'s super effective!' else if @user.has('THROWN 2 SANDALS') @announce cb, 'But ' + @user.name + ' is out of sandals and has none to throw!' else @user.addStatus(new Thrown (1)) @target.damage(@getDamage()) @announce cb, @user.name + ' throws one flip flop at ' + @target.name
true
$ = require 'lib/jquery.js' Move = require './../move.coffee' # PI:NAME:<NAME>END_PI's favorite move. Does base damage of 0.5, # Never very effective module.exports = class Sandal extends Move constructor: () -> super 'THROW SANDAL' getDamage: () -> return 1 use: (cb) -> super() Thrown = require 'effects/thrown.coffee' if @user.has('THROWN 1 SANDAL') @user.removeStatus('THROWN 1 SANDAL') @user.addStatus(new Thrown(2)) @target.damage(@getDamage() * 2) @announce cb, @user.name + ' has thrown their other sandal! It\'s super effective!' else if @user.has('THROWN 2 SANDALS') @announce cb, 'But ' + @user.name + ' is out of sandals and has none to throw!' else @user.addStatus(new Thrown (1)) @target.damage(@getDamage()) @announce cb, @user.name + ' throws one flip flop at ' + @target.name
[ { "context": "cheCode: 'GC12345'\n Finder: UserName: 'Foobar'\n LogType: WptLogTypeId: 2\n ", "end": 644, "score": 0.9994658827781677, "start": 638, "tag": "USERNAME", "value": "Foobar" }, { "context": "ess.env.DB_USER ? 'postgres'\n password: process.env.DB_PASSWORD\n database: process.env.DB ? 'gc'\n\n ", "end": 1411, "score": 0.9862216711044312, "start": 1388, "tag": "PASSWORD", "value": "process.env.DB_PASSWORD" }, { "context": "l}/logs/latest\"\n .query username: 'Foobar'\n .set 'Accept', 'application/json", "end": 2466, "score": 0.9996583461761475, "start": 2460, "tag": "USERNAME", "value": "Foobar" }, { "context": "l}/logs/latest\"\n .query username: 'foOBar'\n .set 'Accept', 'application/json", "end": 2898, "score": 0.999692440032959, "start": 2892, "tag": "USERNAME", "value": "foOBar" }, { "context": "ogs/latest\"\n .query username: 'nobody'\n .set 'Accept', 'application/", "end": 3594, "score": 0.9996079206466675, "start": 3588, "tag": "USERNAME", "value": "nobody" } ]
storage/test/integration-geolog.coffee
foobert/gc
1
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geologService = require '../lib/geolog' describe 'REST routes for logs', -> @timeout 15000 db = null token = null url = null setupTestData = Promise.coroutine (geologs) -> geologs = JSON.parse JSON.stringify geologs g = geologService db yield g.deleteAll() for geolog in geologs yield g.upsert geolog gl = (id, options) -> defaults = Code: "GL#{id}" CacheCode: 'GC12345' Finder: UserName: 'Foobar' LogType: WptLogTypeId: 2 UTCCreateDate: '/Date(1431813667662)/' VisitDate: '/Date(1431889200000-0700)/' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: process.env.DB_PASSWORD database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 10 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe 'GET /logs/latest', -> it 'should get the latest log for the given username', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' b = gl '101', VisitDate: '/Date(1421889200000-0700)/' yield setupTestData [a, b] response = yield request.get "#{url}/logs/latest" .query username: 'Foobar' .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should accept the username in any case', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .query username: 'foOBar' .set 'Accept', 'application/json' expect(response.text).to.equal 'GL100' it 'should return the latest if no username is given', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should return 404 if no logs can be found', Promise.coroutine -> try yield request.get "#{url}/logs/latest" .query username: 'nobody' .set 'Accept', 'application/json' expect(true, 'expected an error').to.be.false catch err expect(err.status).to.equal 404 describe 'POST /log', -> it 'should create a new log', Promise.coroutine -> a = gl '100' yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = \'gl100\'' finally done() expect(result.rowCount).to.equal 1 expect(result.rows[0].data).to.deep.equal a it 'should return 201', Promise.coroutine -> a = gl '100' response = yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a expect(response.status).to.equal 201
126353
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geologService = require '../lib/geolog' describe 'REST routes for logs', -> @timeout 15000 db = null token = null url = null setupTestData = Promise.coroutine (geologs) -> geologs = JSON.parse JSON.stringify geologs g = geologService db yield g.deleteAll() for geolog in geologs yield g.upsert geolog gl = (id, options) -> defaults = Code: "GL#{id}" CacheCode: 'GC12345' Finder: UserName: 'Foobar' LogType: WptLogTypeId: 2 UTCCreateDate: '/Date(1431813667662)/' VisitDate: '/Date(1431889200000-0700)/' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: <PASSWORD> database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 10 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe 'GET /logs/latest', -> it 'should get the latest log for the given username', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' b = gl '101', VisitDate: '/Date(1421889200000-0700)/' yield setupTestData [a, b] response = yield request.get "#{url}/logs/latest" .query username: 'Foobar' .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should accept the username in any case', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .query username: 'foOBar' .set 'Accept', 'application/json' expect(response.text).to.equal 'GL100' it 'should return the latest if no username is given', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should return 404 if no logs can be found', Promise.coroutine -> try yield request.get "#{url}/logs/latest" .query username: 'nobody' .set 'Accept', 'application/json' expect(true, 'expected an error').to.be.false catch err expect(err.status).to.equal 404 describe 'POST /log', -> it 'should create a new log', Promise.coroutine -> a = gl '100' yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = \'gl100\'' finally done() expect(result.rowCount).to.equal 1 expect(result.rows[0].data).to.deep.equal a it 'should return 201', Promise.coroutine -> a = gl '100' response = yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a expect(response.status).to.equal 201
true
{expect} = require 'chai' Promise = require 'bluebird' request = require 'superagent-as-promised' access = require '../lib/access' geologService = require '../lib/geolog' describe 'REST routes for logs', -> @timeout 15000 db = null token = null url = null setupTestData = Promise.coroutine (geologs) -> geologs = JSON.parse JSON.stringify geologs g = geologService db yield g.deleteAll() for geolog in geologs yield g.upsert geolog gl = (id, options) -> defaults = Code: "GL#{id}" CacheCode: 'GC12345' Finder: UserName: 'Foobar' LogType: WptLogTypeId: 2 UTCCreateDate: '/Date(1431813667662)/' VisitDate: '/Date(1431889200000-0700)/' merge = (a, b) -> return a unless b? for k, v of b if typeof v is 'object' a[k] = {} unless a[k]? merge a[k], v else a[k] = v a merge defaults, options before Promise.coroutine -> url = "http://#{process.env.APP_PORT_8081_TCP_ADDR}:#{process.env.APP_PORT_8081_TCP_PORT}" db = require('../lib/db') host: process.env.DB_PORT_5432_TCP_ADDR ? 'localhost' user: process.env.DB_USER ? 'postgres' password: PI:PASSWORD:<PASSWORD>END_PI database: process.env.DB ? 'gc' a = access db token = yield a.getToken() tries = 10 appRunning = false while tries-- > 0 try response = yield request.get url if response.status is 200 console.log "found app at #{url}" appRunning = true break yield Promise.delay 1000 catch err yield Promise.delay 1000 if not appRunning throw new Error "App is not running at #{url}" beforeEach Promise.coroutine -> yield setupTestData [] describe 'GET /logs/latest', -> it 'should get the latest log for the given username', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' b = gl '101', VisitDate: '/Date(1421889200000-0700)/' yield setupTestData [a, b] response = yield request.get "#{url}/logs/latest" .query username: 'Foobar' .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should accept the username in any case', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .query username: 'foOBar' .set 'Accept', 'application/json' expect(response.text).to.equal 'GL100' it 'should return the latest if no username is given', Promise.coroutine -> a = gl '100', VisitDate: '/Date(1431889200000-0700)/' yield setupTestData [a] response = yield request.get "#{url}/logs/latest" .set 'Accept', 'application/json' expect(response.status).to.equal 200 expect(response.text).to.equal 'GL100' it 'should return 404 if no logs can be found', Promise.coroutine -> try yield request.get "#{url}/logs/latest" .query username: 'nobody' .set 'Accept', 'application/json' expect(true, 'expected an error').to.be.false catch err expect(err.status).to.equal 404 describe 'POST /log', -> it 'should create a new log', Promise.coroutine -> a = gl '100' yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a [client, done] = yield db.connect() try result = yield client.queryAsync 'SELECT data FROM logs WHERE lower(id) = \'gl100\'' finally done() expect(result.rowCount).to.equal 1 expect(result.rows[0].data).to.deep.equal a it 'should return 201', Promise.coroutine -> a = gl '100' response = yield request .post "#{url}/log" .set 'Content-Type', 'application/json' .set 'X-Token', token .send a expect(response.status).to.equal 201
[ { "context": "#\n# Created by Simba on 9/29/15.\n#\n\npostFontStyleDefault='font-size:la", "end": 20, "score": 0.9948605298995972, "start": 15, "tag": "NAME", "value": "Simba" } ]
hotShareWeb/client/posts/0_showPostsStyle.coffee
fay1986/mobile_app_server
4
# # Created by Simba on 9/29/15. # postFontStyleDefault='font-size:large;'; postFontStyleNormal='font-size:large;'; postFontStyleQuota='font-size:15px;background:#F5F5F5;padding-left:3%;padding-right:3%;color:grey;'; @calcTextItemStyle = (layoutObj)-> fontStyle = postFontStyleDefault alignStyle = 'text-align:left;' if layoutObj if layoutObj.font if layoutObj.font is 'normal' fontStyle=postFontStyleNormal else if layoutObj.font is 'quota' fontStyle=postFontStyleQuota if layoutObj.align if layoutObj.align is 'right' alignStyle = "text-align:right;" else if layoutObj.align is 'center' alignStyle = "text-align:center;" if layoutObj.weight alignStyle = "font-weight:"+layoutObj.weight+";" fontStyle+alignStyle
66432
# # Created by <NAME> on 9/29/15. # postFontStyleDefault='font-size:large;'; postFontStyleNormal='font-size:large;'; postFontStyleQuota='font-size:15px;background:#F5F5F5;padding-left:3%;padding-right:3%;color:grey;'; @calcTextItemStyle = (layoutObj)-> fontStyle = postFontStyleDefault alignStyle = 'text-align:left;' if layoutObj if layoutObj.font if layoutObj.font is 'normal' fontStyle=postFontStyleNormal else if layoutObj.font is 'quota' fontStyle=postFontStyleQuota if layoutObj.align if layoutObj.align is 'right' alignStyle = "text-align:right;" else if layoutObj.align is 'center' alignStyle = "text-align:center;" if layoutObj.weight alignStyle = "font-weight:"+layoutObj.weight+";" fontStyle+alignStyle
true
# # Created by PI:NAME:<NAME>END_PI on 9/29/15. # postFontStyleDefault='font-size:large;'; postFontStyleNormal='font-size:large;'; postFontStyleQuota='font-size:15px;background:#F5F5F5;padding-left:3%;padding-right:3%;color:grey;'; @calcTextItemStyle = (layoutObj)-> fontStyle = postFontStyleDefault alignStyle = 'text-align:left;' if layoutObj if layoutObj.font if layoutObj.font is 'normal' fontStyle=postFontStyleNormal else if layoutObj.font is 'quota' fontStyle=postFontStyleQuota if layoutObj.align if layoutObj.align is 'right' alignStyle = "text-align:right;" else if layoutObj.align is 'center' alignStyle = "text-align:center;" if layoutObj.weight alignStyle = "font-weight:"+layoutObj.weight+";" fontStyle+alignStyle
[ { "context": "key: 'name'\n schema.keyed_params('2123123', 'fred').should.eql Key: {identifier: '2123123', name: '", "end": 1759, "score": 0.9909106492996216, "start": 1755, "tag": "NAME", "value": "fred" }, { "context": "').should.eql Key: {identifier: '2123123', name: 'fred'}\n\n it 'should handle simple key with range an", "end": 1813, "score": 0.9976235628128052, "start": 1809, "tag": "NAME", "value": "fred" }, { "context": "key: 'name'\n schema.keyed_params('2123123', 'fred', {foo: 'bar'}).should.eql Key: {identifier: '212", "end": 1990, "score": 0.9973019361495972, "start": 1986, "tag": "NAME", "value": "fred" }, { "context": "}).should.eql Key: {identifier: '2123123', name: 'fred'}, foo: 'bar'\n\n it 'should handle object key n", "end": 2058, "score": 0.9990431070327759, "start": 2054, "tag": "NAME", "value": "fred" }, { "context": "schema.keyed_params(identifier: '2123123', name: 'fred').should.eql Key: {identifier: '2123123', name: '", "end": 2662, "score": 0.9995040893554688, "start": 2658, "tag": "NAME", "value": "fred" }, { "context": "').should.eql Key: {identifier: '2123123', name: 'fred'}\n\n it 'should handle object key with range an", "end": 2716, "score": 0.9994901418685913, "start": 2712, "tag": "NAME", "value": "fred" }, { "context": "schema.keyed_params(identifier: '2123123', name: 'fred', {foo: 'bar'}).should.eql Key: {identifier: '212", "end": 2911, "score": 0.999629020690918, "start": 2907, "tag": "NAME", "value": "fred" }, { "context": "}).should.eql Key: {identifier: '2123123', name: 'fred'}, foo: 'bar'\n\n describe '.key_for', ->\n\n it ", "end": 2979, "score": 0.9995272755622864, "start": 2975, "tag": "NAME", "value": "fred" } ]
test/key_schema_tests.coffee
JohnnyDevMode/fireball
0
KeySchema = require '../src/key_schema' keygen = require 'keygen' describe 'Key Schema Tests', -> describe '@constructor', -> it 'should default hash_key and size', -> schema = new KeySchema() schema.hash.should.eql 'identifier' schema.size.should.eql keygen.large it 'should take hash_key and default size', -> schema = new KeySchema hash_key: 'some_key' console.log schema schema.hash.should.eql 'some_key' schema.size.should.eql keygen.large it 'should take hash_key and range and default size', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key' schema.range.should.eql 'other_key' schema.size.should.eql keygen.large it 'should take hash_key, range and size and default auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small schema.size.should.eql keygen.small schema.auto.should.eql true it 'should take hash_key, range, size and auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small, generate_hash_key: false schema.auto.should.eql false describe '.keyed_params', -> it 'should handle simple key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123').should.eql Key: identifier: '2123123' it 'should handle simple key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle simple key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', 'fred').should.eql Key: {identifier: '2123123', name: 'fred'} it 'should handle simple key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', 'fred', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: 'fred'}, foo: 'bar' it 'should handle object key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123').should.eql {Key: identifier: '2123123'} it 'should handle object key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle object key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: 'fred').should.eql Key: {identifier: '2123123', name: 'fred'} it 'should handle object key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: 'fred', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: 'fred'}, foo: 'bar' describe '.key_for', -> it 'should extract key from item no range', -> schema = new KeySchema hash_key: 'identifier' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item, 'identifier' key.should.eql identifier: '12312' it 'should extract key from item with range', -> schema = new KeySchema hash_key: 'foo', range_key: 'baz' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item key.should.eql foo: 'bar', baz: 'quk' it 'should use proided hash value', -> schema = new KeySchema hash_key: 'identifier' key = schema.key_for '12312', 'identifier' key.should.eql identifier: '12312'
186014
KeySchema = require '../src/key_schema' keygen = require 'keygen' describe 'Key Schema Tests', -> describe '@constructor', -> it 'should default hash_key and size', -> schema = new KeySchema() schema.hash.should.eql 'identifier' schema.size.should.eql keygen.large it 'should take hash_key and default size', -> schema = new KeySchema hash_key: 'some_key' console.log schema schema.hash.should.eql 'some_key' schema.size.should.eql keygen.large it 'should take hash_key and range and default size', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key' schema.range.should.eql 'other_key' schema.size.should.eql keygen.large it 'should take hash_key, range and size and default auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small schema.size.should.eql keygen.small schema.auto.should.eql true it 'should take hash_key, range, size and auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small, generate_hash_key: false schema.auto.should.eql false describe '.keyed_params', -> it 'should handle simple key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123').should.eql Key: identifier: '2123123' it 'should handle simple key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle simple key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', '<NAME>').should.eql Key: {identifier: '2123123', name: '<NAME>'} it 'should handle simple key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', '<NAME>', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: '<NAME>'}, foo: 'bar' it 'should handle object key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123').should.eql {Key: identifier: '2123123'} it 'should handle object key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle object key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: '<NAME>').should.eql Key: {identifier: '2123123', name: '<NAME>'} it 'should handle object key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: '<NAME>', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: '<NAME>'}, foo: 'bar' describe '.key_for', -> it 'should extract key from item no range', -> schema = new KeySchema hash_key: 'identifier' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item, 'identifier' key.should.eql identifier: '12312' it 'should extract key from item with range', -> schema = new KeySchema hash_key: 'foo', range_key: 'baz' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item key.should.eql foo: 'bar', baz: 'quk' it 'should use proided hash value', -> schema = new KeySchema hash_key: 'identifier' key = schema.key_for '12312', 'identifier' key.should.eql identifier: '12312'
true
KeySchema = require '../src/key_schema' keygen = require 'keygen' describe 'Key Schema Tests', -> describe '@constructor', -> it 'should default hash_key and size', -> schema = new KeySchema() schema.hash.should.eql 'identifier' schema.size.should.eql keygen.large it 'should take hash_key and default size', -> schema = new KeySchema hash_key: 'some_key' console.log schema schema.hash.should.eql 'some_key' schema.size.should.eql keygen.large it 'should take hash_key and range and default size', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key' schema.range.should.eql 'other_key' schema.size.should.eql keygen.large it 'should take hash_key, range and size and default auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small schema.size.should.eql keygen.small schema.auto.should.eql true it 'should take hash_key, range, size and auto ', -> schema = new KeySchema hash_key: 'some_key', range_key: 'other_key', key_size: keygen.small, generate_hash_key: false schema.auto.should.eql false describe '.keyed_params', -> it 'should handle simple key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123').should.eql Key: identifier: '2123123' it 'should handle simple key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params('2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle simple key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', 'PI:NAME:<NAME>END_PI').should.eql Key: {identifier: '2123123', name: 'PI:NAME:<NAME>END_PI'} it 'should handle simple key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params('2123123', 'PI:NAME:<NAME>END_PI', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: 'PI:NAME:<NAME>END_PI'}, foo: 'bar' it 'should handle object key no params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123').should.eql {Key: identifier: '2123123'} it 'should handle object key with params', -> schema = new KeySchema hash_key: 'identifier' schema.keyed_params(identifier: '2123123', {foo: 'bar'}).should.eql Key: {identifier: '2123123'}, foo: 'bar' it 'should handle object key with range', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: 'PI:NAME:<NAME>END_PI').should.eql Key: {identifier: '2123123', name: 'PI:NAME:<NAME>END_PI'} it 'should handle object key with range and params', -> schema = new KeySchema hash_key: 'identifier', range_key: 'name' schema.keyed_params(identifier: '2123123', name: 'PI:NAME:<NAME>END_PI', {foo: 'bar'}).should.eql Key: {identifier: '2123123', name: 'PI:NAME:<NAME>END_PI'}, foo: 'bar' describe '.key_for', -> it 'should extract key from item no range', -> schema = new KeySchema hash_key: 'identifier' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item, 'identifier' key.should.eql identifier: '12312' it 'should extract key from item with range', -> schema = new KeySchema hash_key: 'foo', range_key: 'baz' item = identifier: '12312', foo: 'bar', baz: 'quk' key = schema.key_for item key.should.eql foo: 'bar', baz: 'quk' it 'should use proided hash value', -> schema = new KeySchema hash_key: 'identifier' key = schema.key_for '12312', 'identifier' key.should.eql identifier: '12312'
[ { "context": " context =\n user:\n name: 'bouzuya'\n email: 'm@bouzuya.net'\n expec", "end": 1737, "score": 0.9366351962089539, "start": 1730, "tag": "USERNAME", "value": "bouzuya" }, { "context": ":\n name: 'bouzuya'\n email: 'm@bouzuya.net'\n expected = [\n tag: 'p'\n ", "end": 1772, "score": 0.9999260902404785, "start": 1759, "tag": "EMAIL", "value": "m@bouzuya.net" }, { "context": " class: 'user-email'\n children: ['m@bouzuya.net']\n ]\n ]\n template = bHtml ", "end": 2115, "score": 0.9999257326126099, "start": 2102, "tag": "EMAIL", "value": "m@bouzuya.net" }, { "context": " empty: []\n users: [\n name: 'bouzuya'\n ,\n name: 'emanon001'\n ", "end": 7025, "score": 0.851412832736969, "start": 7018, "tag": "NAME", "value": "bouzuya" }, { "context": " name: 'bouzuya'\n ,\n name: 'emanon001'\n ]\n expected = [\n tag: ", "end": 7067, "score": 0.9996616244316101, "start": 7058, "tag": "USERNAME", "value": "emanon001" }, { "context": " class: 'user-name'\n children: ['bouzuya']\n ]\n ,\n tag: 'p'\n ", "end": 7293, "score": 0.8190854787826538, "start": 7286, "tag": "NAME", "value": "bouzuya" }, { "context": " class: 'user-name'\n children: ['emanon001']\n ]\n ]\n template = bHtml ", "end": 7511, "score": 0.9996999502182007, "start": 7502, "tag": "USERNAME", "value": "emanon001" }, { "context": " context =\n user:\n name: 'bouzuya'\n expected = [\n tag: 'p'\n ", "end": 8300, "score": 0.5449895262718201, "start": 8299, "tag": "USERNAME", "value": "b" }, { "context": " context =\n user:\n name: 'bouzuya'\n expected = [\n tag: 'p'\n ", "end": 8302, "score": 0.5685154795646667, "start": 8300, "tag": "NAME", "value": "ou" }, { "context": " context =\n user:\n name: 'bouzuya'\n expected = [\n tag: 'p'\n ", "end": 8304, "score": 0.6428616046905518, "start": 8302, "tag": "USERNAME", "value": "zu" }, { "context": "context =\n user:\n name: 'bouzuya'\n expected = [\n tag: 'p'\n ", "end": 8306, "score": 0.7234796285629272, "start": 8304, "tag": "NAME", "value": "ya" }, { "context": " class: 'user-name'\n children: ['bouzuya']\n ]\n ]\n template = bHtml ", "end": 8520, "score": 0.7474446296691895, "start": 8513, "tag": "NAME", "value": "bouzuya" } ]
test/index-test.coffee
b-html/mithril-b-html-plus
1
assert = require 'power-assert' sinon = require 'sinon' bHtml = require './' describe 'index', -> beforeEach -> @sinon = sinon.sandbox.create() afterEach -> @sinon.restore() context 'comment', -> context 'simple', -> it 'works', -> source = ''' <!-- hoge ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p <!-- hoge ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'doctype', -> context 'simple', -> it 'works', -> source = ''' <!doctype html ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> # no tests context 'element', -> context 'simple', -> it 'works', -> source = ''' <p ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name <span @class user-email @b-text user.email ''' context = user: name: 'bouzuya' email: 'm@bouzuya.net' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['bouzuya'] , tag: 'span' attrs: class: 'user-email' children: ['m@bouzuya.net'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'empty element', -> context 'simple', -> it 'works', -> source = ''' </img ''' context = {} expected = [ tag: 'img' attrs: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-repeat i in images @b-attr src: i.src ''' context = images: [ src: '/images/1.png' , src: '/images/2.png' ] expected = [ tag: 'img' attrs: src: '/images/1.png' , tag: 'img' attrs: src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context 'new line text', -> context 'simple', -> it 'works', -> source = ''' |text ''' context = {} expected = ['\ntext'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' |line1 <p |line2 |line3 ''' context = {} expected = [ '\nline1' tag: 'p' attrs: {} children: [ '\nline2' '\nline3' ] ] template = bHtml source assert.deepEqual template(context), expected context 'text', -> context 'simple', -> it 'works', -> source = ''' text ''' context = {} expected = ['text'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' line1 >@line2 <p >|line3 ''' context = {} expected = [ 'line1' '@line2' tag: 'p' attrs: {} children: [ '|line3' ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-attr', -> context 'simple', -> it 'works', -> source = ''' </img @b-attr src: src ''' context = src: '/images/1.png' expected = [ tag: 'img' attrs: src: '/images/1.png' ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-attr alt: image.alt, src: image.src ''' context = image: alt: 'sample' src: '/images/2.png' expected = [ tag: 'img' attrs: alt: 'sample' src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context.skip '@b-html', -> it 'doesn\'t work', -> assert.fail() context '@b-if', -> context 'simple', -> it 'works', -> source = ''' <p @b-if isShow ''' context = isShow: false expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-if parent <span @b-if child hide show ''' context = parent: true child: false expected = [ tag: 'p' attrs: {} children: ['show'] ] template = bHtml source assert.deepEqual template(context), expected context '@b-repeat', -> context 'simple', -> it 'works', -> source = ''' <p @b-repeat message in messages @b-text message ''' context = messages: [ 'hello' 'world' ] expected = [ tag: 'p' attrs: {} children: ['hello'] , tag: 'p' attrs: {} children: ['world'] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-repeat i in empty <p @class user @b-repeat user in users <span @class user-name @b-text user.name dummy text ''' context = empty: [] users: [ name: 'bouzuya' , name: 'emanon001' ] expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['bouzuya'] ] , tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['emanon001'] ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-text', -> context 'simple', -> it 'works', -> source = ''' <p @b-text message ''' context = message: 'hello!' expected = [ tag: 'p' attrs: {} children: [ 'hello!' ] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name dummy text ''' context = user: name: 'bouzuya' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['bouzuya'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'mithril.component', -> context 'simple', -> it 'works', -> dummy = {} MyComponent = view: -> source = ''' <my-component ''' context = mithril: component: @sinon.stub().returns(dummy) 'my-component': MyComponent expected = [dummy] template = bHtml source assert.deepEqual template(context), expected component = context.mithril.component assert component.callCount is 1 assert component.getCall(0).args[0] is MyComponent assert.deepEqual component.getCall(0).args[1], {} context.skip 'complex', -> it 'doesn\'t works', -> # TODO: nested component
215284
assert = require 'power-assert' sinon = require 'sinon' bHtml = require './' describe 'index', -> beforeEach -> @sinon = sinon.sandbox.create() afterEach -> @sinon.restore() context 'comment', -> context 'simple', -> it 'works', -> source = ''' <!-- hoge ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p <!-- hoge ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'doctype', -> context 'simple', -> it 'works', -> source = ''' <!doctype html ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> # no tests context 'element', -> context 'simple', -> it 'works', -> source = ''' <p ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name <span @class user-email @b-text user.email ''' context = user: name: 'bouzuya' email: '<EMAIL>' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['bouzuya'] , tag: 'span' attrs: class: 'user-email' children: ['<EMAIL>'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'empty element', -> context 'simple', -> it 'works', -> source = ''' </img ''' context = {} expected = [ tag: 'img' attrs: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-repeat i in images @b-attr src: i.src ''' context = images: [ src: '/images/1.png' , src: '/images/2.png' ] expected = [ tag: 'img' attrs: src: '/images/1.png' , tag: 'img' attrs: src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context 'new line text', -> context 'simple', -> it 'works', -> source = ''' |text ''' context = {} expected = ['\ntext'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' |line1 <p |line2 |line3 ''' context = {} expected = [ '\nline1' tag: 'p' attrs: {} children: [ '\nline2' '\nline3' ] ] template = bHtml source assert.deepEqual template(context), expected context 'text', -> context 'simple', -> it 'works', -> source = ''' text ''' context = {} expected = ['text'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' line1 >@line2 <p >|line3 ''' context = {} expected = [ 'line1' '@line2' tag: 'p' attrs: {} children: [ '|line3' ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-attr', -> context 'simple', -> it 'works', -> source = ''' </img @b-attr src: src ''' context = src: '/images/1.png' expected = [ tag: 'img' attrs: src: '/images/1.png' ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-attr alt: image.alt, src: image.src ''' context = image: alt: 'sample' src: '/images/2.png' expected = [ tag: 'img' attrs: alt: 'sample' src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context.skip '@b-html', -> it 'doesn\'t work', -> assert.fail() context '@b-if', -> context 'simple', -> it 'works', -> source = ''' <p @b-if isShow ''' context = isShow: false expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-if parent <span @b-if child hide show ''' context = parent: true child: false expected = [ tag: 'p' attrs: {} children: ['show'] ] template = bHtml source assert.deepEqual template(context), expected context '@b-repeat', -> context 'simple', -> it 'works', -> source = ''' <p @b-repeat message in messages @b-text message ''' context = messages: [ 'hello' 'world' ] expected = [ tag: 'p' attrs: {} children: ['hello'] , tag: 'p' attrs: {} children: ['world'] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-repeat i in empty <p @class user @b-repeat user in users <span @class user-name @b-text user.name dummy text ''' context = empty: [] users: [ name: '<NAME>' , name: 'emanon001' ] expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['<NAME>'] ] , tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['emanon001'] ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-text', -> context 'simple', -> it 'works', -> source = ''' <p @b-text message ''' context = message: 'hello!' expected = [ tag: 'p' attrs: {} children: [ 'hello!' ] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name dummy text ''' context = user: name: 'b<NAME>zu<NAME>' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['<NAME>'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'mithril.component', -> context 'simple', -> it 'works', -> dummy = {} MyComponent = view: -> source = ''' <my-component ''' context = mithril: component: @sinon.stub().returns(dummy) 'my-component': MyComponent expected = [dummy] template = bHtml source assert.deepEqual template(context), expected component = context.mithril.component assert component.callCount is 1 assert component.getCall(0).args[0] is MyComponent assert.deepEqual component.getCall(0).args[1], {} context.skip 'complex', -> it 'doesn\'t works', -> # TODO: nested component
true
assert = require 'power-assert' sinon = require 'sinon' bHtml = require './' describe 'index', -> beforeEach -> @sinon = sinon.sandbox.create() afterEach -> @sinon.restore() context 'comment', -> context 'simple', -> it 'works', -> source = ''' <!-- hoge ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p <!-- hoge ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'doctype', -> context 'simple', -> it 'works', -> source = ''' <!doctype html ''' context = {} expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> # no tests context 'element', -> context 'simple', -> it 'works', -> source = ''' <p ''' context = {} expected = [ tag: 'p' attrs: {} children: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name <span @class user-email @b-text user.email ''' context = user: name: 'bouzuya' email: 'PI:EMAIL:<EMAIL>END_PI' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['bouzuya'] , tag: 'span' attrs: class: 'user-email' children: ['PI:EMAIL:<EMAIL>END_PI'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'empty element', -> context 'simple', -> it 'works', -> source = ''' </img ''' context = {} expected = [ tag: 'img' attrs: [] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-repeat i in images @b-attr src: i.src ''' context = images: [ src: '/images/1.png' , src: '/images/2.png' ] expected = [ tag: 'img' attrs: src: '/images/1.png' , tag: 'img' attrs: src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context 'new line text', -> context 'simple', -> it 'works', -> source = ''' |text ''' context = {} expected = ['\ntext'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' |line1 <p |line2 |line3 ''' context = {} expected = [ '\nline1' tag: 'p' attrs: {} children: [ '\nline2' '\nline3' ] ] template = bHtml source assert.deepEqual template(context), expected context 'text', -> context 'simple', -> it 'works', -> source = ''' text ''' context = {} expected = ['text'] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' line1 >@line2 <p >|line3 ''' context = {} expected = [ 'line1' '@line2' tag: 'p' attrs: {} children: [ '|line3' ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-attr', -> context 'simple', -> it 'works', -> source = ''' </img @b-attr src: src ''' context = src: '/images/1.png' expected = [ tag: 'img' attrs: src: '/images/1.png' ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' </img @b-attr alt: image.alt, src: image.src ''' context = image: alt: 'sample' src: '/images/2.png' expected = [ tag: 'img' attrs: alt: 'sample' src: '/images/2.png' ] template = bHtml source assert.deepEqual template(context), expected context.skip '@b-html', -> it 'doesn\'t work', -> assert.fail() context '@b-if', -> context 'simple', -> it 'works', -> source = ''' <p @b-if isShow ''' context = isShow: false expected = [] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-if parent <span @b-if child hide show ''' context = parent: true child: false expected = [ tag: 'p' attrs: {} children: ['show'] ] template = bHtml source assert.deepEqual template(context), expected context '@b-repeat', -> context 'simple', -> it 'works', -> source = ''' <p @b-repeat message in messages @b-text message ''' context = messages: [ 'hello' 'world' ] expected = [ tag: 'p' attrs: {} children: ['hello'] , tag: 'p' attrs: {} children: ['world'] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @b-repeat i in empty <p @class user @b-repeat user in users <span @class user-name @b-text user.name dummy text ''' context = empty: [] users: [ name: 'PI:NAME:<NAME>END_PI' , name: 'emanon001' ] expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['PI:NAME:<NAME>END_PI'] ] , tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['emanon001'] ] ] template = bHtml source assert.deepEqual template(context), expected context '@b-text', -> context 'simple', -> it 'works', -> source = ''' <p @b-text message ''' context = message: 'hello!' expected = [ tag: 'p' attrs: {} children: [ 'hello!' ] ] template = bHtml source assert.deepEqual template(context), expected context 'complex', -> it 'works', -> source = ''' <p @class user <span @class user-name @b-text user.name dummy text ''' context = user: name: 'bPI:NAME:<NAME>END_PIzuPI:NAME:<NAME>END_PI' expected = [ tag: 'p' attrs: class: 'user' children: [ tag: 'span' attrs: class: 'user-name' children: ['PI:NAME:<NAME>END_PI'] ] ] template = bHtml source assert.deepEqual template(context), expected context 'mithril.component', -> context 'simple', -> it 'works', -> dummy = {} MyComponent = view: -> source = ''' <my-component ''' context = mithril: component: @sinon.stub().returns(dummy) 'my-component': MyComponent expected = [dummy] template = bHtml source assert.deepEqual template(context), expected component = context.mithril.component assert component.callCount is 1 assert component.getCall(0).args[0] is MyComponent assert.deepEqual component.getCall(0).args[1], {} context.skip 'complex', -> it 'doesn\'t works', -> # TODO: nested component
[ { "context": "character classes in regular expressions\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------", "end": 121, "score": 0.9997583627700806, "start": 102, "tag": "NAME", "value": "Ian Christian Myers" } ]
src/rules/no-empty-character-class.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to flag the use of empty character classes in regular expressions # @author Ian Christian Myers ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ### # plain-English description of the following regexp: # 0. `^` fix the match at the beginning of the string # 1. `\/`: the `/` that begins the regexp # 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following # 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) # 2.1. `\\.`: an escape sequence # 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty # 3. `\/` the `/` that ends the regexp # 4. `[gimuy]*`: optional regexp flags # 5. `$`: fix the match at the end of the string ### regex = /// ^ / ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* / [gimuys]* $ ///u justContentRegex = /// ^ ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* $ ///u withoutCommentLines = (regexChunk) -> regexChunk.replace /^\s*#.*$/m, '' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow empty character classes in regular expressions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-empty-character-class' schema: [] messages: unexpected: 'Empty class.' create: (context) -> sourceCode = context.getSourceCode() Literal: (node) -> token = sourceCode.getFirstToken node return unless token.type is 'RegularExpression' unless regex.test withoutCommentLines node.raw context.report {node, messageId: 'unexpected'} TemplateElement: (node) -> return unless ( node.value?.raw? and node.parent?.parent?.type is 'InterpolatedRegExpLiteral' ) unless justContentRegex.test withoutCommentLines node.value.raw context.report node: node.parent.parent, messageId: 'unexpected'
203058
###* # @fileoverview Rule to flag the use of empty character classes in regular expressions # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ### # plain-English description of the following regexp: # 0. `^` fix the match at the beginning of the string # 1. `\/`: the `/` that begins the regexp # 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following # 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) # 2.1. `\\.`: an escape sequence # 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty # 3. `\/` the `/` that ends the regexp # 4. `[gimuy]*`: optional regexp flags # 5. `$`: fix the match at the end of the string ### regex = /// ^ / ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* / [gimuys]* $ ///u justContentRegex = /// ^ ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* $ ///u withoutCommentLines = (regexChunk) -> regexChunk.replace /^\s*#.*$/m, '' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow empty character classes in regular expressions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-empty-character-class' schema: [] messages: unexpected: 'Empty class.' create: (context) -> sourceCode = context.getSourceCode() Literal: (node) -> token = sourceCode.getFirstToken node return unless token.type is 'RegularExpression' unless regex.test withoutCommentLines node.raw context.report {node, messageId: 'unexpected'} TemplateElement: (node) -> return unless ( node.value?.raw? and node.parent?.parent?.type is 'InterpolatedRegExpLiteral' ) unless justContentRegex.test withoutCommentLines node.value.raw context.report node: node.parent.parent, messageId: 'unexpected'
true
###* # @fileoverview Rule to flag the use of empty character classes in regular expressions # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ### # plain-English description of the following regexp: # 0. `^` fix the match at the beginning of the string # 1. `\/`: the `/` that begins the regexp # 2. `([^\\[]|\\.|\[([^\\\]]|\\.)+\])*`: regexp contents; 0 or more of the following # 2.0. `[^\\[]`: any character that's not a `\` or a `[` (anything but escape sequences and character classes) # 2.1. `\\.`: an escape sequence # 2.2. `\[([^\\\]]|\\.)+\]`: a character class that isn't empty # 3. `\/` the `/` that ends the regexp # 4. `[gimuy]*`: optional regexp flags # 5. `$`: fix the match at the end of the string ### regex = /// ^ / ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* / [gimuys]* $ ///u justContentRegex = /// ^ ( [^\\[] | \\[\S\s] | \[ ( [^\\\]] | \\. )+ \] )* $ ///u withoutCommentLines = (regexChunk) -> regexChunk.replace /^\s*#.*$/m, '' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow empty character classes in regular expressions' category: 'Possible Errors' recommended: yes url: 'https://eslint.org/docs/rules/no-empty-character-class' schema: [] messages: unexpected: 'Empty class.' create: (context) -> sourceCode = context.getSourceCode() Literal: (node) -> token = sourceCode.getFirstToken node return unless token.type is 'RegularExpression' unless regex.test withoutCommentLines node.raw context.report {node, messageId: 'unexpected'} TemplateElement: (node) -> return unless ( node.value?.raw? and node.parent?.parent?.type is 'InterpolatedRegExpLiteral' ) unless justContentRegex.test withoutCommentLines node.value.raw context.report node: node.parent.parent, messageId: 'unexpected'
[ { "context": " more'\n buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa'\n ", "end": 7702, "score": 0.992554783821106, "start": 7686, "tag": "USERNAME", "value": "skitzysandcastle" }, { "context": "y join?'\n buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa'\n ", "end": 9915, "score": 0.9646735191345215, "start": 9898, "tag": "USERNAME", "value": "@skitzysandcastle" }, { "context": "me more'\n buttonAction: 'https://medium.com/@skitzysandcastle/flitters-497f7c33aa96'\n }\n {\n re", "end": 10927, "score": 0.9547178745269775, "start": 10910, "tag": "USERNAME", "value": "@skitzysandcastle" }, { "context": "a taste'\n buttonAction: 'https://medium.com/@skitzysandcastle/the-era-of-lampshade-89594f16386c'\n }\n ", "end": 14964, "score": 0.995004415512085, "start": 14947, "tag": "USERNAME", "value": "@skitzysandcastle" }, { "context": " <Tickle inView={inView} to='https://medium.com/@skitzysandcastle'>\n# more\n# </Tickle>\n# </l.Centered>\n", "end": 21568, "score": 0.9993801116943359, "start": 21552, "tag": "USERNAME", "value": "skitzysandcastle" }, { "context": "/l.IntroText>\n# }\n# </l.Centered>\n#\n# export Jesus = (p) =>\n# [ref, inView] = useInView(threshold:", "end": 23319, "score": 0.9169760942459106, "start": 23314, "tag": "NAME", "value": "Jesus" } ]
app/components/Bopz/Mangina.coffee
samerce/flitandland
0
import React, {useRef, useEffect, useState, useLayoutEffect, useMemo, useCallback} from 'react' import MailingList from '../MailingList/it.coffee' import Player from 'react-player' import l from './styled' import * as c from '../../constants' import {useSprings} from 'react-spring' import {useDrag} from 'react-use-gesture' import {useInView} from 'react-intersection-observer' import {cx} from '../../utils/style' import useScreenSize from '../../hooks/useScreenSize.coffee' import useToggle from '../../hooks/useToggle.coffee' import useDelayedReveal from '../../hooks/useDelayedReveal.coffee' import useBus from '../../hooks/useBus.coffee' import {openInNewTab} from '../../utils/nav' BookUrl = 'https://www.amazon.com/gp/product/171000892X/' FlitterFormUrl = 'https://forms.gle/8mzToRg25jVfBLSP8' Image = (p) => {screenWidth, screenHeight} = useScreenSize() height = useMemo (=> screenHeight * .9), [screenHeight] root = p.root or 'commons/' <l.Image {...p} src={c.SRC_URL + root + p.name} className={cx [p.className]: yes, portrait: screenWidth < screenHeight, } fullHeight={height} /> VideoConfig = file: attributes: {preload: 'auto'} youtube: preload: yes playerVars: {modestbranding: yes, rel: no, controls: yes} Video = (p) => player = useRef() [playing, togglePlaying] = useToggle yes [didClickOnce, setDidClickOnce] = useState no {screenWidth} = useScreenSize() size = useMemo (=> width = if p.height then (16/9) * p.height else screenWidth * .85 height = if p.height then p.height else (9/16) * width {width, height} ), [screenWidth] url = if p.name then c.CDN_URL + 'videos/' + p.name + '.mp4' else p.url onClick = => if didClickOnce then togglePlaying() else setDidClickOnce yes <l.VideoRoot> <Player url={url} wrapper={l.Video} width={size.width} height={size.height} playing={p.inView and playing} playsinline muted={not didClickOnce} loop={yes} onClick={onClick} controls={didClickOnce} config={VideoConfig} ref={player} onPlay={=> player.current.getInternalPlayer().pauseVideo() if not p.inView} /> <l.VideoSoundPrompt className={cx hide: didClickOnce} onClick={onClick}> click for audio </l.VideoSoundPrompt> </l.VideoRoot> Tickle = (p) => [classes] = useDelayedReveal p.inView, p.delay || 4000 <l.more href={p.to} target='_blank' className={cx hide: not p.inView, [classes]: yes, [p.className]: yes }> {p.children} </l.more> useLoader = (doneCount) => [count, setCount] = useState 0 [loaded, setIsLoaded] = useState no increment = useCallback (=> if not loaded then setCount (c) => c + 1), [loaded] useLayoutEffect (=> setIsLoaded(yes) if count >= doneCount), [count] [loaded, increment] from = (x = 0) => x: x, y: 0 to = (delay = 0) => x: 0, y: 0, delay: delay OutNow = (p) => <l.OutNow onClick={=> cast 'book.openCheckout'} className={cx show: p.show} delay={p.delay}> <l.woo>new book</l.woo> <l.yow>out now</l.yow> </l.OutNow> Deck = (p) => [ref, inView] = useInView(threshold: .54) [loaded, markLoaded] = useLoader p.cards.length [mode, setMode] = useState 'intro' [topIndex, setTopIndex] = useState 0 [spins] = useState => p.cards.map => Math.random() * 4 * (if Math.random() > .5 then -1 else 1) {screenWidth, screenHeight} = useScreenSize() {buttonAction, buttonText} = p.cards[topIndex] numCards = p.cards.length incrementIndex = => setTopIndex (i) => (i + 1) % numCards decrementIndex = => setTopIndex (i) => ((i - 1) + numCards) % numCards goToNext = => currentTopIndex = +topIndex set (i) => {x: screenWidth * 1.3} if i is currentTopIndex after 200, => incrementIndex() set (i) => {x: 0} if i is currentTopIndex goToPrev = => prevIndex = ((topIndex - 1) + numCards) % numCards set (i) => {x: screenWidth * -1.3} if i is prevIndex after 200, => decrementIndex() set (i) => {x: 0} if i is prevIndex [props, set] = useSprings p.cards.length, (i) => from: from(screenWidth * 1.3) # handleDrag = ({ # args: [index], down, movement: [mx, my], direction: [xDir, yDir], velocity, touches # }) => # return if touches > 1 # # trigger = no # if not down and velocity > 0.2 # trigger = yes # after 200, => # incrementIndex() # set (i) => from() if index is i # # set (i) => # return unless index is i # x: if trigger then screenWidth * 1.3 * xDir * velocity else if down then mx else 0 # y: if trigger then screenHeight * 1.3 * yDir * velocity else if down then my else 0 # config: # friction: 50 # tension: 300 #if down then 200 else if trigger then 200 else 500 # withDrag = useDrag handleDrag, {axis: 'x'} cardDelay = (i) => (numCards - i - 1) * 324 + 500 curtainsUp = => setMode 'show' set (i) => to(cardDelay(i)) ga 'send', 'event', { eventCategory: 'deck' eventAction: 'view' eventLabel: p.id } useLayoutEffect (=> return if mode is 'show' return curtainsUp() if loaded and inView and mode is 'loading' timer = after (if p.id is 'book' then 2160 else 1080), => if loaded and inView and mode isnt 'show' then curtainsUp() else if inView then setMode 'loading' => timer.clear() ), [loaded, inView, mode] [covered, setCovered] = useState no useBus 'book.openCheckout': => setCovered yes 'book.closeCheckout': => setCovered no <l.Deck ref={ref} key={ref} id={p.id}> {if p.id is 'book' <OutNow show={mode is 'show'} delay={cardDelay(0)} /> } <l.Title className={cx loading: mode isnt 'show'}> {p.title()} <l.LoadingText>{p.loading() if mode isnt 'show'}</l.LoadingText> </l.Title> <l.CardRoot className={cx hide: mode isnt 'show' or not inView}> {props.map ({x, y, rot, scale}, thisIndex) => isTop = topIndex is thisIndex zIndex = if isTop then numCards else (numCards - (thisIndex - topIndex)) % numCards <l.Card key={thisIndex} spin={spins[thisIndex]} style={{x, y, zIndex}}> {p.cards[thisIndex].render({ markLoaded, disabled: not isTop or not inView or covered })} </l.Card> } </l.CardRoot> <l.ActionZone delay={cardDelay(0) + 500} className={cx hide: mode isnt 'show'}> <l.TinyAction onClick={goToPrev}><a>&lsaquo;</a></l.TinyAction> {if typeof buttonAction is 'function' <l.BigAction onClick={buttonAction}> <a>{buttonText}</a> </l.BigAction> else <l.BigAction> <a href={buttonAction} target='_blank'> {buttonText} </a> </l.BigAction> } <l.TinyAction onClick={goToNext}><a>&rsaquo;</a></l.TinyAction> </l.ActionZone> </l.Deck> export Book = => <Deck id='book' title={=> <div>drag queen&nbsp;<l.yow>in the</l.yow>&nbsp;white house</div>} loading={=> <>brushing some wigs...</>} cards={[ { render: (p) => <Image name='dqitwh cover mq.jpg' className='cover fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the new book' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='evolution'> <div> evolution cannot be stoppped<br/> long-shot drag queen runs for president<br/> and congress turns purple </div> </l.Pot> buttonText: 'read more' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] {screenWidth, screenHeight, shape} = useScreenSize() videoHeight = useMemo (=> if shape is 'landscape' then screenHeight * .5 else screenWidth * .9 * (9/16) ), [screenWidth, screenHeight] <Video url='https://www.youtube.com/watch?v=-VkMsRHsAmM' inView={not p.disabled} height={videoHeight} /> buttonText: 'i’m so in!' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='realness'> <div> it’s time for over-the-top <l.zon>realness</l.zon> to shock the <l.zon>conscience</l.zon> of our nation </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='back cover sd.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='girlish.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='child with sign.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'youtube' buttonAction: c.YouTubeUrl } { render: (p) => <Image name='merman 1.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='nonviolent revolution small.png' className='revo' onLoad={p.markLoaded} /> buttonText: 'i’m into it' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot> <MailingList disabled={p.disabled} /> </l.Pot> buttonText: 'why join?' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='scroll'> <img src={c.SRC_URL + 'commons/solwhite.png'} /> <div> scroll down for more </div> <div>▼</div> </l.Pot> buttonText: 'let’s go' buttonAction: => document.getElementById('scroll-root').scroll top: innerHeight, behavior: 'smooth' } ]} /> export Flitter = => <Deck id='flitter' title={=> <>flitters</>} loading={=> <>beading some heels...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='getpaid'> what if you could work<br /> anywhere, anytime,<br/> doing almost anything<br/> <l.zon>& get paid for it?</l.zon> </l.Pot> buttonText: 'tell me more' buttonAction: 'https://medium.com/@skitzysandcastle/flitters-497f7c33aa96' } { render: (p) => <Image name='glitterfaeries.jpg' onLoad={p.markLoaded} /> buttonText: 'roving art' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> imagine millions of flitters roaming america, being society’s antidepressant. that’s their job. stirring happiness & deescalating high-pressure situations. </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='flitsis.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='job'> <div> job description:<br/> <l.zon>spread joy & knowledge</l.zon> </div> </l.Pot> buttonText: 'i’m in' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] {screenHeight} = useScreenSize() videoHeight = useMemo (=> screenHeight * .5), [screenHeight] <l.Pot className='classrooms'> <div className='txtbox'> <l.zon>flitters</l.zon> open classrooms in the trenches </div> <Video url='https://www.youtube.com/watch?v=kWC957au5c8' inView={not p.disabled} height={videoHeight} /> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='tough'> <div> <l.zon>flitters</l.zon> facilitate tough dialogues<br/> with levity & light </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> offer yoga & meditation </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> play dress up & do makeovers </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => <Image name='mikeyfizzwhimzeh.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='rovingart'> <div> <l.zon>flitters</l.zon> pick up trash,<br/> plant trees,<br/> host events, <br/> raise vibes—<br/> they are roving <l.zon>creation!</l.zon> </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } ]} /> export Lampshade = => <Deck id='lampshade' title={=> <div>lampshade<l.yow> country club</l.yow></div>} loading={=> <>pulling some espresso...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitandland'> <div><l.zon>community&nbsp;</l.zon>meet<l.zon>&nbsp;commodity</l.zon></div> </l.Pot> buttonText: 'get a taste' buttonAction: 'https://medium.com/@skitzysandcastle/the-era-of-lampshade-89594f16386c' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='exist'> expansive public space to simply <l.zon>exist</l.zon> </l.Pot> buttonText: 'liberate the static' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='lampshade warm.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> public space where anyone from anywhere can go at any time for any reason whatever. we have a chance to make all people feel iconic. directly a part of it. in the heat. </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='lampshade.jpg' onLoad={p.markLoaded} /> buttonText: 'moooore' buttonAction: c.InstagramUrl } ]} /> export EymU = => <Deck id='eymu' title={=> <div>eym<l.yow>u</l.yow></div>} loading={=> <>solving some integrals...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='shock'> <div> mindful capitalism </div> </l.Pot> buttonText: 'read more' buttonAction: c.TwitterUrl } { render: (p) => <Image name='eym.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch volunteer'> <l.al>communally owned<br/>means of production</l.al> <div> maybe you donate two hours of sweeping the space every week and that’s how you get access. maybe you offer the temple space a guided meditation twice a week and that’s how you get access. maybe you’re a caretaker for the 7th floor glass-dome garden managing 200 weekly volunteers and that’s how you get access. maybe you’re rich as hell and give a million dollars.— </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='ice.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='hollywood'> <div> <l.zon>hollywood</l.zon> heads to the<br/> <l.zon>heartland</l.zon> </div> </l.Pot> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } ]} /> export Creation = => <Deck id='creation' title={=> <div>creation&nbsp;<l.yow>poetcards</l.yow></div>} loading={=> <>mixing some paint...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='whimsy'> <div> <l.zon>cling to your whimsy</l.zon> you are a delightful stimulant<br/> when in doubt, make art </div> </l.Pot> buttonText: 'etsy get some' buttonAction: c.EtsyUrl } { render: (p) => <Image name='dreams+of+lucy.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'bloom baby' buttonAction: c.EtsyUrl } { render: (p) => <Image name='the+flight+home.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'stick out' buttonAction: c.EtsyUrl } { render: (p) => <Image name='camus cabaret.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'it can only be right' buttonAction: c.EtsyUrl } { render: (p) => <Image name="moby's+dick.jpg" root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'collapse the dark' buttonAction: c.EtsyUrl } { render: (p) => <Image name='train+hoppin+charlie.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'peace, forget the rest' buttonAction: c.EtsyUrl } { render: (p) => <Image name='prance.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'when in doubt, prance' buttonAction: c.EtsyUrl } { render: (p) => <Image name='be+your+own+therapy.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be your own therapy' buttonAction: c.EtsyUrl } { render: (p) => <Image name='submerged+explorations.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'you are the guru' buttonAction: c.EtsyUrl } { render: (p) => <Image name='unicorn-merman.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be you' buttonAction: c.EtsyUrl } ]} /> export Footer = => <l.Centered className='bottom'> <div className='book-link'> <a onClick={=> cast 'book.openCheckout'}> get the new book! </a> </div> <a href={c.MediumUrl} target='_blank'> <i className='fab fa-medium-m' /> </a> <a href={c.InstagramUrl} target='_blank'> <i className='fab fa-instagram' /> </a> <a href={c.YouTubeUrl} target='_blank'> <i className='fab fa-youtube' /> </a> <a href={c.TwitterUrl} target='_blank'> <i className='fab fa-twitter' /> </a> <l.woo className='footer-brand'>express your mess</l.woo> </l.Centered> # export Mangina = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='mangina.jpg' className='fullHeight' /> # <Tickle inView={inView} # to='https://www.etsy.com/listing/674899618/men-from-mangina-modern-art-nude-print'> # get it # </Tickle> # </l.Centered> # export Yes = => # [ref, inView] = useInView(threshold: .54) # <l.Centered className='pong' ref={ref}> # <l.Pot> # emancipated lands of<l.zon>&nbsp;yes, and&nbsp;</l.zon>await you—<br/> # whole celestial realms outside the absurd world of no. # </l.Pot> # <Tickle inView={inView} to='https://medium.com/@skitzysandcastle'> # more # </Tickle> # </l.Centered> # # export Trump = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='trumpf.jpg' /> # <Tickle inView={inView} to='https://pixabay.com/users/tiburi-2851152/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1915273'> # tibor janosi mozes # </Tickle> # </l.Centered> # # export Waggle = => # <l.Centered className='ping'> # <l.Pot> # flicker flop ripple dart waggle waving loot—<br/> # wonderful hangs everywhere so i sample the fruit. # </l.Pot> # </l.Centered> # # export TJ = => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video url='https://www.youtube.com/watch?v=rmXjuF1GLK0' inView={inView} /> # </l.Centered> # # Texts = [ # {content: 'if 100 million of us put four quarters in our pocket every single day and gave them out to the first four people that wanted them, then $100 million a day would circulate into the hands of those who need a break.', delay: 0}, # {content: 'that’s $365 billion a year, one quarter at a time.', delay: 5000}, # # {content: 'power will tell you it’s hopeless. that the problems are too great to contemplate. that this is as good as it gets.', duration: 1000}, # # {content: 'it’s the lie of our lifetime.', duration: 1000}, # ] # export Intro = (p) => # [ref, inView] = useInView(threshold: .5, triggerOnce: yes) # delay = 0 # <l.Centered ref={ref} className='intro pong'> # {Texts.map (text) => # delay += text.delay # <l.IntroText delay={delay} className={cx show: inView}> # {text.content} # </l.IntroText> # } # </l.Centered> # # export Jesus = (p) => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video name='jubileeq' inView={inView} /> # </l.Centered> # # export Heart = => # <l.Centered className='pong'> # <l.Pot> # <l.zon>hollywood</l.zon> heads to the<l.zon>&nbsp;heartland</l.zon> # </l.Pot> # </l.Centered> # # export Revolution = => # <l.Centered> # <Image name='nonviolent revolution small.png' className='revo' /> # </l.Centered> # # # export Mitch = (p) => # <l.Centered> # <Image name='mitch.jpg' /> # </l.Centered> # # export Seed = => # <l.Centered className='pong'> # <l.Pot> # start with a single<l.zon>&nbsp;flitter</l.zon>. one seed.<br/> # an idea. sent out on the thimble of<l.zon>&nbsp;love</l.zon>.<br/> # an act of pure<l.zon>&nbsp;creation</l.zon>. # </l.Pot> # </l.Centered> # # export Eymboard = (p) => # <l.Centered> # <Image name='eymboard.jpg' /> # </l.Centered> # # export Whimsy = => # <l.Centered className='pong'> # <l.Pot> # cling to your<l.zon>&nbsp;whimsy,</l.zon><br/> # you are a delightful stimulant; <br/> # best deployed as stirring propaganda<br/> # that never loses sight of the sun. # </l.Pot> # </l.Centered> # # # export Sneakers = (p) => # <l.Centered className='sneakers'> # <Image name='sneakers.jpg' className='fullHeight' /> # </l.Centered> # # export Reborn = => # <l.Centered className='ping'> # <l.Pot> # whatever you call it:<br/> # <l.zon>get dislodged from the system</l.zon><br/><br/> # # freedom cost me everything<br/> # which turns out to be nothing at all<br/><br/> # # waking to yes will kill you—<br/> # and then you will be<l.zon>&nbsp;reborn</l.zon><br/><br/> # # i would get rid of everything<br/> # <l.yow>and <a href={BookUrl} target='_blank'>begin again</a>—</l.yow> # </l.Pot> # </l.Centered> # Intro.duration = 3000 # Mangina.duration = 1500 # Trump.duration = 1000 # PaintShow.duration = 15000 # Jesus.duration = 4000 # Mitch.duration = 2000 # Eymboard.duration = 10000 # Sneakers.duration = 5000 # LandingPage.duration = 0
195611
import React, {useRef, useEffect, useState, useLayoutEffect, useMemo, useCallback} from 'react' import MailingList from '../MailingList/it.coffee' import Player from 'react-player' import l from './styled' import * as c from '../../constants' import {useSprings} from 'react-spring' import {useDrag} from 'react-use-gesture' import {useInView} from 'react-intersection-observer' import {cx} from '../../utils/style' import useScreenSize from '../../hooks/useScreenSize.coffee' import useToggle from '../../hooks/useToggle.coffee' import useDelayedReveal from '../../hooks/useDelayedReveal.coffee' import useBus from '../../hooks/useBus.coffee' import {openInNewTab} from '../../utils/nav' BookUrl = 'https://www.amazon.com/gp/product/171000892X/' FlitterFormUrl = 'https://forms.gle/8mzToRg25jVfBLSP8' Image = (p) => {screenWidth, screenHeight} = useScreenSize() height = useMemo (=> screenHeight * .9), [screenHeight] root = p.root or 'commons/' <l.Image {...p} src={c.SRC_URL + root + p.name} className={cx [p.className]: yes, portrait: screenWidth < screenHeight, } fullHeight={height} /> VideoConfig = file: attributes: {preload: 'auto'} youtube: preload: yes playerVars: {modestbranding: yes, rel: no, controls: yes} Video = (p) => player = useRef() [playing, togglePlaying] = useToggle yes [didClickOnce, setDidClickOnce] = useState no {screenWidth} = useScreenSize() size = useMemo (=> width = if p.height then (16/9) * p.height else screenWidth * .85 height = if p.height then p.height else (9/16) * width {width, height} ), [screenWidth] url = if p.name then c.CDN_URL + 'videos/' + p.name + '.mp4' else p.url onClick = => if didClickOnce then togglePlaying() else setDidClickOnce yes <l.VideoRoot> <Player url={url} wrapper={l.Video} width={size.width} height={size.height} playing={p.inView and playing} playsinline muted={not didClickOnce} loop={yes} onClick={onClick} controls={didClickOnce} config={VideoConfig} ref={player} onPlay={=> player.current.getInternalPlayer().pauseVideo() if not p.inView} /> <l.VideoSoundPrompt className={cx hide: didClickOnce} onClick={onClick}> click for audio </l.VideoSoundPrompt> </l.VideoRoot> Tickle = (p) => [classes] = useDelayedReveal p.inView, p.delay || 4000 <l.more href={p.to} target='_blank' className={cx hide: not p.inView, [classes]: yes, [p.className]: yes }> {p.children} </l.more> useLoader = (doneCount) => [count, setCount] = useState 0 [loaded, setIsLoaded] = useState no increment = useCallback (=> if not loaded then setCount (c) => c + 1), [loaded] useLayoutEffect (=> setIsLoaded(yes) if count >= doneCount), [count] [loaded, increment] from = (x = 0) => x: x, y: 0 to = (delay = 0) => x: 0, y: 0, delay: delay OutNow = (p) => <l.OutNow onClick={=> cast 'book.openCheckout'} className={cx show: p.show} delay={p.delay}> <l.woo>new book</l.woo> <l.yow>out now</l.yow> </l.OutNow> Deck = (p) => [ref, inView] = useInView(threshold: .54) [loaded, markLoaded] = useLoader p.cards.length [mode, setMode] = useState 'intro' [topIndex, setTopIndex] = useState 0 [spins] = useState => p.cards.map => Math.random() * 4 * (if Math.random() > .5 then -1 else 1) {screenWidth, screenHeight} = useScreenSize() {buttonAction, buttonText} = p.cards[topIndex] numCards = p.cards.length incrementIndex = => setTopIndex (i) => (i + 1) % numCards decrementIndex = => setTopIndex (i) => ((i - 1) + numCards) % numCards goToNext = => currentTopIndex = +topIndex set (i) => {x: screenWidth * 1.3} if i is currentTopIndex after 200, => incrementIndex() set (i) => {x: 0} if i is currentTopIndex goToPrev = => prevIndex = ((topIndex - 1) + numCards) % numCards set (i) => {x: screenWidth * -1.3} if i is prevIndex after 200, => decrementIndex() set (i) => {x: 0} if i is prevIndex [props, set] = useSprings p.cards.length, (i) => from: from(screenWidth * 1.3) # handleDrag = ({ # args: [index], down, movement: [mx, my], direction: [xDir, yDir], velocity, touches # }) => # return if touches > 1 # # trigger = no # if not down and velocity > 0.2 # trigger = yes # after 200, => # incrementIndex() # set (i) => from() if index is i # # set (i) => # return unless index is i # x: if trigger then screenWidth * 1.3 * xDir * velocity else if down then mx else 0 # y: if trigger then screenHeight * 1.3 * yDir * velocity else if down then my else 0 # config: # friction: 50 # tension: 300 #if down then 200 else if trigger then 200 else 500 # withDrag = useDrag handleDrag, {axis: 'x'} cardDelay = (i) => (numCards - i - 1) * 324 + 500 curtainsUp = => setMode 'show' set (i) => to(cardDelay(i)) ga 'send', 'event', { eventCategory: 'deck' eventAction: 'view' eventLabel: p.id } useLayoutEffect (=> return if mode is 'show' return curtainsUp() if loaded and inView and mode is 'loading' timer = after (if p.id is 'book' then 2160 else 1080), => if loaded and inView and mode isnt 'show' then curtainsUp() else if inView then setMode 'loading' => timer.clear() ), [loaded, inView, mode] [covered, setCovered] = useState no useBus 'book.openCheckout': => setCovered yes 'book.closeCheckout': => setCovered no <l.Deck ref={ref} key={ref} id={p.id}> {if p.id is 'book' <OutNow show={mode is 'show'} delay={cardDelay(0)} /> } <l.Title className={cx loading: mode isnt 'show'}> {p.title()} <l.LoadingText>{p.loading() if mode isnt 'show'}</l.LoadingText> </l.Title> <l.CardRoot className={cx hide: mode isnt 'show' or not inView}> {props.map ({x, y, rot, scale}, thisIndex) => isTop = topIndex is thisIndex zIndex = if isTop then numCards else (numCards - (thisIndex - topIndex)) % numCards <l.Card key={thisIndex} spin={spins[thisIndex]} style={{x, y, zIndex}}> {p.cards[thisIndex].render({ markLoaded, disabled: not isTop or not inView or covered })} </l.Card> } </l.CardRoot> <l.ActionZone delay={cardDelay(0) + 500} className={cx hide: mode isnt 'show'}> <l.TinyAction onClick={goToPrev}><a>&lsaquo;</a></l.TinyAction> {if typeof buttonAction is 'function' <l.BigAction onClick={buttonAction}> <a>{buttonText}</a> </l.BigAction> else <l.BigAction> <a href={buttonAction} target='_blank'> {buttonText} </a> </l.BigAction> } <l.TinyAction onClick={goToNext}><a>&rsaquo;</a></l.TinyAction> </l.ActionZone> </l.Deck> export Book = => <Deck id='book' title={=> <div>drag queen&nbsp;<l.yow>in the</l.yow>&nbsp;white house</div>} loading={=> <>brushing some wigs...</>} cards={[ { render: (p) => <Image name='dqitwh cover mq.jpg' className='cover fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the new book' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='evolution'> <div> evolution cannot be stoppped<br/> long-shot drag queen runs for president<br/> and congress turns purple </div> </l.Pot> buttonText: 'read more' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] {screenWidth, screenHeight, shape} = useScreenSize() videoHeight = useMemo (=> if shape is 'landscape' then screenHeight * .5 else screenWidth * .9 * (9/16) ), [screenWidth, screenHeight] <Video url='https://www.youtube.com/watch?v=-VkMsRHsAmM' inView={not p.disabled} height={videoHeight} /> buttonText: 'i’m so in!' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='realness'> <div> it’s time for over-the-top <l.zon>realness</l.zon> to shock the <l.zon>conscience</l.zon> of our nation </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='back cover sd.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='girlish.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='child with sign.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'youtube' buttonAction: c.YouTubeUrl } { render: (p) => <Image name='merman 1.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='nonviolent revolution small.png' className='revo' onLoad={p.markLoaded} /> buttonText: 'i’m into it' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot> <MailingList disabled={p.disabled} /> </l.Pot> buttonText: 'why join?' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='scroll'> <img src={c.SRC_URL + 'commons/solwhite.png'} /> <div> scroll down for more </div> <div>▼</div> </l.Pot> buttonText: 'let’s go' buttonAction: => document.getElementById('scroll-root').scroll top: innerHeight, behavior: 'smooth' } ]} /> export Flitter = => <Deck id='flitter' title={=> <>flitters</>} loading={=> <>beading some heels...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='getpaid'> what if you could work<br /> anywhere, anytime,<br/> doing almost anything<br/> <l.zon>& get paid for it?</l.zon> </l.Pot> buttonText: 'tell me more' buttonAction: 'https://medium.com/@skitzysandcastle/flitters-497f7c33aa96' } { render: (p) => <Image name='glitterfaeries.jpg' onLoad={p.markLoaded} /> buttonText: 'roving art' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> imagine millions of flitters roaming america, being society’s antidepressant. that’s their job. stirring happiness & deescalating high-pressure situations. </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='flitsis.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='job'> <div> job description:<br/> <l.zon>spread joy & knowledge</l.zon> </div> </l.Pot> buttonText: 'i’m in' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] {screenHeight} = useScreenSize() videoHeight = useMemo (=> screenHeight * .5), [screenHeight] <l.Pot className='classrooms'> <div className='txtbox'> <l.zon>flitters</l.zon> open classrooms in the trenches </div> <Video url='https://www.youtube.com/watch?v=kWC957au5c8' inView={not p.disabled} height={videoHeight} /> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='tough'> <div> <l.zon>flitters</l.zon> facilitate tough dialogues<br/> with levity & light </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> offer yoga & meditation </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> play dress up & do makeovers </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => <Image name='mikeyfizzwhimzeh.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='rovingart'> <div> <l.zon>flitters</l.zon> pick up trash,<br/> plant trees,<br/> host events, <br/> raise vibes—<br/> they are roving <l.zon>creation!</l.zon> </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } ]} /> export Lampshade = => <Deck id='lampshade' title={=> <div>lampshade<l.yow> country club</l.yow></div>} loading={=> <>pulling some espresso...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitandland'> <div><l.zon>community&nbsp;</l.zon>meet<l.zon>&nbsp;commodity</l.zon></div> </l.Pot> buttonText: 'get a taste' buttonAction: 'https://medium.com/@skitzysandcastle/the-era-of-lampshade-89594f16386c' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='exist'> expansive public space to simply <l.zon>exist</l.zon> </l.Pot> buttonText: 'liberate the static' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='lampshade warm.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> public space where anyone from anywhere can go at any time for any reason whatever. we have a chance to make all people feel iconic. directly a part of it. in the heat. </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='lampshade.jpg' onLoad={p.markLoaded} /> buttonText: 'moooore' buttonAction: c.InstagramUrl } ]} /> export EymU = => <Deck id='eymu' title={=> <div>eym<l.yow>u</l.yow></div>} loading={=> <>solving some integrals...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='shock'> <div> mindful capitalism </div> </l.Pot> buttonText: 'read more' buttonAction: c.TwitterUrl } { render: (p) => <Image name='eym.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch volunteer'> <l.al>communally owned<br/>means of production</l.al> <div> maybe you donate two hours of sweeping the space every week and that’s how you get access. maybe you offer the temple space a guided meditation twice a week and that’s how you get access. maybe you’re a caretaker for the 7th floor glass-dome garden managing 200 weekly volunteers and that’s how you get access. maybe you’re rich as hell and give a million dollars.— </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='ice.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='hollywood'> <div> <l.zon>hollywood</l.zon> heads to the<br/> <l.zon>heartland</l.zon> </div> </l.Pot> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } ]} /> export Creation = => <Deck id='creation' title={=> <div>creation&nbsp;<l.yow>poetcards</l.yow></div>} loading={=> <>mixing some paint...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='whimsy'> <div> <l.zon>cling to your whimsy</l.zon> you are a delightful stimulant<br/> when in doubt, make art </div> </l.Pot> buttonText: 'etsy get some' buttonAction: c.EtsyUrl } { render: (p) => <Image name='dreams+of+lucy.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'bloom baby' buttonAction: c.EtsyUrl } { render: (p) => <Image name='the+flight+home.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'stick out' buttonAction: c.EtsyUrl } { render: (p) => <Image name='camus cabaret.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'it can only be right' buttonAction: c.EtsyUrl } { render: (p) => <Image name="moby's+dick.jpg" root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'collapse the dark' buttonAction: c.EtsyUrl } { render: (p) => <Image name='train+hoppin+charlie.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'peace, forget the rest' buttonAction: c.EtsyUrl } { render: (p) => <Image name='prance.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'when in doubt, prance' buttonAction: c.EtsyUrl } { render: (p) => <Image name='be+your+own+therapy.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be your own therapy' buttonAction: c.EtsyUrl } { render: (p) => <Image name='submerged+explorations.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'you are the guru' buttonAction: c.EtsyUrl } { render: (p) => <Image name='unicorn-merman.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be you' buttonAction: c.EtsyUrl } ]} /> export Footer = => <l.Centered className='bottom'> <div className='book-link'> <a onClick={=> cast 'book.openCheckout'}> get the new book! </a> </div> <a href={c.MediumUrl} target='_blank'> <i className='fab fa-medium-m' /> </a> <a href={c.InstagramUrl} target='_blank'> <i className='fab fa-instagram' /> </a> <a href={c.YouTubeUrl} target='_blank'> <i className='fab fa-youtube' /> </a> <a href={c.TwitterUrl} target='_blank'> <i className='fab fa-twitter' /> </a> <l.woo className='footer-brand'>express your mess</l.woo> </l.Centered> # export Mangina = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='mangina.jpg' className='fullHeight' /> # <Tickle inView={inView} # to='https://www.etsy.com/listing/674899618/men-from-mangina-modern-art-nude-print'> # get it # </Tickle> # </l.Centered> # export Yes = => # [ref, inView] = useInView(threshold: .54) # <l.Centered className='pong' ref={ref}> # <l.Pot> # emancipated lands of<l.zon>&nbsp;yes, and&nbsp;</l.zon>await you—<br/> # whole celestial realms outside the absurd world of no. # </l.Pot> # <Tickle inView={inView} to='https://medium.com/@skitzysandcastle'> # more # </Tickle> # </l.Centered> # # export Trump = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='trumpf.jpg' /> # <Tickle inView={inView} to='https://pixabay.com/users/tiburi-2851152/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1915273'> # tibor janosi mozes # </Tickle> # </l.Centered> # # export Waggle = => # <l.Centered className='ping'> # <l.Pot> # flicker flop ripple dart waggle waving loot—<br/> # wonderful hangs everywhere so i sample the fruit. # </l.Pot> # </l.Centered> # # export TJ = => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video url='https://www.youtube.com/watch?v=rmXjuF1GLK0' inView={inView} /> # </l.Centered> # # Texts = [ # {content: 'if 100 million of us put four quarters in our pocket every single day and gave them out to the first four people that wanted them, then $100 million a day would circulate into the hands of those who need a break.', delay: 0}, # {content: 'that’s $365 billion a year, one quarter at a time.', delay: 5000}, # # {content: 'power will tell you it’s hopeless. that the problems are too great to contemplate. that this is as good as it gets.', duration: 1000}, # # {content: 'it’s the lie of our lifetime.', duration: 1000}, # ] # export Intro = (p) => # [ref, inView] = useInView(threshold: .5, triggerOnce: yes) # delay = 0 # <l.Centered ref={ref} className='intro pong'> # {Texts.map (text) => # delay += text.delay # <l.IntroText delay={delay} className={cx show: inView}> # {text.content} # </l.IntroText> # } # </l.Centered> # # export <NAME> = (p) => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video name='jubileeq' inView={inView} /> # </l.Centered> # # export Heart = => # <l.Centered className='pong'> # <l.Pot> # <l.zon>hollywood</l.zon> heads to the<l.zon>&nbsp;heartland</l.zon> # </l.Pot> # </l.Centered> # # export Revolution = => # <l.Centered> # <Image name='nonviolent revolution small.png' className='revo' /> # </l.Centered> # # # export Mitch = (p) => # <l.Centered> # <Image name='mitch.jpg' /> # </l.Centered> # # export Seed = => # <l.Centered className='pong'> # <l.Pot> # start with a single<l.zon>&nbsp;flitter</l.zon>. one seed.<br/> # an idea. sent out on the thimble of<l.zon>&nbsp;love</l.zon>.<br/> # an act of pure<l.zon>&nbsp;creation</l.zon>. # </l.Pot> # </l.Centered> # # export Eymboard = (p) => # <l.Centered> # <Image name='eymboard.jpg' /> # </l.Centered> # # export Whimsy = => # <l.Centered className='pong'> # <l.Pot> # cling to your<l.zon>&nbsp;whimsy,</l.zon><br/> # you are a delightful stimulant; <br/> # best deployed as stirring propaganda<br/> # that never loses sight of the sun. # </l.Pot> # </l.Centered> # # # export Sneakers = (p) => # <l.Centered className='sneakers'> # <Image name='sneakers.jpg' className='fullHeight' /> # </l.Centered> # # export Reborn = => # <l.Centered className='ping'> # <l.Pot> # whatever you call it:<br/> # <l.zon>get dislodged from the system</l.zon><br/><br/> # # freedom cost me everything<br/> # which turns out to be nothing at all<br/><br/> # # waking to yes will kill you—<br/> # and then you will be<l.zon>&nbsp;reborn</l.zon><br/><br/> # # i would get rid of everything<br/> # <l.yow>and <a href={BookUrl} target='_blank'>begin again</a>—</l.yow> # </l.Pot> # </l.Centered> # Intro.duration = 3000 # Mangina.duration = 1500 # Trump.duration = 1000 # PaintShow.duration = 15000 # Jesus.duration = 4000 # Mitch.duration = 2000 # Eymboard.duration = 10000 # Sneakers.duration = 5000 # LandingPage.duration = 0
true
import React, {useRef, useEffect, useState, useLayoutEffect, useMemo, useCallback} from 'react' import MailingList from '../MailingList/it.coffee' import Player from 'react-player' import l from './styled' import * as c from '../../constants' import {useSprings} from 'react-spring' import {useDrag} from 'react-use-gesture' import {useInView} from 'react-intersection-observer' import {cx} from '../../utils/style' import useScreenSize from '../../hooks/useScreenSize.coffee' import useToggle from '../../hooks/useToggle.coffee' import useDelayedReveal from '../../hooks/useDelayedReveal.coffee' import useBus from '../../hooks/useBus.coffee' import {openInNewTab} from '../../utils/nav' BookUrl = 'https://www.amazon.com/gp/product/171000892X/' FlitterFormUrl = 'https://forms.gle/8mzToRg25jVfBLSP8' Image = (p) => {screenWidth, screenHeight} = useScreenSize() height = useMemo (=> screenHeight * .9), [screenHeight] root = p.root or 'commons/' <l.Image {...p} src={c.SRC_URL + root + p.name} className={cx [p.className]: yes, portrait: screenWidth < screenHeight, } fullHeight={height} /> VideoConfig = file: attributes: {preload: 'auto'} youtube: preload: yes playerVars: {modestbranding: yes, rel: no, controls: yes} Video = (p) => player = useRef() [playing, togglePlaying] = useToggle yes [didClickOnce, setDidClickOnce] = useState no {screenWidth} = useScreenSize() size = useMemo (=> width = if p.height then (16/9) * p.height else screenWidth * .85 height = if p.height then p.height else (9/16) * width {width, height} ), [screenWidth] url = if p.name then c.CDN_URL + 'videos/' + p.name + '.mp4' else p.url onClick = => if didClickOnce then togglePlaying() else setDidClickOnce yes <l.VideoRoot> <Player url={url} wrapper={l.Video} width={size.width} height={size.height} playing={p.inView and playing} playsinline muted={not didClickOnce} loop={yes} onClick={onClick} controls={didClickOnce} config={VideoConfig} ref={player} onPlay={=> player.current.getInternalPlayer().pauseVideo() if not p.inView} /> <l.VideoSoundPrompt className={cx hide: didClickOnce} onClick={onClick}> click for audio </l.VideoSoundPrompt> </l.VideoRoot> Tickle = (p) => [classes] = useDelayedReveal p.inView, p.delay || 4000 <l.more href={p.to} target='_blank' className={cx hide: not p.inView, [classes]: yes, [p.className]: yes }> {p.children} </l.more> useLoader = (doneCount) => [count, setCount] = useState 0 [loaded, setIsLoaded] = useState no increment = useCallback (=> if not loaded then setCount (c) => c + 1), [loaded] useLayoutEffect (=> setIsLoaded(yes) if count >= doneCount), [count] [loaded, increment] from = (x = 0) => x: x, y: 0 to = (delay = 0) => x: 0, y: 0, delay: delay OutNow = (p) => <l.OutNow onClick={=> cast 'book.openCheckout'} className={cx show: p.show} delay={p.delay}> <l.woo>new book</l.woo> <l.yow>out now</l.yow> </l.OutNow> Deck = (p) => [ref, inView] = useInView(threshold: .54) [loaded, markLoaded] = useLoader p.cards.length [mode, setMode] = useState 'intro' [topIndex, setTopIndex] = useState 0 [spins] = useState => p.cards.map => Math.random() * 4 * (if Math.random() > .5 then -1 else 1) {screenWidth, screenHeight} = useScreenSize() {buttonAction, buttonText} = p.cards[topIndex] numCards = p.cards.length incrementIndex = => setTopIndex (i) => (i + 1) % numCards decrementIndex = => setTopIndex (i) => ((i - 1) + numCards) % numCards goToNext = => currentTopIndex = +topIndex set (i) => {x: screenWidth * 1.3} if i is currentTopIndex after 200, => incrementIndex() set (i) => {x: 0} if i is currentTopIndex goToPrev = => prevIndex = ((topIndex - 1) + numCards) % numCards set (i) => {x: screenWidth * -1.3} if i is prevIndex after 200, => decrementIndex() set (i) => {x: 0} if i is prevIndex [props, set] = useSprings p.cards.length, (i) => from: from(screenWidth * 1.3) # handleDrag = ({ # args: [index], down, movement: [mx, my], direction: [xDir, yDir], velocity, touches # }) => # return if touches > 1 # # trigger = no # if not down and velocity > 0.2 # trigger = yes # after 200, => # incrementIndex() # set (i) => from() if index is i # # set (i) => # return unless index is i # x: if trigger then screenWidth * 1.3 * xDir * velocity else if down then mx else 0 # y: if trigger then screenHeight * 1.3 * yDir * velocity else if down then my else 0 # config: # friction: 50 # tension: 300 #if down then 200 else if trigger then 200 else 500 # withDrag = useDrag handleDrag, {axis: 'x'} cardDelay = (i) => (numCards - i - 1) * 324 + 500 curtainsUp = => setMode 'show' set (i) => to(cardDelay(i)) ga 'send', 'event', { eventCategory: 'deck' eventAction: 'view' eventLabel: p.id } useLayoutEffect (=> return if mode is 'show' return curtainsUp() if loaded and inView and mode is 'loading' timer = after (if p.id is 'book' then 2160 else 1080), => if loaded and inView and mode isnt 'show' then curtainsUp() else if inView then setMode 'loading' => timer.clear() ), [loaded, inView, mode] [covered, setCovered] = useState no useBus 'book.openCheckout': => setCovered yes 'book.closeCheckout': => setCovered no <l.Deck ref={ref} key={ref} id={p.id}> {if p.id is 'book' <OutNow show={mode is 'show'} delay={cardDelay(0)} /> } <l.Title className={cx loading: mode isnt 'show'}> {p.title()} <l.LoadingText>{p.loading() if mode isnt 'show'}</l.LoadingText> </l.Title> <l.CardRoot className={cx hide: mode isnt 'show' or not inView}> {props.map ({x, y, rot, scale}, thisIndex) => isTop = topIndex is thisIndex zIndex = if isTop then numCards else (numCards - (thisIndex - topIndex)) % numCards <l.Card key={thisIndex} spin={spins[thisIndex]} style={{x, y, zIndex}}> {p.cards[thisIndex].render({ markLoaded, disabled: not isTop or not inView or covered })} </l.Card> } </l.CardRoot> <l.ActionZone delay={cardDelay(0) + 500} className={cx hide: mode isnt 'show'}> <l.TinyAction onClick={goToPrev}><a>&lsaquo;</a></l.TinyAction> {if typeof buttonAction is 'function' <l.BigAction onClick={buttonAction}> <a>{buttonText}</a> </l.BigAction> else <l.BigAction> <a href={buttonAction} target='_blank'> {buttonText} </a> </l.BigAction> } <l.TinyAction onClick={goToNext}><a>&rsaquo;</a></l.TinyAction> </l.ActionZone> </l.Deck> export Book = => <Deck id='book' title={=> <div>drag queen&nbsp;<l.yow>in the</l.yow>&nbsp;white house</div>} loading={=> <>brushing some wigs...</>} cards={[ { render: (p) => <Image name='dqitwh cover mq.jpg' className='cover fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the new book' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='evolution'> <div> evolution cannot be stoppped<br/> long-shot drag queen runs for president<br/> and congress turns purple </div> </l.Pot> buttonText: 'read more' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] {screenWidth, screenHeight, shape} = useScreenSize() videoHeight = useMemo (=> if shape is 'landscape' then screenHeight * .5 else screenWidth * .9 * (9/16) ), [screenWidth, screenHeight] <Video url='https://www.youtube.com/watch?v=-VkMsRHsAmM' inView={not p.disabled} height={videoHeight} /> buttonText: 'i’m so in!' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='realness'> <div> it’s time for over-the-top <l.zon>realness</l.zon> to shock the <l.zon>conscience</l.zon> of our nation </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='back cover sd.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='girlish.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='child with sign.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'youtube' buttonAction: c.YouTubeUrl } { render: (p) => <Image name='merman 1.jpg' onLoad={p.markLoaded} /> buttonText: 'instagram' buttonAction: c.InstagramUrl } { render: (p) => <Image name='nonviolent revolution small.png' className='revo' onLoad={p.markLoaded} /> buttonText: 'i’m into it' buttonAction: => cast 'book.openCheckout' } { render: (p) => useEffect p.markLoaded, [] <l.Pot> <MailingList disabled={p.disabled} /> </l.Pot> buttonText: 'why join?' buttonAction: 'https://medium.com/@skitzysandcastle/in-the-beginning-was-the-end-88c928e7d3aa' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='scroll'> <img src={c.SRC_URL + 'commons/solwhite.png'} /> <div> scroll down for more </div> <div>▼</div> </l.Pot> buttonText: 'let’s go' buttonAction: => document.getElementById('scroll-root').scroll top: innerHeight, behavior: 'smooth' } ]} /> export Flitter = => <Deck id='flitter' title={=> <>flitters</>} loading={=> <>beading some heels...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='getpaid'> what if you could work<br /> anywhere, anytime,<br/> doing almost anything<br/> <l.zon>& get paid for it?</l.zon> </l.Pot> buttonText: 'tell me more' buttonAction: 'https://medium.com/@skitzysandcastle/flitters-497f7c33aa96' } { render: (p) => <Image name='glitterfaeries.jpg' onLoad={p.markLoaded} /> buttonText: 'roving art' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> imagine millions of flitters roaming america, being society’s antidepressant. that’s their job. stirring happiness & deescalating high-pressure situations. </div> </l.Pot> buttonText: 'sample the book' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='flitsis.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='job'> <div> job description:<br/> <l.zon>spread joy & knowledge</l.zon> </div> </l.Pot> buttonText: 'i’m in' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] {screenHeight} = useScreenSize() videoHeight = useMemo (=> screenHeight * .5), [screenHeight] <l.Pot className='classrooms'> <div className='txtbox'> <l.zon>flitters</l.zon> open classrooms in the trenches </div> <Video url='https://www.youtube.com/watch?v=kWC957au5c8' inView={not p.disabled} height={videoHeight} /> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='tough'> <div> <l.zon>flitters</l.zon> facilitate tough dialogues<br/> with levity & light </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> offer yoga & meditation </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='yoga'> <div> <l.zon>flitters</l.zon> play dress up & do makeovers </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => <Image name='mikeyfizzwhimzeh.jpg' className='fullHeight' onLoad={p.markLoaded} /> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='rovingart'> <div> <l.zon>flitters</l.zon> pick up trash,<br/> plant trees,<br/> host events, <br/> raise vibes—<br/> they are roving <l.zon>creation!</l.zon> </div> </l.Pot> buttonText: 'sign me up!' buttonAction: FlitterFormUrl } ]} /> export Lampshade = => <Deck id='lampshade' title={=> <div>lampshade<l.yow> country club</l.yow></div>} loading={=> <>pulling some espresso...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitandland'> <div><l.zon>community&nbsp;</l.zon>meet<l.zon>&nbsp;commodity</l.zon></div> </l.Pot> buttonText: 'get a taste' buttonAction: 'https://medium.com/@skitzysandcastle/the-era-of-lampshade-89594f16386c' } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='exist'> expansive public space to simply <l.zon>exist</l.zon> </l.Pot> buttonText: 'liberate the static' buttonAction: => cast 'book.openCheckout' } { render: (p) => <Image name='lampshade warm.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch'> <div> public space where anyone from anywhere can go at any time for any reason whatever. we have a chance to make all people feel iconic. directly a part of it. in the heat. </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='lampshade.jpg' onLoad={p.markLoaded} /> buttonText: 'moooore' buttonAction: c.InstagramUrl } ]} /> export EymU = => <Deck id='eymu' title={=> <div>eym<l.yow>u</l.yow></div>} loading={=> <>solving some integrals...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='shock'> <div> mindful capitalism </div> </l.Pot> buttonText: 'read more' buttonAction: c.TwitterUrl } { render: (p) => <Image name='eym.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='flitpitch volunteer'> <l.al>communally owned<br/>means of production</l.al> <div> maybe you donate two hours of sweeping the space every week and that’s how you get access. maybe you offer the temple space a guided meditation twice a week and that’s how you get access. maybe you’re a caretaker for the 7th floor glass-dome garden managing 200 weekly volunteers and that’s how you get access. maybe you’re rich as hell and give a million dollars.— </div> </l.Pot> buttonText: 'read more' buttonAction: c.GoogleBookPreview } { render: (p) => <Image name='ice.jpg' onLoad={p.markLoaded} /> buttonText: 'see more' buttonAction: c.InstagramUrl } { render: (p) => useEffect p.markLoaded, [] <l.Pot className='hollywood'> <div> <l.zon>hollywood</l.zon> heads to the<br/> <l.zon>heartland</l.zon> </div> </l.Pot> buttonText: 'get the book' buttonAction: => cast 'book.openCheckout' } ]} /> export Creation = => <Deck id='creation' title={=> <div>creation&nbsp;<l.yow>poetcards</l.yow></div>} loading={=> <>mixing some paint...</>} cards={[ { render: (p) => useEffect p.markLoaded, [] <l.Pot className='whimsy'> <div> <l.zon>cling to your whimsy</l.zon> you are a delightful stimulant<br/> when in doubt, make art </div> </l.Pot> buttonText: 'etsy get some' buttonAction: c.EtsyUrl } { render: (p) => <Image name='dreams+of+lucy.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'bloom baby' buttonAction: c.EtsyUrl } { render: (p) => <Image name='the+flight+home.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'stick out' buttonAction: c.EtsyUrl } { render: (p) => <Image name='camus cabaret.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'it can only be right' buttonAction: c.EtsyUrl } { render: (p) => <Image name="moby's+dick.jpg" root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'collapse the dark' buttonAction: c.EtsyUrl } { render: (p) => <Image name='train+hoppin+charlie.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'peace, forget the rest' buttonAction: c.EtsyUrl } { render: (p) => <Image name='prance.jpg' className='fullHeight' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'when in doubt, prance' buttonAction: c.EtsyUrl } { render: (p) => <Image name='be+your+own+therapy.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be your own therapy' buttonAction: c.EtsyUrl } { render: (p) => <Image name='submerged+explorations.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'you are the guru' buttonAction: c.EtsyUrl } { render: (p) => <Image name='unicorn-merman.jpg' root='poetcards/' onLoad={p.markLoaded} /> buttonText: 'be you' buttonAction: c.EtsyUrl } ]} /> export Footer = => <l.Centered className='bottom'> <div className='book-link'> <a onClick={=> cast 'book.openCheckout'}> get the new book! </a> </div> <a href={c.MediumUrl} target='_blank'> <i className='fab fa-medium-m' /> </a> <a href={c.InstagramUrl} target='_blank'> <i className='fab fa-instagram' /> </a> <a href={c.YouTubeUrl} target='_blank'> <i className='fab fa-youtube' /> </a> <a href={c.TwitterUrl} target='_blank'> <i className='fab fa-twitter' /> </a> <l.woo className='footer-brand'>express your mess</l.woo> </l.Centered> # export Mangina = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='mangina.jpg' className='fullHeight' /> # <Tickle inView={inView} # to='https://www.etsy.com/listing/674899618/men-from-mangina-modern-art-nude-print'> # get it # </Tickle> # </l.Centered> # export Yes = => # [ref, inView] = useInView(threshold: .54) # <l.Centered className='pong' ref={ref}> # <l.Pot> # emancipated lands of<l.zon>&nbsp;yes, and&nbsp;</l.zon>await you—<br/> # whole celestial realms outside the absurd world of no. # </l.Pot> # <Tickle inView={inView} to='https://medium.com/@skitzysandcastle'> # more # </Tickle> # </l.Centered> # # export Trump = (p) => # [ref, inView] = useInView(threshold: .54) # <l.Centered ref={ref}> # <Image name='trumpf.jpg' /> # <Tickle inView={inView} to='https://pixabay.com/users/tiburi-2851152/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1915273'> # tibor janosi mozes # </Tickle> # </l.Centered> # # export Waggle = => # <l.Centered className='ping'> # <l.Pot> # flicker flop ripple dart waggle waving loot—<br/> # wonderful hangs everywhere so i sample the fruit. # </l.Pot> # </l.Centered> # # export TJ = => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video url='https://www.youtube.com/watch?v=rmXjuF1GLK0' inView={inView} /> # </l.Centered> # # Texts = [ # {content: 'if 100 million of us put four quarters in our pocket every single day and gave them out to the first four people that wanted them, then $100 million a day would circulate into the hands of those who need a break.', delay: 0}, # {content: 'that’s $365 billion a year, one quarter at a time.', delay: 5000}, # # {content: 'power will tell you it’s hopeless. that the problems are too great to contemplate. that this is as good as it gets.', duration: 1000}, # # {content: 'it’s the lie of our lifetime.', duration: 1000}, # ] # export Intro = (p) => # [ref, inView] = useInView(threshold: .5, triggerOnce: yes) # delay = 0 # <l.Centered ref={ref} className='intro pong'> # {Texts.map (text) => # delay += text.delay # <l.IntroText delay={delay} className={cx show: inView}> # {text.content} # </l.IntroText> # } # </l.Centered> # # export PI:NAME:<NAME>END_PI = (p) => # [ref, inView] = useInView(threshold: .5) # <l.Centered ref={ref}> # <Video name='jubileeq' inView={inView} /> # </l.Centered> # # export Heart = => # <l.Centered className='pong'> # <l.Pot> # <l.zon>hollywood</l.zon> heads to the<l.zon>&nbsp;heartland</l.zon> # </l.Pot> # </l.Centered> # # export Revolution = => # <l.Centered> # <Image name='nonviolent revolution small.png' className='revo' /> # </l.Centered> # # # export Mitch = (p) => # <l.Centered> # <Image name='mitch.jpg' /> # </l.Centered> # # export Seed = => # <l.Centered className='pong'> # <l.Pot> # start with a single<l.zon>&nbsp;flitter</l.zon>. one seed.<br/> # an idea. sent out on the thimble of<l.zon>&nbsp;love</l.zon>.<br/> # an act of pure<l.zon>&nbsp;creation</l.zon>. # </l.Pot> # </l.Centered> # # export Eymboard = (p) => # <l.Centered> # <Image name='eymboard.jpg' /> # </l.Centered> # # export Whimsy = => # <l.Centered className='pong'> # <l.Pot> # cling to your<l.zon>&nbsp;whimsy,</l.zon><br/> # you are a delightful stimulant; <br/> # best deployed as stirring propaganda<br/> # that never loses sight of the sun. # </l.Pot> # </l.Centered> # # # export Sneakers = (p) => # <l.Centered className='sneakers'> # <Image name='sneakers.jpg' className='fullHeight' /> # </l.Centered> # # export Reborn = => # <l.Centered className='ping'> # <l.Pot> # whatever you call it:<br/> # <l.zon>get dislodged from the system</l.zon><br/><br/> # # freedom cost me everything<br/> # which turns out to be nothing at all<br/><br/> # # waking to yes will kill you—<br/> # and then you will be<l.zon>&nbsp;reborn</l.zon><br/><br/> # # i would get rid of everything<br/> # <l.yow>and <a href={BookUrl} target='_blank'>begin again</a>—</l.yow> # </l.Pot> # </l.Centered> # Intro.duration = 3000 # Mangina.duration = 1500 # Trump.duration = 1000 # PaintShow.duration = 15000 # Jesus.duration = 4000 # Mitch.duration = 2000 # Eymboard.duration = 10000 # Sneakers.duration = 5000 # LandingPage.duration = 0
[ { "context": "value='some value'/><input type='password' value='some value'/>\n <textarea>some text</textarea><label f", "end": 8306, "score": 0.7597037553787231, "start": 8296, "tag": "PASSWORD", "value": "some value" }, { "context": "/>\n <input type='password' id='third' value='some value'/>\"\n document.getElementById(\"test-div\").inner", "end": 15584, "score": 0.7414541244506836, "start": 15574, "tag": "PASSWORD", "value": "some value" }, { "context": "egisterStateChange\", { enabled: \"one\", passKeys: \"two\" }\n\n assert.isTrue test.enabled == \"one\"\n a", "end": 17138, "score": 0.8276212215423584, "start": 17135, "tag": "KEY", "value": "two" } ]
tests/dom_tests/dom_tests.coffee
nightwing/vimium
3
# Install frontend event handlers. installListeners() installListener = (element, event, callback) -> element.addEventListener event, (-> callback.apply(this, arguments)), true # A count of the number of keyboard events received by the page (for the most recently-sent keystroke). E.g., # we expect 3 if the keystroke is passed through (keydown, keypress, keyup), and 0 if it is suppressed. pageKeyboardEventCount = 0 sendKeyboardEvent = (key) -> pageKeyboardEventCount = 0 response = window.callPhantom request: "keyboard" key: key # These listeners receive events after the main frontend listeners, and do not receive suppressed events. for type in [ "keydown", "keypress", "keyup" ] installListener window, type, (event) -> pageKeyboardEventCount += 1 # Some tests have side effects on the handler stack and the active mode, so these are reset on setup. initializeModeState = -> Mode.reset() handlerStack.reset() initializeModes() # We use "m" as the only mapped key, "p" as a passkey, and "u" as an unmapped key. refreshCompletionKeys completionKeys: "mp" handlerStack.bubbleEvent "registerStateChange", enabled: true passKeys: "p" handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "" # Tell Settings that it's been loaded. Settings.isLoaded = true # Shoulda.js doesn't support async code, so we try not to use any. Utils.nextTick = (func) -> func() # # Retrieve the hint markers as an array object. # getHintMarkers = -> Array::slice.call document.getElementsByClassName("vimiumHintMarker"), 0 stubSettings = (key, value) -> stub Settings.cache, key, JSON.stringify value # # Generate tests that are common to both default and filtered # link hinting modes. # createGeneralHintTests = (isFilteredMode) -> context "Link hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" document.getElementById("test-div").innerHTML = testContent stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" tearDown -> document.getElementById("test-div").innerHTML = "" should "create hints when activated, discard them when deactivated", -> linkHints = LinkHints.activateMode() assert.isFalse not linkHints.hintMarkerContainingDiv? linkHints.deactivateMode() assert.isTrue not linkHints.hintMarkerContainingDiv? should "position items correctly", -> assertStartPosition = (element1, element2) -> assert.equal element1.getClientRects()[0].left, element2.getClientRects()[0].left assert.equal element1.getClientRects()[0].top, element2.getClientRects()[0].top stub document.body, "style", "static" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() stub document.body.style, "position", "relative" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() createGeneralHintTests false createGeneralHintTests true inputs = [] context "Test link hints for focusing input elements correctly", setup -> initializeModeState() testDiv = document.getElementById("test-div") testDiv.innerHTML = "" stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Every HTML5 input type except for hidden. We should be able to activate all of them with link hints. inputTypes = ["button", "checkbox", "color", "date", "datetime", "datetime-local", "email", "file", "image", "month", "number", "password", "radio", "range", "reset", "search", "submit", "tel", "text", "time", "url", "week"] for type in inputTypes input = document.createElement "input" input.type = type testDiv.appendChild input inputs.push input tearDown -> document.getElementById("test-div").innerHTML = "" should "Focus each input when its hint text is typed", -> for input in inputs input.scrollIntoView() # Ensure the element is visible so we create a link hint for it. activeListener = ensureCalled (event) -> input.blur() if event.type == "focus" input.addEventListener "focus", activeListener, false input.addEventListener "click", activeListener, false LinkHints.activateMode() [hint] = getHintMarkers().filter (hint) -> input == hint.clickableItem sendKeyboardEvent char for char in hint.hintString input.removeEventListener "focus", activeListener, false input.removeEventListener "click", activeListener, false context "Alphabetical link hints", setup -> initializeModeState() stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Three hints will trigger double hint chars. createLinks 3 @linkHints = LinkHints.activateMode() tearDown -> @linkHints.deactivateMode() document.getElementById("test-div").innerHTML = "" should "label the hints correctly", -> # TODO(philc): This test verifies the current behavior, but the current behavior is incorrect. # The output here should be something like aa, ab, b. hintMarkers = getHintMarkers() expectedHints = ["aa", "ba", "ab"] for hint, i in expectedHints assert.equal hint, hintMarkers[i].hintString should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "A" assert.equal "none", hintMarkers[1].style.display assert.equal "", hintMarkers[0].style.display context "Filtered link hints", # Note. In all of these tests, the order of the elements returned by getHintMarkers() may be different from # the order they are listed in the test HTML content. This is because LinkHints.activateMode() sorts the # elements. setup -> stubSettings "filterLinkHints", true stubSettings "linkHintNumbers", "0123456789" context "Text hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" + "<a>trait</a>" + "<a>track<img alt='alt text'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the hints", -> hintMarkers = getHintMarkers() for i in [0...4] assert.equal (i + 1).toString(), hintMarkers[i].textContent.toLowerCase() should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "T" sendKeyboardEvent "R" assert.equal "none", hintMarkers[0].style.display assert.equal "1", hintMarkers[1].hintString assert.equal "", hintMarkers[1].style.display sendKeyboardEvent "A" assert.equal "2", hintMarkers[3].hintString context "Image hints", setup -> initializeModeState() testContent = "<a><img alt='alt text'/></a><a><img alt='alt text' title='some title'/></a> <a><img title='some title'/></a>" + "<a><img src='' width='320px' height='100px'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the images", -> hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-4]/, "N" assert.equal 4, hintMarkers.length assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N: some title" in hintMarkers assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N" in hintMarkers context "Input hints", setup -> initializeModeState() testContent = "<input type='text' value='some value'/><input type='password' value='some value'/> <textarea>some text</textarea><label for='test-input'/>a label</label> <input type='text' id='test-input' value='some value'/> <label for='test-input-2'/>a label: </label><input type='text' id='test-input-2' value='some value'/>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the input elements", -> hintMarkers = getHintMarkers() hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-5]/, "N" assert.equal 5, hintMarkers.length assert.isTrue "N" in hintMarkers assert.isTrue "N" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N" in hintMarkers context "Input focus", setup -> initializeModeState() testContent = "<input type='text' id='first'/><input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "focus the first element", -> focusInput 1 assert.equal "first", document.activeElement.id should "focus the nth element", -> focusInput 100 assert.equal "third", document.activeElement.id should "activate insert mode on the first element", -> focusInput 1 assert.isTrue InsertMode.permanentInstance.isActive() should "activate insert mode on the first element", -> focusInput 100 assert.isTrue InsertMode.permanentInstance.isActive() should "activate the most recently-selected input if the count is 1", -> focusInput 3 focusInput 1 assert.equal "third", document.activeElement.id should "not trigger insert if there are no inputs", -> document.getElementById("test-div").innerHTML = "" focusInput 1 assert.isFalse InsertMode.permanentInstance.isActive() # TODO: these find prev/next link tests could be refactored into unit tests which invoke a function which has # a tighter contract than goNext(), since they test minor aspects of goNext()'s link matching behavior, and we # don't need to construct external state many times over just to test that. # i.e. these tests should look something like: # assert.equal(findLink(html("<a href=...">))[0].href, "first") # These could then move outside of the dom_tests file. context "Find prev / next links", setup -> initializeModeState() window.location.hash = "" should "find exact matches", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>nextcorrupted</a> <a href='#second'>next page</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "match against non-word patterns", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>&gt;&gt;</a> """ stubSettings "nextPatterns", ">>" goNext() assert.equal '#first', window.location.hash should "favor matches with fewer words", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>lorem ipsum next</a> <a href='#second'>next!</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "find link relation in header", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> """ goNext() assert.equal '#first', window.location.hash should "favor link relation to text matching", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> <a href='#second'>next</a> """ goNext() assert.equal '#first', window.location.hash should "match mixed case link relation", -> document.getElementById("test-div").innerHTML = """ <link rel='Next' href='#first'> """ goNext() assert.equal '#first', window.location.hash createLinks = (n) -> for i in [0...n] by 1 link = document.createElement("a") link.textContent = "test" document.getElementById("test-div").appendChild link context "Normal mode", setup -> initializeModeState() should "suppress mapped keys", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 should "not suppress unmapped keys", -> sendKeyboardEvent "u" assert.equal pageKeyboardEventCount, 3 should "not suppress escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 should "not suppress passKeys", -> sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 3 should "suppress passKeys with a non-empty keyQueue", -> handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "p" sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 0 context "Insert mode", setup -> initializeModeState() @insertMode = new InsertMode global: true should "not suppress mapped keys in insert mode", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 3 should "exit on escape", -> assert.isTrue @insertMode.modeIsActive sendKeyboardEvent "escape" assert.isFalse @insertMode.modeIsActive should "resume normal mode after leaving insert mode", -> @insertMode.exit() sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 context "Triggering insert mode", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/> <p id='fourth' contenteditable='true'/> <p id='fifth'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.activeElement?.blur() document.getElementById("test-div").innerHTML = "" should "trigger insert mode on focus of text input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("first").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of password input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("third").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of contentEditable elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fourth").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "not trigger insert mode on other elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fifth").focus() assert.isFalse InsertMode.permanentInstance.isActive() context "Mode utilities", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "not have duplicate singletons", -> count = 0 class Test extends Mode constructor: -> count += 1; super singleton: Test exit: -> count -= 1; super() assert.isTrue count == 0 for [1..10] mode = new Test() assert.isTrue count == 1 mode.exit() assert.isTrue count == 0 should "exit on escape", -> test = new Mode exitOnEscape: true assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse test.modeIsActive should "not exit on escape if not enabled", -> test = new Mode exitOnEscape: false assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 assert.isTrue test.modeIsActive should "exit on blur", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: element assert.isTrue test.modeIsActive element.blur() assert.isFalse test.modeIsActive should "not exit on blur if not enabled", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: false assert.isTrue test.modeIsActive element.blur() assert.isTrue test.modeIsActive should "register state change", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerStateChange", { enabled: "one", passKeys: "two" } assert.isTrue test.enabled == "one" assert.isTrue test.passKeys == "two" should "register the keyQueue", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "hello" assert.isTrue test.keyQueue == "hello" context "PostFindMode", setup -> initializeModeState() testContent = "<input type='text' id='first'/>" document.getElementById("test-div").innerHTML = testContent document.getElementById("first").focus() @postFindMode = new PostFindMode tearDown -> document.getElementById("test-div").innerHTML = "" should "be a singleton", -> assert.isTrue @postFindMode.modeIsActive new PostFindMode assert.isFalse @postFindMode.modeIsActive should "suppress unmapped printable keys", -> sendKeyboardEvent "m" assert.equal 0, pageKeyboardEventCount should "be deactivated on click events", -> handlerStack.bubbleEvent "click", target: document.activeElement assert.isFalse @postFindMode.modeIsActive should "enter insert mode on immediate escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse @postFindMode.modeIsActive should "not enter insert mode on subsequent escapes", -> sendKeyboardEvent "a" sendKeyboardEvent "escape" assert.isTrue @postFindMode.modeIsActive
7000
# Install frontend event handlers. installListeners() installListener = (element, event, callback) -> element.addEventListener event, (-> callback.apply(this, arguments)), true # A count of the number of keyboard events received by the page (for the most recently-sent keystroke). E.g., # we expect 3 if the keystroke is passed through (keydown, keypress, keyup), and 0 if it is suppressed. pageKeyboardEventCount = 0 sendKeyboardEvent = (key) -> pageKeyboardEventCount = 0 response = window.callPhantom request: "keyboard" key: key # These listeners receive events after the main frontend listeners, and do not receive suppressed events. for type in [ "keydown", "keypress", "keyup" ] installListener window, type, (event) -> pageKeyboardEventCount += 1 # Some tests have side effects on the handler stack and the active mode, so these are reset on setup. initializeModeState = -> Mode.reset() handlerStack.reset() initializeModes() # We use "m" as the only mapped key, "p" as a passkey, and "u" as an unmapped key. refreshCompletionKeys completionKeys: "mp" handlerStack.bubbleEvent "registerStateChange", enabled: true passKeys: "p" handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "" # Tell Settings that it's been loaded. Settings.isLoaded = true # Shoulda.js doesn't support async code, so we try not to use any. Utils.nextTick = (func) -> func() # # Retrieve the hint markers as an array object. # getHintMarkers = -> Array::slice.call document.getElementsByClassName("vimiumHintMarker"), 0 stubSettings = (key, value) -> stub Settings.cache, key, JSON.stringify value # # Generate tests that are common to both default and filtered # link hinting modes. # createGeneralHintTests = (isFilteredMode) -> context "Link hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" document.getElementById("test-div").innerHTML = testContent stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" tearDown -> document.getElementById("test-div").innerHTML = "" should "create hints when activated, discard them when deactivated", -> linkHints = LinkHints.activateMode() assert.isFalse not linkHints.hintMarkerContainingDiv? linkHints.deactivateMode() assert.isTrue not linkHints.hintMarkerContainingDiv? should "position items correctly", -> assertStartPosition = (element1, element2) -> assert.equal element1.getClientRects()[0].left, element2.getClientRects()[0].left assert.equal element1.getClientRects()[0].top, element2.getClientRects()[0].top stub document.body, "style", "static" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() stub document.body.style, "position", "relative" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() createGeneralHintTests false createGeneralHintTests true inputs = [] context "Test link hints for focusing input elements correctly", setup -> initializeModeState() testDiv = document.getElementById("test-div") testDiv.innerHTML = "" stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Every HTML5 input type except for hidden. We should be able to activate all of them with link hints. inputTypes = ["button", "checkbox", "color", "date", "datetime", "datetime-local", "email", "file", "image", "month", "number", "password", "radio", "range", "reset", "search", "submit", "tel", "text", "time", "url", "week"] for type in inputTypes input = document.createElement "input" input.type = type testDiv.appendChild input inputs.push input tearDown -> document.getElementById("test-div").innerHTML = "" should "Focus each input when its hint text is typed", -> for input in inputs input.scrollIntoView() # Ensure the element is visible so we create a link hint for it. activeListener = ensureCalled (event) -> input.blur() if event.type == "focus" input.addEventListener "focus", activeListener, false input.addEventListener "click", activeListener, false LinkHints.activateMode() [hint] = getHintMarkers().filter (hint) -> input == hint.clickableItem sendKeyboardEvent char for char in hint.hintString input.removeEventListener "focus", activeListener, false input.removeEventListener "click", activeListener, false context "Alphabetical link hints", setup -> initializeModeState() stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Three hints will trigger double hint chars. createLinks 3 @linkHints = LinkHints.activateMode() tearDown -> @linkHints.deactivateMode() document.getElementById("test-div").innerHTML = "" should "label the hints correctly", -> # TODO(philc): This test verifies the current behavior, but the current behavior is incorrect. # The output here should be something like aa, ab, b. hintMarkers = getHintMarkers() expectedHints = ["aa", "ba", "ab"] for hint, i in expectedHints assert.equal hint, hintMarkers[i].hintString should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "A" assert.equal "none", hintMarkers[1].style.display assert.equal "", hintMarkers[0].style.display context "Filtered link hints", # Note. In all of these tests, the order of the elements returned by getHintMarkers() may be different from # the order they are listed in the test HTML content. This is because LinkHints.activateMode() sorts the # elements. setup -> stubSettings "filterLinkHints", true stubSettings "linkHintNumbers", "0123456789" context "Text hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" + "<a>trait</a>" + "<a>track<img alt='alt text'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the hints", -> hintMarkers = getHintMarkers() for i in [0...4] assert.equal (i + 1).toString(), hintMarkers[i].textContent.toLowerCase() should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "T" sendKeyboardEvent "R" assert.equal "none", hintMarkers[0].style.display assert.equal "1", hintMarkers[1].hintString assert.equal "", hintMarkers[1].style.display sendKeyboardEvent "A" assert.equal "2", hintMarkers[3].hintString context "Image hints", setup -> initializeModeState() testContent = "<a><img alt='alt text'/></a><a><img alt='alt text' title='some title'/></a> <a><img title='some title'/></a>" + "<a><img src='' width='320px' height='100px'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the images", -> hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-4]/, "N" assert.equal 4, hintMarkers.length assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N: some title" in hintMarkers assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N" in hintMarkers context "Input hints", setup -> initializeModeState() testContent = "<input type='text' value='some value'/><input type='password' value='<PASSWORD>'/> <textarea>some text</textarea><label for='test-input'/>a label</label> <input type='text' id='test-input' value='some value'/> <label for='test-input-2'/>a label: </label><input type='text' id='test-input-2' value='some value'/>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the input elements", -> hintMarkers = getHintMarkers() hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-5]/, "N" assert.equal 5, hintMarkers.length assert.isTrue "N" in hintMarkers assert.isTrue "N" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N" in hintMarkers context "Input focus", setup -> initializeModeState() testContent = "<input type='text' id='first'/><input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "focus the first element", -> focusInput 1 assert.equal "first", document.activeElement.id should "focus the nth element", -> focusInput 100 assert.equal "third", document.activeElement.id should "activate insert mode on the first element", -> focusInput 1 assert.isTrue InsertMode.permanentInstance.isActive() should "activate insert mode on the first element", -> focusInput 100 assert.isTrue InsertMode.permanentInstance.isActive() should "activate the most recently-selected input if the count is 1", -> focusInput 3 focusInput 1 assert.equal "third", document.activeElement.id should "not trigger insert if there are no inputs", -> document.getElementById("test-div").innerHTML = "" focusInput 1 assert.isFalse InsertMode.permanentInstance.isActive() # TODO: these find prev/next link tests could be refactored into unit tests which invoke a function which has # a tighter contract than goNext(), since they test minor aspects of goNext()'s link matching behavior, and we # don't need to construct external state many times over just to test that. # i.e. these tests should look something like: # assert.equal(findLink(html("<a href=...">))[0].href, "first") # These could then move outside of the dom_tests file. context "Find prev / next links", setup -> initializeModeState() window.location.hash = "" should "find exact matches", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>nextcorrupted</a> <a href='#second'>next page</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "match against non-word patterns", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>&gt;&gt;</a> """ stubSettings "nextPatterns", ">>" goNext() assert.equal '#first', window.location.hash should "favor matches with fewer words", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>lorem ipsum next</a> <a href='#second'>next!</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "find link relation in header", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> """ goNext() assert.equal '#first', window.location.hash should "favor link relation to text matching", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> <a href='#second'>next</a> """ goNext() assert.equal '#first', window.location.hash should "match mixed case link relation", -> document.getElementById("test-div").innerHTML = """ <link rel='Next' href='#first'> """ goNext() assert.equal '#first', window.location.hash createLinks = (n) -> for i in [0...n] by 1 link = document.createElement("a") link.textContent = "test" document.getElementById("test-div").appendChild link context "Normal mode", setup -> initializeModeState() should "suppress mapped keys", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 should "not suppress unmapped keys", -> sendKeyboardEvent "u" assert.equal pageKeyboardEventCount, 3 should "not suppress escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 should "not suppress passKeys", -> sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 3 should "suppress passKeys with a non-empty keyQueue", -> handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "p" sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 0 context "Insert mode", setup -> initializeModeState() @insertMode = new InsertMode global: true should "not suppress mapped keys in insert mode", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 3 should "exit on escape", -> assert.isTrue @insertMode.modeIsActive sendKeyboardEvent "escape" assert.isFalse @insertMode.modeIsActive should "resume normal mode after leaving insert mode", -> @insertMode.exit() sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 context "Triggering insert mode", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/> <p id='fourth' contenteditable='true'/> <p id='fifth'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.activeElement?.blur() document.getElementById("test-div").innerHTML = "" should "trigger insert mode on focus of text input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("first").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of password input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("third").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of contentEditable elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fourth").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "not trigger insert mode on other elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fifth").focus() assert.isFalse InsertMode.permanentInstance.isActive() context "Mode utilities", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='<PASSWORD>'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "not have duplicate singletons", -> count = 0 class Test extends Mode constructor: -> count += 1; super singleton: Test exit: -> count -= 1; super() assert.isTrue count == 0 for [1..10] mode = new Test() assert.isTrue count == 1 mode.exit() assert.isTrue count == 0 should "exit on escape", -> test = new Mode exitOnEscape: true assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse test.modeIsActive should "not exit on escape if not enabled", -> test = new Mode exitOnEscape: false assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 assert.isTrue test.modeIsActive should "exit on blur", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: element assert.isTrue test.modeIsActive element.blur() assert.isFalse test.modeIsActive should "not exit on blur if not enabled", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: false assert.isTrue test.modeIsActive element.blur() assert.isTrue test.modeIsActive should "register state change", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerStateChange", { enabled: "one", passKeys: "<KEY>" } assert.isTrue test.enabled == "one" assert.isTrue test.passKeys == "two" should "register the keyQueue", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "hello" assert.isTrue test.keyQueue == "hello" context "PostFindMode", setup -> initializeModeState() testContent = "<input type='text' id='first'/>" document.getElementById("test-div").innerHTML = testContent document.getElementById("first").focus() @postFindMode = new PostFindMode tearDown -> document.getElementById("test-div").innerHTML = "" should "be a singleton", -> assert.isTrue @postFindMode.modeIsActive new PostFindMode assert.isFalse @postFindMode.modeIsActive should "suppress unmapped printable keys", -> sendKeyboardEvent "m" assert.equal 0, pageKeyboardEventCount should "be deactivated on click events", -> handlerStack.bubbleEvent "click", target: document.activeElement assert.isFalse @postFindMode.modeIsActive should "enter insert mode on immediate escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse @postFindMode.modeIsActive should "not enter insert mode on subsequent escapes", -> sendKeyboardEvent "a" sendKeyboardEvent "escape" assert.isTrue @postFindMode.modeIsActive
true
# Install frontend event handlers. installListeners() installListener = (element, event, callback) -> element.addEventListener event, (-> callback.apply(this, arguments)), true # A count of the number of keyboard events received by the page (for the most recently-sent keystroke). E.g., # we expect 3 if the keystroke is passed through (keydown, keypress, keyup), and 0 if it is suppressed. pageKeyboardEventCount = 0 sendKeyboardEvent = (key) -> pageKeyboardEventCount = 0 response = window.callPhantom request: "keyboard" key: key # These listeners receive events after the main frontend listeners, and do not receive suppressed events. for type in [ "keydown", "keypress", "keyup" ] installListener window, type, (event) -> pageKeyboardEventCount += 1 # Some tests have side effects on the handler stack and the active mode, so these are reset on setup. initializeModeState = -> Mode.reset() handlerStack.reset() initializeModes() # We use "m" as the only mapped key, "p" as a passkey, and "u" as an unmapped key. refreshCompletionKeys completionKeys: "mp" handlerStack.bubbleEvent "registerStateChange", enabled: true passKeys: "p" handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "" # Tell Settings that it's been loaded. Settings.isLoaded = true # Shoulda.js doesn't support async code, so we try not to use any. Utils.nextTick = (func) -> func() # # Retrieve the hint markers as an array object. # getHintMarkers = -> Array::slice.call document.getElementsByClassName("vimiumHintMarker"), 0 stubSettings = (key, value) -> stub Settings.cache, key, JSON.stringify value # # Generate tests that are common to both default and filtered # link hinting modes. # createGeneralHintTests = (isFilteredMode) -> context "Link hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" document.getElementById("test-div").innerHTML = testContent stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" tearDown -> document.getElementById("test-div").innerHTML = "" should "create hints when activated, discard them when deactivated", -> linkHints = LinkHints.activateMode() assert.isFalse not linkHints.hintMarkerContainingDiv? linkHints.deactivateMode() assert.isTrue not linkHints.hintMarkerContainingDiv? should "position items correctly", -> assertStartPosition = (element1, element2) -> assert.equal element1.getClientRects()[0].left, element2.getClientRects()[0].left assert.equal element1.getClientRects()[0].top, element2.getClientRects()[0].top stub document.body, "style", "static" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() stub document.body.style, "position", "relative" linkHints = LinkHints.activateMode() hintMarkers = getHintMarkers() assertStartPosition document.getElementsByTagName("a")[0], hintMarkers[0] assertStartPosition document.getElementsByTagName("a")[1], hintMarkers[1] linkHints.deactivateMode() createGeneralHintTests false createGeneralHintTests true inputs = [] context "Test link hints for focusing input elements correctly", setup -> initializeModeState() testDiv = document.getElementById("test-div") testDiv.innerHTML = "" stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Every HTML5 input type except for hidden. We should be able to activate all of them with link hints. inputTypes = ["button", "checkbox", "color", "date", "datetime", "datetime-local", "email", "file", "image", "month", "number", "password", "radio", "range", "reset", "search", "submit", "tel", "text", "time", "url", "week"] for type in inputTypes input = document.createElement "input" input.type = type testDiv.appendChild input inputs.push input tearDown -> document.getElementById("test-div").innerHTML = "" should "Focus each input when its hint text is typed", -> for input in inputs input.scrollIntoView() # Ensure the element is visible so we create a link hint for it. activeListener = ensureCalled (event) -> input.blur() if event.type == "focus" input.addEventListener "focus", activeListener, false input.addEventListener "click", activeListener, false LinkHints.activateMode() [hint] = getHintMarkers().filter (hint) -> input == hint.clickableItem sendKeyboardEvent char for char in hint.hintString input.removeEventListener "focus", activeListener, false input.removeEventListener "click", activeListener, false context "Alphabetical link hints", setup -> initializeModeState() stubSettings "filterLinkHints", false stubSettings "linkHintCharacters", "ab" # Three hints will trigger double hint chars. createLinks 3 @linkHints = LinkHints.activateMode() tearDown -> @linkHints.deactivateMode() document.getElementById("test-div").innerHTML = "" should "label the hints correctly", -> # TODO(philc): This test verifies the current behavior, but the current behavior is incorrect. # The output here should be something like aa, ab, b. hintMarkers = getHintMarkers() expectedHints = ["aa", "ba", "ab"] for hint, i in expectedHints assert.equal hint, hintMarkers[i].hintString should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "A" assert.equal "none", hintMarkers[1].style.display assert.equal "", hintMarkers[0].style.display context "Filtered link hints", # Note. In all of these tests, the order of the elements returned by getHintMarkers() may be different from # the order they are listed in the test HTML content. This is because LinkHints.activateMode() sorts the # elements. setup -> stubSettings "filterLinkHints", true stubSettings "linkHintNumbers", "0123456789" context "Text hints", setup -> initializeModeState() testContent = "<a>test</a>" + "<a>tress</a>" + "<a>trait</a>" + "<a>track<img alt='alt text'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the hints", -> hintMarkers = getHintMarkers() for i in [0...4] assert.equal (i + 1).toString(), hintMarkers[i].textContent.toLowerCase() should "narrow the hints", -> hintMarkers = getHintMarkers() sendKeyboardEvent "T" sendKeyboardEvent "R" assert.equal "none", hintMarkers[0].style.display assert.equal "1", hintMarkers[1].hintString assert.equal "", hintMarkers[1].style.display sendKeyboardEvent "A" assert.equal "2", hintMarkers[3].hintString context "Image hints", setup -> initializeModeState() testContent = "<a><img alt='alt text'/></a><a><img alt='alt text' title='some title'/></a> <a><img title='some title'/></a>" + "<a><img src='' width='320px' height='100px'/></a>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the images", -> hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-4]/, "N" assert.equal 4, hintMarkers.length assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N: some title" in hintMarkers assert.isTrue "N: alt text" in hintMarkers assert.isTrue "N" in hintMarkers context "Input hints", setup -> initializeModeState() testContent = "<input type='text' value='some value'/><input type='password' value='PI:PASSWORD:<PASSWORD>END_PI'/> <textarea>some text</textarea><label for='test-input'/>a label</label> <input type='text' id='test-input' value='some value'/> <label for='test-input-2'/>a label: </label><input type='text' id='test-input-2' value='some value'/>" document.getElementById("test-div").innerHTML = testContent @linkHints = LinkHints.activateMode() tearDown -> document.getElementById("test-div").innerHTML = "" @linkHints.deactivateMode() should "label the input elements", -> hintMarkers = getHintMarkers() hintMarkers = getHintMarkers().map (marker) -> marker.textContent.toLowerCase() # We don't know the actual hint numbers which will be assigned, so we replace them with "N". hintMarkers = hintMarkers.map (str) -> str.replace /^[1-5]/, "N" assert.equal 5, hintMarkers.length assert.isTrue "N" in hintMarkers assert.isTrue "N" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N: a label" in hintMarkers assert.isTrue "N" in hintMarkers context "Input focus", setup -> initializeModeState() testContent = "<input type='text' id='first'/><input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "focus the first element", -> focusInput 1 assert.equal "first", document.activeElement.id should "focus the nth element", -> focusInput 100 assert.equal "third", document.activeElement.id should "activate insert mode on the first element", -> focusInput 1 assert.isTrue InsertMode.permanentInstance.isActive() should "activate insert mode on the first element", -> focusInput 100 assert.isTrue InsertMode.permanentInstance.isActive() should "activate the most recently-selected input if the count is 1", -> focusInput 3 focusInput 1 assert.equal "third", document.activeElement.id should "not trigger insert if there are no inputs", -> document.getElementById("test-div").innerHTML = "" focusInput 1 assert.isFalse InsertMode.permanentInstance.isActive() # TODO: these find prev/next link tests could be refactored into unit tests which invoke a function which has # a tighter contract than goNext(), since they test minor aspects of goNext()'s link matching behavior, and we # don't need to construct external state many times over just to test that. # i.e. these tests should look something like: # assert.equal(findLink(html("<a href=...">))[0].href, "first") # These could then move outside of the dom_tests file. context "Find prev / next links", setup -> initializeModeState() window.location.hash = "" should "find exact matches", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>nextcorrupted</a> <a href='#second'>next page</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "match against non-word patterns", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>&gt;&gt;</a> """ stubSettings "nextPatterns", ">>" goNext() assert.equal '#first', window.location.hash should "favor matches with fewer words", -> document.getElementById("test-div").innerHTML = """ <a href='#first'>lorem ipsum next</a> <a href='#second'>next!</a> """ stubSettings "nextPatterns", "next" goNext() assert.equal '#second', window.location.hash should "find link relation in header", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> """ goNext() assert.equal '#first', window.location.hash should "favor link relation to text matching", -> document.getElementById("test-div").innerHTML = """ <link rel='next' href='#first'> <a href='#second'>next</a> """ goNext() assert.equal '#first', window.location.hash should "match mixed case link relation", -> document.getElementById("test-div").innerHTML = """ <link rel='Next' href='#first'> """ goNext() assert.equal '#first', window.location.hash createLinks = (n) -> for i in [0...n] by 1 link = document.createElement("a") link.textContent = "test" document.getElementById("test-div").appendChild link context "Normal mode", setup -> initializeModeState() should "suppress mapped keys", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 should "not suppress unmapped keys", -> sendKeyboardEvent "u" assert.equal pageKeyboardEventCount, 3 should "not suppress escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 should "not suppress passKeys", -> sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 3 should "suppress passKeys with a non-empty keyQueue", -> handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "p" sendKeyboardEvent "p" assert.equal pageKeyboardEventCount, 0 context "Insert mode", setup -> initializeModeState() @insertMode = new InsertMode global: true should "not suppress mapped keys in insert mode", -> sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 3 should "exit on escape", -> assert.isTrue @insertMode.modeIsActive sendKeyboardEvent "escape" assert.isFalse @insertMode.modeIsActive should "resume normal mode after leaving insert mode", -> @insertMode.exit() sendKeyboardEvent "m" assert.equal pageKeyboardEventCount, 0 context "Triggering insert mode", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='some value'/> <p id='fourth' contenteditable='true'/> <p id='fifth'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.activeElement?.blur() document.getElementById("test-div").innerHTML = "" should "trigger insert mode on focus of text input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("first").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of password input", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("third").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "trigger insert mode on focus of contentEditable elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fourth").focus() assert.isTrue InsertMode.permanentInstance.isActive() should "not trigger insert mode on other elements", -> assert.isFalse InsertMode.permanentInstance.isActive() document.getElementById("fifth").focus() assert.isFalse InsertMode.permanentInstance.isActive() context "Mode utilities", setup -> initializeModeState() testContent = "<input type='text' id='first'/> <input style='display:none;' id='second'/> <input type='password' id='third' value='PI:PASSWORD:<PASSWORD>END_PI'/>" document.getElementById("test-div").innerHTML = testContent tearDown -> document.getElementById("test-div").innerHTML = "" should "not have duplicate singletons", -> count = 0 class Test extends Mode constructor: -> count += 1; super singleton: Test exit: -> count -= 1; super() assert.isTrue count == 0 for [1..10] mode = new Test() assert.isTrue count == 1 mode.exit() assert.isTrue count == 0 should "exit on escape", -> test = new Mode exitOnEscape: true assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse test.modeIsActive should "not exit on escape if not enabled", -> test = new Mode exitOnEscape: false assert.isTrue test.modeIsActive sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 2 assert.isTrue test.modeIsActive should "exit on blur", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: element assert.isTrue test.modeIsActive element.blur() assert.isFalse test.modeIsActive should "not exit on blur if not enabled", -> element = document.getElementById("first") element.focus() test = new Mode exitOnBlur: false assert.isTrue test.modeIsActive element.blur() assert.isTrue test.modeIsActive should "register state change", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerStateChange", { enabled: "one", passKeys: "PI:KEY:<KEY>END_PI" } assert.isTrue test.enabled == "one" assert.isTrue test.passKeys == "two" should "register the keyQueue", -> test = new Mode trackState: true handlerStack.bubbleEvent "registerKeyQueue", keyQueue: "hello" assert.isTrue test.keyQueue == "hello" context "PostFindMode", setup -> initializeModeState() testContent = "<input type='text' id='first'/>" document.getElementById("test-div").innerHTML = testContent document.getElementById("first").focus() @postFindMode = new PostFindMode tearDown -> document.getElementById("test-div").innerHTML = "" should "be a singleton", -> assert.isTrue @postFindMode.modeIsActive new PostFindMode assert.isFalse @postFindMode.modeIsActive should "suppress unmapped printable keys", -> sendKeyboardEvent "m" assert.equal 0, pageKeyboardEventCount should "be deactivated on click events", -> handlerStack.bubbleEvent "click", target: document.activeElement assert.isFalse @postFindMode.modeIsActive should "enter insert mode on immediate escape", -> sendKeyboardEvent "escape" assert.equal pageKeyboardEventCount, 0 assert.isFalse @postFindMode.modeIsActive should "not enter insert mode on subsequent escapes", -> sendKeyboardEvent "a" sendKeyboardEvent "escape" assert.isTrue @postFindMode.modeIsActive
[ { "context": "icons/magnumci@2x.png'\n\n @_fields.push\n key: 'webhookUrl'\n type: 'text'\n readonly: true\n descript", "end": 927, "score": 0.90056312084198, "start": 917, "tag": "KEY", "value": "webhookUrl" } ]
src/services/magnumci.coffee
jianliaoim/talk-services
40
util = require '../util' _receiveWebhook = ({body}) -> payload = body?.payload try if toString.call(payload) is '[object String]' payload = JSON.parse payload return false unless toString.call(payload) is '[object Object]' catch err return false throw new Error('Params missing') unless payload.title message = attachments: [ category: 'quote' data: title: payload.title text: payload.message redirectUrl: payload.build_url ] message module.exports = -> @title = 'Magnum CI' @template = 'webhook' @summary = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @description = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @iconUrl = util.static 'images/icons/magnumci@2x.png' @_fields.push key: 'webhookUrl' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Magnum CI 中使用。' en: 'Copy this web hook to your Magnum CI account to use it.' @registerEvent 'service.webhook', _receiveWebhook
91711
util = require '../util' _receiveWebhook = ({body}) -> payload = body?.payload try if toString.call(payload) is '[object String]' payload = JSON.parse payload return false unless toString.call(payload) is '[object Object]' catch err return false throw new Error('Params missing') unless payload.title message = attachments: [ category: 'quote' data: title: payload.title text: payload.message redirectUrl: payload.build_url ] message module.exports = -> @title = 'Magnum CI' @template = 'webhook' @summary = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @description = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @iconUrl = util.static 'images/icons/magnumci@2x.png' @_fields.push key: '<KEY>' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Magnum CI 中使用。' en: 'Copy this web hook to your Magnum CI account to use it.' @registerEvent 'service.webhook', _receiveWebhook
true
util = require '../util' _receiveWebhook = ({body}) -> payload = body?.payload try if toString.call(payload) is '[object String]' payload = JSON.parse payload return false unless toString.call(payload) is '[object Object]' catch err return false throw new Error('Params missing') unless payload.title message = attachments: [ category: 'quote' data: title: payload.title text: payload.message redirectUrl: payload.build_url ] message module.exports = -> @title = 'Magnum CI' @template = 'webhook' @summary = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @description = util.i18n zh: '可用于私有项目的持续集成平台' en: 'Hosted Continuous Integration Platform for Private Repositories' @iconUrl = util.static 'images/icons/magnumci@2x.png' @_fields.push key: 'PI:KEY:<KEY>END_PI' type: 'text' readonly: true description: util.i18n zh: '复制 web hook 地址到你的 Magnum CI 中使用。' en: 'Copy this web hook to your Magnum CI account to use it.' @registerEvent 'service.webhook', _receiveWebhook
[ { "context": " list of hosts for a specific host\n#\n# Author:\n# pstack\n\nmodule.exports = (robot) ->\n\n password = \"0pent", "end": 553, "score": 0.9996460676193237, "start": 547, "tag": "USERNAME", "value": "pstack" }, { "context": "stack\n\nmodule.exports = (robot) ->\n\n password = \"0pentab1e\"\n url = \"https://tyson\"\n user = \"hubot\"\n auth ", "end": 607, "score": 0.9994074106216431, "start": 598, "tag": "PASSWORD", "value": "0pentab1e" }, { "context": "d = \"0pentab1e\"\n url = \"https://tyson\"\n user = \"hubot\"\n auth = 'Basic ' + new Buffer(\"#{user}:#{passwo", "end": 648, "score": 0.9991163015365601, "start": 643, "tag": "USERNAME", "value": "hubot" } ]
src/scripts/foreman.coffee
ryantomlinson/hubot-scripts
0
# Description: # Script to interact with foreman # # Dependencies: # None # # Configuration: # HUBOT_FOREMAN_URL # HUBOT_FOREMAN_USER # HUBOT_FOREMAN_PASSWORD # # Commands: # hubot foreman hosts - gets a list of hosts from foreman # hubot foreman environments - gets a lot of environments from foreman # hubot foreman users - gets a list of users from foreman # hubot foreman facts - gets a list of facts from foreman # hubot foreman [HOST] facts - gets a list of hosts for a specific host # # Author: # pstack module.exports = (robot) -> password = "0pentab1e" url = "https://tyson" user = "hubot" auth = 'Basic ' + new Buffer("#{user}:#{password}").toString('base64') query = (msg, path) -> msg.http("#{url}/#{path}?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) host = (msg, host) -> msg.http("#{url}/#{host}/facts?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) robot.respond /foreman (hosts|environments|users|facts})/i, (msg) -> if msg.message.user.id is robot.name return query msg, msg.match[1], (text) -> msg.send(text) robot.respond /foreman (.*) facts/i, (msg) -> if msg.message.user.id is robot.name return host msg, msg.match[1], (text) -> msg.send(text)
172079
# Description: # Script to interact with foreman # # Dependencies: # None # # Configuration: # HUBOT_FOREMAN_URL # HUBOT_FOREMAN_USER # HUBOT_FOREMAN_PASSWORD # # Commands: # hubot foreman hosts - gets a list of hosts from foreman # hubot foreman environments - gets a lot of environments from foreman # hubot foreman users - gets a list of users from foreman # hubot foreman facts - gets a list of facts from foreman # hubot foreman [HOST] facts - gets a list of hosts for a specific host # # Author: # pstack module.exports = (robot) -> password = "<PASSWORD>" url = "https://tyson" user = "hubot" auth = 'Basic ' + new Buffer("#{user}:#{password}").toString('base64') query = (msg, path) -> msg.http("#{url}/#{path}?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) host = (msg, host) -> msg.http("#{url}/#{host}/facts?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) robot.respond /foreman (hosts|environments|users|facts})/i, (msg) -> if msg.message.user.id is robot.name return query msg, msg.match[1], (text) -> msg.send(text) robot.respond /foreman (.*) facts/i, (msg) -> if msg.message.user.id is robot.name return host msg, msg.match[1], (text) -> msg.send(text)
true
# Description: # Script to interact with foreman # # Dependencies: # None # # Configuration: # HUBOT_FOREMAN_URL # HUBOT_FOREMAN_USER # HUBOT_FOREMAN_PASSWORD # # Commands: # hubot foreman hosts - gets a list of hosts from foreman # hubot foreman environments - gets a lot of environments from foreman # hubot foreman users - gets a list of users from foreman # hubot foreman facts - gets a list of facts from foreman # hubot foreman [HOST] facts - gets a list of hosts for a specific host # # Author: # pstack module.exports = (robot) -> password = "PI:PASSWORD:<PASSWORD>END_PI" url = "https://tyson" user = "hubot" auth = 'Basic ' + new Buffer("#{user}:#{password}").toString('base64') query = (msg, path) -> msg.http("#{url}/#{path}?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) host = (msg, host) -> msg.http("#{url}/#{host}/facts?format=json") .headers 'Authorization': auth .request({rejectUnauthorized: false}) (err, res, body) -> msg.send(body) robot.respond /foreman (hosts|environments|users|facts})/i, (msg) -> if msg.message.user.id is robot.name return query msg, msg.match[1], (text) -> msg.send(text) robot.respond /foreman (.*) facts/i, (msg) -> if msg.message.user.id is robot.name return host msg, msg.match[1], (text) -> msg.send(text)
[ { "context": "ader: loader\n wrapped\n greeting: 'Hei'\n name: 'Maailma'\n , (err, res) -", "end": 4769, "score": 0.9461231231689453, "start": 4766, "tag": "NAME", "value": "Hei" }, { "context": "rapped\n greeting: 'Hei'\n name: 'Maailma'\n , (err, res) ->\n return done er", "end": 4795, "score": 0.9987758994102478, "start": 4788, "tag": "NAME", "value": "Maailma" }, { "context": " chai.expect(res).to.eql\n out: 'Hei Maailma'\n done()\n describe 'with a default va", "end": 4917, "score": 0.9390133619308472, "start": 4906, "tag": "NAME", "value": "Hei Maailma" }, { "context": " loader: loader\n wrapped\n name: 'Maailma'\n , (err, res) ->\n return done er", "end": 6240, "score": 0.9997560381889343, "start": 6233, "tag": "NAME", "value": "Maailma" }, { "context": " chai.expect(res).to.eql\n out: 'Hello Maailma'\n done()\n describe 'with a function ret", "end": 6364, "score": 0.9997342228889465, "start": 6357, "tag": "NAME", "value": "Maailma" } ]
spec/AsComponent.coffee
rrothenb/noflo
0
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' path = require 'path' root = path.resolve __dirname, '../' urlPrefix = './' isBrowser = false else noflo = require 'noflo' root = 'noflo' urlPrefix = '/' isBrowser = true describe 'asComponent interface', -> loader = null before (done) -> loader = new noflo.ComponentLoader root loader.listComponents done describe 'with a synchronous function taking a single parameter', -> describe 'with returned value', -> func = (hello) -> return "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() it 'should forward brackets to OUT port', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err ins = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() error = new noflo.internalSocket.createSocket() instance.inPorts.hello.attach ins instance.outPorts.out.attach out instance.outPorts.error.attach error received = [] expected = [ 'openBracket a' 'data Hello Foo' 'data Hello Bar' 'data Hello Baz' 'closeBracket a' ] error.once 'data', (data) -> done data out.on 'ip', (ip) -> received.push "#{ip.type} #{ip.data}" return unless received.length is expected.length chai.expect(received).to.eql expected done() ins.post new noflo.IP 'openBracket', 'a' ins.post new noflo.IP 'data', 'Foo' ins.post new noflo.IP 'data', 'Bar' ins.post new noflo.IP 'data', 'Baz' ins.post new noflo.IP 'closeBracket', 'a' describe 'with returned NULL', -> func = (hello) -> return null it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-null', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-null', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.be.a 'null' done() describe 'with a thrown exception', -> func = (hello) -> throw new Error "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking a multiple parameters', -> describe 'with returned value', -> func = (greeting, name) -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-two', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-two', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-two', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['greeting', 'name'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-two', loader: loader wrapped greeting: 'Hei' name: 'Maailma' , (err, res) -> return done err if err chai.expect(res).to.eql out: 'Hei Maailma' done() describe 'with a default value', -> before -> @skip() if isBrowser # Browser runs with ES5 which didn't have defaults func = (name, greeting = 'Hello') -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-default', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-default', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-default', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['name', 'greeting'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] chai.expect(instance.inPorts.name.isRequired()).to.equal true chai.expect(instance.inPorts.name.hasDefault()).to.equal false chai.expect(instance.inPorts.greeting.isRequired()).to.equal false chai.expect(instance.inPorts.greeting.hasDefault()).to.equal true done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-default', loader: loader wrapped name: 'Maailma' , (err, res) -> return done err if err chai.expect(res).to.eql out: 'Hello Maailma' done() describe 'with a function returning a Promise', -> describe 'with a resolved promise', -> before -> @skip() if isBrowser and typeof window.Promise is 'undefined' func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> resolve "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'promise-one', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/promise-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with a rejected promise', -> before -> if isBrowser and typeof window.Promise is 'undefined' return @skip() func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> reject new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking zero parameters', -> describe 'with returned value', -> func = () -> return "Hello there" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello there' done() describe 'with a built-in function', -> it 'should be possible to componentize', (done) -> component = -> noflo.asComponent Math.random loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.be.a 'number' done() describe 'with an asynchronous function taking a single parameter and callback', -> describe 'with successful callback', -> func = (hello, callback) -> setTimeout -> callback null, "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/async-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/async-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with failed callback', -> func = (hello, callback) -> setTimeout -> callback new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done()
115938
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' path = require 'path' root = path.resolve __dirname, '../' urlPrefix = './' isBrowser = false else noflo = require 'noflo' root = 'noflo' urlPrefix = '/' isBrowser = true describe 'asComponent interface', -> loader = null before (done) -> loader = new noflo.ComponentLoader root loader.listComponents done describe 'with a synchronous function taking a single parameter', -> describe 'with returned value', -> func = (hello) -> return "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() it 'should forward brackets to OUT port', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err ins = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() error = new noflo.internalSocket.createSocket() instance.inPorts.hello.attach ins instance.outPorts.out.attach out instance.outPorts.error.attach error received = [] expected = [ 'openBracket a' 'data Hello Foo' 'data Hello Bar' 'data Hello Baz' 'closeBracket a' ] error.once 'data', (data) -> done data out.on 'ip', (ip) -> received.push "#{ip.type} #{ip.data}" return unless received.length is expected.length chai.expect(received).to.eql expected done() ins.post new noflo.IP 'openBracket', 'a' ins.post new noflo.IP 'data', 'Foo' ins.post new noflo.IP 'data', 'Bar' ins.post new noflo.IP 'data', 'Baz' ins.post new noflo.IP 'closeBracket', 'a' describe 'with returned NULL', -> func = (hello) -> return null it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-null', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-null', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.be.a 'null' done() describe 'with a thrown exception', -> func = (hello) -> throw new Error "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking a multiple parameters', -> describe 'with returned value', -> func = (greeting, name) -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-two', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-two', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-two', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['greeting', 'name'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-two', loader: loader wrapped greeting: '<NAME>' name: '<NAME>' , (err, res) -> return done err if err chai.expect(res).to.eql out: '<NAME>' done() describe 'with a default value', -> before -> @skip() if isBrowser # Browser runs with ES5 which didn't have defaults func = (name, greeting = 'Hello') -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-default', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-default', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-default', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['name', 'greeting'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] chai.expect(instance.inPorts.name.isRequired()).to.equal true chai.expect(instance.inPorts.name.hasDefault()).to.equal false chai.expect(instance.inPorts.greeting.isRequired()).to.equal false chai.expect(instance.inPorts.greeting.hasDefault()).to.equal true done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-default', loader: loader wrapped name: '<NAME>' , (err, res) -> return done err if err chai.expect(res).to.eql out: 'Hello <NAME>' done() describe 'with a function returning a Promise', -> describe 'with a resolved promise', -> before -> @skip() if isBrowser and typeof window.Promise is 'undefined' func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> resolve "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'promise-one', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/promise-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with a rejected promise', -> before -> if isBrowser and typeof window.Promise is 'undefined' return @skip() func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> reject new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking zero parameters', -> describe 'with returned value', -> func = () -> return "Hello there" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello there' done() describe 'with a built-in function', -> it 'should be possible to componentize', (done) -> component = -> noflo.asComponent Math.random loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.be.a 'number' done() describe 'with an asynchronous function taking a single parameter and callback', -> describe 'with successful callback', -> func = (hello, callback) -> setTimeout -> callback null, "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/async-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/async-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with failed callback', -> func = (hello, callback) -> setTimeout -> callback new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done()
true
if typeof process isnt 'undefined' and process.execPath and process.execPath.match /node|iojs/ chai = require 'chai' unless chai noflo = require '../src/lib/NoFlo.coffee' path = require 'path' root = path.resolve __dirname, '../' urlPrefix = './' isBrowser = false else noflo = require 'noflo' root = 'noflo' urlPrefix = '/' isBrowser = true describe 'asComponent interface', -> loader = null before (done) -> loader = new noflo.ComponentLoader root loader.listComponents done describe 'with a synchronous function taking a single parameter', -> describe 'with returned value', -> func = (hello) -> return "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() it 'should forward brackets to OUT port', (done) -> loader.load 'ascomponent/sync-one', (err, instance) -> return done err if err ins = new noflo.internalSocket.createSocket() out = new noflo.internalSocket.createSocket() error = new noflo.internalSocket.createSocket() instance.inPorts.hello.attach ins instance.outPorts.out.attach out instance.outPorts.error.attach error received = [] expected = [ 'openBracket a' 'data Hello Foo' 'data Hello Bar' 'data Hello Baz' 'closeBracket a' ] error.once 'data', (data) -> done data out.on 'ip', (ip) -> received.push "#{ip.type} #{ip.data}" return unless received.length is expected.length chai.expect(received).to.eql expected done() ins.post new noflo.IP 'openBracket', 'a' ins.post new noflo.IP 'data', 'Foo' ins.post new noflo.IP 'data', 'Bar' ins.post new noflo.IP 'data', 'Baz' ins.post new noflo.IP 'closeBracket', 'a' describe 'with returned NULL', -> func = (hello) -> return null it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-null', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-null', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.be.a 'null' done() describe 'with a thrown exception', -> func = (hello) -> throw new Error "Hello #{hello}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking a multiple parameters', -> describe 'with returned value', -> func = (greeting, name) -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-two', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-two', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-two', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['greeting', 'name'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-two', loader: loader wrapped greeting: 'PI:NAME:<NAME>END_PI' name: 'PI:NAME:<NAME>END_PI' , (err, res) -> return done err if err chai.expect(res).to.eql out: 'PI:NAME:<NAME>END_PI' done() describe 'with a default value', -> before -> @skip() if isBrowser # Browser runs with ES5 which didn't have defaults func = (name, greeting = 'Hello') -> return "#{greeting} #{name}" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-default', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/sync-default', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-default', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['name', 'greeting'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] chai.expect(instance.inPorts.name.isRequired()).to.equal true chai.expect(instance.inPorts.name.hasDefault()).to.equal false chai.expect(instance.inPorts.greeting.isRequired()).to.equal false chai.expect(instance.inPorts.greeting.hasDefault()).to.equal true done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-default', loader: loader wrapped name: 'PI:NAME:<NAME>END_PI' , (err, res) -> return done err if err chai.expect(res).to.eql out: 'Hello PI:NAME:<NAME>END_PI' done() describe 'with a function returning a Promise', -> describe 'with a resolved promise', -> before -> @skip() if isBrowser and typeof window.Promise is 'undefined' func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> resolve "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'promise-one', component, done it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/promise-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with a rejected promise', -> before -> if isBrowser and typeof window.Promise is 'undefined' return @skip() func = (hello) -> return new Promise (resolve, reject) -> setTimeout -> reject new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done() describe 'with a synchronous function taking zero parameters', -> describe 'with returned value', -> func = () -> return "Hello there" it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello there' done() describe 'with a built-in function', -> it 'should be possible to componentize', (done) -> component = -> noflo.asComponent Math.random loader.registerComponent 'ascomponent', 'sync-zero', component, done it 'should contain correct ports', (done) -> loader.load 'ascomponent/sync-zero', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['in'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/sync-zero', loader: loader wrapped 'bang', (err, res) -> return done err if err chai.expect(res).to.be.a 'number' done() describe 'with an asynchronous function taking a single parameter and callback', -> describe 'with successful callback', -> func = (hello, callback) -> setTimeout -> callback null, "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-one', component, done it 'should be loadable', (done) -> loader.load 'ascomponent/async-one', done it 'should contain correct ports', (done) -> loader.load 'ascomponent/async-one', (err, instance) -> return done err if err chai.expect(Object.keys(instance.inPorts.ports)).to.eql ['hello'] chai.expect(Object.keys(instance.outPorts.ports)).to.eql ['out', 'error'] done() it 'should send to OUT port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-one', loader: loader wrapped 'World', (err, res) -> return done err if err chai.expect(res).to.equal 'Hello World' done() describe 'with failed callback', -> func = (hello, callback) -> setTimeout -> callback new Error "Hello #{hello}" , 5 it 'should be possible to componentize', (done) -> component = -> noflo.asComponent func loader.registerComponent 'ascomponent', 'async-throw', component, done it 'should send to ERROR port', (done) -> wrapped = noflo.asCallback 'ascomponent/async-throw', loader: loader wrapped 'Error', (err) -> chai.expect(err).to.be.an 'error' chai.expect(err.message).to.equal 'Hello Error' done()
[ { "context": "ist - Show the watched repositories\n#\n# Author:\n# nounoursheureux\n\nrequest = require('request')\n\nmodule.exports = (", "end": 346, "score": 0.9994174838066101, "start": 331, "tag": "USERNAME", "value": "nounoursheureux" }, { "context": "ser: process.env.HUBOT_WATCH_USERNAME,\n pass: process.env.HUBOT_WATCH_PASSWORD\n },\n headers: {\n 'User-Agent':", "end": 701, "score": 0.9194433689117432, "start": 677, "tag": "PASSWORD", "value": "process.env.HUBOT_WATCH_" } ]
lib/hubot-watch.coffee
nounoursheureux/hubot-watch
1
# Description: # Watch Github repositories with Hubot # # Dependencies: # "request": "*" # # Configuration: # HUBOT_WATCH_USERNAME # HUBOT_WATCH_PASSWORD # HUBOT_WATCH_IGNORED # # Commands: # hubot watch <repository> - Add the repository to the watchlist # hubot watch list - Show the watched repositories # # Author: # nounoursheureux request = require('request') module.exports = (robot) -> if not process.env.HUBOT_WATCH_USERNAME or not process.env.HUBOT_WATCH_PASSWORD robot.send '','Please provide your Github credentials' return watched = [] req_options = { json: true, auth: { user: process.env.HUBOT_WATCH_USERNAME, pass: process.env.HUBOT_WATCH_PASSWORD }, headers: { 'User-Agent': 'hubot-watch' } } robot.respond /watch (.+)\/(.+)/i, (res) -> repo = "#{res.match[1]}/#{res.match[2]}" if watched[repo] res.send 'I am already watching this repository' else req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err,response,obj) -> throw err if err if obj.message res.send obj.message else watched[repo] = obj[0].id res.send "Watching #{repo}" robot.respond /watch list/i, (res) -> for repo of watched res.send repo setInterval -> for repo of watched req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err, response, obj) -> if obj[0].id != watched[repo] robot.send '',repo + ": " + handleEvent obj[0] unless process.env.HUBOT_WATCH_IGNORED and process.env.HUBOT_WATCH_IGNORED.indexOf(obj[0].type) isnt -1 watched[repo] = obj[0].id ,1000 handleEvent = (event) -> switch event.type when "IssuesEvent" return "#{event.actor.login} #{event.payload.action} issue ##{event.payload.issue.number}: #{event.payload.issue.title}" when "IssueCommentEvent" return "#{event.actor.login} commented on issue ##{event.payload.issue.number}: #{event.payload.comment.body}" when "PullRequestEvent" return "#{event.actor.login} #{event.payload.action} pull request ##{event.payload.pull_request.number}: #{event.payload.pull_request.title}" when "PushEvent" return "#{event.actor.login} pushed to #{event.payload.ref.replace('refs/heads/','')}" when "CreateEvent" return "#{event.actor.login} created #{event.payload.ref_type} #{event.payload.ref}" when "DeleteEvent" return "#{event.actor.login} deleted #{event.payload.ref_type} #{event.payload.ref}" when "GollumEvent" return "#{event.actor.login} #{event.payload.pages[0].action} the wiki page: #{event.payload.pages[0].title}" when "MemberEvent" return "#{event.actor.login} #{event.payload.action} #{event.payload.member.login} to the collaborators" when "WatchEvent" return "#{event.actor.login} gave a star" when "ForkEvent" return "#{event.actor.login} forked to #{event.payload.forkee.full-name}" else return "Cannot handle event type: #{event.type}"
125244
# Description: # Watch Github repositories with Hubot # # Dependencies: # "request": "*" # # Configuration: # HUBOT_WATCH_USERNAME # HUBOT_WATCH_PASSWORD # HUBOT_WATCH_IGNORED # # Commands: # hubot watch <repository> - Add the repository to the watchlist # hubot watch list - Show the watched repositories # # Author: # nounoursheureux request = require('request') module.exports = (robot) -> if not process.env.HUBOT_WATCH_USERNAME or not process.env.HUBOT_WATCH_PASSWORD robot.send '','Please provide your Github credentials' return watched = [] req_options = { json: true, auth: { user: process.env.HUBOT_WATCH_USERNAME, pass: <PASSWORD>PASSWORD }, headers: { 'User-Agent': 'hubot-watch' } } robot.respond /watch (.+)\/(.+)/i, (res) -> repo = "#{res.match[1]}/#{res.match[2]}" if watched[repo] res.send 'I am already watching this repository' else req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err,response,obj) -> throw err if err if obj.message res.send obj.message else watched[repo] = obj[0].id res.send "Watching #{repo}" robot.respond /watch list/i, (res) -> for repo of watched res.send repo setInterval -> for repo of watched req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err, response, obj) -> if obj[0].id != watched[repo] robot.send '',repo + ": " + handleEvent obj[0] unless process.env.HUBOT_WATCH_IGNORED and process.env.HUBOT_WATCH_IGNORED.indexOf(obj[0].type) isnt -1 watched[repo] = obj[0].id ,1000 handleEvent = (event) -> switch event.type when "IssuesEvent" return "#{event.actor.login} #{event.payload.action} issue ##{event.payload.issue.number}: #{event.payload.issue.title}" when "IssueCommentEvent" return "#{event.actor.login} commented on issue ##{event.payload.issue.number}: #{event.payload.comment.body}" when "PullRequestEvent" return "#{event.actor.login} #{event.payload.action} pull request ##{event.payload.pull_request.number}: #{event.payload.pull_request.title}" when "PushEvent" return "#{event.actor.login} pushed to #{event.payload.ref.replace('refs/heads/','')}" when "CreateEvent" return "#{event.actor.login} created #{event.payload.ref_type} #{event.payload.ref}" when "DeleteEvent" return "#{event.actor.login} deleted #{event.payload.ref_type} #{event.payload.ref}" when "GollumEvent" return "#{event.actor.login} #{event.payload.pages[0].action} the wiki page: #{event.payload.pages[0].title}" when "MemberEvent" return "#{event.actor.login} #{event.payload.action} #{event.payload.member.login} to the collaborators" when "WatchEvent" return "#{event.actor.login} gave a star" when "ForkEvent" return "#{event.actor.login} forked to #{event.payload.forkee.full-name}" else return "Cannot handle event type: #{event.type}"
true
# Description: # Watch Github repositories with Hubot # # Dependencies: # "request": "*" # # Configuration: # HUBOT_WATCH_USERNAME # HUBOT_WATCH_PASSWORD # HUBOT_WATCH_IGNORED # # Commands: # hubot watch <repository> - Add the repository to the watchlist # hubot watch list - Show the watched repositories # # Author: # nounoursheureux request = require('request') module.exports = (robot) -> if not process.env.HUBOT_WATCH_USERNAME or not process.env.HUBOT_WATCH_PASSWORD robot.send '','Please provide your Github credentials' return watched = [] req_options = { json: true, auth: { user: process.env.HUBOT_WATCH_USERNAME, pass: PI:PASSWORD:<PASSWORD>END_PIPASSWORD }, headers: { 'User-Agent': 'hubot-watch' } } robot.respond /watch (.+)\/(.+)/i, (res) -> repo = "#{res.match[1]}/#{res.match[2]}" if watched[repo] res.send 'I am already watching this repository' else req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err,response,obj) -> throw err if err if obj.message res.send obj.message else watched[repo] = obj[0].id res.send "Watching #{repo}" robot.respond /watch list/i, (res) -> for repo of watched res.send repo setInterval -> for repo of watched req_options.url = "https://api.github.com/repos/#{repo}/events" request req_options, (err, response, obj) -> if obj[0].id != watched[repo] robot.send '',repo + ": " + handleEvent obj[0] unless process.env.HUBOT_WATCH_IGNORED and process.env.HUBOT_WATCH_IGNORED.indexOf(obj[0].type) isnt -1 watched[repo] = obj[0].id ,1000 handleEvent = (event) -> switch event.type when "IssuesEvent" return "#{event.actor.login} #{event.payload.action} issue ##{event.payload.issue.number}: #{event.payload.issue.title}" when "IssueCommentEvent" return "#{event.actor.login} commented on issue ##{event.payload.issue.number}: #{event.payload.comment.body}" when "PullRequestEvent" return "#{event.actor.login} #{event.payload.action} pull request ##{event.payload.pull_request.number}: #{event.payload.pull_request.title}" when "PushEvent" return "#{event.actor.login} pushed to #{event.payload.ref.replace('refs/heads/','')}" when "CreateEvent" return "#{event.actor.login} created #{event.payload.ref_type} #{event.payload.ref}" when "DeleteEvent" return "#{event.actor.login} deleted #{event.payload.ref_type} #{event.payload.ref}" when "GollumEvent" return "#{event.actor.login} #{event.payload.pages[0].action} the wiki page: #{event.payload.pages[0].title}" when "MemberEvent" return "#{event.actor.login} #{event.payload.action} #{event.payload.member.login} to the collaborators" when "WatchEvent" return "#{event.actor.login} gave a star" when "ForkEvent" return "#{event.actor.login} forked to #{event.payload.forkee.full-name}" else return "Cannot handle event type: #{event.type}"
[ { "context": "\"Myśliwiec TIE\"\n name: \"Pilot Eskadry Czarnych\"\n '\"Winged Gundark\"':\n name: \"S", "end": 8103, "score": 0.7276742458343506, "start": 8096, "tag": "NAME", "value": "zarnych" }, { "context": " name: \"Pilot Eskadry Czarnych\"\n '\"Winged Gundark\"':\n name: \"Skrzydlaty Gundark\"\n ", "end": 8129, "score": 0.9236757159233093, "start": 8115, "tag": "NAME", "value": "Winged Gundark" }, { "context": "h\"\n '\"Winged Gundark\"':\n name: \"Skrzydlaty Gundark\"\n ship: \"Myśliwiec TIE\"\n te", "end": 8170, "score": 0.9994423389434814, "start": 8152, "tag": "NAME", "value": "Skrzydlaty Gundark" }, { "context": "%.\"\"\"\n '\"Night Beast\"':\n name: \"Nocny Potwór\"\n ship: \"Myśliwiec TIE\"\n te", "end": 8373, "score": 0.9997555017471313, "start": 8361, "tag": "NAME", "value": "Nocny Potwór" }, { "context": "ku.\"\"\"\n '\"Dark Curse\"':\n name: \"Mroczna Klątwa\"\n ship: \"Myśliwiec TIE\"\n te", "end": 8742, "score": 0.9998754858970642, "start": 8728, "tag": "NAME", "value": "Mroczna Klątwa" }, { "context": "kupienia ani przerzucać kości ataku.\"\"\"\n '\"Mauler Mithel\"':\n ship: \"Myśliwiec TIE\"\n ", "end": 8931, "score": 0.9996094703674316, "start": 8918, "tag": "NAME", "value": "Mauler Mithel" }, { "context": " \"Alpha Squadron Pilot\":\n name: \"Pilot Eskadry Alfa\"\n \"Avenger Squadron Pilot\":\n ", "end": 9338, "score": 0.6877190470695496, "start": 9337, "tag": "NAME", "value": "E" }, { "context": "ha Squadron Pilot\":\n name: \"Pilot Eskadry Alfa\"\n \"Avenger Squadron Pilot\":\n na", "end": 9349, "score": 0.7361570596694946, "start": 9342, "tag": "NAME", "value": "ry Alfa" }, { "context": "\"Avenger Squadron Pilot\":\n name: \"Pilot Eskadry Mścicieli\"\n \"Saber Squadron Pilot\":\n ", "end": 9417, "score": 0.7247439026832581, "start": 9410, "tag": "NAME", "value": "Eskadry" }, { "context": "quadron Pilot\":\n name: \"Pilot Eskadry Mścicieli\"\n \"Saber Squadron Pilot\":\n name", "end": 9427, "score": 0.758370041847229, "start": 9419, "tag": "NAME", "value": "ścicieli" }, { "context": " \"Saber Squadron Pilot\":\n name: \"Pilot Eskadry Szabel\"\n \"Royal Guard Pilot\":\n name: \"", "end": 9500, "score": 0.9995935559272766, "start": 9486, "tag": "NAME", "value": "Eskadry Szabel" }, { "context": " name: \"Pilot imperialny gwardzista\"\n \"\\\"Fel's Wrath\\\"\":\n name: \"\\\"Gniew Fel'a\\\"\"\n ", "end": 9601, "score": 0.9924663305282593, "start": 9590, "tag": "NAME", "value": "Fel's Wrath" }, { "context": "\"\n \"\\\"Fel's Wrath\\\"\":\n name: \"\\\"Gniew Fel'a\\\"\"\n text: \"\"\"Zostajesz zniszczony dopi", "end": 9638, "score": 0.9997835159301758, "start": 9627, "tag": "NAME", "value": "Gniew Fel'a" }, { "context": "ub wyższa od twojej wartości kadłuba.\"\"\"\n \"Lieutenant Lorrir\":\n name: \"Porucznik Lorrir\"\n ", "end": 9851, "score": 0.9998737573623657, "start": 9834, "tag": "NAME", "value": "Lieutenant Lorrir" }, { "context": "\"\n \"Lieutenant Lorrir\":\n name: \"Porucznik Lorrir\"\n text: \"\"\"Kiedy wykonujesz akcję \"bec", "end": 9889, "score": 0.9998560547828674, "start": 9873, "tag": "NAME", "value": "Porucznik Lorrir" }, { "context": "ć (%BANKLEFT% 1) lub (%BANKRIGHT% 1).\"\"\"\n \"Kir Kanos\":\n text: \"\"\"Kiedy atakujesz w Zasięgu ", "end": 10083, "score": 0.999894917011261, "start": 10074, "tag": "NAME", "value": "Kir Kanos" }, { "context": " aby dodać 1 %HIT% do swojego wyniku.\"\"\"\n \"Tetran Cowall\":\n text: \"\"\"Kiedy ujawnisz manewr %UTU", "end": 10229, "score": 0.9998987317085266, "start": 10216, "tag": "NAME", "value": "Tetran Cowall" }, { "context": "o prędkość wynosiła \"1\", \"3\" lub \"5\".\"\"\"\n \"Turr Phennir\":\n text: \"\"\"Po wykonaniu ataku możesz ", "end": 10379, "score": 0.999891459941864, "start": 10367, "tag": "NAME", "value": "Turr Phennir" }, { "context": "armową akcję \"dopalacz\" lub \"beczka\".\"\"\"\n \"Carnor Jax\":\n text: \"\"\"Wrogie statki w Zasięgu 1 ", "end": 10498, "score": 0.9998880624771118, "start": 10488, "tag": "NAME", "value": "Carnor Jax" }, { "context": "i wydawać żetonów skupienia i uników.\"\"\"\n \"Soontir Fel\":\n text: \"\"\"Kiedy otrzymujesz żeton st", "end": 10661, "score": 0.9998824000358582, "start": 10650, "tag": "NAME", "value": "Soontir Fel" }, { "context": "T% 2).\"\"\"\n '\"Whisper\"':\n name: \"Szept\"\n text: \"\"\"Po tym jak wykonasz atak, k", "end": 11147, "score": 0.6780827641487122, "start": 11142, "tag": "NAME", "value": "Szept" }, { "context": "\n name: \"Pilot Eskadry Delta\"\n \"Colonel Vessery\":\n name: \"Pułkownik Vessery\"\n ", "end": 11459, "score": 0.9795443415641785, "start": 11444, "tag": "NAME", "value": "Colonel Vessery" }, { "context": "ta\"\n \"Colonel Vessery\":\n name: \"Pułkownik Vessery\"\n text: \"\"\"Kiedy atakujesz, zaraz po s", "end": 11498, "score": 0.9991066455841064, "start": 11481, "tag": "NAME", "value": "Pułkownik Vessery" }, { "context": "bie czerwony żeton namierzonego celu.\"\"\"\n \"Rexler Brath\":\n text: \"\"\"Po tym jak wykonasz atak, ", "end": 11675, "score": 0.9759472012519836, "start": 11663, "tag": "NAME", "value": "Rexler Brath" }, { "context": " name: \"Pilot Eskadry Gamma\"\n \"Captain Jonus\":\n ship: \"Bombowiec TIE\"\n n", "end": 12100, "score": 0.6863970756530762, "start": 12091, "tag": "NAME", "value": "ain Jonus" }, { "context": " ship: \"Bombowiec TIE\"\n name: \"Kapitan Jonus\"\n text: \"Kiedy inny przyjazny statek w", "end": 12169, "score": 0.9883948564529419, "start": 12156, "tag": "NAME", "value": "Kapitan Jonus" }, { "context": " name: \"Pilot Eskadry Szturmu\"\n \"Maarek Stele\":\n text: \"\"\"Kiedy twój atak zadaje obr", "end": 12790, "score": 0.999852180480957, "start": 12778, "tag": "NAME", "value": "Maarek Stele" }, { "context": ", którą zadajesz, a pozostałe odrzuć.\"\"\"\n \"Darth Vader\":\n text: \"\"\"Podczas swojego kroku \"Wyk", "end": 12976, "score": 0.9993114471435547, "start": 12965, "tag": "NAME", "value": "Darth Vader" }, { "context": "ywania akcji\" możesz wykonać 2 akcje.\"\"\"\n \"Commander Alozen\":\n name: \"Komandor Alozen\"\n ", "end": 13094, "score": 0.9997400045394897, "start": 13078, "tag": "NAME", "value": "Commander Alozen" }, { "context": "\"\"\n \"Commander Alozen\":\n name: \"Komandor Alozen\"\n text: \"\"\"Na początku fazy walki może", "end": 13131, "score": 0.9998397827148438, "start": 13116, "tag": "NAME", "value": "Komandor Alozen" }, { "context": "ięgu 1 od ciebie.\"\"\"\n # Firespray\n \"Bounty Hunter\":\n name:\"Łowca nagród\"\n \"Kath S", "end": 13290, "score": 0.9989383816719055, "start": 13277, "tag": "NAME", "value": "Bounty Hunter" }, { "context": "espray\n \"Bounty Hunter\":\n name:\"Łowca nagród\"\n \"Kath Scarlet\":\n text: \"\"\"Kie", "end": 13323, "score": 0.8668785095214844, "start": 13311, "tag": "NAME", "value": "Łowca nagród" }, { "context": "Hunter\":\n name:\"Łowca nagród\"\n \"Kath Scarlet\":\n text: \"\"\"Kiedy atakujesz, obrońca o", "end": 13346, "score": 0.999790370464325, "start": 13334, "tag": "NAME", "value": "Kath Scarlet" }, { "context": "uluje co najmniej jeden wynik %CRIT%.\"\"\"\n \"Boba Fett\":\n text: \"\"\"Kiedy ujawniasz manewr skr", "end": 13488, "score": 0.9998389482498169, "start": 13479, "tag": "NAME", "value": "Boba Fett" }, { "context": " manewr skrętu o tej samej prędkości.\"\"\"\n \"Krassis Trelix\":\n text: \"\"\"Kiedy atakujesz przy pomoc", "end": 13684, "score": 0.9996399879455566, "start": 13670, "tag": "NAME", "value": "Krassis Trelix" }, { "context": "ość ataku.\"\"\"\n # Prom typu Lambda\n \"Captain Kagi\":\n ship: \"Prom typu Lambda\"\n ", "end": 13837, "score": 0.9998373985290527, "start": 13825, "tag": "NAME", "value": "Captain Kagi" }, { "context": " ship: \"Prom typu Lambda\"\n name: \"Kapitan Kagi\"\n text: \"\"\"Kiedy wrogi statek namierza", "end": 13908, "score": 0.9998912811279297, "start": 13896, "tag": "NAME", "value": "Kapitan Kagi" }, { "context": "ierzyć twój statek, jeśli to możliwe.\"\"\"\n \"Colonel Jendon\":\n name: \"Pułkownik Jendon\"\n ", "end": 14036, "score": 0.9998940229415894, "start": 14022, "tag": "NAME", "value": "Colonel Jendon" }, { "context": ".\"\"\"\n \"Colonel Jendon\":\n name: \"Pułkownik Jendon\"\n ship: \"Prom typu Lambda\"\n ", "end": 14074, "score": 0.9998988509178162, "start": 14058, "tag": "NAME", "value": "Pułkownik Jendon" }, { "context": "iebieskiego żetonu namierzonego celu.\"\"\"\n \"Captain Yorr\":\n ship: \"Prom typu Lambda\"\n ", "end": 14339, "score": 0.9998449087142944, "start": 14327, "tag": "NAME", "value": "Captain Yorr" }, { "context": " ship: \"Prom typu Lambda\"\n name: \"Kapitan Yorr\"\n text: \"\"\"Kiedy inny przyjazny statek", "end": 14410, "score": 0.9998955130577087, "start": 14398, "tag": "NAME", "value": "Kapitan Yorr" }, { "context": "grupy Omicron\"\n # VT-49 Decimator\n \"Captain Oicunn\":\n ship: \"Decimator VT-49\"\n ", "end": 14746, "score": 0.9996384978294373, "start": 14732, "tag": "NAME", "value": "Captain Oicunn" }, { "context": " ship: \"Decimator VT-49\"\n name: \"Kapitan Oicunn\"\n text: \"\"\"Po wykonaniu manewru, każdy", "end": 14818, "score": 0.9998835921287537, "start": 14804, "tag": "NAME", "value": "Kapitan Oicunn" }, { "context": "się stykasz, otrzymuje 1 uszkodzenie.\"\"\"\n \"Rear Admiral Chiraneau\":\n ship: \"Decimator ", "end": 14945, "score": 0.9933736324310303, "start": 14941, "tag": "NAME", "value": "Rear" }, { "context": "stykasz, otrzymuje 1 uszkodzenie.\"\"\"\n \"Rear Admiral Chiraneau\":\n ship: \"Decimator VT-49\"\n ", "end": 14963, "score": 0.9987640976905823, "start": 14946, "tag": "NAME", "value": "Admiral Chiraneau" }, { "context": " ship: \"Decimator VT-49\"\n name: \"Kontradmirał Chiraneau\"\n text: \"\"\"Kiedy atakujesz w Zasięgu 1", "end": 15043, "score": 0.9998894929885864, "start": 15021, "tag": "NAME", "value": "Kontradmirał Chiraneau" }, { "context": " ship: \"Decimator VT-49\"\n name: \"Dowódca Patrolu\"\n \"Commander Kenkirk\":\n ship: \"", "end": 15259, "score": 0.9993972778320312, "start": 15244, "tag": "NAME", "value": "Dowódca Patrolu" }, { "context": "-49\"\n name: \"Dowódca Patrolu\"\n \"Commander Kenkirk\":\n ship: \"Decimator VT-49\"\n ", "end": 15287, "score": 0.999733567237854, "start": 15270, "tag": "NAME", "value": "Commander Kenkirk" }, { "context": " ship: \"Decimator VT-49\"\n name: \"Commandant Kenkirk\"\n text: \"\"\"Jeśli nie masz żadnych osło", "end": 15363, "score": 0.9997575879096985, "start": 15345, "tag": "NAME", "value": "Commandant Kenkirk" }, { "context": "artość twojej zwrotności wzrasta o 1.\"\"\"\n \"Juno Eclipse\":\n text: \"\"\"When you reveal your maneu", "end": 15529, "score": 0.9212787747383118, "start": 15517, "tag": "NAME", "value": "Juno Eclipse" }, { "context": "e its speed by 1 (to a minimum of 1).\"\"\"\n \"Zertik Strom\":\n text: \"\"\"Enemy ships at Range 1 can", "end": 15673, "score": 0.9982417821884155, "start": 15661, "tag": "NAME", "value": "Zertik Strom" }, { "context": "ir range combat bonus when attacking.\"\"\"\n \"Lieutenant Colzet\":\n text: \"\"\"At the start of the End ph", "end": 15801, "score": 0.9997232556343079, "start": 15784, "tag": "NAME", "value": "Lieutenant Colzet" }, { "context": " \"Red Squadron Pilot\":\n name: \"Pilot Eskadry Czerwonych\"\n \"Rookie Pilot\":\n name: \"Niedo", "end": 16082, "score": 0.9779423475265503, "start": 16064, "tag": "NAME", "value": "Eskadry Czerwonych" }, { "context": " name: \"Pilot Eskadry Czerwonych\"\n \"Rookie Pilot\":\n name: \"Niedoświadczony pilot\"\n ", "end": 16105, "score": 0.8668850660324097, "start": 16093, "tag": "NAME", "value": "Rookie Pilot" }, { "context": "onych\"\n \"Rookie Pilot\":\n name: \"Niedoświadczony pilot\"\n \"Wedge Antilles\":\n ", "end": 16128, "score": 0.5527094602584839, "start": 16127, "tag": "NAME", "value": "N" }, { "context": "\"\n \"Rookie Pilot\":\n name: \"Niedoświadczony pilot\"\n \"Wedge Antilles\":\n text", "end": 16142, "score": 0.7369058132171631, "start": 16132, "tag": "NAME", "value": "świadczony" }, { "context": " name: \"Niedoświadczony pilot\"\n \"Wedge Antilles\":\n text: \"\"\"Kiedy atakujesz zredukuj w", "end": 16173, "score": 0.9945823550224304, "start": 16159, "tag": "NAME", "value": "Wedge Antilles" }, { "context": "wrotności obrońcy o 1 (do minimum 0).\"\"\"\n \"Garven Dreis\":\n text: \"\"\"Po tym jak wydasz żeton sk", "end": 16293, "score": 0.9994993209838867, "start": 16281, "tag": "NAME", "value": "Garven Dreis" }, { "context": " w Zasięgu 1-2 (zamiast go odrzucać).\"\"\"\n \"Biggs Darklighter\":\n text: \"\"\"Inne przyjazne statki w Za", "end": 16480, "score": 0.9663826823234558, "start": 16463, "tag": "NAME", "value": "Biggs Darklighter" }, { "context": " atakujący może na cel wybrać ciebie.\"\"\"\n \"Luke Skywalker\":\n text: \"\"\"Kiedy się bronisz, możesz ", "end": 16644, "score": 0.9946379661560059, "start": 16630, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "ich wyników %FOCUS% na wynik %EVADE%.\"\"\"\n \"Wes Janson\":\n text: \"\"\"Po wykonaniu ataku możesz ", "end": 16770, "score": 0.9997765421867371, "start": 16760, "tag": "NAME", "value": "Wes Janson" }, { "context": "ub niebieski żeton namierzonego celu.\"\"\"\n \"Jek Porkins\":\n text: \"\"\"Kiedy otrzymujesz żeton st", "end": 16926, "score": 0.9998543858528137, "start": 16915, "tag": "NAME", "value": "Jek Porkins" }, { "context": "rzymuje 1 zakrytą kartę uszkodzenia.\"\"\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Kiedy zdobywasz l", "end": 17114, "score": 0.9996221661567688, "start": 17108, "tag": "NAME", "value": "Hobbie" }, { "context": " 1 zakrytą kartę uszkodzenia.\"\"\"\n '\"Hobbie\" Klivian':\n text: \"\"\"Kiedy zdobywasz lub wydaje", "end": 17123, "score": 0.9997072219848633, "start": 17116, "tag": "NAME", "value": "Klivian" }, { "context": "nąć ze swojego statku 1 żeton stresu.\"\"\"\n \"Tarn Mison\":\n text: \"\"\"Kiedy wrogi statek wybiera", "end": 17271, "score": 0.9998188614845276, "start": 17261, "tag": "NAME", "value": "Tarn Mison" }, { "context": " \"Gold Squadron Pilot\":\n name: \"Pilot Eskadry Złotych\"\n \"Gray Squadron Pilot\":\n name:", "end": 17460, "score": 0.7257853746414185, "start": 17445, "tag": "NAME", "value": "Eskadry Złotych" }, { "context": " \"Gray Squadron Pilot\":\n name: \"Pilot Eskadry Szarych\"\n '\"Dutch\" Vander':\n text: \"\"\"P", "end": 17533, "score": 0.8249211311340332, "start": 17518, "tag": "NAME", "value": "Eskadry Szarych" }, { "context": " name: \"Pilot Eskadry Szarych\"\n '\"Dutch\" Vander':\n text: \"\"\"Po namierzeniu cel", "end": 17550, "score": 0.9992654323577881, "start": 17545, "tag": "NAME", "value": "Dutch" }, { "context": " name: \"Pilot Eskadry Szarych\"\n '\"Dutch\" Vander':\n text: \"\"\"Po namierzeniu celu wybier", "end": 17558, "score": 0.9911841154098511, "start": 17552, "tag": "NAME", "value": "Vander" }, { "context": "tatek może natychmiast namierzyć cel.\"\"\"\n \"Horton Salm\":\n text: \"\"\"Kiedy atakujesz w Zasięgu ", "end": 17712, "score": 0.9997571110725403, "start": 17701, "tag": "NAME", "value": "Horton Salm" }, { "context": "reen Squadron Pilot\":\n name: \"Pilot Eskadry Zielonych\"\n \"Prototype Pilot\":\n ", "end": 17928, "score": 0.636114239692688, "start": 17924, "tag": "NAME", "value": "adry" }, { "context": "quadron Pilot\":\n name: \"Pilot Eskadry Zielonych\"\n \"Prototype Pilot\":\n name: \"Pi", "end": 17938, "score": 0.8141425251960754, "start": 17930, "tag": "NAME", "value": "ielonych" }, { "context": "ot\":\n name: \"Pilot prototypu\"\n \"Tycho Celchu\":\n text: \"\"\"Możesz wykonywać akcje naw", "end": 18024, "score": 0.9945220947265625, "start": 18012, "tag": "NAME", "value": "Tycho Celchu" }, { "context": " nawet jeśli posiadasz żetony stresu.\"\"\"\n \"Arvel Crynyd\":\n text: \"\"\"Możesz wybrać na cel swoje", "end": 18132, "score": 0.9986249208450317, "start": 18120, "tag": "NAME", "value": "Arvel Crynyd" }, { "context": "\n \"Outer Rim Smuggler\":\n name: \"Przemytnik z Zewnętrznych Rubierzy\"\n \"Chewbacca\":\n ", "end": 18353, "score": 0.9575995206832886, "start": 18343, "tag": "NAME", "value": "Przemytnik" }, { "context": "ter Rim Smuggler\":\n name: \"Przemytnik z Zewnętrznych Rubierzy\"\n \"Chewbacca\":\n text: \"\"\"Kiedy ", "end": 18377, "score": 0.9081193804740906, "start": 18356, "tag": "NAME", "value": "Zewnętrznych Rubierzy" }, { "context": " \"Przemytnik z Zewnętrznych Rubierzy\"\n \"Chewbacca\":\n text: \"\"\"Kiedy otrzymujesz odkrytą ", "end": 18397, "score": 0.5877425074577332, "start": 18391, "tag": "NAME", "value": "wbacca" }, { "context": "akryj (bez rozpatrywania jej efektu).\"\"\"\n \"Lando Calrissian\":\n text: \"\"\"Po wykonaniu zielonego man", "end": 18548, "score": 0.9967452883720398, "start": 18532, "tag": "NAME", "value": "Lando Calrissian" }, { "context": "\":\n name: \"Agent rebeliantów\"\n \"Roark Garnet\":\n text: '''Na początku fazy walki wyb", "end": 19485, "score": 0.9990604519844055, "start": 19473, "tag": "NAME", "value": "Roark Garnet" }, { "context": "ości tego pilota jakby wynosiła \"12\".'''\n \"Kyle Katarn\":\n text: \"\"\"Na początku fazy walki moż", "end": 19682, "score": 0.9998801350593567, "start": 19671, "tag": "NAME", "value": "Kyle Katarn" }, { "context": "ego przyjaznego statku w Zasięgu 1-3.\"\"\"\n \"Jan Ors\":\n text: \"\"\"Kiedy inny przyjazny state", "end": 19839, "score": 0.999774158000946, "start": 19832, "tag": "NAME", "value": "Jan Ors" }, { "context": " Squadron Pilot\":\n name: \"Pilot Eskadry Tala\"\n ship: \"Z-95 Łowca głów\"\n \"Lie", "end": 20228, "score": 0.5655627846717834, "start": 20224, "tag": "NAME", "value": "Tala" }, { "context": "ala\"\n ship: \"Z-95 Łowca głów\"\n \"Lieutenant Blount\":\n name: \"Porucznik Blount\"\n ", "end": 20292, "score": 0.9977091550827026, "start": 20275, "tag": "NAME", "value": "Lieutenant Blount" }, { "context": "\"\n \"Lieutenant Blount\":\n name: \"Porucznik Blount\"\n ship: \"Z-95 Łowca głów\"\n ", "end": 20330, "score": 0.9993376731872559, "start": 20314, "tag": "NAME", "value": "Porucznik Blount" }, { "context": "t jeśli nie otrzymał żadnych uszkodzeń.\"\n \"Airen Cracken\":\n ship: \"Z-95 Łowca głów\"\n ", "end": 20510, "score": 0.9996697306632996, "start": 20497, "tag": "NAME", "value": "Airen Cracken" }, { "context": " name: \"Pilot Eskadry Czarnego Księżyca\"\n \"Etahn A'baht\":\n text: \"\"\"Kiedy wrogi statek w twoim", "end": 20881, "score": 0.9996390342712402, "start": 20869, "tag": "NAME", "value": "Etahn A'baht" }, { "context": "z jego wyników %HIT% na wynik %CRIT%.\"\"\"\n \"Corran Horn\":\n text: \"\"\"Na początku fazy końcowej ", "end": 21057, "score": 0.9998836517333984, "start": 21046, "tag": "NAME", "value": "Corran Horn" }, { "context": "tępnej rundzie.\"\"\"\n # Asy Rebelii\n \"Jake Farrell\":\n text: \"\"\"Po tym jak wykonasz akcję ", "end": 21221, "score": 0.999893844127655, "start": 21209, "tag": "NAME", "value": "Jake Farrell" }, { "context": "armową akcję \"dopalacz\" lub \"beczka\".\"\"\"\n \"Gemmer Sojan\":\n text: \"\"\"Dopóki znajdujesz się w Za", "end": 21403, "score": 0.9998968839645386, "start": 21391, "tag": "NAME", "value": "Gemmer Sojan" }, { "context": "zwiększ swoją wartość zwrotności o 1.\"\"\"\n \"Keyan Farlander\":\n text: \"\"\"Kiedy atakujesz możesz usu", "end": 21560, "score": 0.9998967051506042, "start": 21545, "tag": "NAME", "value": "Keyan Farlander" }, { "context": "ystkie swoje wyniki %FOCUS% na %HIT%.\"\"\"\n \"Nera Dantels\":\n text: \"\"\"Możesz wykonać atak dodatk", "end": 21706, "score": 0.9998588562011719, "start": 21694, "tag": "NAME", "value": "Nera Dantels" }, { "context": "Rozpatrz jedną z nich a drugą odrzuć.\"\"\"\n \"Eaden Vrill\":\n text: \"\"\"Podczas wykonywania ataku ", "end": 22733, "score": 0.9001814723014832, "start": 22722, "tag": "NAME", "value": "Eaden Vrill" }, { "context": "ucasz 1 dodatkową kością.\"\"\"\n \"Wild Space Fringer\":\n name: \"Outsider z Dzikiej Przestr", "end": 22914, "score": 0.6068333387374878, "start": 22910, "tag": "NAME", "value": "ring" }, { "context": " \"Wild Space Fringer\":\n name: \"Outsider z Dzikiej Przestrzeni\"\n\n # Scum and Villai", "end": 22946, "score": 0.6594574451446533, "start": 22941, "tag": "NAME", "value": "sider" }, { "context": "Wild Space Fringer\":\n name: \"Outsider z Dzikiej Przestrzeni\"\n\n # Scum and Villainy\n # Starviper", "end": 22968, "score": 0.9753782749176025, "start": 22949, "tag": "NAME", "value": "Dzikiej Przestrzeni" }, { "context": " # Scum and Villainy\n # Starviper\n \"Prince Xizor\":\n name: \"Książe Xizor\"\n te", "end": 23040, "score": 0.999671459197998, "start": 23028, "tag": "NAME", "value": "Prince Xizor" }, { "context": "rviper\n \"Prince Xizor\":\n name: \"Książe Xizor\"\n text: \"\"\"Kiedy się bronisz, przyjazn", "end": 23074, "score": 0.9998018741607666, "start": 23062, "tag": "NAME", "value": "Książe Xizor" }, { "context": "ik %HIT% lub %CRIT% (zamiast ciebie).\"\"\"\n \"Guri\":\n text: \"\"\"Na początku fazy walki, je", "end": 23231, "score": 0.9127126932144165, "start": 23227, "tag": "NAME", "value": "Guri" }, { "context": ".\"\"\"\n \"Black Sun Vigo\":\n name: \"Vigo Czarnego Słońca\"\n \"Black Sun Enforcer\":\n name: ", "end": 23446, "score": 0.9960300326347351, "start": 23426, "tag": "NAME", "value": "Vigo Czarnego Słońca" }, { "context": "\n \"Black Sun Enforcer\":\n name: \"Wysłannik Czarnego Słońca\"\n # Interceptor M3-A\n \"Cartel Space", "end": 23522, "score": 0.9992212057113647, "start": 23497, "tag": "NAME", "value": "Wysłannik Czarnego Słońca" }, { "context": " name: \"Weteran Tansarii Point\"\n \"Serissu\":\n text: \"\"\"Kiedy inny przyjazny state", "end": 23703, "score": 0.9992609620094299, "start": 23696, "tag": "NAME", "value": "Serissu" }, { "context": "broni, może przerzucić 1 kość obrony.\"\"\"\n \"Laetin A'shera\":\n text: \"Po tym jak obronisz się prze", "end": 23835, "score": 0.9998753666877747, "start": 23821, "tag": "NAME", "value": "Laetin A'shera" }, { "context": " (%TURNRIGHT% 3).\"\"\"\n # Firespray\n \"Boba Fett (Scum)\":\n name: \"\"\"Boba Fett (Szumowin", "end": 24639, "score": 0.9998987317085266, "start": 24630, "tag": "NAME", "value": "Boba Fett" }, { "context": "\n \"Boba Fett (Scum)\":\n name: \"\"\"Boba Fett (Szumowiny)\"\"\"\n text: \"\"\"Kiedy atakuje", "end": 24679, "score": 0.9999032616615295, "start": 24670, "tag": "NAME", "value": "Boba Fett" }, { "context": "ci za każdy wrogi statek w Zasięgu 1.\"\"\"\n \"Kath Scarlet (Scum)\":\n name: \"\"\"Kath Scarlet (Szumo", "end": 24843, "score": 0.9998663067817688, "start": 24831, "tag": "NAME", "value": "Kath Scarlet" }, { "context": " \"Kath Scarlet (Scum)\":\n name: \"\"\"Kath Scarlet (Szumowiny)\"\"\"\n text: \"\"\"Kiedy atakuje", "end": 24886, "score": 0.9998995065689087, "start": 24874, "tag": "NAME", "value": "Kath Scarlet" }, { "context": "ia, rzucasz 1 dodatkową kością ataku.\"\"\"\n \"Emon Azzameen\":\n text: \"\"\"Kiedy zrzucasz bombę, może", "end": 25054, "score": 0.999899685382843, "start": 25041, "tag": "NAME", "value": "Emon Azzameen" }, { "context": "3] (zamiast wzornika [%STRAIGHT% 1]).\"\"\"\n \"Mandalorian Mercenary\":\n name: \"Mandaloriański najemnik\"\n ", "end": 25241, "score": 0.9999046921730042, "start": 25220, "tag": "NAME", "value": "Mandalorian Mercenary" }, { "context": " \"Mandalorian Mercenary\":\n name: \"Mandaloriański najemnik\"\n # Y-Wing\n \"Kavil\":\n te", "end": 25286, "score": 0.999904215335846, "start": 25263, "tag": "NAME", "value": "Mandaloriański najemnik" }, { "context": "andaloriański najemnik\"\n # Y-Wing\n \"Kavil\":\n text: \"\"\"Kiedy atakujesz statek zna", "end": 25319, "score": 0.999870777130127, "start": 25314, "tag": "NAME", "value": "Kavil" }, { "context": "ia, rzucasz 1 dodatkową kością ataku.\"\"\"\n \"Drea Renthal\":\n text: \"\"\"Po tym jak wydasz żeton na", "end": 25465, "score": 0.9998936653137207, "start": 25453, "tag": "NAME", "value": "Drea Renthal" }, { "context": "ać 1 żeton stresu, aby namierzyć cel.\"\"\"\n \"Hired Gun\" :\n name: \"Najemnik\"\n \"Syndicat", "end": 25604, "score": 0.9998054504394531, "start": 25595, "tag": "NAME", "value": "Hired Gun" }, { "context": " cel.\"\"\"\n \"Hired Gun\" :\n name: \"Najemnik\"\n \"Syndicate Thug\":\n name: \"Zbi", "end": 25635, "score": 0.9998858571052551, "start": 25627, "tag": "NAME", "value": "Najemnik" }, { "context": "ired Gun\" :\n name: \"Najemnik\"\n \"Syndicate Thug\":\n name: \"Zbir z syndykatu\"\n # ", "end": 25660, "score": 0.99968421459198, "start": 25646, "tag": "NAME", "value": "Syndicate Thug" }, { "context": "nik\"\n \"Syndicate Thug\":\n name: \"Zbir z syndykatu\"\n # HWK\n \"Dace Bonearm\":\n ", "end": 25697, "score": 0.9952486157417297, "start": 25682, "tag": "NAME", "value": "Zbir z syndykat" }, { "context": " name: \"Zbir z syndykatu\"\n # HWK\n \"Dace Bonearm\":\n text: \"\"\"Kiedy wrogi statek w Zasię", "end": 25735, "score": 0.9998844861984253, "start": 25723, "tag": "NAME", "value": "Dace Bonearm" }, { "context": "y dany statek otrzymał 1 uszkodzenie.\"\"\"\n \"Palob Godalhi\":\n text: \"\"\"Na początku fazy walki moż", "end": 25970, "score": 0.9998754262924194, "start": 25957, "tag": "NAME", "value": "Palob Godalhi" }, { "context": "Zasięgu 1-2 i przypisać go do siebie.\"\"\"\n \"Torkil Mux\":\n text: \"\"\"Na koniec fazy aktywacji w", "end": 26140, "score": 0.9998771548271179, "start": 26130, "tag": "NAME", "value": "Torkil Mux" }, { "context": "i pilota wybranego statku wynosi \"0\".\"\"\"\n \"Spice Runner\":\n name: \"Przemytnik przyprawy\"\n ", "end": 26332, "score": 0.9992473125457764, "start": 26320, "tag": "NAME", "value": "Spice Runner" }, { "context": "0\".\"\"\"\n \"Spice Runner\":\n name: \"Przemytnik przyprawy\"\n # Z-95\n \"Black Sun Soldier\":\n ", "end": 26374, "score": 0.9965659379959106, "start": 26354, "tag": "NAME", "value": "Przemytnik przyprawy" }, { "context": "5\n \"Black Sun Soldier\":\n name: \"Żolnierz Czarnego Słońca\"\n ship: \"Z-95 Łowca głów\"\n \"Bin", "end": 26463, "score": 0.9989777207374573, "start": 26439, "tag": "NAME", "value": "Żolnierz Czarnego Słońca" }, { "context": " ship: \"Z-95 Łowca głów\"\n \"Binayre Pirate\":\n name: \"Pirat z Binayre\"\n ", "end": 26524, "score": 0.697044849395752, "start": 26515, "tag": "NAME", "value": "re Pirate" }, { "context": "łów\"\n \"Binayre Pirate\":\n name: \"Pirat z Binayre\"\n ship: \"Z-95 Łowca głów\"\n \"N'D", "end": 26561, "score": 0.9962190389633179, "start": 26546, "tag": "NAME", "value": "Pirat z Binayre" }, { "context": "yre\"\n ship: \"Z-95 Łowca głów\"\n \"N'Dru Suhlak\":\n ship: \"Z-95 Łowca głów\"\n ", "end": 26620, "score": 0.9966368675231934, "start": 26608, "tag": "NAME", "value": "N'Dru Suhlak" }, { "context": "a żadnych innych przyjaznych statków.\"\"\"\n \"Kaa'to Leeachos\":\n ship: \"Z-95 Łowca głów\"\n ", "end": 26820, "score": 0.9991849064826965, "start": 26805, "tag": "NAME", "value": "Kaa'to Leeachos" }, { "context": "Zasięgu 1-2 i przypisać go do siebie.\"\"\"\n \"Latts Razzi\":\n text: \"\"\"When a friendly ship decla", "end": 27037, "score": 0.9993001222610474, "start": 27026, "tag": "NAME", "value": "Latts Razzi" }, { "context": "uce its agility by 1 for that attack.\"\"\"\n \"Graz the Hunter\":\n text: \"\"\"When defending, if the att", "end": 27226, "score": 0.9783037304878235, "start": 27211, "tag": "NAME", "value": "Graz the Hunter" }, { "context": "g arc, roll 1 additional defense die.\"\"\"\n \"Esege Tuketu\":\n text: \"\"\"When another friendly ship", "end": 27364, "score": 0.9828518033027649, "start": 27352, "tag": "NAME", "value": "Esege Tuketu" }, { "context": "against the that ship.\"\"\"\n # T-70\n \"Poe Dameron\":\n text: \"\"\"When attacking or defendin", "end": 28738, "score": 0.9888706207275391, "start": 28727, "tag": "NAME", "value": "Poe Dameron" }, { "context": " your equipped %ELITE% Upgrade card.\"\"\"\n '\"Wampa\"':\n text: \"\"\"When attacking, you may c", "end": 30156, "score": 0.9855525493621826, "start": 30151, "tag": "NAME", "value": "Wampa" }, { "context": "acedown Damage card to the defender.\"\"\"\n '\"Chaser\"':\n text: \"\"\"When another friendly shi", "end": 30325, "score": 0.928504228591919, "start": 30319, "tag": "NAME", "value": "Chaser" }, { "context": "n, assign a focus token to your ship.\"\"\"\n 'Ezra Bridger':\n text: \"\"\"When defending, if you are", "end": 30469, "score": 0.9987955093383789, "start": 30457, "tag": "NAME", "value": "Ezra Bridger" }, { "context": " %FOCUS% results to %EVADE% results.\"\"\"\n '\"Zeta Leader\"':\n text: '''When attacking, if you ar", "end": 30621, "score": 0.8165265917778015, "start": 30610, "tag": "NAME", "value": "Zeta Leader" }, { "context": "ress token to roll 1 additional die.'''\n '\"Epsilon Ace\"':\n text: '''While you do not have any", "end": 30768, "score": 0.9716989398002625, "start": 30757, "tag": "NAME", "value": "Epsilon Ace" }, { "context": "treat your pilot skill value as \"12.\"'''\n \"Kanan Jarrus\":\n text: \"\"\"When an enemy ship at Rang", "end": 30895, "score": 0.9994238615036011, "start": 30883, "tag": "NAME", "value": "Kanan Jarrus" }, { "context": "e attacker rolls 1 fewer attack die.\"\"\"\n '\"Chopper\"':\n text: \"\"\"At the start of the Comba", "end": 31065, "score": 0.9893691539764404, "start": 31058, "tag": "NAME", "value": "Chopper" }, { "context": "are touching receives 1 stress token.\"\"\"\n 'Hera Syndulla (Attack Shuttle)':\n text: \"\"\"When you ", "end": 31207, "score": 0.969430148601532, "start": 31194, "tag": "NAME", "value": "Hera Syndulla" }, { "context": "ther maneuver of the same difficulty.\"\"\"\n 'Sabine Wren':\n text: \"\"\"Immediately before you rev", "end": 31381, "score": 0.9958311319351196, "start": 31370, "tag": "NAME", "value": "Sabine Wren" }, { "context": "a free boost or barrel roll action.\"\"\"\n '\"Zeb\" Orrelios':\n text: '''When defending, ", "end": 31518, "score": 0.8537710309028625, "start": 31516, "tag": "NAME", "value": "eb" }, { "context": " %CRIT% results before %HIT% results.'''\n 'Tomax Bren':\n ship: \"Bombowiec TIE\"\n t", "end": 31642, "score": 0.9968649744987488, "start": 31632, "tag": "NAME", "value": "Tomax Bren" }, { "context": " Upgrade card, flip that card faceup.'''\n 'Ello Asty':\n text: '''While you are not stressed", "end": 31803, "score": 0.9971241354942322, "start": 31794, "tag": "NAME", "value": "Ello Asty" }, { "context": "LRIGHT% maneuvers as white maneuvers.'''\n \"Valen Rudor\":\n text: \"\"\"After defending, you may p", "end": 31956, "score": 0.9968253970146179, "start": 31945, "tag": "NAME", "value": "Valen Rudor" }, { "context": "ss tokens to another ship at Range 1.\"\"\"\n \"Tel Trevura\":\n text: \"\"\"The first time you would b", "end": 32190, "score": 0.9989537000656128, "start": 32179, "tag": "NAME", "value": "Tel Trevura" }, { "context": "4 facedown Damage cards to this ship.\"\"\"\n \"Manaroo\":\n text: \"\"\"At the start of the Combat", "end": 32382, "score": 0.9085555076599121, "start": 32375, "tag": "NAME", "value": "Manaroo" }, { "context": "o you to another friendly ship.\"\"\"\n '\"Deathfire\"':\n ship: \"Bombowiec TIE\"\n ", "end": 32560, "score": 0.519104540348053, "start": 32556, "tag": "NAME", "value": "fire" }, { "context": "Upgrade card action as a free action.'''\n \"Maarek Stele (TIE Defender)\":\n text: \"\"\"When your a", "end": 32773, "score": 0.9991305470466614, "start": 32761, "tag": "NAME", "value": "Maarek Stele" }, { "context": "se 1 to deal, and discard the others.\"\"\"\n \"Countess Ryad\":\n text: \"\"\"When you reveal a %STRAIGH", "end": 32969, "score": 0.9997920989990234, "start": 32956, "tag": "NAME", "value": "Countess Ryad" }, { "context": "u may treat it as a %KTURN% maneuver.\"\"\"\n \"Poe Dameron (PS9)\":\n text: \"\"\"When attacking or de", "end": 33095, "score": 0.9985154867172241, "start": 33084, "tag": "NAME", "value": "Poe Dameron" }, { "context": "results to a %HIT% or %EVADE% result.\"\"\"\n \"Rey\":\n text: \"\"\"When attacking or defendin", "end": 33267, "score": 0.9513967037200928, "start": 33264, "tag": "NAME", "value": "Rey" }, { "context": "oll up to 2 of your blank results.\"\"\"\n 'Han Solo (TFA)':\n text: '''When you are placed ", "end": 33434, "score": 0.9089382886886597, "start": 33430, "tag": "NAME", "value": "Solo" }, { "context": "rea beyond Range 3 of enemy ships.'''\n 'Chewbacca (TFA)':\n text: '''After another friend", "end": 33594, "score": 0.6950611472129822, "start": 33588, "tag": "NAME", "value": "wbacca" }, { "context": "tlefield), you may perform an attack.'''\n 'Norra Wexley':\n text: '''When attacking or defendin", "end": 33765, "score": 0.9996919631958008, "start": 33753, "tag": "NAME", "value": "Norra Wexley" }, { "context": "to add 1 %FOCUS% result to your roll.'''\n 'Shara Bey':\n text: '''When another friendly ship", "end": 33932, "score": 0.9996570348739624, "start": 33923, "tag": "NAME", "value": "Shara Bey" }, { "context": "r blue target lock tokens as its own.'''\n 'Thane Kyrell':\n text: '''After an enemy ship in you", "end": 34088, "score": 0.9998340606689453, "start": 34076, "tag": "NAME", "value": "Thane Kyrell" }, { "context": " ship, you may perform a free action.'''\n 'Braylen Stramm':\n text: '''After you execute a maneuv", "end": 34252, "score": 0.9990785717964172, "start": 34238, "tag": "NAME", "value": "Braylen Stramm" }, { "context": " 1 stress token from your ship.'''\n '\"Quickdraw\"':\n text: '''Once per round, when you ", "end": 34424, "score": 0.8066363334655762, "start": 34420, "tag": "NAME", "value": "draw" }, { "context": "perform a primary weapon attack.'''\n '\"Backdraft\"':\n text: '''When attacking a ship ins", "end": 34558, "score": 0.7589504718780518, "start": 34553, "tag": "NAME", "value": "draft" }, { "context": "ing arc, you may add 1 %CRIT% result.'''\n 'Fenn Rau':\n text: '''When attacking or defendin", "end": 34688, "score": 0.9950674176216125, "start": 34680, "tag": "NAME", "value": "Fenn Rau" }, { "context": "nge 1, you may roll 1 additional die.'''\n 'Old Teroch':\n text: '''At the start of the Combat", "end": 34827, "score": 0.9835292100906372, "start": 34817, "tag": "NAME", "value": "Old Teroch" }, { "context": " discards all focus and evade tokens.'''\n 'Kad Solus':\n text: '''After you execute a red ma", "end": 35021, "score": 0.9987326264381409, "start": 35012, "tag": "NAME", "value": "Kad Solus" }, { "context": ", assign 2 focus tokens to your ship.'''\n 'Ketsu Onyo':\n text: '''At the start of the Combat", "end": 35137, "score": 0.9992344975471497, "start": 35127, "tag": "NAME", "value": "Ketsu Onyo" }, { "context": "s, assign 1 tractor beam token to it.'''\n 'Asajj Ventress':\n text: '''At the start of the Combat", "end": 35361, "score": 0.9985038638114929, "start": 35347, "tag": "NAME", "value": "Asajj Ventress" }, { "context": "ing arc, assign 1 stress token to it.'''\n 'Sabine Wren (Scum)':\n text: '''When defending agai", "end": 35545, "score": 0.9952037930488586, "start": 35534, "tag": "NAME", "value": "Sabine Wren" }, { "context": "ay add 1 %FOCUS% result to your roll.'''\n 'Sabine Wren (TIE Fighter)':\n ship: 'Myśliwiec TIE'", "end": 35723, "score": 0.9926575422286987, "start": 35712, "tag": "NAME", "value": "Sabine Wren" }, { "context": " %CRIT% results before %HIT% results.'''\n 'Kylo Ren':\n text: '''The first time you are hit", "end": 36078, "score": 0.9997778534889221, "start": 36070, "tag": "NAME", "value": "Kylo Ren" }, { "context": "Side\" Condition card to the attacker.'''\n 'Unkar Plutt':\n text: '''At the end of the Activati", "end": 36248, "score": 0.9995787143707275, "start": 36237, "tag": "NAME", "value": "Unkar Plutt" }, { "context": " token to each ship you are touching.'''\n 'Cassian Andor':\n text: '''At the start of the Activa", "end": 36418, "score": 0.9998480677604675, "start": 36405, "tag": "NAME", "value": "Cassian Andor" }, { "context": "m 1 other friendly ship at Range 1-2.'''\n 'Bodhi Rook':\n text: '''When a friendly ship acqui", "end": 36573, "score": 0.9996480941772461, "start": 36563, "tag": "NAME", "value": "Bodhi Rook" }, { "context": "ip at Range 1-3 of any friendly ship.'''\n 'Heff Tobber':\n text: '''After an enemy ship execut", "end": 36738, "score": 0.9998313188552856, "start": 36727, "tag": "NAME", "value": "Heff Tobber" }, { "context": ". If you do, receive 1 stress token.'''\n 'Nien Nunb':\n text: '''When you receive a stress ", "end": 37396, "score": 0.9997850656509399, "start": 37387, "tag": "NAME", "value": "Nien Nunb" }, { "context": " may discard that stress token.'''\n '\"Snap\" Wexley':\n text: '''After you execute a 2-, 3-", "end": 37574, "score": 0.8992984294891357, "start": 37568, "tag": "NAME", "value": "Wexley" }, { "context": " you may perform a free boost action.'''\n 'Jess Pava':\n text: '''When attacking or defendin", "end": 37737, "score": 0.9998365640640259, "start": 37728, "tag": "NAME", "value": "Jess Pava" }, { "context": " each other friendly ship at Range 1.'''\n 'Ahsoka Tano':\n ship: 'Myśliwiec TIE'\n t", "end": 37884, "score": 0.9996401071548462, "start": 37873, "tag": "NAME", "value": "Ahsoka Tano" }, { "context": "nge 1. It may perform 1 free action.'''\n 'Captain Rex':\n ship: 'Myśliwiec TIE'\n t", "end": 38096, "score": 0.9992680549621582, "start": 38085, "tag": "NAME", "value": "Captain Rex" }, { "context": "Fire\" Condition card to the defender.'''\n 'Major Stridan':\n text: '''For the purpose of your ac", "end": 38270, "score": 0.9979509711265564, "start": 38257, "tag": "NAME", "value": "Major Stridan" }, { "context": "ips at Range 2-3 as being at Range 1.'''\n 'Lieutenant Dormitz':\n text: '''During setup, friendly shi", "end": 38438, "score": 0.9996989369392395, "start": 38420, "tag": "NAME", "value": "Lieutenant Dormitz" }, { "context": "in the play area at Range 1-2 of you.'''\n 'Constable Zuvio':\n text: '''When you reveal a reverse ", "end": 38576, "score": 0.9992977380752563, "start": 38561, "tag": "NAME", "value": "Constable Zuvio" }, { "context": "e \"<strong>Action:</strong>\" header).'''\n 'Sarco Plank':\n text: '''When defending, instead of", "end": 38766, "score": 0.9997302889823914, "start": 38755, "tag": "NAME", "value": "Sarco Plank" }, { "context": "the maneuver you executed this round.'''\n \"Talonbane Cobra\":\n text: \"\"\"When attacking or defendin", "end": 38968, "score": 0.9987322688102722, "start": 38953, "tag": "NAME", "value": "Talonbane Cobra" }, { "context": " effect of your range combat bonuses.\"\"\"\n 'Genesis Red':\n text: '''After you acquire a target", "end": 39092, "score": 0.9934065341949463, "start": 39081, "tag": "NAME", "value": "Genesis Red" }, { "context": "ber of each token as the locked ship.'''\n 'Quinn Jast':\n text: '''At the start of the Combat", "end": 39279, "score": 0.9996334314346313, "start": 39269, "tag": "NAME", "value": "Quinn Jast" }, { "context": "O% or %MISSILE% Upgrade cards faceup.'''\n 'Inaldra':\n text: '''When attacking or defendin", "end": 39472, "score": 0.9988932609558105, "start": 39465, "tag": "NAME", "value": "Inaldra" }, { "context": "ld to reroll any number of your dice.'''\n 'Sunny Bounder':\n text: '''Once per round, after you ", "end": 39608, "score": 0.9888643026351929, "start": 39595, "tag": "NAME", "value": "Sunny Bounder" }, { "context": " of your dice, add 1 matching result.'''\n 'Lieutenant Kestal':\n text: '''When attacking, you may sp", "end": 39781, "score": 0.99952232837677, "start": 39764, "tag": "NAME", "value": "Lieutenant Kestal" }, { "context": "efender's blank and %FOCUS% results.'''\n '\"Double Edge\"':\n text: '''Once per round, after you", "end": 39932, "score": 0.7203949689865112, "start": 39921, "tag": "NAME", "value": "Double Edge" }, { "context": "rm an attack with a different weapon.'''\n 'Viktor Hel':\n text: '''After defending, if you di", "end": 40109, "score": 0.9995448589324951, "start": 40099, "tag": "NAME", "value": "Viktor Hel" }, { "context": "the attacker receives 1 stress token.'''\n 'Lowhhrick':\n text: '''When another friendl", "end": 40247, "score": 0.8871367573738098, "start": 40244, "tag": "USERNAME", "value": "Low" }, { "context": " attacker receives 1 stress token.'''\n 'Lowhhrick':\n text: '''When another friendly ship", "end": 40253, "score": 0.7562045454978943, "start": 40247, "tag": "NAME", "value": "hhrick" }, { "context": ", the defender adds 1 %EVADE% result.'''\n 'Wullffwarro':\n text: '''When attacking, if you hav", "end": 40432, "score": 0.9396859407424927, "start": 40421, "tag": "NAME", "value": "Wullffwarro" }, { "context": "to you, roll 1 additional attack die.'''\n 'Dalan Oberos':\n text: '''If you are not stressed, w", "end": 40593, "score": 0.99974125623703, "start": 40581, "tag": "NAME", "value": "Dalan Oberos" }, { "context": "te of the original revealed maneuver.'''\n 'Thweek':\n text: '''During setup, before the \"", "end": 40864, "score": 0.9467309713363647, "start": 40858, "tag": "NAME", "value": "Thweek" }, { "context": "\" or \"Mimicked\" Condition card to it.'''\n 'Captain Jostero':\n text: '''Once per round, after an e", "end": 41051, "score": 0.9998321533203125, "start": 41036, "tag": "NAME", "value": "Captain Jostero" }, { "context": " perform an attack against that ship.'''\n 'Major Vynder':\n text: '''When defending, if you hav", "end": 41255, "score": 0.9962999820709229, "start": 41243, "tag": "NAME", "value": "Major Vynder" }, { "context": "token, roll 1 additional defense die.'''\n 'Lieutenant Karsabi':\n text: '''When you receive a weapons", "end": 41394, "score": 0.9998971223831177, "start": 41376, "tag": "NAME", "value": "Lieutenant Karsabi" }, { "context": " receive 1 stress token to remove it.'''\n 'Torani Kulda':\n text: '''After you perform an attac", "end": 41555, "score": 0.9998846054077148, "start": 41543, "tag": "NAME", "value": "Torani Kulda" }, { "context": "ve all of its focus and evade tokens.'''\n 'Dalan Oberos (Kimogila)':\n text: '''At the start of", "end": 41769, "score": 0.9998105764389038, "start": 41757, "tag": "NAME", "value": "Dalan Oberos" }, { "context": "ur bullseye firing arc at Range 1-3 .'''\n 'Fenn Rau (Sheathipede)':\n text: '''When an enem", "end": 41952, "score": 0.9998856782913208, "start": 41944, "tag": "NAME", "value": "Fenn Rau" }, { "context": "y its dice when attacking this round.'''\n 'Ezra Bridger (Sheathipede)':\n text: \"\"\"When defendi", "end": 42263, "score": 0.9998747110366821, "start": 42251, "tag": "NAME", "value": "Ezra Bridger" }, { "context": "fewer defense die, to a minimum of 0.'''\n 'Kylo Ren (TIE Silencer)':\n text: '''The first t", "end": 43353, "score": 0.9982761740684509, "start": 43345, "tag": "NAME", "value": "Kylo Ren" }, { "context": "wer defense dice (to a minimum of 0).'''\n 'Kullbee Sperado':\n text: '''After you perform a boost ", "end": 43705, "score": 0.9934372901916504, "start": 43690, "tag": "NAME", "value": "Kullbee Sperado" }, { "context": "or %FOCUS% results to a %HIT% result.'''\n 'Leevan Tenza':\n text: '''After you perform a boost ", "end": 44054, "score": 0.9953897595405579, "start": 44042, "tag": "NAME", "value": "Leevan Tenza" }, { "context": "tress token to receive 1 evade token.'''\n 'Saw Gerrera':\n text: '''When a friendly ship at Ra", "end": 44192, "score": 0.7691413164138794, "start": 44181, "tag": "NAME", "value": "Saw Gerrera" }, { "context": "ge card, it may reroll 1 attack die.'''\n 'Benthic Two-Tubes':\n text: '''After you perfor", "end": 44355, "score": 0.8137261867523193, "start": 44349, "tag": "NAME", "value": "enthic" }, { "context": "n it to a friendly ship at Range 1-2.'''\n 'Captain Feroph':\n text: '''When defending, if the att", "end": 44533, "score": 0.9993382692337036, "start": 44519, "tag": "NAME", "value": "Captain Feroph" }, { "context": ", add 1 %EVADE% result to your roll.'''\n '\"Vizier\"':\n text: '''After a friendly ship exe", "end": 44654, "score": 0.9207848310470581, "start": 44648, "tag": "NAME", "value": "Vizier" }, { "context": " of your focus or evade tokens to it.'''\n 'Magva Yarro':\n text: '''When another friendly ship", "end": 44855, "score": 0.99980628490448, "start": 44844, "tag": "NAME", "value": "Magva Yarro" }, { "context": "cannot reroll more than 1 attack die.'''\n 'Edrio Two-Tubes':\n text: '''When you become the ", "end": 45005, "score": 0.9378157258033752, "start": 44996, "tag": "NAME", "value": "Edrio Two" }, { "context": "u.\"\"\"\n \"Swarm Tactics\":\n name: \"Taktyka roju\"\n text: \"\"\"Na początku fazy walki wybi", "end": 45472, "score": 0.9963738322257996, "start": 45460, "tag": "NAME", "value": "Taktyka roju" }, { "context": "ej.\"\"\"\n \"Squad Leader\":\n name: \"Dowódca eskadry\"\n text: \"\"\"<strong>Akcja:</strong> Wyb", "end": 45719, "score": 0.9998831152915955, "start": 45704, "tag": "NAME", "value": "Dowódca eskadry" }, { "context": "\"\"\"\n \"Expert Handling\":\n name: \"Mistrzowskie manewrowanie\"\n text: \"\"\"„<strong>Akcja:</strong> Wy", "end": 45993, "score": 0.9920594096183777, "start": 45968, "tag": "NAME", "value": "Mistrzowskie manewrowanie" }, { "context": " celu znajdujący się na Twoim statku.\"\"\"\n \"Marksmanship\":\n name: \"Celność\"\n tex", "end": 46256, "score": 0.6246328353881836, "start": 46248, "tag": "NAME", "value": "Marksman" }, { "context": "ku.\"\"\"\n \"Marksmanship\":\n name: \"Celność\"\n text: \"\"\"<strong>Akcja:</strong> Kie", "end": 46289, "score": 0.9976844191551208, "start": 46282, "tag": "NAME", "value": "Celność" }, { "context": "ie pozostałe wyniki %FOCUS% na %HIT%.\"\"\"\n \"Daredevil\":\n name: \"Ryzykant\"\n text: ", "end": 46483, "score": 0.9914834499359131, "start": 46474, "tag": "NAME", "value": "Daredevil" }, { "context": "%HIT%.\"\"\"\n \"Daredevil\":\n name: \"Ryzykant\"\n text: \"\"\"<strong>Akcja:</strong> Wyk", "end": 46513, "score": 0.9987845420837402, "start": 46505, "tag": "NAME", "value": "Ryzykant" }, { "context": "IT%.\"\"\"\n \"Elusiveness\":\n name: \"Nieuchwytność\"\n text: \"\"\"Kiedy się bronisz możesz ot", "end": 46876, "score": 0.9984228014945984, "start": 46863, "tag": "NAME", "value": "Nieuchwytność" }, { "context": "Następnie otrzymujesz 1 żeton stresu.\"\"\"\n \"Deadeye\":\n name: \"Strzelec wyborowy\"\n ", "end": 47342, "score": 0.9467248916625977, "start": 47335, "tag": "NAME", "value": "Deadeye" }, { "context": " stresu.\"\"\"\n \"Deadeye\":\n name: \"Strzelec wyborowy\"\n text: \"\"\"Możesz traktować nagłówek <", "end": 47381, "score": 0.9980152249336243, "start": 47364, "tag": "NAME", "value": "Strzelec wyborowy" }, { "context": " zamiast niego wydać żeton skupienia.\"\"\"\n \"Expose\":\n name: \"Odsłonięcie\"\n tex", "end": 47648, "score": 0.5903071165084839, "start": 47642, "tag": "NAME", "value": "Expose" }, { "context": "kupienia.\"\"\"\n \"Expose\":\n name: \"Odsłonięcie\"\n text: \"\"\"<strong>Akcja:</strong> Do ", "end": 47681, "score": 0.9974641799926758, "start": 47670, "tag": "NAME", "value": "Odsłonięcie" }, { "context": " 1 i zmniejsz wartość zwrotności o 1.\"\"\"\n \"Wingman\":\n name: \"Skrzydłowy\"\n text", "end": 47842, "score": 0.9946662783622742, "start": 47835, "tag": "NAME", "value": "Wingman" }, { "context": "ści o 1.\"\"\"\n \"Wingman\":\n name: \"Skrzydłowy\"\n text: \"\"\"Na początku fazy walki usuń", "end": 47874, "score": 0.9985702037811279, "start": 47864, "tag": "NAME", "value": "Skrzydłowy" }, { "context": "nnego przyjaznego statku w Zasięgu 1.\"\"\"\n \"Decoy\":\n name: \"Zmyłka\"\n text: \"\"", "end": 47998, "score": 0.985255241394043, "start": 47993, "tag": "NAME", "value": "Decoy" }, { "context": "Zasięgu 1.\"\"\"\n \"Decoy\":\n name: \"Zmyłka\"\n text: \"\"\"Na początku fazy walki może", "end": 48026, "score": 0.9986206889152527, "start": 48020, "tag": "NAME", "value": "Zmyłka" }, { "context": "kiem wartościami umiejętności pilota.\"\"\"\n \"Outmaneuver\":\n name: \"Wymanewrowanie\"\n ", "end": 48222, "score": 0.9896947741508484, "start": 48211, "tag": "NAME", "value": "Outmaneuver" }, { "context": "ota.\"\"\"\n \"Outmaneuver\":\n name: \"Wymanewrowanie\"\n text: \"\"\"Kiedy atakujesz statek w sw", "end": 48258, "score": 0.9988744854927063, "start": 48244, "tag": "NAME", "value": "Wymanewrowanie" }, { "context": "artość zwrotności o 1 (do minimum 0).\"\"\"\n \"Predator\":\n name: \"Drapieżnik\"\n text", "end": 48450, "score": 0.9719938039779663, "start": 48442, "tag": "NAME", "value": "Predator" }, { "context": "mum 0).\"\"\"\n \"Predator\":\n name: \"Drapieżnik\"\n text: \"\"\"Kiedy atakujesz, możesz prz", "end": 48482, "score": 0.9990339279174805, "start": 48472, "tag": "NAME", "value": "Drapieżnik" }, { "context": "\n \"Draw Their Fire\":\n name: \"Ściągnięcie ognia\"\n text: \"\"\"Kiedy przyjazny statek w Za", "end": 48741, "score": 0.8747988939285278, "start": 48727, "tag": "NAME", "value": "ągnięcie ognia" }, { "context": " otrzymać 1 z nie anulowanych %CRIT%.\"\"\"\n \"Adrenaline Rush\":\n name: \"Zastrzyk adrenaliny\"\n ", "end": 48916, "score": 0.8658549189567566, "start": 48901, "tag": "NAME", "value": "Adrenaline Rush" }, { "context": "\"\"\"\n \"Adrenaline Rush\":\n name: \"Zastrzyk adrenaliny\"\n text: \"\"\"Kiedy ujawnisz czerwony man", "end": 48957, "score": 0.9269788265228271, "start": 48938, "tag": "NAME", "value": "Zastrzyk adrenaliny" }, { "context": "\"\n \"Veteran Instincts\":\n name: \"Instynkt weterana\"\n text: \"\"\"Zwiększ swoją wartość umiej", "end": 49167, "score": 0.8440724015235901, "start": 49150, "tag": "NAME", "value": "Instynkt weterana" }, { "context": "o 2.\"\"\"\n \"Opportunist\":\n name: \"Oportunista\"\n text: \"\"\"Kiedy atakujesz, jeśli obro", "end": 49293, "score": 0.9488697648048401, "start": 49282, "tag": "NAME", "value": "Oportunista" }, { "context": "ości, jeśli posiadasz żetony stresu.\"\"\"\n \"Lone Wolf\":\n name : \"Samotny wilk\"\n t", "end": 49561, "score": 0.9560537934303284, "start": 49553, "tag": "NAME", "value": "one Wolf" }, { "context": "resu.\"\"\"\n \"Lone Wolf\":\n name : \"Samotny wilk\"\n text: \"\"\"Jeśli w zasięgu 1-2 nie ma ", "end": 49596, "score": 0.9992830157279968, "start": 49584, "tag": "NAME", "value": "Samotny wilk" }, { "context": "\"\"\"\n \"Stay On Target\":\n name: \"Utrzymać cel\"\n text: \"\"\"Kiedy ujawnisz swój man", "end": 49814, "score": 0.6243432760238647, "start": 49807, "tag": "NAME", "value": "trzymać" }, { "context": "RIT%.\"\"\"\n \"Bodyguard\":\n name : \"Ochroniarz\"\n text: \"\"\"%PL_SCUMONLY%%LINEBREAK% Na", "end": 50641, "score": 0.878220796585083, "start": 50631, "tag": "NAME", "value": "Ochroniarz" }, { "context": "woje puste ścianki na wyniki %FOCUS%.\"\"\"\n \"Flechette Torpedoes\":\n name: \"Torpedy rozpryskowe\"\n ", "end": 54000, "score": 0.9815424680709839, "start": 53981, "tag": "NAME", "value": "Flechette Torpedoes" }, { "context": " \"Flechette Torpedoes\":\n name: \"Torpedy rozpryskowe\"\n text: \"\"\"<strong>Atak (namierzony ce", "end": 54041, "score": 0.9967483878135681, "start": 54022, "tag": "NAME", "value": "Torpedy rozpryskowe" }, { "context": "j.\"\"\"\n \"Ion Torpedoes\":\n name: \"Torpedy jonowe\"\n text: \"\"\"<strong>Atak (namierzony ce", "end": 54357, "score": 0.9968774914741516, "start": 54343, "tag": "NAME", "value": "Torpedy jonowe" }, { "context": " \"Ion Pulse Missiles\":\n name: \"Jonowe rakiety pulsacyjne\"\n text: \"\"\"<strong>Atak (na", "end": 56816, "score": 0.6853070855140686, "start": 56805, "tag": "NAME", "value": "owe rakiety" }, { "context": ".\"\"\"\n \"Chardaan Refit\":\n name: \"Naprawy na Chardaanie\"\n text: \"\"\"<span class=\"card-restricti", "end": 57084, "score": 0.9707902073860168, "start": 57063, "tag": "NAME", "value": "Naprawy na Chardaanie" }, { "context": "\"\"\"\n \"Proton Rockets\":\n name: \"Rakiety protonowe\"\n text: \"\"\"<strong>Atak ", "end": 57265, "score": 0.5612104535102844, "start": 57263, "tag": "NAME", "value": "ak" }, { "context": "bes\n \"Seismic Charges\":\n name: \"Ładunki sejsmiczne\"\n text: \"\"\"Kiedy odkrywasz swój wskaźn", "end": 57565, "score": 0.9851158857345581, "start": 57547, "tag": "NAME", "value": "Ładunki sejsmiczne" }, { "context": "żeton, żeton ten zostaje zdetonowany.\"\"\"\n \"Proton Bombs\":\n name: \"Bomby protonowe\"\n ", "end": 58097, "score": 0.9701681137084961, "start": 58085, "tag": "NAME", "value": "Proton Bombs" }, { "context": "ny.\"\"\"\n \"Proton Bombs\":\n name: \"Bomby protonowe\"\n text: \"\"\"Kiedy odkrywasz swój wskaźn", "end": 58134, "score": 0.9982355237007141, "start": 58119, "tag": "NAME", "value": "Bomby protonowe" }, { "context": "# Canons\n \"Ion Cannon\":\n name: \"Działo Jonowe\"\n text: \"\"\"<strong>Atak: Zaatakuj 1 st", "end": 58402, "score": 0.9994195103645325, "start": 58389, "tag": "NAME", "value": "Działo Jonowe" }, { "context": "\n \"Heavy Laser Cannon\":\n name: \"Ciężkie działo laserowe\"\n text: \"\"\"<strong>Atak: Zaatakuj 1 st", "end": 58671, "score": 0.9994949698448181, "start": 58648, "tag": "NAME", "value": "Ciężkie działo laserowe" }, { "context": "\"\"\n \"Flechette Cannon\":\n name: \"Działo rozpryskowe\"\n text: \"\"\"<strong>Atak: Zaatakuj 1 st", "end": 59121, "score": 0.9997453689575195, "start": 59103, "tag": "NAME", "value": "Działo rozpryskowe" }, { "context": "amierzonego celu.\"\"\"\n # Équipages\n \"Gunner\":\n name: \"Artylerzysta\"\n te", "end": 61124, "score": 0.9694840908050537, "start": 61118, "tag": "NAME", "value": "Gunner" }, { "context": " # Équipages\n \"Gunner\":\n name: \"Artylerzysta\"\n text: \"\"\"Po wykonaniu ataku, który n", "end": 61158, "score": 0.998927116394043, "start": 61146, "tag": "NAME", "value": "Artylerzysta" }, { "context": "e nie możesz wykonać kolejnego ataku.\"\"\"\n \"Mercenary Copilot\":\n name: \"Najemny drugi pilot\"\n ", "end": 61352, "score": 0.9982625842094421, "start": 61335, "tag": "NAME", "value": "Mercenary Copilot" }, { "context": "\"\n \"Mercenary Copilot\":\n name: \"Najemny drugi pilot\"\n text: \"\"\"Kiedy atakujesz w Zasiegu 3", "end": 61393, "score": 0.997795820236206, "start": 61374, "tag": "NAME", "value": "Najemny drugi pilot" }, { "context": "\"\"\n \"Weapons Engineer\":\n name: \"Inżynier uzbrojenia\"\n text: \"\"\"Możesz namierzać naraz 2 st", "end": 61571, "score": 0.9996182918548584, "start": 61552, "tag": "NAME", "value": "Inżynier uzbrojenia" }, { "context": "cel, możesz namierzyć 2 różne statki.\"\"\"\n \"Luke Skywalker\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%P", "end": 61767, "score": 0.9979074001312256, "start": 61753, "tag": "NAME", "value": "Luke Skywalker" }, { "context": "esz zmienić 1 wynik %FOCUS% na %HIT%.\"\"\"\n \"Nien Nunb\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%M", "end": 61969, "score": 0.9990846514701843, "start": 61960, "tag": "NAME", "value": "Nien Nunb" }, { "context": "IGHT%, jakby były to zielone manewry.\"\"\"\n \"Chewbacca\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%K", "end": 62117, "score": 0.9825782179832458, "start": 62108, "tag": "NAME", "value": "Chewbacca" }, { "context": "\"\"\n \"Recon Specialist\":\n name: \"Specjalista zwiadu\"\n text: \"\"\"Kiedy wykonujesz akcję skup", "end": 62374, "score": 0.9985101819038391, "start": 62356, "tag": "NAME", "value": "Specjalista zwiadu" }, { "context": "pienia.\"\"\"\n \"Saboteur\":\n name: \"Sabotażysta\"\n text: \"\"\"<strong>Akcja:</strong> Wyb", "end": 62540, "score": 0.9981734156608582, "start": 62529, "tag": "NAME", "value": "Sabotażysta" }, { "context": "\n \"Intelligence Agent\":\n name: \"Agent wywiadu\"\n text: \"\"\"Na początku fazy ak", "end": 62820, "score": 0.5594608783721924, "start": 62815, "tag": "NAME", "value": "Agent" }, { "context": " \"Intelligence Agent\":\n name: \"Agent wywiadu\"\n text: \"\"\"Na początku fazy aktywacji ", "end": 62828, "score": 0.8991196155548096, "start": 62821, "tag": "NAME", "value": "wywiadu" }, { "context": "rzeć manewr wybrany przez ten statek.\"\"\"\n \"Darth Vader\":\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREA", "end": 62989, "score": 0.8128141760826111, "start": 62978, "tag": "NAME", "value": "Darth Vader" }, { "context": "e.\"\"\"\n \"Rebel Captive\":\n name: \"Rebeliancki jeniec\"\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREAK", "end": 63267, "score": 0.9998072385787964, "start": 63249, "tag": "NAME", "value": "Rebeliancki jeniec" }, { "context": "\"\n \"Flight Instructor\":\n name: \"Instruktor pilotażu\"\n text: \"\"\"Kiedy się bronisz, możesz p", "end": 63498, "score": 0.9983813166618347, "start": 63479, "tag": "NAME", "value": "Instruktor pilotażu" }, { "context": "truktor pilotażu\"\n text: \"\"\"Kiedy się bronisz, możesz przerzucić 1 ze swoich wyników %FOCUS%", "end": 63535, "score": 0.7739657163619995, "start": 63532, "tag": "NAME", "value": "ron" }, { "context": "OCUS%.\"\"\"\n \"Navigator\":\n name: \"Nawigator\"\n text: \"\"\"Kiedy ujawnisz swój manewr,", "end": 63766, "score": 0.9998719692230225, "start": 63757, "tag": "NAME", "value": "Nawigator" }, { "context": "jeśli posiadasz jakieś żetony stresu.\"\"\"\n \"Lando Calrissian\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%<", "end": 64012, "score": 0.9998735785484314, "start": 63996, "tag": "NAME", "value": "Lando Calrissian" }, { "context": " swojego statku 1 żeton uniku.%FOCUS%\"\"\"\n \"Mara Jade\":\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREA", "end": 64278, "score": 0.9998343586921692, "start": 64269, "tag": "NAME", "value": "Mara Jade" }, { "context": "u.\"\"\"\n \"Fleet Officer\":\n name: \"Oficer floty\"\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREAK", "end": 64495, "score": 0.9998539090156555, "start": 64483, "tag": "NAME", "value": "Oficer floty" }, { "context": "następnie otrzymujesz 1 żeton stresu.\"\"\"\n \"Han Solo\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%T", "end": 64727, "score": 0.747739851474762, "start": 64719, "tag": "NAME", "value": "Han Solo" }, { "context": "ystkie swoje wyniki %FOCUS% na %HIT%.\"\"\"\n \"Leia Organa\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%N", "end": 64951, "score": 0.9785066843032837, "start": 64940, "tag": "NAME", "value": "Leia Organa" }, { "context": "1 ze swoich odkrytych kart uszkodzeń.\"\"\"\n \"Carlist Rieekan\":\n text: \"\"\"%PL_HUGESHIPONLY% %PL_REBE", "end": 65512, "score": 0.999898374080658, "start": 65497, "tag": "NAME", "value": "Carlist Rieekan" }, { "context": "zyjaznego statku jakby wynosiła \"12\".\"\"\"\n \"Jan Dodonna\":\n text: \"\"\"%PL_HUGESHIPONLY% %PL_REBE", "end": 65758, "score": 0.9998878240585327, "start": 65747, "tag": "NAME", "value": "Jan Dodonna" }, { "context": "CRIT%.\"\"\"\n \"Tactician\":\n name: \"Taktyk\"\n text: \"Po tym jak wykonasz atak prze", "end": 65978, "score": 0.9992775321006775, "start": 65972, "tag": "NAME", "value": "Taktyk" }, { "context": "modyfikacjami) dodaj 1 wynik %EVADE%.\"\"\"\n \"Kyle Katarn\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%P", "end": 66700, "score": 0.9999048113822937, "start": 66689, "tag": "NAME", "value": "Kyle Katarn" }, { "context": "ać do swojego statku żeton skupienia.\"\"\"\n \"Jan Ors\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%R", "end": 66872, "score": 0.9998459815979004, "start": 66865, "tag": "NAME", "value": "Jan Ors" }, { "context": "isać żeton uniku (zamiast skupienia).\"\"\"\n \"Toryn Farr\":\n text: \"\"\"%PL_HUGESHIPONLY% %PL_REBE", "end": 67122, "score": 0.9999011158943176, "start": 67112, "tag": "NAME", "value": "Toryn Farr" }, { "context": " \"Targeting Coordinator\":\n name: \"Koordynator namierzania\"\n text: \"\"\"<strong>Energia:</strong> M", "end": 67485, "score": 0.9998056292533875, "start": 67462, "tag": "NAME", "value": "Koordynator namierzania" }, { "context": "ku niebieski żeton namierzonego celu.\"\"\"\n \"Raymus Antilles\":\n text: \"\"\"%PL_HUGESHIPONLY% %PL_REBE", "end": 67725, "score": 0.9998464584350586, "start": 67710, "tag": "NAME", "value": "Raymus Antilles" }, { "context": " przydziel do niego 1 żeton stresu.\"\"\"\n '\"Leebo\"':\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%", "end": 67981, "score": 0.9373581409454346, "start": 67977, "tag": "NAME", "value": "eebo" }, { "context": " Następnie otrzymujesz 1 żeton jonów.\"\"\"\n \"Dash Rendar\":\n text: \"\"\"%PL_REBELONLY%%LINEBREAK%M", "end": 68149, "score": 0.9630855917930603, "start": 68138, "tag": "NAME", "value": "Dash Rendar" }, { "context": "oje ataki nie mogą być przyblokowane.\"\"\"\n \"Ysanne Isard\":\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREA", "end": 68328, "score": 0.9998456239700317, "start": 68316, "tag": "NAME", "value": "Ysanne Isard" }, { "context": "a, możesz wykonać darmową akcję unik.\"\"\"\n \"Moff Jerjerrod\":\n text: \"\"\"%PL_IMPERIALONLY%%LINEBREA", "end": 68564, "score": 0.9998941421508789, "start": 68550, "tag": "NAME", "value": "Moff Jerjerrod" }, { "context": "e\n \"Frequency Jammer\":\n name: \"Zakłócacz częstotliwości\"\n text: \"\"\"Kiedy wykonujesz akcję Zakł", "end": 69442, "score": 0.7773101329803467, "start": 69419, "tag": "NAME", "value": "akłócacz częstotliwości" }, { "context": " \"Średni transportowiec GR-75\"\n name: \"Powiększona ładownia\"\n text: \"\"\"<span class=\"card-restricti", "end": 69763, "score": 0.9223019480705261, "start": 69743, "tag": "NAME", "value": "Powiększona ładownia" }, { "context": "y.\"\"\"\n \"Comms Booster\":\n name: \"Wzmacniacz łączności\"\n text: \"\"\"<strong>Energia:</strong> W", "end": 70032, "score": 0.9024578928947449, "start": 70012, "tag": "NAME", "value": "Wzmacniacz łączności" }, { "context": "ia.\"\"\"\n \"Slicer Tools\":\n name: \"Narzędzia hakera\"\n text: \"\"\"<strong>Akcja:</strong> Wyb", "end": 70290, "score": 0.9995520114898682, "start": 70274, "tag": "NAME", "value": "Narzędzia hakera" }, { "context": "\"\"\n \"Shield Projector\":\n name: \"Projektor osłon\"\n text: \"\"\"Kiedy wrogi statek stanie s", "end": 70596, "score": 0.9990788102149963, "start": 70581, "tag": "NAME", "value": "Projektor osłon" }, { "context": " \"Tibanna Gas Supplies\":\n name: \"Zapasy gazu Tibanna\"\n text: \"\"\"<strong>Energia:</strong> M", "end": 70842, "score": 0.9993934035301208, "start": 70823, "tag": "NAME", "value": "Zapasy gazu Tibanna" }, { "context": "\n \"Ionization Reactor\":\n name: \"Reaktor jonizacyjny\"\n text: \"\"\"<strong>Energia:</strong> W", "end": 71018, "score": 0.9986430406570435, "start": 70999, "tag": "NAME", "value": "Reaktor jonizacyjny" }, { "context": ".\"\"\"\n \"Engine Booster\":\n name: \"Dopalacz silnika\"\n text: \"\"\"Tuż przed tym jak odkryjesz", "end": 71267, "score": 0.9998012185096741, "start": 71251, "tag": "NAME", "value": "Dopalacz silnika" }, { "context": "\n \"Single Turbolasers\":\n name: \"Pojedyńcze Turbolasery\"\n text: \"\"\"<strong>Atak (energia):</st", "end": 72320, "score": 0.9293640851974487, "start": 72298, "tag": "NAME", "value": "Pojedyńcze Turbolasery" }, { "context": "Équipe\n \"Gunnery Team\":\n name: \"Zespół artylerzystów\"\n text: \"\"\"Raz na rundę kiedy atakujes", "end": 72944, "score": 0.9992111921310425, "start": 72924, "tag": "NAME", "value": "Zespół artylerzystów" }, { "context": "IT%.\"\"\"\n \"Sensor Team\":\n name: \"Zespół obsługi sensorów\"\n text: \"\"\"Kiedy namierzasz c", "end": 73165, "score": 0.9921721816062927, "start": 73151, "tag": "NAME", "value": "Zespół obsługi" }, { "context": "\"\"\n \"Engineering Team\":\n name: \"Zespół techników\"\n text: \"\"\"Podczas fazy aktywacji, kie", "end": 73352, "score": 0.9973874688148499, "start": 73336, "tag": "NAME", "value": "Zespół techników" }, { "context": "\n \"Inertial Dampeners\":\n name: \"Tłumiki inercyjne\"\n text: \"\"\"Kiedy ujawniasz swój manewr", "end": 73594, "score": 0.9981582760810852, "start": 73577, "tag": "NAME", "value": "Tłumiki inercyjne" }, { "context": "\"\n \"Dead Man's Switch\":\n name: \"Włącznik samobójcy\"\n text: \"\"\"Kiedy zostajesz zniszczony,", "end": 73828, "score": 0.9992358684539795, "start": 73810, "tag": "NAME", "value": "Włącznik samobójcy" }, { "context": "\n '\"Hot Shot\" Blaster':\n name: \"Gorący strzał\"\n text: \"\"\"<strong>Atak:</strong> Odrz", "end": 74260, "score": 0.9978619813919067, "start": 74247, "tag": "NAME", "value": "Gorący strzał" }, { "context": " \"Salvaged Astromech\":\n name: \"Astromech z odzysku\"\n text: \"Kiedy otrzymujesz k", "end": 74471, "score": 0.51470947265625, "start": 74469, "tag": "NAME", "value": "ch" }, { "context": "rzuć tę kartę rozwinięcia.%LINEBREAK%.\"\n '\"Genius\"':\n name: \"Geniusz\"\n text: ", "end": 74694, "score": 0.9658724069595337, "start": 74688, "tag": "NAME", "value": "Genius" }, { "context": "NEBREAK%.\"\n '\"Genius\"':\n name: \"Geniusz\"\n text: \"\"\"Jeśli jesteś wyposażony w b", "end": 74724, "score": 0.9976881146430969, "start": 74717, "tag": "NAME", "value": "Geniusz" }, { "context": "\n \"Unhinged Astromech\":\n name: \"Szalony astromech\"\n text: \"\"\"Możesz traktować manewry o ", "end": 74975, "score": 0.9923816323280334, "start": 74958, "tag": "NAME", "value": "Szalony astromech" }, { "context": " wybrane przez ciebie kości.\"\"\"\n \"R4 Agromech\":\n name: \"Agromech R4\"\n tex", "end": 75317, "score": 0.6139681339263916, "start": 75315, "tag": "NAME", "value": "ch" }, { "context": "ści.\"\"\"\n \"R4 Agromech\":\n name: \"Agromech R4\"\n text: \"\"\"Kiedy atakujesz, po wydaniu", "end": 75350, "score": 0.9891148805618286, "start": 75339, "tag": "NAME", "value": "Agromech R4" }, { "context": " skupienia, możesz namierzyć obrońcę.\"\"\"\n \"Emperor Palpatine\":\n text: \"\"\"%IMPERIALONLY%%LINEBREAK%O", "end": 75474, "score": 0.7928714752197266, "start": 75457, "tag": "NAME", "value": "Emperor Palpatine" }, { "context": "el <strong>all</strong> dice results.\"\"\"\n 'Agent Kallus':\n text: '''%IMPERIALONLY%%LINEBREAK%A", "end": 78700, "score": 0.8750520348548889, "start": 78688, "tag": "NAME", "value": "Agent Kallus" }, { "context": "hey activate during the Combat phase.\"\"\"\n 'Kanan Jarrus':\n text: \"\"\"%REBELONLY%%LINEBREAK%Once", "end": 82190, "score": 0.9975303411483765, "start": 82178, "tag": "NAME", "value": "Kanan Jarrus" }, { "context": "euver, you may acquire a target lock.'''\n 'Hera Syndulla':\n text: \"\"\"%REBELONLY%%LINEBREAK%You ", "end": 82949, "score": 0.9184772968292236, "start": 82936, "tag": "NAME", "value": "Hera Syndulla" }, { "context": "aneuvers even while you are stressed.\"\"\"\n 'Ezra Bridger':\n text: \"\"\"%REBELONLY%%LINEBREAK%When", "end": 83089, "score": 0.9879634976387024, "start": 83077, "tag": "NAME", "value": "Ezra Bridger" }, { "context": "r %FOCUS% results to a %CRIT% result.\"\"\"\n 'Sabine Wren':\n text: \"\"\"%REBELONLY%%LINEBREAK%Your", "end": 83256, "score": 0.9902573823928833, "start": 83245, "tag": "NAME", "value": "Sabine Wren" }, { "context": "oken if it does not already have one.\"\"\"\n \"Boba Fett\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%After", "end": 85429, "score": 0.9998345375061035, "start": 85420, "tag": "NAME", "value": "Boba Fett" }, { "context": "rd 1 of the defender's Upgrade cards.\"\"\"\n \"Dengar\":\n text: \"\"\"%SCUMONLY%%LINEBREAK%When ", "end": 85651, "score": 0.9962136745452881, "start": 85645, "tag": "NAME", "value": "Dengar" }, { "context": " instead reroll up to 2 attack dice.\"\"\"\n '\"Gonk\"':\n text: \"\"\"%SCUMONLY%%LINEBREAK%<str", "end": 85838, "score": 0.9968454241752625, "start": 85834, "tag": "NAME", "value": "Gonk" }, { "context": " may add 1 %HIT% result to your roll.'''\n 'Ketsu Onyo':\n text: '''%SCUMONLY%%LINEBREAK%At th", "end": 88095, "score": 0.976049542427063, "start": 88085, "tag": "NAME", "value": "Ketsu Onyo" }, { "context": "s not remove its tractor beam tokens.'''\n 'Latts Razzi':\n text: '''%SCUMONLY%%LINEBREAK%When ", "end": 88301, "score": 0.9971617460250854, "start": 88290, "tag": "NAME", "value": "Latts Razzi" }, { "context": "acedown Damage card.'''\n # Wave X\n 'Kylo Ren':\n text: '''%IMPERIALONLY%%LINEBREAK%<", "end": 89406, "score": 0.9993833899497986, "start": 89398, "tag": "NAME", "value": "Kylo Ren" }, { "context": "n card to an enemy ship at Range 1-3.'''\n 'Unkar Plutt':\n text: '''%SCUMONLY%%LINEBREAK%After", "end": 89590, "score": 0.9985576868057251, "start": 89579, "tag": "NAME", "value": "Unkar Plutt" }, { "context": " 1 %FOCUS% result to a %CRIT% result.'''\n 'Jyn Erso':\n text: '''%REBELONLY%%LINEBREAK%<str", "end": 90073, "score": 0.9998093843460083, "start": 90065, "tag": "NAME", "value": "Jyn Erso" }, { "context": "more than 3 focus tokens in this way.'''\n 'Cassian Andor':\n text: '''%REBELONLY%%LINEBREAK%At t", "end": 90354, "score": 0.9998270273208618, "start": 90341, "tag": "NAME", "value": "Cassian Andor" }, { "context": "rotate your dial to another maneuver.'''\n 'Finn':\n text: '''%REBELONLY%%LINEBREAK%When", "end": 90627, "score": 0.9649045467376709, "start": 90623, "tag": "NAME", "value": "Finn" }, { "context": " may add 1 blank result to your roll.'''\n 'Rey':\n text: '''%REBELONLY%%LINEBREAK%At t", "end": 90825, "score": 0.9671781063079834, "start": 90822, "tag": "NAME", "value": "Rey" }, { "context": "lank result, discard Scavenger Crane.'''\n 'Bodhi Rook':\n text: '''%REBELONLY%%LINEBREAK%When", "end": 94251, "score": 0.8832992315292358, "start": 94241, "tag": "NAME", "value": "Bodhi Rook" }, { "context": "ip at Range 1-3 of any friendly ship.'''\n 'Baze Malbus':\n text: '''%REBELONLY%%LINEBREAK%Afte", "end": 94419, "score": 0.8248049020767212, "start": 94408, "tag": "NAME", "value": "Baze Malbus" }, { "context": "n a ship outside of your firing arc).'''\n 'Cikatro Vizago':\n text: '''%SCUMONLY%%LINEBREAK%At th", "end": 95967, "score": 0.9980231523513794, "start": 95953, "tag": "NAME", "value": "Cikatro Vizago" }, { "context": "ns disabled token to flip this card.'''\n 'Wookiee Commandos':\n text: '''When attacking, you may re", "end": 97319, "score": 0.7769879102706909, "start": 97303, "tag": "NAME", "value": "ookiee Commandos" }, { "context": "cus or evade token to flip this card.'''\n 'Jabba the Hutt':\n text: '''%SCUMONLY%%LINEBREAK%When ", "end": 98265, "score": 0.7820003628730774, "start": 98251, "tag": "NAME", "value": "Jabba the Hutt" }, { "context": "if that action is on your action bar.'''\n 'Debris Gambit':\n text: '''%SMALLSHIPONLY%%LINEBREAK%", "end": 103616, "score": 0.998988687992096, "start": 103603, "tag": "NAME", "value": "Debris Gambit" }, { "context": "the attacker receives 1 stress token.'''\n 'Saw Gerrera':\n text: '''%REBELONLY%%LINEBREAK%When", "end": 104220, "score": 0.9991544485092163, "start": 104209, "tag": "NAME", "value": "Saw Gerrera" }, { "context": "ur %FOCUS% results to %CRIT% results.'''\n 'Director Krennic':\n text: '''During setup, before the \"", "end": 104391, "score": 0.9995157122612, "start": 104375, "tag": "NAME", "value": "Director Krennic" }, { "context": " Empire ship with 3 or fewer shields.'''\n 'Magva Yarro':\n text: '''%REBELONLY%%LINEBREAK%Afte", "end": 104587, "score": 0.9997145533561707, "start": 104576, "tag": "NAME", "value": "Magva Yarro" }, { "context": "suit Lasers\":\n name: \"Lasery antypościgowe\"\n text: \"\"\"%PL_LARGESHIPONLY%Po tym ja", "end": 106483, "score": 0.6706498861312866, "start": 106480, "tag": "NAME", "value": "owe" }, { "context": "\"\"\"\n \"Tactical Jammer\":\n name: \"Zakłócacz taktyczny\"\n text: \"\"\"%PL_LARGESHIPONLY%%LINEBREA", "end": 108490, "score": 0.9955970048904419, "start": 108471, "tag": "NAME", "value": "Zakłócacz taktyczny" }, { "context": "i.\"\"\"\n \"Autothrusters\":\n name: \"Autodopalacze\"\n text: \"\"\"Kiedy się bronisz, jeśli je", "end": 108648, "score": 0.8987123966217041, "start": 108635, "tag": "NAME", "value": "Autodopalacze" }, { "context": " rozwinięć zyskuje symbol %TORPEDO%.\"\"\"\n \"Millennium Falcon\":\n name: \"Sokół Millenium\"\n ", "end": 114305, "score": 0.6321858167648315, "start": 114299, "tag": "NAME", "value": "illenn" }, { "context": "ć zyskuje symbol %TORPEDO%.\"\"\"\n \"Millennium Falcon\":\n name: \"Sokół Millenium\"\n ", "end": 114315, "score": 0.8131792545318604, "start": 114309, "tag": "NAME", "value": "Falcon" }, { "context": "\"\n \"Millennium Falcon\":\n name: \"Sokół Millenium\"\n text: \"\"\"<span class=\"card-restricti", "end": 114352, "score": 0.9998666048049927, "start": 114337, "tag": "NAME", "value": "Sokół Millenium" }, { "context": "k akcji zyskuje symbol akcji %EVADE%.\"\"\"\n \"Moldy Crow\":\n text: \"\"\"<span class=\"card-restrict", "end": 114508, "score": 0.9968881607055664, "start": 114498, "tag": "NAME", "value": "Moldy Crow" }, { "context": " ship: \"TIE Interceptor\"\n name: \"TIE Imperialnego Gwardzisty\"\n text: \"\"\"<span class=\"card-restricti", "end": 115084, "score": 0.9945491552352905, "start": 115057, "tag": "NAME", "value": "TIE Imperialnego Gwardzisty" }, { "context": "ności pilota wynosi \"4\" lub mniej.\"\"\"\n \"Dodonna's Pride\":\n name: \"Duma Dodonny\"\n ", "end": 115387, "score": 0.6350600719451904, "start": 115383, "tag": "NAME", "value": "onna" }, { "context": "\"\"\"\n \"Dodonna's Pride\":\n name: \"Duma Dodonny\"\n ship: \"Korweta CR90 (dziób)\"\n ", "end": 115429, "score": 0.9998603463172913, "start": 115417, "tag": "NAME", "value": "Duma Dodonny" }, { "context": "Następnie otrzymujesz 1 żeton stresu.\"\"\"\n \"Virago\":\n text: \"\"\"<span class=\"card-restrict", "end": 118055, "score": 0.9813992381095886, "start": 118049, "tag": "NAME", "value": "Virago" }, { "context": "ptor (Missile)':\n name: 'Intercepteur \"Scyk Lourd\" (Rakieta)'\n text: \"\"\"<span class=\"car", "end": 118996, "score": 0.9624573588371277, "start": 118986, "tag": "NAME", "value": "Scyk Lourd" }, { "context": " you may perform a free evade action.\"\"\"\n \"Mist Hunter\":\n text: \"\"\"<span class=\"card-restrict", "end": 120970, "score": 0.8880228996276855, "start": 120959, "tag": "NAME", "value": "Mist Hunter" }, { "context": ", a friendly ship at Range 1-2 equipped with the \"Director Krennic\" Upgrade card may acquire a target lock on the de", "end": 133850, "score": 0.7301527857780457, "start": 133834, "tag": "NAME", "value": "Director Krennic" } ]
coffeescripts/cards-pl.coffee
idavidka/xwing
100
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.pl = 'Polski' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations['Polski'] = action : "Barrel Roll": "Beczka" "Boost": "Dopalacz" "Evade": "Unik" "Focus": "Skupienie" "Target Lock": "Namierzenie celu" "Recover": "Naprawa" "Reinforce": "Umocnienie" "Jam": "Zakłócanie" "Coordinate": "Koordynacja" "Cloak": "Maskowanie" slot: "Astromech": "Astromech" "Bomb": "Bomba" "Cannon": "Działo" "Crew": "Załoga" "Elite": "Talent elitarny" "Missile": "Rakiety" "System": "System" "Torpedo": "Torpedy" "Turret": "Wieżyczka" "Cargo": "Ładunek" "Hardpoint": "Punkt konstrukcyjny" "Team": "Drużyna" "Illicit": "Kontrabanda" "Salvaged Astromech": "Złomowane astromechy" sources: # needed? "Core": "Zestaw Podstawowy" "A-Wing Expansion Pack": "Zestaw dodatkowy A-Wing" "B-Wing Expansion Pack": "Zestaw dodatkowy B-Wing" "X-Wing Expansion Pack": "Zestaw dodatkowy X-Wing" "Y-Wing Expansion Pack": "Zestaw dodatkowy Y-Wing" "Millennium Falcon Expansion Pack": "Zestaw dodatkowy Sokół Millennium" "HWK-290 Expansion Pack": "Zestaw dodatkowy HWK-290" "TIE Fighter Expansion Pack": "Zestaw dodatkowy Myśliwiec TIE" "TIE Interceptor Expansion Pack": "Zestaw dodatkowy TIE Interceptor" "TIE Bomber Expansion Pack": "Zestaw dodatkowy Bombowiec TIE" "TIE Advanced Expansion Pack": "Zestaw dodatkowy TIE Advanced" "Lambda-Class Shuttle Expansion Pack": "Zestaw dodatkowy Prom typu Lambda" "Slave I Expansion Pack": "Zestaw dodatkowy Slave I" "Imperial Aces Expansion Pack": "Zestaw dodatkowy Asy Imperium" "Rebel Transport Expansion Pack": "Zestaw dodatkowy Rebeliancki transportowiec" "Z-95 Headhunter Expansion Pack": "Zestaw dodatkowy Z-95 Łowca Głów" "TIE Defender Expansion Pack": "Zestaw dodatkowy TIE Defender" "E-Wing Expansion Pack": "Zestaw dodatkowy E-Wing" "TIE Phantom Expansion Pack": "Zestaw dodatkowy TIE Phantom" "Tantive IV Expansion Pack": "Zestaw dodatkowy Tantive IV" "Rebel Aces Expansion Pack": "Zestaw dodatkowy Asy Rebelii" "YT-2400 Freighter Expansion Pack": "Zestaw dodatkowy YT-2400" "VT-49 Decimator Expansion Pack": "Zestaw dodatkowy Decimator VT-49" "StarViper Expansion Pack": "Zestaw dodatkowy StarViper" "M3-A Interceptor Expansion Pack": "Zestaw dodatkowy M3-A Interceptor" "IG-2000 Expansion Pack": "Zestaw dodatkowy IG-2000" "Most Wanted Expansion Pack": "Zestaw dodatkowy Poszukiwani" "Imperial Raider Expansion Pack": "Zestaw dodatkowy Imperialny Patrolowiec" "The Force Awakens Core Set": "The Force Awakens Core Set" ui: shipSelectorPlaceholder: "Wybór statków" pilotSelectorPlaceholder: "Wybór pilotów" upgradePlaceholder: (translator, language, slot) -> "#{translator language, 'slot', slot}" modificationPlaceholder: "Modyfikacje" titlePlaceholder: "Tytuł" upgradeHeader: (translator, language, slot) -> "Amélioration #{translator language, 'slot', slot}" unreleased: "niewydane" epic: "epickie" byCSSSelector: # Warnings '.unreleased-content-used .translated': 'This squad uses unreleased content!</span>' '.epic-content-used .translated': 'This squad uses Epic content!' '.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!' '.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!' '.collection-invalid .translated': 'You cannot field this list with your collection!' # Type selector '.game-type-selector option[value="standard"]': 'Standard' '.game-type-selector option[value="custom"]': 'Custom' '.game-type-selector option[value="epic"]': 'Epic' '.game-type-selector option[value="team-epic"]': 'Team Epic' # Card browser '.xwing-card-browser .translate.sort-cards-by': 'Sortuj karty po' '.xwing-card-browser option[value="name"]': 'nazwie' '.xwing-card-browser option[value="source"]': 'źródle' '.xwing-card-browser option[value="type-by-points"]': 'typie (po punktach)' '.xwing-card-browser option[value="type-by-name"]': 'typie (po nazwie)' '.xwing-card-browser .translate.select-a-card': 'Wybierz kartę z listy po prawej' '.xwing-card-browser .info-range td': 'Zasięg’' # Info well '.info-well .info-ship td.info-header': 'Statek' '.info-well .info-skill td.info-header': 'Umiejętność pilota' '.info-well .info-actions td.info-header': 'Akcje' '.info-well .info-upgrades td.info-header': 'Ulepszenia' '.info-well .info-range td.info-header': 'Zasięg' # Squadron edit buttons '.clear-squad' : 'Wyczyść eskadrę' '.save-list' : 'Zapisz' '.save-list-as' : 'Zapisz jako ...' '.delete-list' : 'Usuń' '.backend-list-my-squads' : 'Lista eskadr' '.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i>&nbsp;Drukuj \ Wyświetl jako </span>Tekst' '.randomize' : 'randomizuj' '.randomize-options' : 'Opcje ...' '.notes-container > span' : 'Squad Notes' # Print/View modal '.bbcode-list' : 'Skopiuj BBCode poniżej i wklej go do swojego posta.<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.html-list' : '<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.vertical-space-checkbox' : """Dodaj miejsce na karty ulepszeń \ uszkodzeń podczas drukowania <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Wydrukuj w kolorze <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="fa fa-print"></i>&nbsp;Drukuj' # Randomizer options '.do-randomize' : 'Generuj' # Top tab bar '#empireTab' : 'Imperium Galaktyczne' '#rebelTab' : 'Sojusz Rebeliancki' '#scumTab' : 'Szumowiny i Nikczemnicy' '#browserTab' : 'Przeglądarka kart' '#aboutTab' : 'O stronie' singular: 'pilots': 'Pilot' 'modifications': 'Modyfikacja' 'titles': 'Tytuł' types: 'Pilot': 'Pilot' 'Modification': 'Modyfikacja' 'Title': 'Tytuł' exportObj.cardLoaders ?= {} exportObj.cardLoaders['Polski'] = () -> exportObj.cardLanguage = 'Polski' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Rename ships exportObj.renameShip 'TIE Fighter', 'Myśliwiec TIE' exportObj.renameShip 'TIE Bomber', 'Bombowiec TIE' exportObj.renameShip 'Lambda-Class Shuttle', 'Prom typu Lambda' exportObj.renameShip 'VT-49 Decimator', 'Decimator VT-49' exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Łowca głów' exportObj.renameShip 'CR90 Corvette (Aft)', 'Korweta CR90 (rufa)' exportObj.renameShip 'CR90 Corvette (Fore)', 'Corvette CR90 (dziób)' exportObj.renameShip 'GR-75 Medium Transport', 'Średni transportowiec GR-75' # Names don't need updating, but text needs to be set pilot_translations = # Empire # Myśliwiec TIE "Academy Pilot": ship: "Myśliwiec TIE" name: "Pilot z Akademii" "Obsidian Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry Obsydianowych" "Black Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry Czarnych" '"Winged Gundark"': name: "Skrzydlaty Gundark" ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" '"Night Beast"': name: "Nocny Potwór" ship: "Myśliwiec TIE" text: """Po wykonaniu zielonego manewru możesz wykonać darmową akcję skupienia.""" '"Backstabber"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz będąc poza polem rażenia broniącego się statku, rzucasz 1 dodatkową kością ataku.""" '"Dark Curse"': name: "Mroczna Klątwa" ship: "Myśliwiec TIE" text: """Kiedy się bronisz statki które cię atakują nie mogą wydawać żetonów skupienia ani przerzucać kości ataku.""" '"Mauler Mithel"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, rzucasz 1 dodatkową kością ataku.""" '"Howlrunner"': ship: "Myśliwiec TIE" text: """Kiedy inny przyjazny statek w zasięgu 1 atakuje przy pomocy swojej podstawowej broni, może przerzucić 1 kość ataku.""" # TIE Interceptor "Alpha Squadron Pilot": name: "Pilot Eskadry Alfa" "Avenger Squadron Pilot": name: "Pilot Eskadry Mścicieli" "Saber Squadron Pilot": name: "Pilot Eskadry Szabel" "Royal Guard Pilot": name: "Pilot imperialny gwardzista" "\"Fel's Wrath\"": name: "\"Gniew Fel'a\"" text: """Zostajesz zniszczony dopiero pod koniec fazy walki, w której liczba kart uszkodzeń przypisanych do ciebie będzie równa, lub wyższa od twojej wartości kadłuba.""" "Lieutenant Lorrir": name: "Porucznik Lorrir" text: """Kiedy wykonujesz akcję "beczka", możesz otrzymać 1 żeton stresu, aby zamiast wzornika manewru (%STRAIGHT% 1) użyć (%BANKLEFT% 1) lub (%BANKRIGHT% 1).""" "Kir Kanos": text: """Kiedy atakujesz w Zasięgu 2-3, możesz wydać 1 żeton uników, aby dodać 1 %HIT% do swojego wyniku.""" "Tetran Cowall": text: """Kiedy ujawnisz manewr %UTURN% możesz traktować go tak, jakby jego prędkość wynosiła "1", "3" lub "5".""" "Turr Phennir": text: """Po wykonaniu ataku możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "Carnor Jax": text: """Wrogie statki w Zasięgu 1 nie mogą wykonywać akcji "skupienie" oraz "unik", ani wydawać żetonów skupienia i uników.""" "Soontir Fel": text: """Kiedy otrzymujesz żeton stresu, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Phantom "Sigma Squadron Pilot": name: "Pilot Eskadry Sigma" "Shadow Squadron Pilot": name: "Pilot Eskadry Cieni" '"Echo"': text: """Kiedy się demaskujesz musisz użyć wzornika manewru (%BANKLEFT% 2) lub (%BANKRIGHT% 2) zamiast wzornika (%STRAIGHT% 2).""" '"Whisper"': name: "Szept" text: """Po tym jak wykonasz atak, który trafi cel, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Defender "Onyx Squadron Pilot": name: "Pilot Eskadry Onyx" "Delta Squadron Pilot": name: "Pilot Eskadry Delta" "Colonel Vessery": name: "Pułkownik Vessery" text: """Kiedy atakujesz, zaraz po swoim rzucie kośćmi ataku możesz namierzyć obrońcę, jeśli ma na sobie czerwony żeton namierzonego celu.""" "Rexler Brath": text: """Po tym jak wykonasz atak, który zada obrońcy co najmniej jedną kartę uszkodzenia, możesz wydać żeton skupienia aby odkryć te karty.""" # Bombowiec TIE "Scimitar Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Sejmitarów" "Gamma Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Gamma" "Captain Jonus": ship: "Bombowiec TIE" name: "Kapitan Jonus" text: "Kiedy inny przyjazny statek w Zasięgu 1 atakuje przy pomocy dodatkowej broni, może przerzucić maksymalnie 2 kości ataku." "Major Rhymer": ship: "Bombowiec TIE" text: "Kiedy atakujesz przy pomocy dodatkowej broni, możesz zwiększyć lub zmniejszyć zasięg broni o 1. Musisz przy tym zachować limit zasięgu 1-3." "Gamma Squadron Veteran": ship: "Bombowiec TIE" # TIE Advanced "Tempest Squadron Pilot": name: "Pilot Eskadry Burzy" "Storm Squadron Pilot": name: "Pilot Eskadry Szturmu" "Maarek Stele": text: """Kiedy twój atak zadaje obrońcy odkrytą kartę uszkodzenia, wylosuj 3 karty uszkodzeń, wybierz 1 z nich, którą zadajesz, a pozostałe odrzuć.""" "Darth Vader": text: """Podczas swojego kroku "Wykonywania akcji" możesz wykonać 2 akcje.""" "Commander Alozen": name: "Komandor Alozen" text: """Na początku fazy walki możesz namierzyć wrogi statek znajdujący się w Zasięgu 1 od ciebie.""" # Firespray "Bounty Hunter": name:"Łowca nagród" "Kath Scarlet": text: """Kiedy atakujesz, obrońca otrzymuje 1 żeton stresu, jeśli anuluje co najmniej jeden wynik %CRIT%.""" "Boba Fett": text: """Kiedy ujawniasz manewr skrętu (%BANKLEFT% lub %BANKRIGHT%) możesz przestawić swój wskaźnik manewrów na drugi manewr skrętu o tej samej prędkości.""" "Krassis Trelix": text: """Kiedy atakujesz przy pomocy dodatkowej broni, możesz przerzucić 1 kość ataku.""" # Prom typu Lambda "Captain Kagi": ship: "Prom typu Lambda" name: "Kapitan Kagi" text: """Kiedy wrogi statek namierza cel, musi namierzyć twój statek, jeśli to możliwe.""" "Colonel Jendon": name: "Pułkownik Jendon" ship: "Prom typu Lambda" text: """Na początku fazy walki możesz przypisać 1 ze swoich niebieskich żetonów namierzonego celu do przyjaznego statku w Zasięgu 1, jeśli ten nie ma niebieskiego żetonu namierzonego celu.""" "Captain Yorr": ship: "Prom typu Lambda" name: "Kapitan Yorr" text: """Kiedy inny przyjazny statek w Zasięgu 1-2 ma otrzymać żeton stresu, gdy ty masz 2 lub mniej żetonów stresu, możesz przypisać do siebie ten żeton stresu.""" "Omicron Group Pilot": ship: "Prom typu Lambda" name: "Pilot grupy Omicron" # VT-49 Decimator "Captain Oicunn": ship: "Decimator VT-49" name: "Kapitan Oicunn" text: """Po wykonaniu manewru, każdy wrogi statek z którym się stykasz, otrzymuje 1 uszkodzenie.""" "Rear Admiral Chiraneau": ship: "Decimator VT-49" name: "Kontradmirał Chiraneau" text: """Kiedy atakujesz w Zasięgu 1-2, możesz zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Patrol Leader": ship: "Decimator VT-49" name: "Dowódca Patrolu" "Commander Kenkirk": ship: "Decimator VT-49" name: "Commandant Kenkirk" text: """Jeśli nie masz żadnych osłon i masz przypisaną co najmniej 1 kartę uszkodzenia, wartość twojej zwrotności wzrasta o 1.""" "Juno Eclipse": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "Zertik Strom": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "Lieutenant Colzet": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" # Rebels # X-Wing "Red Squadron Pilot": name: "Pilot Eskadry Czerwonych" "Rookie Pilot": name: "Niedoświadczony pilot" "Wedge Antilles": text: """Kiedy atakujesz zredukuj wartość zwrotności obrońcy o 1 (do minimum 0).""" "Garven Dreis": text: """Po tym jak wydasz żeton skupienia możesz umieścić dany żeton na dowolnym innym przyjaznym statku w Zasięgu 1-2 (zamiast go odrzucać).""" "Biggs Darklighter": text: """Inne przyjazne statki w Zasięgu 1 nie mogą być wybierane na cel ataku, jeśli atakujący może na cel wybrać ciebie.""" "Luke Skywalker": text: """Kiedy się bronisz, możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %EVADE%.""" "Wes Janson": text: """Po wykonaniu ataku możesz usunąć z obrońcy 1 żeton skupienia, uników, lub niebieski żeton namierzonego celu.""" "Jek Porkins": text: """Kiedy otrzymujesz żeton stresu możesz usunąć go i rzucić 1 kością ataku. Jeśli wypadnie %HIT%, ten statek otrzymuje 1 zakrytą kartę uszkodzenia.""" '"Hobbie" Klivian': text: """Kiedy zdobywasz lub wydajesz żeton namierzonego celu, możesz usunąć ze swojego statku 1 żeton stresu.""" "Tarn Mison": text: """Kiedy wrogi statek wybiera cię na cel ataku, możesz namierzyć ten statek.""" # Y-Wing "Gold Squadron Pilot": name: "Pilot Eskadry Złotych" "Gray Squadron Pilot": name: "Pilot Eskadry Szarych" '"Dutch" Vander': text: """Po namierzeniu celu wybierz przyjazny statek w Zasięgu 1-2. Wybrany statek może natychmiast namierzyć cel.""" "Horton Salm": text: """Kiedy atakujesz w Zasięgu 2-3, możesz przerzucić dowolne ze swoich kości, na których wypadły puste ścianki.""" # A-Wing "Green Squadron Pilot": name: "Pilot Eskadry Zielonych" "Prototype Pilot": name: "Pilot prototypu" "Tycho Celchu": text: """Możesz wykonywać akcje nawet jeśli posiadasz żetony stresu.""" "Arvel Crynyd": text: """Możesz wybrać na cel swojego ataku wrogi statek, z którym się stykasz, jeżeli ten znajduje się w twoim polu rażenia.""" # YT-1300 "Outer Rim Smuggler": name: "Przemytnik z Zewnętrznych Rubierzy" "Chewbacca": text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, natychmiast ją zakryj (bez rozpatrywania jej efektu).""" "Lando Calrissian": text: """Po wykonaniu zielonego manewru wybierz jeden inny przyjazny statek w Zasięgu 1. Statek ten może wykonać 1 darmową akcję przedstawioną na jego pasku akcji.""" "Han Solo": text: """Kiedy atakujesz możesz przerzucić wszystkie swoje kości ataku. Jeśli zdecydujesz się to zrobić musisz przerzucić tyle ze swoich kości, ile możesz.""" # B-Wing "Dagger Squadron Pilot": name: "Pilot Eskadry Sztyletów" "Blue Squadron Pilot": name: "Pilot Eskadry Niebieskich" "Ten Numb": text: """Kiedy atakujesz, 1 z twoich wyników [crt-hit] nie może być anulowany przy pomocy kości obrony.""" "Ibtisam": text: """Kiedy atakujesz lub się bronisz mając co najmniej 1 żeton stresu, możesz przerzucić jedną ze swoich kości.""" # HWK-290 "Rebel Operative": name: "Agent rebeliantów" "Roark Garnet": text: '''Na początku fazy walki wybierz 1 inny przyjazny statek w zasięgu 1-3. Do końca tej fazy traktuj wartość umiejętności tego pilota jakby wynosiła "12".''' "Kyle Katarn": text: """Na początku fazy walki możesz przypisać 1 ze swoich żetonów skupienia do innego przyjaznego statku w Zasięgu 1-3.""" "Jan Ors": text: """Kiedy inny przyjazny statek w Zasięgu 1-3 atakuje, gdy nie masz żadnych żetonów stresu, możesz otrzymać 1 żeton stresu aby umożliwić mu rzut 1 dodatkową kością ataku.""" # Z-95 "Bandit Squadron Pilot": name: "Pilot Eskadry Bandytów" ship: "Z-95 Łowca głów" "Tala Squadron Pilot": name: "Pilot Eskadry Tala" ship: "Z-95 Łowca głów" "Lieutenant Blount": name: "Porucznik Blount" ship: "Z-95 Łowca głów" text: "Kiedy atakujesz, obrońca zostaje trafiony twoim atakiem nawet jeśli nie otrzymał żadnych uszkodzeń." "Airen Cracken": ship: "Z-95 Łowca głów" text: """Po wykonaniu ataku możesz wybrać inny przyjazny statek w Zasięgu 1. Dany statek może wykonać 1 darmową akcję.""" # E-Wing "Knave Squadron Pilot": name: "Pilot Eskadry Szelm" "Blackmoon Squadron Pilot": name: "Pilot Eskadry Czarnego Księżyca" "Etahn A'baht": text: """Kiedy wrogi statek w twoim polu rażenia, w Zasięgu 1-3 się broni, atakujący może zmienić 1 z jego wyników %HIT% na wynik %CRIT%.""" "Corran Horn": text: """Na początku fazy końcowej możesz wykonać jeden atak. Nie możesz atakować w następnej rundzie.""" # Asy Rebelii "Jake Farrell": text: """Po tym jak wykonasz akcję skupienia lub zostanie ci przypisany żeton skupienia, możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "Gemmer Sojan": text: """Dopóki znajdujesz się w Zasięgu 1 od co najmniej 1 wrogiego statku, zwiększ swoją wartość zwrotności o 1.""" "Keyan Farlander": text: """Kiedy atakujesz możesz usunąć 1 żeton stresu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "Nera Dantels": text: """Możesz wykonać atak dodatkową bronią %TORPEDO%, skierowany przeciwko wrogim statkom znajdującym się poza twoim polem rażenia.""" # Transportowiec Rebelii "GR-75 Medium Transport": name: "Średni transportowiec GR-75" ship: "Średni transportowiec GR-75" # CR90 "CR90 Corvette (Fore)": ship: "Korweta CR90 (dziób)" name: "Korweta CR90 (dziób)" text: """Kiedy atakujesz przy pomocy swojej głównej broni, możesz wydać 1 żeton energii aby rzucać 1 dodatkową kością ataku.""" "CR90 Corvette (Aft)": ship: "Korweta CR90 (rufa)" name: "Korweta CR90 (rufa)" # YT-2400 "Dash Rendar": text: """Podczas fazy aktywacji i w czasie wykonywania akcji możesz ignorować przeszkody.""" '"Leebo"': text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, dobierz 1 dodatkową kartę uszkodzenia. Rozpatrz jedną z nich a drugą odrzuć.""" "Eaden Vrill": text: """Podczas wykonywania ataku przy pomocy broni podstawowej, którego celem jest statek z żetonem stresu, rzucasz 1 dodatkową kością.""" "Wild Space Fringer": name: "Outsider z Dzikiej Przestrzeni" # Scum and Villainy # Starviper "Prince Xizor": name: "Książe Xizor" text: """Kiedy się bronisz, przyjazny statek w Zasięgu 1 może otrzymać 1 nieanulowany wynik %HIT% lub %CRIT% (zamiast ciebie).""" "Guri": text: """Na początku fazy walki, jeśli jesteś w Zasięgu 1 od wrogiego statku, możesz przypisać do swojego statku 1 żeton skupienia.""" "Black Sun Vigo": name: "Vigo Czarnego Słońca" "Black Sun Enforcer": name: "Wysłannik Czarnego Słońca" # Interceptor M3-A "Cartel Spacer": name: "Pilot kartelu" "Tansarii Point Veteran": name: "Weteran Tansarii Point" "Serissu": text: """Kiedy inny przyjazny statek w Zasięgu 1 się broni, może przerzucić 1 kość obrony.""" "Laetin A'shera": text: "Po tym jak obronisz się przed atakiem, jeśli atak nie trafił, możesz przypisać do swojego statku 1 żeton uniku." # Agressor "IG-88A": text: """Po tym jak wykonasz atak, który zniszczy obrońcę, możesz odzyskać 1 osłonę.""" "IG-88B": text: """Raz na rundę, po tym jak wykonasz atak, który nie trafi w wybrany cel, możesz wykonać atak przy pomocy dodatkowej broni %CANON%, w którą jesteś wyposażony.""" "IG-88C": text: """Po tym jak wykonasz akcję „dopalacz” możesz przypisać do swojego statku 1 żeton uniku.""" "IG-88D": text: """Możesz wykonać manewr (%SLOOPLEFT% 3) lub (%SLOOPRIGHT% 3) używając odpowiednio wzornika (%TURNLEFT% 3) lub (%TURNRIGHT% 3).""" # Firespray "Boba Fett (Scum)": name: """Boba Fett (Szumowiny)""" text: """Kiedy atakujesz lub się bronisz możesz przerzucić 1 ze swoich kości za każdy wrogi statek w Zasięgu 1.""" "Kath Scarlet (Scum)": name: """Kath Scarlet (Szumowiny)""" text: """Kiedy atakujesz statek znajdujący się w twoim pomocniczym polu rażenia, rzucasz 1 dodatkową kością ataku.""" "Emon Azzameen": text: """Kiedy zrzucasz bombę, możesz użyć wzornika [%TURNLEFT% 3], [%STRAIGHT% 3], lub [%TURNRIGHT% 3] (zamiast wzornika [%STRAIGHT% 1]).""" "Mandalorian Mercenary": name: "Mandaloriański najemnik" # Y-Wing "Kavil": text: """Kiedy atakujesz statek znajdujący się poza twoim polem rażenia, rzucasz 1 dodatkową kością ataku.""" "Drea Renthal": text: """Po tym jak wydasz żeton namierzonego celu, możesz otrzymać 1 żeton stresu, aby namierzyć cel.""" "Hired Gun" : name: "Najemnik" "Syndicate Thug": name: "Zbir z syndykatu" # HWK "Dace Bonearm": text: """Kiedy wrogi statek w Zasięgu 1-3 otrzyma co najmniej jeden żeton jonów, a ty nie masz żetonu stresu, możesz otrzymać 1 żeton stresu aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "Palob Godalhi": text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z wrogiego statku w Zasięgu 1-2 i przypisać go do siebie.""" "Torkil Mux": text: """Na koniec fazy aktywacji wybierz jeden wrogi statek w Zasięgu 1-2. Do końca fazy walki wartość umiejętności pilota wybranego statku wynosi "0".""" "Spice Runner": name: "Przemytnik przyprawy" # Z-95 "Black Sun Soldier": name: "Żolnierz Czarnego Słońca" ship: "Z-95 Łowca głów" "Binayre Pirate": name: "Pirat z Binayre" ship: "Z-95 Łowca głów" "N'Dru Suhlak": ship: "Z-95 Łowca głów" text: """Kiedy atakujesz rzucasz 1 dodatkową kością ataku, jeśli w Zasięgu 1-2 nie ma żadnych innych przyjaznych statków.""" "Kaa'to Leeachos": ship: "Z-95 Łowca głów" text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z innego przyjaznego statku w Zasięgu 1-2 i przypisać go do siebie.""" "Latts Razzi": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "Graz the Hunter": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "Esege Tuketu": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" '"Redline"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"Deathrain"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Moralo Eval": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" 'Gozanti-class Cruiser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"Scourge"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "The Inquisitor": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "Zuckuss": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" # T-70 "Poe Dameron": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" '"Blue Ace"': text: """When performing a boost action, you may use the (%TURNLEFT% 1) or (%TURNRIGHT% 1) template.""" # TIE/fo '"Omega Ace"': text: """When attacking, you may spend a focus token and a target lock you have on the defender to change all of your results to %CRIT% results.""" '"Epsilon Leader"': text: """At the start of the Combat phase, remove 1 stress token from each friendly ship at Range 1.""" '"Zeta Ace"': text: """When performing a barrel roll you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" '"Red Ace"': text: '''The first time you remove a shield token from your ship each round, assign 1 evade token to your ship.''' '"Omega Leader"': text: '''Enemy ships that you have locked cannot modify any dice when attacking you or defending against your attacks.''' 'Hera Syndulla': text: '''When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.''' '"Youngster"': text: """Friendly TIE fighters at Range 1-3 may perform the action on your equipped %ELITE% Upgrade card.""" '"Wampa"': text: """When attacking, you may cancel all die results. If you cancel a %CRIT% result, deal 1 facedown Damage card to the defender.""" '"Chaser"': text: """When another friendly ship at Range 1 spends a focus token, assign a focus token to your ship.""" 'Ezra Bridger': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"Zeta Leader"': text: '''When attacking, if you are not stressed, you may receive 1 stress token to roll 1 additional die.''' '"Epsilon Ace"': text: '''While you do not have any Damage cards, treat your pilot skill value as "12."''' "Kanan Jarrus": text: """When an enemy ship at Range 1-2 is attacking, you may spend a focus token. If you do, the attacker rolls 1 fewer attack die.""" '"Chopper"': text: """At the start of the Combat phase, each enemy ship you are touching receives 1 stress token.""" 'Hera Syndulla (Attack Shuttle)': text: """When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.""" 'Sabine Wren': text: """Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.""" '"Zeb" Orrelios': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'Tomax Bren': ship: "Bombowiec TIE" text: '''Once per round, after you discard an %ELITE% Upgrade card, flip that card faceup.''' 'Ello Asty': text: '''While you are not stressed, you may treat your %TROLLLEFT% and %TROLLRIGHT% maneuvers as white maneuvers.''' "Valen Rudor": text: """After defending, you may perform a free action.""" "4-LOM": text: """At the start of the End phase, you may assign 1 of your stress tokens to another ship at Range 1.""" "Tel Trevura": text: """The first time you would be destroyed, instead cancel any remaining damage, discard all Damage cards, and deal 4 facedown Damage cards to this ship.""" "Manaroo": text: """At the start of the Combat phase, you may assign all focus, evade, and target lock tokens assigned to you to another friendly ship.""" '"Deathfire"': ship: "Bombowiec TIE" text: '''When you reveal your maneuver dial or after you perform an action, you may perform a %BOMB% Upgrade card action as a free action.''' "Maarek Stele (TIE Defender)": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "Countess Ryad": text: """When you reveal a %STRAIGHT% maneuver, you may treat it as a %KTURN% maneuver.""" "Poe Dameron (PS9)": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" "Rey": text: """When attacking or defending, if the enemy ship is inside of your firing arc, you may reroll up to 2 of your blank results.""" 'Han Solo (TFA)': text: '''When you are placed during setup, you can be placed anywhere in the play area beyond Range 3 of enemy ships.''' 'Chewbacca (TFA)': text: '''After another friendly ship at Range 1-3 is destroyed (but has not fled the battlefield), you may perform an attack.''' 'Norra Wexley': text: '''When attacking or defending, you may spend a target lock you have on the enemy ship to add 1 %FOCUS% result to your roll.''' 'Shara Bey': text: '''When another friendly ship at Range 1-2 is attacking, it may treat your blue target lock tokens as its own.''' 'Thane Kyrell': text: '''After an enemy ship in your firing arc at Range 1-3 attacks another friendly ship, you may perform a free action.''' 'Braylen Stramm': text: '''After you execute a maneuver, you may roll an attack die. On a %HIT% or %CRIT% result, remove 1 stress token from your ship.''' '"Quickdraw"': text: '''Once per round, when you lose a shield token, you may perform a primary weapon attack.''' '"Backdraft"': text: '''When attacking a ship inside your auxiliary firing arc, you may add 1 %CRIT% result.''' 'Fenn Rau': text: '''When attacking or defending, if the enemy ship is at Range 1, you may roll 1 additional die.''' 'Old Teroch': text: '''At the start of the Combat phase, you may choose 1 enemy ship at Range 1. If you are inside its firing arc, it discards all focus and evade tokens.''' 'Kad Solus': text: '''After you execute a red maneuver, assign 2 focus tokens to your ship.''' 'Ketsu Onyo': text: '''At the start of the Combat phase, you may choose a ship at Range 1. If it is inside your primary <strong>and</strong> mobile firing arcs, assign 1 tractor beam token to it.''' 'Asajj Ventress': text: '''At the start of the Combat phase, you may choose a ship at Range 1-2. If it inside your mobile firing arc, assign 1 stress token to it.''' 'Sabine Wren (Scum)': text: '''When defending against an enemy ship inside your mobile firing arc at Range 1-2, you may add 1 %FOCUS% result to your roll.''' 'Sabine Wren (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.''' '"Zeb" Orrelios (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'Kylo Ren': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' 'Unkar Plutt': text: '''At the end of the Activation phase, you <strong>must</strong> assign a tractor beam token to each ship you are touching.''' 'Cassian Andor': text: '''At the start of the Activation phase, you may remove 1 stress token from 1 other friendly ship at Range 1-2.''' 'Bodhi Rook': text: '''When a friendly ship acquires a target lock, that ship can lock onto an enemy ship at Range 1-3 of any friendly ship.''' 'Heff Tobber': text: '''After an enemy ship executes a maneuver that causes it to overlap your ship, you may perform a free action.''' '''"Duchess"''': text: '''While you have the "Adaptive Ailerons" Upgrade card equipped, you may choose to ignore its card ability.''' '''"Pure Sabacc"''': text: '''When attacking, if you have 1 or fewer Damage cards, roll 1 additional attack die.''' '''"Countdown"''': text: '''When defending, if you are not stressed, during the "Compare Results" step, you may suffer 1 damage to cancel all dice results. If you do, receive 1 stress token.''' 'Nien Nunb': text: '''When you receive a stress token, if there is an enemy ship inside your firing arc at Range 1, you may discard that stress token.''' '"Snap" Wexley': text: '''After you execute a 2-, 3-, or 4-speed maneuver, if you are not touching a ship, you may perform a free boost action.''' 'Jess Pava': text: '''When attacking or defending, you may reroll 1 of your dice for each other friendly ship at Range 1.''' 'Ahsoka Tano': ship: 'Myśliwiec TIE' text: '''At the start of the Combat phase, you may spend 1 focus token to choose a friendly ship at Range 1. It may perform 1 free action.''' 'Captain Rex': ship: 'Myśliwiec TIE' text: '''After you perform an attack, assign the "Suppressive Fire" Condition card to the defender.''' 'Major Stridan': text: '''For the purpose of your actions and Upgrade cards, you may treat friendly ships at Range 2-3 as being at Range 1.''' 'Lieutenant Dormitz': text: '''During setup, friendly ships may placed anywhere in the play area at Range 1-2 of you.''' 'Constable Zuvio': text: '''When you reveal a reverse maneuver, you may drop a bomb using your front guides (including a bomb with the "<strong>Action:</strong>" header).''' 'Sarco Plank': text: '''When defending, instead of using your agility value, you may roll a number of defense dice equal to the speed of the maneuver you executed this round.''' "Talonbane Cobra": text: """When attacking or defending, double the effect of your range combat bonuses.""" 'Genesis Red': text: '''After you acquire a target lock, assign focus and evade tokens to your ship until you have the same number of each token as the locked ship.''' 'Quinn Jast': text: '''At the start of the Combat phase, you may receive a weapons disabled token to flip one of your discarded %TORPEDO% or %MISSILE% Upgrade cards faceup.''' 'Inaldra': text: '''When attacking or defending, you may spend 1 shield to reroll any number of your dice.''' 'Sunny Bounder': text: '''Once per round, after you roll or reroll dice, if you have the same result on each of your dice, add 1 matching result.''' 'Lieutenant Kestal': text: '''When attacking, you may spend 1 focus token to cancel all of the defender's blank and %FOCUS% results.''' '"Double Edge"': text: '''Once per round, after you perform a secondary weapon attack that does not hit, you may perform an attack with a different weapon.''' 'Viktor Hel': text: '''After defending, if you did not roll exactly 2 defense dice, the attacker receives 1 stress token.''' 'Lowhhrick': text: '''When another friendly ship at Range 1 is defending, you may spend 1 reinforce token. If you do, the defender adds 1 %EVADE% result.''' 'Wullffwarro': text: '''When attacking, if you have no shields and at least 1 Damage card assigned to you, roll 1 additional attack die.''' 'Dalan Oberos': text: '''If you are not stressed, when you reveal a turn, bank, or Segnor's Loop maneuver, you may instead treat it as a red Tallon Roll maneuver of the same direction (left or right) using the template of the original revealed maneuver.''' 'Thweek': text: '''During setup, before the "Place Forces" step, you may choose 1 enemy ship and assign the "Shadowed" or "Mimicked" Condition card to it.''' 'Captain Jostero': text: '''Once per round, after an enemy ship that is not defending against an attack suffers damage or critical damage, you may perform an attack against that ship.''' 'Major Vynder': text: '''When defending, if you have a weapons disabled token, roll 1 additional defense die.''' 'Lieutenant Karsabi': text: '''When you receive a weapons disabled token, if you are not stressed, you may receive 1 stress token to remove it.''' 'Torani Kulda': text: '''After you perform an attack, each enemy ship inside your bullseye firing arc at Range 1-3 must choose to suffer 1 damage or remove all of its focus and evade tokens.''' 'Dalan Oberos (Kimogila)': text: '''At the start of the Combat phase, you may acquire a target lock on an enemy ship inside your bullseye firing arc at Range 1-3 .''' 'Fenn Rau (Sheathipede)': text: '''When an enemy ship inside your firing arc at Range 1-3 becomes the active ship during the Combat phase, if you are not stressed, you may receive 1 stress token. If you do, that ship cannot spend tokens to modify its dice when attacking this round.''' 'Ezra Bridger (Sheathipede)': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"Zeb" Orrelios (Sheathipede)': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'AP-5': text: '''When you perform the coordinate action, after you choose a friendly ship and before it performs a free action, you may receive 2 stress tokens to remove 1 stress token from it.''' '"Crimson Leader"': text: '''When attacking, if the defender is inside your firing arc, you may spend 1 %HIT% or %CRIT% result to assign the "Rattled" Condition to the defender.''' '"Crimson Specialist"': text: '''When placing a bomb token you dropped after revealing your maneuver dial, you may place the bomb token anywhere on the play area touching your ship.''' '"Cobalt Leader"': text: '''When attacking, if the defender is at range 1 of a bomb token, the defender rolls 1 fewer defense die, to a minimum of 0.''' 'Kylo Ren (TIE Silencer)': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' 'Test Pilot "Blackout"': text: '''When attacking, if the attack is obstructed, the defender rolls 2 fewer defense dice (to a minimum of 0).''' 'Kullbee Sperado': text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.''' 'Major Vermeil': text: '''When attacking, if the defender does not have a focus or evade token, you may change one of your blank or %FOCUS% results to a %HIT% result.''' 'Leevan Tenza': text: '''After you perform a boost action, you may receive 1 stress token to receive 1 evade token.''' 'Saw Gerrera': text: '''When a friendly ship at Range 1-2 attacks, if it is stressed or has at least 1 Damage card, it may reroll 1 attack die.''' 'Benthic Two-Tubes': text: '''After you perform a focus action, you may remove 1 of your focus tokens to assign it to a friendly ship at Range 1-2.''' 'Captain Feroph': text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.''' '"Vizier"': text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.''' 'Magva Yarro': text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.''' 'Edrio Two-Tubes': text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.''' upgrade_translations = #Elitarna zdolność "Determination": name: "Determinacja" text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia z cechą "Pilot", natychmiast ją odrzuć bez rozpatrywania jej efektu.""" "Swarm Tactics": name: "Taktyka roju" text: """Na początku fazy walki wybierz 1 przyjazny statek w Zasięgu 1. Do końca tej fazy traktuj wybrany statek, jakby jego wartość umiejętności pilota była równa twojej.""" "Squad Leader": name: "Dowódca eskadry" text: """<strong>Akcja:</strong> Wybierz 1 statek w Zasięgu 1-2, który ma niższą wartość umiejętności pilota niż ty. %LINEBREAK% Wybrany statek może natychmiast wykonać 1 darmową akcję.""" "Expert Handling": name: "Mistrzowskie manewrowanie" text: """„<strong>Akcja:</strong> Wykonaj darmową akcję „beczka”. Jeśli nie masz symbolu akcji %BARRELROLL%, otrzymujesz 1 żeton stresu. Następnie możesz usunąć jeden wrogi żeton namierzonego celu znajdujący się na Twoim statku.""" "Marksmanship": name: "Celność" text: """<strong>Akcja:</strong> Kiedy atakujesz w tej rundzie, możesz zamienić 1 swój wynik %FOCUS% na %CRIT%, a wszystkie pozostałe wyniki %FOCUS% na %HIT%.""" "Daredevil": name: "Ryzykant" text: """<strong>Akcja:</strong> Wykonaj biały manewr (%TURNLEFT% 1) lub (%TURNRIGHT% 1)". Następnie otrzymujesz żeton stresu. %LINEBREAK% Następnie, jeśli nie masz symbolu akcji %BOOST%, rzuć 2 kośćmi ataku. Otrzymujesz wszystkie wyrzucone uszkodzenia %HIT% i uszkodzenia krytyczne %CRIT%.""" "Elusiveness": name: "Nieuchwytność" text: """Kiedy się bronisz możesz otrzymać 1 żeton stresu, aby wybrać jedną kość ataku. Atakujący musi przerzucić tą kość. Nie możesz skorzystać z tej zdolności, jeśli jeśli masz co najmniej 1 żeton stresu.""" "Push the Limit": name: "Na granicy ryzyka" text: """Raz na rundę po wykonaniu akcji, możesz wykonać 1 darmową akcję przedstawioną na twoim pasku akcji. Następnie otrzymujesz 1 żeton stresu.""" "Deadeye": name: "Strzelec wyborowy" text: """Możesz traktować nagłówek <strong>"Atak (namierzony cel):"</strong> jako <strong>"Atak (skupienie):"</strong>. %LINEBREAK% Kiedy atak zmusza cię do wydania żetonu namierzonego celu, możesz zamiast niego wydać żeton skupienia.""" "Expose": name: "Odsłonięcie" text: """<strong>Akcja:</strong> Do końca rundy zwiększ wartość swojej podstawowej broni o 1 i zmniejsz wartość zwrotności o 1.""" "Wingman": name: "Skrzydłowy" text: """Na początku fazy walki usuń 1 żeton stresu z innego przyjaznego statku w Zasięgu 1.""" "Decoy": name: "Zmyłka" text: """Na początku fazy walki możesz wybrać 1 przyjazny statek w Zasięgu 1-2. Do końca fazy zamieniasz się z danym statkiem wartościami umiejętności pilota.""" "Outmaneuver": name: "Wymanewrowanie" text: """Kiedy atakujesz statek w swoim polu rażenia, a nie znajdujesz się w polu rażenia danego statku, zmniejsz jego wartość zwrotności o 1 (do minimum 0).""" "Predator": name: "Drapieżnik" text: """Kiedy atakujesz, możesz przerzucić 1 kość ataku. Jeśli wartość umiejętnosci pilota obrońcy wynosi "2" lub mniej, możesz przerzucić maksymalnie 2 kości ataku (zamiast 1).""" "Draw Their Fire": name: "Ściągnięcie ognia" text: """Kiedy przyjazny statek w Zasięgu 1 zostaje trafiony podczas ataku, możesz zamiast niego otrzymać 1 z nie anulowanych %CRIT%.""" "Adrenaline Rush": name: "Zastrzyk adrenaliny" text: """Kiedy ujawnisz czerwony manewr, możesz odrzucić tę kartę, aby do końca fazy aktywacji traktować ten manewr jako biały.""" "Veteran Instincts": name: "Instynkt weterana" text: """Zwiększ swoją wartość umiejętności pilota o 2.""" "Opportunist": name: "Oportunista" text: """Kiedy atakujesz, jeśli obrońca nie ma żadnych żetonów skupienia ani uników, możesz otrzymać 1 żeton stresu aby rzucić 1 dodatkową kością ataku.%LINEBREAK%Nie możesz skorzystać z tej zdolności, jeśli posiadasz żetony stresu.""" "Lone Wolf": name : "Samotny wilk" text: """Jeśli w zasięgu 1-2 nie ma żadnych innych przyjaznych statków, kiedy się bronisz lub atakujesz, możesz przerzucić 1 wynik z pustą ścianką.""" "Stay On Target": name: "Utrzymać cel" text: """Kiedy ujawnisz swój manewr możesz obrócić swój wskaźnik na inny manewr o tej samej prędkości.%LINEBREAK%Traktuj ten manewr jako czerwony.""" "Ruthlessness": name: "Bezwzględność" text: """%PL_IMPERIALONLY%%LINEBREAK% Po tym jak przeprowadzisz atak, który trafi w cel, musisz wybrać 1 inny statek w Zasięgu 1 od obrońcy (nie siebie). Statek ten otrzymuje 1 uszkodzenie.""" "Intimidation": name: "Zastraszenie" text: """Dopóki stykasz się z wrogim statkiem, jego zwrotność zostaje zmniejszona o 1.""" "Calculation": name: "Kalkulacje" text: """Kiedy atakujesz, możesz wydać żeton skupienia, aby zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Bodyguard": name : "Ochroniarz" text: """%PL_SCUMONLY%%LINEBREAK% Na początku fazy walki możesz wydać żeton skupienia aby wybrać przyjazny statek w Zasięgu 1 o wartości umiejętności pilota wyższej od ciebie. Do końca rundy zwiększ jego wartość zwrotności o 1.""" # Astromechs "R2 Astromech": name: "Astromech R2" text: """Możesz traktować wszystkie manewry o prędkości 1 i 2, jakby były to zielone manewry.""" "R2-D2": text: """Po wykonaniu zielonego manewru możesz odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R2-F2": text: """<strong>Akcja:</strong> Do końca tej rundy zwiększ swoją wartość zwrotności o 1.""" "R5-D8": text: """<strong>Akcja:</strong> Rzuć jedną kością obrony.%LINEBREAK% Jeżeli wypadnie wynik %EVADE% lub %FOCUS%, odrzuć jedną ze swoich zakrytych kart uszkodzeń.""" "R5-K6": text: """Po wydaniu swojego rzetonu namierzonego celu rzuć 1 kością obrony.%LINEBREAK% Jeżeli wypadnie %EVADE% natychmiast zdobywasz żeton namierzonego celu dla tego samego statku. Nie możesz wydać nowego żetonu namierzonego celu podczas tego ataku.""" "R5 Astromech": name: "Astromech R5" text: """Podczas fazy końcowej możesz wybrać 1 ze swoich odkrytych kart z cechą "Statek" i ją zakryć.""" "R7 Astromech": name: "Astromech R7" text: """Raz na rundę kiedy się bronisz, jeśli namierzasz atakującego, możesz wydać żeton namierzonego celu aby wybrać dowolną liczbę kości ataku. Atakujący musi przerzucić wybrane kości.""" "R7-T1": text: """<strong>Akcja:</strong> Wybierz wrogi statek w Zasięgu 1-2. Jeżeli znajdujesz się w polu rażenia wybranego statku, możesz namierzyć dany statek. Następnie możesz wykonać darmową akcję "dopalacz".""" "R4-D6": text: """Kiedy zostaniesz trafiony w wyniku ataku, a pośród wyników rzutu są co najmniej 3 nieaulowalne wyniki %HIT% możesz wybrać i anulować wszystkie poza 2. Za każdy wynik anulowany w ten sposób otrzymujesz 1 żeton stresu.""" "R5-P9": text: """Na koniec fazy walki możesz wydać jeden ze swoich żetonów skupienia, aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R3-A2": text: """Kiedy wybierzesz cel ataku, jeżeli obrońca znajduje się w twoim polu rażenia, możesz otrzymać 1 żeton stresu, aby sprawić żeby obrońca otrzymał 1 żeton stresu.""" "R2-D6": text: """Twój pasek rowinięć zyskuje symbol %ELITE%.%LINEBREAK% Nie możesz przypisać tej karty rozwinięcia do swojego statku jeżeli masz już symbol rozwinięcia %ELITE% lub jeżeli wartość umiejętności pilota wynosi 2 lub mniej.""" # Torpilles "Proton Torpedoes": name: "Torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Advanced Proton Torpedoes": name: "Zaaw. torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić maksymalnie 3 swoje puste ścianki na wyniki %FOCUS%.""" "Flechette Torpedoes": name: "Torpedy rozpryskowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Po wykonaniu tego ataku obrońca otrzymuje 1 żeton stresu jeżeli jego wartość kadłuba wynosi 4 lub mniej.""" "Ion Torpedoes": name: "Torpedy jonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeżeli ten atak trafi w wybrany cel, obrońca oraz każdy statek w Zasięgu 1 od niego otrzymuje 1 żeton jonów.""" "Bomb Loadout": name: "Ładunek bomb" text: """<span class="card-restriction">Tylko Y-wing. Ograniczenie.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %BOMB%.""" # Tourelles "Ion Cannon Turret": name: "Wieżyczka z działem jonowym" text: """<strong>Atak:</strong> Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Jeśli atak ten trafi w wybrany statek, otrzymuje on 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Blaster Turret": name: "Wieżyczka blasterowa" text: """<strong>Atak (skupienie):</strong> Wydaj 1 żeton skupienia, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" "Autoblaster Turret": name: "Wieżyczka autoblasterowa" text: """<strong>Atak: Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przy pomocy kości obrony. Obrońca może anulować wyniki %CRIT% przed %HIT%.""" # Missiles "Concussion Missiles": name: "Rakiety wstrząsowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników z pustą ścianką na wynik %HIT%.""" "Cluster Missiles": name: "Rakiety kasetonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu o odrzuć tę kartę, aby przeprowadzić ten atak dwukrotnie.""" "Homing Missiles": name: "Rakiety samonaprowadzające" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Podczas tego ataku obrońca nie może wydawać żetonów uniku.""" "Assault Missiles": name: "Rakiety szturmowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi w wybrany cel, każdy inny statek w Zasięgu 1 od obrońcy otrzymuje 1 uszkodzenie.""" "Ion Pulse Missiles": name: "Jonowe rakiety pulsacyjne" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi, obrońca otrzymuje 1 uszkodzenie oraz 2 żetony jonów.""" "Chardaan Refit": name: "Naprawy na Chardaanie" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Ta karta ma ujemny koszt w punktach eskadry.""" "Proton Rockets": name: "Rakiety protonowe" text: """<strong>Atak (skupienie):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz rzucić dodatkowymi kośćmi ataku w liczbie równej twojej zwrotności (nie wiecej niż 3).""" # Bombes "Seismic Charges": name: "Ładunki sejsmiczne" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton ładunku sejsmicznego. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" "Proximity Mines": name: "Miny zbliżeniowe" text: """<strong>Akcja:</strong> odrzuć tę kartę aby zrzucić 1 żeton miny zbliżeniowej. Kiedy statek wykona manewr w wyniku którego podstawka statku lub wzornik manewru będzie nachodzić na ten żeton, żeton ten zostaje zdetonowany.""" "Proton Bombs": name: "Bomby protonowe" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton bomby protonowej. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" # Canons "Ion Cannon": name: "Działo Jonowe" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi wybrany cel, obrońca otrzymuje 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystie wyniki kości.""" "Heavy Laser Cannon": name: "Ciężkie działo laserowe" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Natychmiast po rzucie swoimi kośćmi ataku musisz zmienić wszystkie swoje wyniki %CRIT% na wyniki %HIT%.""" "Autoblaster": text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przez kości obrony. Obrońca może anulować wyniki %CRIT% przed wynikami %HIT%.""" "Flechette Cannon": name: "Działo rozpryskowe" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi, obrońca otrzymuje 1 uszkodzenie i, jeśli nie jest zestresowany, otrzymuje także 1 żeton stresu. Następnie anuluj wszystkie wyniki kości.""" '"Mangler" Cannon': name: "Działo typu Mangler" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Kiedy atakujesz, możesz zmienić jeden ze swoich wyników %HIT% na wynik %CRIT%.""" # Systèmes "Enhanced Scopes": name: "Wzmocnione radary" text: """Podczas fazy aktywacji traktuj swoją wartość umiejętności pilota jakby wynosiła "0".""" "Fire-Control System": name: "System kontroli ognia" text: """Po tym jak wykonasz atak, możesz namierzyć obroncę.""" "Advanced Sensors": name: "Zaawanswowane sensory" text: """Zaraz przed tym jak ujawnisz swój manewr, możesz wykonać 1 darmową akcję. %LINEBREAK%Jeżeli skorzystawsz z tej zdolności, musisz w tej rundzie pominąć swój krok "Wykonywania akcji".""" "Sensor Jammer": name: "Zakłócacz sensorów" text: """Kiedy się bronisz możesz zmienić 1 z wyników %HIT% atakującego na wynik %FOCUS%. Atakujący nie może przerzucić kości ze zmienionym wynikiem.""" "Accuracy Corrector": name: "Korektor celności" text: """Kiedy atakujesz, możesz anulować wszystkie swoje wyniki kości. Następnie możesz dodać 2 wyniki %HIT%.%LINEBREAK% Podczas tego ataku nie można ponownie modyfikować twoich kości.""" "Advanced Targeting Computer": name: "Zaawansowany komputer celowniczy" text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK% Kiedy atakujesz namierzonego przez siebie przeciwnika przy pomocy broni podstawowej, do wyniku rzutu kośćmi możesz dodać jeden wynik %CRIT%. Jeżeli to zrobisz, podczas tego ataku nie możesz wydać żetonu namierzonego celu.""" # Équipages "Gunner": name: "Artylerzysta" text: """Po wykonaniu ataku, który nie trafił w wybrany cel, natychmiast wykonaj atak główną bronią. W tej rundzie nie możesz wykonać kolejnego ataku.""" "Mercenary Copilot": name: "Najemny drugi pilot" text: """Kiedy atakujesz w Zasiegu 3 możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" "Weapons Engineer": name: "Inżynier uzbrojenia" text: """Możesz namierzać naraz 2 statki (każdy wrogi statek możesz namierzać tylko raz). %LINEBREAK%Kiedy namierzasz cel, możesz namierzyć 2 różne statki.""" "Luke Skywalker": text: """%PL_REBELONLY%%LINEBREAK%Po wykonaniu ataku, który nie trafi w wybrany cel, natychmiast wykonaj atak główną bronią. Możesz zmienić 1 wynik %FOCUS% na %HIT%.""" "Nien Nunb": text: """%PL_REBELONLY%%LINEBREAK%Możesz traktować wszystkie manewry %STRAIGHT%, jakby były to zielone manewry.""" "Chewbacca": text: """%PL_REBELONLY%%LINEBREAK%Kiedy otrzymujesz kartę uszkodzenia, możesz natychmiast odrzucić tę kartę i odzyskać 1 żeton osłony. Następnie odrzuć tę kartę rozwinięcia.""" "Recon Specialist": name: "Specjalista zwiadu" text: """Kiedy wykonujesz akcję skupienia, przypisz do swojego statku 1 dodatkowy żeton skupienia.""" "Saboteur": name: "Sabotażysta" text: """<strong>Akcja:</strong> Wybierz 1 wrogi statek w Zasięgu 1 i rzuć 1 koscią ataku. Jeśli wypadnie %HIT% lub %CRIT%, wylosuj 1 zakrytą kartę uszkodzenia przypisaną do tego statku, odkryj ją i rozpatrz.""" "Intelligence Agent": name: "Agent wywiadu" text: """Na początku fazy aktywacji wybierz 1 wrogi statek w zasięgu 1-2. Możesz podejrzeć manewr wybrany przez ten statek.""" "Darth Vader": text: """%PL_IMPERIALONLY%%LINEBREAK%Tylko Imperium. Po tym jak wykonasz atak skierowany przeciwko wrogiemu statkowi, możesz otrzymać 2 uszkodzenia, aby zadać temu statkowi 1 krytyczne uszkodzenie.""" "Rebel Captive": name: "Rebeliancki jeniec" text: """%PL_IMPERIALONLY%%LINEBREAK%Raz na rundę, pierwszy statek, który zadeklaruje ciebie jako cel ataku, natychmiast otrzymuje 1 żeton stresu.""" "Flight Instructor": name: "Instruktor pilotażu" text: """Kiedy się bronisz, możesz przerzucić 1 ze swoich wyników %FOCUS%. Jeśli wartość umiejętności atakującego pilota wynosi "2" lub mniej, zamiast tego przerzuć 1 ze swoich pustych scianek.%FOCUS%.""" "Navigator": name: "Nawigator" text: """Kiedy ujawnisz swój manewr, możesz obrócić swój wskaźnik na inny manewr tego samego kierunku. %LINEBREAK%Nie możesz przekręcić wskaźnika na czerwony manewr, jeśli posiadasz jakieś żetony stresu.""" "Lando Calrissian": text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Rzuć 2 koścmi obrony. Za kazdy uzyskany wynik %FOCUS% przypisz do swojego statku 1 żeton skupienia. Za każdy wynik %EVADE% przypisz do swojego statku 1 żeton uniku.%FOCUS%""" "Mara Jade": text: """%PL_IMPERIALONLY%%LINEBREAK% Na koniec fazy walki kazdy wrogi statek w Zasięgu 1, który nie ma żetonu stresu, otrzymuje żeton stresu.""" "Fleet Officer": name: "Oficer floty" text: """%PL_IMPERIALONLY%%LINEBREAK%<strong>Akcja:</strong> Wybierz maksymalnie 2 przyjazne statki w Zasięgu 1-2 i do każdego przypisz po 1 żetonie skupienia, następnie otrzymujesz 1 żeton stresu.""" "Han Solo": text: """%PL_REBELONLY%%LINEBREAK%Tylko rebelianci. Kiedy atakujesz, jeśli namierzyłeś obrońcę, możesz wydać żeton namierzonego celu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "Leia Organa": text: """%PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę, aby umożliwić wszystkim przyjaznym statkom, które ujawiniają czerwony manewr, traktowanie do końca fazy tego manewru jako białego.""" "WED-15 Repair Droid": name: "Droid naprawczy WED-15" text: """%PL_HUGESHIPONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj 1 żeton energii aby odrzucić 1 ze swoich zakrytych kart uszkodzeń albo wydaj 3 żetony energii aby odrzucić 1 ze swoich odkrytych kart uszkodzeń.""" "Carlist Rieekan": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę aby do końca fazy traktować wartość umiejętności pilota każdego przyjaznego statku jakby wynosiła "12".""" "Jan Dodonna": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Kiedy inny przyjazny statek w Zasięgu 1 wykonuje atak, możesz zmienić 1 z jego wyników %HIT% na %CRIT%.""" "Tactician": name: "Taktyk" text: "Po tym jak wykonasz atak przeciwko statkowi znajdującemu się w twoim polu rażenia w Zasiegu 2, statek ten otrzymuje 1 żeton stresu." "R2-D2 (Crew)": name: "R2-D2 (Załoga)" text: """%PL_REBELONLY%%LINEBREAK%Na koniec fazy końcowej, jeśli nie masz żadnych osłon, możesz odzyskać 1 osłonę i rzucić 1 kością ataku. Jeśli wypadnie %HIT% odkryj 1 losową ze swoich zakrytych kart uszkodzeń i ją rozpatrz.""" "C-3PO": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, zanim wykonasz rzut co najmniej 1 koscią obrony, możesz na głos zgadnąć liczbę wyników %EVADE%. Jeśli wypadło tyle %EVADE% (przed modyfikacjami) dodaj 1 wynik %EVADE%.""" "Kyle Katarn": text: """%PL_REBELONLY%%LINEBREAK%Po tym jak usuniesz ze swojego statku żeton stresu, możesz przypisać do swojego statku żeton skupienia.""" "Jan Ors": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, kiedy przyjazny statek w Zasięgu 1-3 wykonuje akcję skupienia lub miałby otrzymać żeton skupienia, możesz danemu statkowi przypisać żeton uniku (zamiast skupienia).""" "Toryn Farr": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj dowolną ilość żetonów energii aby wybrać taką samą liczbę wrogich statków w Zasiegu 1-2. Usuń z wybranych statków wszystkie żetony skupienia, uników i niebieskie żetony namierzonego celu.""" "Targeting Coordinator": name: "Koordynator namierzania" text: """<strong>Energia:</strong> Możesz wydać 1 żeton energii aby wybrać 1 przyjazny statek w Zasięgu 1-2. Namierz cel, a następnie przydziel do wybranego statku niebieski żeton namierzonego celu.""" "Raymus Antilles": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji wybierz 1 wrogi statek w Zasięgu 1-3. Możesz podejrzeć manewr wybrany dla tego statku. Jeżeli jest on biały, przydziel do niego 1 żeton stresu.""" '"Leebo"': text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> wykonaj darmową akcję "dopalacz". Następnie otrzymujesz 1 żeton jonów.""" "Dash Rendar": text: """%PL_REBELONLY%%LINEBREAK%Możesz wykonywać ataki kiedy nachodzisz na przeszkodę. %LINEBREAK%Twoje ataki nie mogą być przyblokowane.""" "Ysanne Isard": text: """%PL_IMPERIALONLY%%LINEBREAK%Na początku fazy walki, jeśli nie masz żadnych osłon, a do twojego statku przypisana jest co najmniej 1 karta uszkodzenia, możesz wykonać darmową akcję unik.""" "Moff Jerjerrod": text: """%PL_IMPERIALONLY%%LINEBREAK%Kiedy otrzymujesz odkrytą kartę uszkodzenia, możesz odrzucić to rozwinięcie lub inną kartę rozwinięcia [crew] aby zakryć tę kartę uszkodzenia (bez rozpatrywania jej efektu).""" "Greedo": text: """%PL_SCUMONLY%%LINEBREAK%Za pierwszym razem kiedy atakujesz lub bronisz sie w każdej rundzie, pierwsza przypisana karta uszkodzenia jest odkryta.""" "Outlaw Tech": name: "Mechanik wyjęty spod prawa" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu czerwonego manewru, możesz przypisać do swojego statku 1 żeton skupienia.""" "K4 Security Droid": name: "Droid ochroniarz K4" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu zielonego manewru możesz namierzyć cel.""" # Soute "Frequency Jammer": name: "Zakłócacz częstotliwości" text: """Kiedy wykonujesz akcję Zakłócanie, wybierz 1 wrogi statek, który nie ma żetonu stresu i znajduje się w Zasięgu 1 od zakłócanego statku. Wybrany statek otrzymuje 1 żeton stresu.""" "Expanded Cargo Hold": ship: "Średni transportowiec GR-75" name: "Powiększona ładownia" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Raz na rundę, kiedy masz otrzymać odkrytą kartę uszkodznia, możesz dobrać te kartę z talii uszkodzeń dziobu lub rufy.""" "Comms Booster": name: "Wzmacniacz łączności" text: """<strong>Energia:</strong> Wydaj 1 żeton energii aby usunąć wszystkie żetony stresu z przyjaznego statku w Zasięgu 1-3, następnie przydziel do tego statku 1 żeton skupienia.""" "Slicer Tools": name: "Narzędzia hakera" text: """<strong>Akcja:</strong> Wybierz co najmniej 1 wrogi statek w Zasięgu 1-3, na ktorym znajduje się żeton stresu. Za każdy wybrany statek możesz wydać 1 żeton energii aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "Shield Projector": name: "Projektor osłon" text: """Kiedy wrogi statek stanie się podczas fazy walki, możesz wydać 3 żetony energii aby do końca fazy zmusić go do zaatakowania ciebie, jeśli to możliwe.""" "Tibanna Gas Supplies": name: "Zapasy gazu Tibanna" text: """<strong>Energia:</strong> Możesz odrzucić tę kartę aby otrzymać 3 żetony energii.""" "Ionization Reactor": name: "Reaktor jonizacyjny" text: """<strong>Energia:</strong> Wydaj 5 żetonów energii z tej karty i odrzuć tą kartę aby sprawić żeby każdy statek w Zasięgu 1 otrzymał 1 uszkodzneie i 1 żeton jonów.""" "Engine Booster": name: "Dopalacz silnika" text: """Tuż przed tym jak odkryjesz swój wskaźnik manewrów, możesz wydać 1 żeton energii aby wykonać biały manewr (%STRAIGHT% 1). Nie możesz skorzystać z tej zdolności, jeśli w jej wyniku będziesz nachodzić na inny statek.""" "Backup Shield Generator": name: "Zapasowy generator osłon" text: """Na koniec każdej rudny możesz wydać 1 żeton energii aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "EM Emitter": name: "Emiter elektro-magnetyczny" text: """Kiedy przyblokujesz atak, obrońca rzuca 3 dodatkowymi kośmi obrony (zamiast 1).""" # Hardpiont "Ion Cannon Battery": name: "Bateria działa jonowego" text: """<strong>Atak (energia):</strong> Aby wykonać ten atak, wydaj 2 żetony energii z tej karty. Jeżeli atak ten trafi w wybrany statek, otrzymuje on 1 krytyczne uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Single Turbolasers": name: "Pojedyńcze Turbolasery" text: """<strong>Atak (energia):</strong> Wydaj 2 żetony energii z tej karty aby wykonać ten atak. Obronca podwaja swoją wartość zwrotności przeciwko temu atakowi. Możesz zmienić jeden ze swoich wyników %FOCUS% na %HIT%.""" "Quad Laser Cannons": name: "Poczwórne działka laserowe" text: """<strong>Atak (energia):</strong> Wydaj 1 żeton energii z tej karty aby wykonać ten atak. Jeśli ten atak nie trafi, możesz natychmiast wydać 1 żeton energii z tej karty aby ponownie przeprowadzić ten atak.""" # Équipe "Gunnery Team": name: "Zespół artylerzystów" text: """Raz na rundę kiedy atakujesz przy pomocy daodatkowej broni, możesz wydać 1 żeton energii aby zmienić 1 ze swoich pustych wyników na %HIT%.""" "Sensor Team": name: "Zespół obsługi sensorów" text: """Kiedy namierzasz cel, możesz namierzyć wrogi statek w Zasięgu 1-5 (zamiast Zasięgu 1-3).""" "Engineering Team": name: "Zespół techników" text: """Podczas fazy aktywacji, kiedy ujawnisz manewr %STRAIGHT%, otrzymujesz 1 dodatkowy żeton energii podczas kroku Otrzymywania energii.""" # Illégal "Inertial Dampeners": name: "Tłumiki inercyjne" text: """Kiedy ujawniasz swój manewr, możesz odrzucić tę kartę żeby zamiast tego wykonać biały manewr [0%STOP%]. Następnie otrzymujesz 1 żeton stresu.""" "Dead Man's Switch": name: "Włącznik samobójcy" text: """Kiedy zostajesz zniszczony, każdy statek w Zasięgu 1 otrzymuje 1 uszkodzenie.""" "Feedback Array": name: "System zwrotny" text: """Podczas fazy walki, zamiast wykonywać jakiekolwiek ataki, możesz otrzymać 1 żeton jonów i 1 uszkodzenie aby wybrać wrogi statek w Zasięgu 1. Wybrany statek otrzymuje 1 uszkodzenie.""" '"Hot Shot" Blaster': name: "Gorący strzał" text: """<strong>Atak:</strong> Odrzuć tę kartę, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" # Astromech récupéré "Salvaged Astromech": name: "Astromech z odzysku" text: "Kiedy otrzymujesz kartę uszkodzenia z cechą Statek, natychmiast możesz ją odrzucić (przed rozpatrzeniem efektu). %LINEBREAK%Następnie odrzuć tę kartę rozwinięcia.%LINEBREAK%." '"Genius"': name: "Geniusz" text: """Jeśli jesteś wyposażony w bombę, która może zostać zrzucona przed ujawnieniem twojego manewru, zamiast tego możesz ją zrzucić po tym jak wykonasz swój manewr.""" "Unhinged Astromech": name: "Szalony astromech" text: """Możesz traktować manewry o prędkości 3 jako zielone.""" "R4-B11": text: """Kiedy atakujesz namierzonego przez siebie obrońcę, możesz wydać żeton namierzonego celu aby wybrać dowolne kości obrony (nawet wszystkie). Następnie obrońca musi przerzucić wybrane przez ciebie kości.""" "R4 Agromech": name: "Agromech R4" text: """Kiedy atakujesz, po wydaniu żetonu skupienia, możesz namierzyć obrońcę.""" "Emperor Palpatine": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" 'Agent Kallus': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" "Shield Technician": text: """%HUGESHIPONLY%%LINEBREAK%When you perform a recover action, instead of spending all of your energy, you can choose any amount of energy to spend.""" "Weapons Guidance": text: """When attacking, you may spend a focus token to change 1 of your blank results to a %HIT% result.""" "BB-8": text: """When you reveal a green maneuver, you may perform a free barrel roll action.""" "R5-X3": text: """Before you reveal your maneuver, you may discard this card to ignore obstacles until the end of the round.""" "Wired": text: """When attacking or defending, if you are stressed, you may reroll 1 or more of your %FOCUS% results.""" 'Cool Hand': text: '''When you receive a stress token, you may discard this card to assign 1 focus or evade token to your ship.''' 'Juke': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking, if you have an evade token, you may change 1 of the defender's %EVADE% results into a %FOCUS% result.''' 'Comm Relay': text: '''You cannot have more than 1 evade token.%LINEBREAK%During the End phase, do not remove an unused evade token from your ship.''' 'Dual Laser Turret': text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).''' 'Broadcast Array': text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.''' 'Rear Admiral Chiraneau': text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.''' 'Ordnance Experts': text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.''' 'Docking Clamps': text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.''' '"Zeb" Orrelios': text: """%REBELONLY%%LINEBREAK%Enemy ships inside your firing arc that you are touching are not considered to be touching you when either you or they activate during the Combat phase.""" 'Kanan Jarrus': text: """%REBELONLY%%LINEBREAK%Once per round, after a friendly ship at Range 1-2 executes a white maneuver, you may remove 1 stress token from that ship.""" 'Reinforced Deflectors': text: """%LARGESHIPONLY%%LINEBREAK%After defending, if you suffered a combination of 3 or more damage and critical damage during the attack, recover 1 shield (up to your shield value).""" 'Dorsal Turret': text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the target of this attack is at Range 1, roll 1 additional attack die.""" 'Targeting Astromech': text: '''After you execute a red maneuver, you may acquire a target lock.''' 'Hera Syndulla': text: """%REBELONLY%%LINEBREAK%You may reveal and execute red maneuvers even while you are stressed.""" 'Ezra Bridger': text: """%REBELONLY%%LINEBREAK%When attacking, if you are stressed, you may change 1 of your %FOCUS% results to a %CRIT% result.""" 'Sabine Wren': text: """%REBELONLY%%LINEBREAK%Your upgrade bar gains the %BOMB% upgrade icon. Once per round, before a friendly bomb token is removed, choose 1 enemy ship at Range 1 of that token. That ship suffers 1 damage.""" '"Chopper"': text: """%REBELONLY%%LINEBREAK%You may perform actions even while you are stressed.%LINEBREAK%After you perform an action while you are stressed, suffer 1 damage.""" 'Construction Droid': text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.''' 'Cluster Bombs': text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.''' "Adaptability": text: """<span class="card-restriction">Dual card.</span>%LINEBREAK%<strong>Side A:</strong> Increase your pilot skill value by 1.%LINEBREAK%<strong>Side B:</strong> Decrease your pilot skill value by 1.""" "Electronic Baffle": text: """When you receive a stress token or an ion token, you may suffer 1 damage to discard that token.""" "4-LOM": text: """%SCUMONLY%%LINEBREAK%When attacking, during the "Modify Attack Dice" step, you may receive 1 ion token to choose 1 of the defender's focus or evade tokens. That token cannot be spent during this attack.""" "Zuckuss": text: """%SCUMONLY%%LINEBREAK%When attacking, you may receive any number of stress tokens to choose an equal number of defense dice. The defender must reroll those dice.""" 'Rage': text: """<strong>Action:</strong> Assign 1 focus token to your ship and receive 2 stress tokens. Until the end of the round, when attacking, you may reroll up to 3 attack dice.""" "Attanni Mindlink": text: """%SCUMONLY%%LINEBREAK%Each time you are assigned a focus or stress token, each other friendly ship with Attanni Mindlink must also be assigned the same type of token if it does not already have one.""" "Boba Fett": text: """%SCUMONLY%%LINEBREAK%After performing an attack, if the defender was dealt a faceup Damage card, you may discard this card to choose and discard 1 of the defender's Upgrade cards.""" "Dengar": text: """%SCUMONLY%%LINEBREAK%When attacking, you may reroll 1 attack die. If the defender is a unique pilot, you may instead reroll up to 2 attack dice.""" '"Gonk"': text: """%SCUMONLY%%LINEBREAK%<strong>Action:</strong> Place 1 shield token on this card.%LINEBREAK%<strong>Action:</strong> Remove 1 shield token from this card to recover 1 shield (up to your shield value).""" "R5-P8": text: """Once per round, after defending, you may roll 1 attack die. On a %HIT% result, the attacker suffers 1 damage. On a %CRIT% result, you and the attacker each suffer 1 damage.""" 'Thermal Detonators': text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 thermal detonator token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Thermal Detonator Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage and receives 1 stress token. Then discard this token.""" "Overclocked R4": text: """During the Combat phase, when you spend a focus token, you may receive 1 stress token to assign 1 focus token to your ship.""" 'Systems Officer': text: '''%IMPERIALONLY%%LINEBREAK%After you execute a green maneuver, choose another friendly ship at Range 1. That ship may acquire a target lock.''' 'Tail Gunner': text: '''When attacking from your rear-facing auxiliary firing arc, reduce the defender's agility by 1 (to a minimum of "0").''' 'R3 Astromech': text: '''Once per round, when attacking with a primary weapon, you may cancel 1 of your %FOCUS% results during the "Modify Attack Dice" step to assign 1 evade token to your ship.''' 'Collision Detector': text: '''When performing a boost, barrel roll, or decloak, your ship and maneuver template can overlap obstacles.%LINEBREAK%When rolling for obstacle damage, ignore all %CRIT% results.''' 'Sensor Cluster': text: '''When defending, you may spend a focus token to change 1 of your blank results to an %EVADE% result.''' 'Fearlessness': text: '''%SCUMONLY%%LINEBREAK%When attacking, if you are inside the defender's firing arc at Range 1 and the defender is inside your firing arc, you may add 1 %HIT% result to your roll.''' 'Ketsu Onyo': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may choose 1 ship in your firing arc at Range 1-2. That ship does not remove its tractor beam tokens.''' 'Latts Razzi': text: '''%SCUMONLY%%LINEBREAK%When defending, you may remove 1 stress token from the attacker to add 1 %EVADE% result to your roll.''' 'IG-88D': text: '''%SCUMONLY%%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).''' 'Rigged Cargo Chute': text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Discard this card to <strong>drop</strong> one cargo token.''' 'Seismic Torpedo': text: '''<strong>Action:</strong> Discard this card to choose an obstacle at Range 1-2 and inside your primary firing arc. Each ship at Range 1 of the obstacle rolls 1 attack die and suffers any damage (%HIT%) or critical damage (%CRIT%) rolled. Then remove the obstacle.''' 'Black Market Slicer Tools': text: '''<strong>Action:</strong> Choose a stressed enemy ship at Range 1-2 and roll 1 attack die. On a (%HIT%) or (%CRIT%) result, remove 1 stress token and deal it 1 facedown Damage card.''' # Wave X 'Kylo Ren': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Assign the "I'll Show You the Dark Side" Condition card to an enemy ship at Range 1-3.''' 'Unkar Plutt': text: '''%SCUMONLY%%LINEBREAK%After executing a maneuver that causes you to overlap an enemy ship, you may suffer 1 damage to perform 1 free action.''' 'A Score to Settle': text: '''During setup, before the "Place Forces" step, choose 1 enemy ship and deal the "A Debt to Pay" Condition card to it.%LINEBREAK%Wehn attacking a ship that has the "A Debt to Pay" Condition card, you may change 1 %FOCUS% result to a %CRIT% result.''' 'Jyn Erso': text: '''%REBELONLY%%LINEBREAK%<strong>Action:</strong> Choose 1 friendly ship at Range 1-2. Assign 1 focus token to that ship for each enemy ship inside your firing arc at Range 1-3. You cannot assign more than 3 focus tokens in this way.''' 'Cassian Andor': text: '''%REBELONLY%%LINEBREAK%At the end of the Planning phase, you may choose an enemy ship at Range 1-2. Guess aloud that ship's bearing and speed, then look at its dial. If you are correct, you may rotate your dial to another maneuver.''' 'Finn': text: '''%REBELONLY%%LINEBREAK%When attacking with a primary weapon or defending, if the enemy ship is inside your firing arc, you may add 1 blank result to your roll.''' 'Rey': text: '''%REBELONLY%%LINEBREAK%At the start of the End phase, you may place 1 of your ship's focus tokens on this card. At the start of the Combat phase, you may assign 1 of those tokens to your ship.''' 'Burnout SLAM': text: '''%LARGESHIPONLY%%LINEBREAK%Your action bar gains the %SLAM% action icon.%LINEBREAK%After you perform a SLAM action, discard this card.''' 'Primed Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Stress tokens do not prevent you from performing boost or barrel roll actions unless you have 3 or more stress tokens.''' 'Pattern Analyzer': text: '''When executing a maneuver, you may resolve the "Check Pilot Stress" step after the "Perform Action" step (instead of before that step).''' 'Snap Shot': text: '''After an enemy ship executes a maneuver, you may perform this attack against that ship. <strong>Attack:</strong> Attack 1 ship. You cannot modify your attack dice and cannot attack again this phase.''' 'M9-G8': text: '''%REBELONLY%%LINEBREAK%When a ship you have locked is attacking, you may choose 1 attack die. The attacker must reroll that die.%LINEBREAK%You can acquire target locks on other friendly ships.''' 'EMP Device': text: '''During the Combat phase, instead of performing any attacks, you may discard this card to assign 2 ion tokens to each ship at Range 1.''' 'Captain Rex': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may assign 1 focus token to your ship.''' 'General Hux': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 3 friendly ships at Range 1-2. Assign 1 focus token to each and assign the "Fanatical Devotion" Condition card to 1 of them. Then receive 1 stress token.''' 'Operations Specialist': text: '''%LIMITED%%LINEBREAK%After a friendly ship at Range 1-2 performs an attack that does not hit, you may assign 1 focus token to a friendly ship at Range 1-3 of the attacker.''' 'Targeting Synchronizer': text: '''When a friendly ship at Range 1-2 is attacking a ship you have locked, the friendly ship treats the "<strong>Attack (target lock):</strong> header as "<strong>Attack:</strong>." If a game effect instructs you to spend a target lock, it may spend your target lock instead.''' 'Hyperwave Comm Scanner': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0," "6," or "12" until the end of the step.%LINEBREAK%During setup, after another friendly ship is placed at Range 1-2, you may assign 1 focus or evade token to it.''' 'Trick Shot': text: '''When attacking, if the attack is obstructed, you may roll 1 additional attack die.''' 'Hotshot Co-pilot': text: '''When attacking with a primary weapon, the defender must spend 1 focus token if able.%LINEBREAK%When defending, the attacker must spend 1 focus token if able.''' '''Scavenger Crane''': text: '''After a ship at Range 1-2 is destroyed, you may choose a discarded %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, or Modification Upgrade card that was equipped to your ship and flip it faceup. Then roll 1 attack die. On a blank result, discard Scavenger Crane.''' 'Bodhi Rook': text: '''%REBELONLY%%LINEBREAK%When you acquire a target lock, you can lock onto an enemy ship at Range 1-3 of any friendly ship.''' 'Baze Malbus': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack against a different ship. You cannot perform another attack this round.''' 'Inspiring Recruit': text: '''Once per round, when a friendly ship at Range 1-2 removes a stress token, it may remove 1 additional stress token.''' 'Swarm Leader': text: '''When performing a primary weapon attack, choose up to 2 other friendly ships that have the defender inside their firing arcs at Range 1-3. Remove 1 evade token from each chosen ship to roll 1 additional attack die for each token removed.''' 'Bistan': text: '''%REBELONLY%%LINEBREAK%When attacking Range 1-2, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Expertise': text: '''When attacking, if you are not stressed, you may change all of your %FOCUS% results to %HIT% results.''' 'BoShek': text: '''When a ship you are touching activates, you may look at its chosen maneuver. If you do, its owner <strong>must</strong> rotate the dial to an adjacent maneuver. The ship can reveal and execute that maneuver even while stressed.''' # C-ROC 'Heavy Laser Turret': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack against 1 ship (even a ship outside of your firing arc).''' 'Cikatro Vizago': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may discard this card to replace a faceup %ILLICIT% or %CARGO% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Azmorigan': text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%At the start of the End phase, you may spend 1 energy to replace a faceup %CREW% or %TEAM% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Quick-release Cargo Locks': text: '''%LINEBREAK%At the end of the Activation phase, you may discard this card to <strong>place</strong> 1 container token.''' 'Supercharged Power Cells': text: '''When attacking, you may discard this card to roll 2 additional attack dice.''' 'ARC Caster': text: '''<span class="card-restriction">Rebel and Scum only.</span>%DUALCARD%%LINEBREAK%<strong>Side A:</strong>%LINEBREAK%<strong>Attack:</strong> Attack 1 ship. If this attack hits, you must choose 1 other ship at Range 1 of the defender to suffer 1 damage.%LINEBREAK%Then flip this card.%LINEBREAK%<strong>Side B:</strong>%LINEBREAK%(Recharging) At the start of the Combat phase, you may receive a weapons disabled token to flip this card.''' 'Wookiee Commandos': text: '''When attacking, you may reroll your %FOCUS% results.''' 'Synced Turret': text: '''<strong>Attack (Target Lock):</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the defender is inside your primary firing arc, you may reroll a number of attack dice up to your primary weapon value.''' 'Unguided Rockets': text: '''<strong>Attack (focus):</strong> Attack 1 Ship.%LINEBREAK%Your attack dice can be modified only by spending a focus token for its standard effect.''' 'Intensity': text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Side A:</strong> After you perform a boost or barrel roll action, you may assign 1 focus or evade token to your ship. If you do, flip this card.%LINEBREAK%<strong>Side B:</strong> (Exhausted) At the end of the Combat phase, you may spend 1 focus or evade token to flip this card.''' 'Jabba the Hutt': text: '''%SCUMONLY%%LINEBREAK%When you equip this card, place 1 illicit token on each %ILLICIT% Upgrade card in your squad. When you are instructed to discard an Upgrade card, you may discard 1 illicit token on that card instead.''' 'IG-RM Thug Droids': text: '''When attacking, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Selflessness': text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%When a friendly ship at Range 1 is hit by an attack, you may discard this card to suffer all uncanceled %HIT% results instead of the target ship.''' 'Breach Specialist': text: '''When you are dealt a faceup Damage card, you may spend 1 reinforce token to flip it facedown (without resolving its effect). If you do, until the end of the round, when you are dealt a faceup Damage card, flip it facedown (without resolving its effect).''' 'R4-E1': text: '''You can perform actions on your %TORPEDO% and %BOMB% Upgrade cards even if you are stressed. After you perform an action in this way, you may discard this card to remove 1 stress token from your ship.''' 'Cruise Missiles': text: '''<strong>Attack (Target Lock):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to the speed of the manuever you performed this round, to a maximum of 4 additional dice.''' 'Ion Dischargers': text: '''After you receive an ion token, you may choose an enemy ship at Range 1. If you do, remove that ion token. Then that ship may choose to receive 1 ion token. If it does, discard this card.''' 'Harpoon Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, assign the "Harpooned!" Condition to the defender.''' 'Ordnance Silos': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When you equip this card, place 3 ordnance tokens on each other equipped %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.''' 'Trajectory Simulator': text: '''You may launch bombs using the (%STRAIGHT% 5) template instead of dropping them. You cannot launch bombs with the "<strong>Action:</strong>" header in this way.''' 'Jamming Beam': text: '''<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, assign the defender 1 jam token. Then cancel <strong>all</strong> dice results.''' 'Linked Battery': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking with a primary or %CANNON% secondary weapon, you may reroll 1 attack die.''' 'Saturation Salvo': text: '''After you perform an attack with a %TORPEDO% or %MISSILE% secondary weapon that does not hit, each ship at Range 1 of the defender with an agility value lower than the squad point cost of the %TORPEDO% or %MISSILE% Upgrade card must roll 1 attack die and suffer any damage (%HIT%) or critical damage (%CRIT%) rolled.''' 'Contraband Cybernetics': text: '''When you become the active ship during the Activation phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, you may perform actions and red maneuvers even while you are stressed.''' 'Maul': text: '''%SCUMONLY% <span class="card-restriction">Ignore this restriction if your squad contains "Ezra Bridger."</span>%LINEBREAK%When attacking, if you are not stressed, you may receive any number of stress tokens to reroll that many attack dice.%LINEBREAK%After performing an attack that hits, you may remove 1 of your stress tokens.''' 'Courier Droid': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0" or "8" until the end of the step.''' '"Chopper" (Astromech)': text: '''<strong>Action: </strong>Discard 1 other equipped Upgrade card to recover 1 shield.''' 'Flight-Assist Astromech': text: '''You cannot attack ships outside your firing arc.%LINEBREAK%After you execute a maneuver, if you did not overlap a ship or obstacle and there are no enemy ships inside your firing arc at Range 1-3, you may perform a free boost or barrel roll action.''' 'Advanced Optics': text: '''You cannot have more than 1 focus token.%LINEBREAK%During the End phase, do not remove an unused focus token from your ship.''' 'Scrambler Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each other ship at Range 1 receives 1 jam token. Then cancel <strong>all</strong> results.''' 'R5-TK': text: '''You can acquire target locks on friendly ships.%LINEBREAK%You can attack friendly ships.''' 'Threat Tracker': text: '''%SMALLSHIPONLY%%LINEBREAK%When an enemy ship inside your firing arc at Range 1-2 becomes thee active ship during the Combat phase, you may spend your target lock on that ship to perform a free boost or barrell roll action if that action is on your action bar.''' 'Debris Gambit': text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Assign 1 evade token to your ship for each obstacle at Range 1, to a maximum of 2 evade tokens.''' 'Targeting Scrambler': text: '''At the start of the Planning phase, you may receive a weapons disabled token to choose a ship at Range 1-3 and assign it the "Scrambled" Condition.''' 'Death Troopers': text: '''After another friendly ship at range 1 becomes the defender, if you are inside the attacker's firing arc at range 1-3, the attacker receives 1 stress token.''' 'Saw Gerrera': text: '''%REBELONLY%%LINEBREAK%When attacking, you may suffer 1 damage to change all of your %FOCUS% results to %CRIT% results.''' 'Director Krennic': text: '''During setup, before the "Place Forces" step, assign the "Optimized Prototype" condition to a friendly Galactic Empire ship with 3 or fewer shields.''' 'Magva Yarro': text: '''%REBELONLY%%LINEBREAK%After defending, you may acquire a target lock on the attacker.''' 'Renegade Refit': text: '''<span class="card-restriction">T-65 X-Wing and U-Wing only.</span>%LINEBREAK%You can equip up to two different Modification upgrades.%LINEBREAK%The squad point cost of each of your equipped %ELITE% upgrades is reduced by 1 (to a minimum of 0).''' 'Tactical Officer': text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.''' 'ISB Slicer': text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.''' 'Thrust Corrector': text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.''' modification_translations = "Shield Upgrade": name: "Ulepszenie osłon" text: """Zwiększ wartość swoich osłon o 1.""" "Advanced Cloaking Device": name: "Zaawansowany system maskowania" text: """<span class="card-restriction">Tylko TIE Phantom.</span>%LINEBREAK%Po tym jak wykonasz atak, możesz wykonać darmową akcję maskowanie.""" ship: "TIE Phantom" "Stealth Device": name: "Urządzenie maskujące" text: """Zwiększ wartość swojej zwrotności o 1. Jeśli zostaniesz trafiony podczas ataku, odrzuć tę kartę.""" "Engine Upgrade": name : "Ulepszenie silnika" text: """Twój pasek rozwinięć zyskuje symbol akcji %BOOST%.""" "Anti-Pursuit Lasers": name: "Lasery antypościgowe" text: """%PL_LARGESHIPONLY%Po tym jak wrogi statek wykona manewr, który sprawi że będzie zachodzić na ciebie, rzuć 1 kością ataku. Jeśli wypadnie %HIT% lub %CRIT%, wrogi statek otrzymuje 1 uszkodzenie.""" "Targeting Computer": name: "Komputer celowniczy" text: """Twój pasek akcji zyskuje symbol akcji %TARGETLOCK%.""" "Hull Upgrade": name: "Ulepszenie kadłuba" text: """Zwiększ wartość swojego kadłuba o 1.""" "Munitions Failsafe": name: "Zabezpieczenie amunicji" text: """Kiedy atakujesz przy pomocy broni dodatkowej, która nakazuje odrzucenie karty po wykonaniu ataku, nie odrzucasz jej jeśli atak nie trafi.""" "Stygium Particle Accelerator": name: "Akcelerator cząsteczek stygium" text: """Kiedy się demaskujesz lub wykonasz akcję maskowanie, możesz wykonać darmową akcję unik.""" "Combat Retrofit": name: "Modyfikacja bojowa" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Zwiększ wartość swojego kadłuba o 2 i wartość swoich osłon o 1.""" ship: "Transport moyen GR-75" "B-Wing/E2": text: """<span class="card-restriction">Tylko B-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %CREW%.""" "Countermeasures": name: "Środki profilaktyczne" text: """%PL_LARGESHIPONLY%%LINEBREAK%Na początku fazy walki możesz odrzucić tę kartę, aby do końca rundy zwiększyć swoją zwrotność o 1. Następnie możesz usunąć ze swojego statku 1 wrogi żeton namierzonego celu.""" "Experimental Interface": name: "Eksperymentalny interfejs" text: """Raz na rundę. Po tym jak wykonasz akcję możesz wykonać 1 darmową akcję z karty rozwinięcia z nagłówkiem <strong>Akcja:</strong>, w którą jesteś wyposażony. Następnie otrzymujesz 1 żeton stresu.""" "Tactical Jammer": name: "Zakłócacz taktyczny" text: """%PL_LARGESHIPONLY%%LINEBREAK%Twój statek może przyblokowywać wrogie ataki.""" "Autothrusters": name: "Autodopalacze" text: """Kiedy się bronisz, jeśli jesteś poza Zasięgiem 2 albo znajdujesz się poza polem rażenia atakującego, możesz zmienić 1 ze swoich pustych wyników na %EVADE%. Możesz wyposażyć swój statek w tę kartę tylko jeśli masz symbol akcji %BOOST%.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" 'Integrated Astromech': text: '''<span class="card-restriction">X-wing only.</span>%LINEBREAK%When you are dealt a Damage card, you may discard 1 of your %ASTROMECH% Upgrade cards to discard that Damage card.''' 'Optimized Generators': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, when you assign energy to an equipped Upgrade card, gain 2 energy.''' 'Automated Protocols': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, after you perform an action that is not a recover or reinforce action, you may spend 1 energy to perform a free recover or reinforce action.''' 'Ordnance Tubes': text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.''' 'Long-Range Scanners': text: '''You can acquire target locks on ships at Range 3 and beyond. You cannot acquire target locks on ships at Range 1-2. You can equip this card only if you have %TORPEDO% and %MISSILE% in your upgrade bar.''' "Guidance Chips": text: """Once per round, when attacking with a %TORPEDO% or %MISSILE% secondary weapon, you may change 1 die result to a %HIT% result (or a %CRIT% result if your primary weapon value is "3" or higher).""" 'Vectored Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Your action bar gains the %BARRELROLL% action icon.''' 'Smuggling Compartment': text: '''<span class="card-restriction">YT-1300 and YT-2400 only.</span>%LINEBREAK%Your upgrade bar gains the %ILLICIT% upgrade icon.%LINEBREAK%You may equip 1 additional Modification upgrade that costs 3 or fewer squad points.''' 'Gyroscopic Targeting': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%At the end of the Combat phase, if you executed a 3-, 4-, or 5-speed maneuver this round, you may rotate your mobile firing arc.''' 'Captured TIE': text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Enemy ships with a pilot skill value lower than yours cannot declare you as the target of an attack. After you perform an attack or when you are the only remaining friendly ship, discard this card.''' 'Spacetug Tractor Array': text: '''<span class="card-restriction">Quadjumper only.</span>%LINEBREAK%<strong>Action:</strong> Choose a ship inside your firing arc at Range 1 and assign a tractor beam token to it. If it is a friendly ship, resolve the effect of the tractor beam token as though it were an enemy ship.''' 'Lightweight Frame': text: '''<span class="card-restriction">TIE only.</span>%LINEBREAK%When defending, after rolling defense dice, if there are more attack dice than defense dice, roll 1 additional defense die.%LINEBREAK%You cannot equip this card if your agility value is "3" or higher.''' 'Pulsed Ray Shield': text: '''<span class="card-restriction">Rebel and Scum only.</span>%LINEBREAK%During the End phase, you may receive 1 ion token to recover 1 shield (up to your shield value). You can equip this card only if your shield value is "1."''' 'Deflective Plating': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When a friendly bomb token detonates, you may choose not to suffer its effects. If you do, roll an attack die. On a %HIT% result, discard this card.''' 'Servomotor S-Foils': text: '''<span class="card-restriction">T-65 X-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong>Your action bar gains %BARRELROLL%. If you are not stressed, when you reveal a (%TURNLEFT% 3) or (3 %TURNRIGHT%) maneuver, you may treat it as a red (%TROLLLEFT% 3) or (%TROLLRIGHT% 3) in the same direction.%LINEBREAK%At the start of the Activation phase, you may flip this card.%LINEBREAK%<strong>Side B (Closed):</strong>Reduce your primary attack value by 1. Your action bar gains %BOOST%. Treat your (%BANKLEFT% 2) and (%BANKRIGHT% 2 ) as green.%LINEBREAK%At the start of the Activation phase, you may flip this card.''' 'Multi-spectral Camouflage': text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.''' title_translations = "Slave I": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %TORPEDO%.""" "Millennium Falcon": name: "Sokół Millenium" text: """<span class="card-restriction">Tylko YT-1300.</span>%LINEBREAK% Twój pasek akcji zyskuje symbol akcji %EVADE%.""" "Moldy Crow": text: """<span class="card-restriction">Tylko HWK-290.</span>%LINEBREAK%Podczas fazy końcowej nie usuwaj ze swojego statku niewykorzystanych żetonów skupienia.""" "ST-321": ship: "Prom typu Lambda" text: """<span class="card-restriction">Navette de classe <em>Lambda</em> uniquement.</span>%LINEBREAK%Quand vous verrouillez une cible, vous pouvez verrouiller n'importe quel vaisseau ennemi situé dans la zone de jeu.""" "Royal Guard TIE": ship: "TIE Interceptor" name: "TIE Imperialnego Gwardzisty" text: """<span class="card-restriction">Tylko TIE Interceptor.</span>%LINEBREAK%Możesz dołączyć do swojego statku maksymalnie 2 różne karty Modyfikacji (zamiast 1). Nie możesz dołączyć tej karty do swojego statku, jeśli wartość umiejętności pilota wynosi "4" lub mniej.""" "Dodonna's Pride": name: "Duma Dodonny" ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy wykonujesz akcję "Koordynacja", możesz wybrać 2 przyjazne statki (zamiast 1). Statki te mogą wykonać po 1 darmowej akcji.""" "A-Wing Test Pilot": name: "Pilot testowy A-winga" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %ELITE%. Nie możesz wyposażyć się w 2 takie same karty rozwinięcia [elite talent]. Nie możesz wyposażyć się w tę kartę, jeśli twoja wartość umiejętności pilota wynosi "1" lub mniej.""" "Tantive IV": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Twój pasek rozwinięć sekcji dziobowej zyskuje po 1 symbolu rozwinięcia %CREW% i %TEAM%.""" "Bright Hope": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Żetony wsparcia przypisane do twojej sekcji dziobowej dostają 2 wyniki %EVADE% (zamiast 1).""" "Quantum Storm": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Na początku fazy końcowej, jeśli masz nie więcej niż 1 żeton energi, otrzymujesz 1 żeton energii.""" "Dutyfree": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Kiedy wykonujesz akcję Zakłócenie, możesz wybrać wrogi statek w Zasięgu 1-3 (zamiast Zasięgu 1-2).""" "Jaina's Light": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy się bronisz, raz na atak, jeśli otrzymujesz odkrytą kartę uszkodzenia, możesz ją odrzucić i dobrać nową odkrytą kartę uszkodzenia.""" "Outrider": text: """<span class="card-restriction">Tylko YT-2400.</span>%LINEBREAK%Dopóki jesteś wyposażony w kartę rozwinięcia [cannon], nie możesz wykonywać ataków bronią podstawową. Przy pomocy dodatkowej broni [cannon] możesz wykonywać ataki skierowane przeciwko statkom znajdujacym się poza twoim polem rażenia. """ "Dauntless": ship: 'Decimator VT-49' text: """<span class="card-restriction">Tylko Decimator VT-49.</span>%LINEBREAK%Po tym jak wykonasz manewr, który sprawi że będziesz nachodzić na inny statek, możesz wykonać 1 darmową akcję. Następnie otrzymujesz 1 żeton stresu.""" "Virago": text: """<span class="card-restriction">Tylko StarViper.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbole rozwinięć %SYSTEM% i %ILLICIT%. Nie możesz wyposażyć swojego statku w tę kartę jeśli wartość umiejętności twojego pilota wynosi „3” lub mniej.""" '"Heavy Scyk" Interceptor (Cannon)': name: 'Interceptor typu Heavy Scyk (Działo)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Torpedo)': name: 'Interceptor typu Heavy Scyk (Torpeda)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Missile)': name: 'Intercepteur "Scyk Lourd" (Rakieta)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" "IG-2000": text: """<span class="card-restriction">Tylko Aggressor.</span>%LINEBREAK%Masz zdolność pilota każdego innego przyjaznego statku z kartą ulepszenia IG-2000 (jako dodatek do swojej zdolności pilota).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Tylko Y-wing.</span>%LINEBREAK%Nie możesz atakować statków znajdujących się poza twoim polem rażenia. Po wykonaniu ataku przy pomocy broni podstawowej, możesz natychmiast wykonać atak przy pomocy dodatkowej broni %TURRET%.""" "Andrasta": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje dwa symbole %BOMB%.""" "TIE/x1": text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %SYSTEM%. %LINEBREAK%Koszt przypisanej do tego statku karty rozwinięcia %SYSTEM% jest obniżony o 4 punkty (do minimum 0).""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "Mist Hunter": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "Punishing One": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" "Assailer": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%When defending, if the targeted section has a reinforce token, you may change 1 %FOCUS% result to a %EVADE% result.""" "Instigator": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform a recover action, recover 1 additional shield.""" "Impetuous": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform an attack that destroys an enemy ship, you may acquire a target lock.""" 'TIE/x7': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Your upgrade bar loses the %CANNON% and %MISSILE% upgrade icons.%LINEBREAK%After executing a 3-, 4-, or 5-speed maneuver, you may assign 1 evade token to your ship.''' 'TIE/D': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Once per round, after you perform an attack with a %CANNON% secondary weapon that costs 3 or fewer squad points, you may perform a primary weapon attack.''' 'TIE Shuttle': ship: 'Bombowiec TIE' text: '''<span class="card-restriction">TIE Bomber only.</span>%LINEBREAK%Your upgrade bar loses all %TORPEDO%, %MISSILE%, and %BOMB% upgrade icons and gains 2 %CREW% upgrade icons. You cannot equip a %CREW% Upgrade card that costs more than 4 squad points.''' 'Requiem': text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.''' 'Vector': text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).''' 'Suppressor': text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.''' 'Black One': text: '''After you perform a boost or barrel roll action, you may remove 1 enemy target lock from a friendly ship at Range 1. You cannot equip this card if your pilot skill is "6" or lower.''' 'Millennium Falcon (TFA)': text: '''After you execute a 3-speed bank maneuver (%BANKLEFT% or %BANKRIGHT%), if you are not touching another ship and you are not stressed, you may receive 1 stress token to rotate your ship 180&deg;.''' 'Alliance Overhaul': text: '''<span class="card-restriction">ARC-170 only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. When attacking from your auxiliary firing arc, you may change 1 of your %FOCUS% results to a %CRIT% result.''' 'Special Ops Training': text: '''<span class="card-restriction">TIE/sf only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. If you do not, you may perform an additional attack from your auxiliary firing arc.''' 'Concord Dawn Protector': text: '''<span class="card-restriction">Protectorate Starfighter only.</span>%LINEBREAK%When defending, if you are inside the attacker's firing arc and at Range 1 and the attacker is inside your firing arc, add 1 %EVADE% result.''' 'Shadow Caster': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%After you perform an attack that hits, if the defender is inside your mobile firing arc and at Range 1-2, you may assign the defender 1 tractor beam token.''' # Wave X '''Sabine's Masterpiece''': ship: 'Myśliwiec TIE' text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Your upgrade bar gains the %CREW% and %ILLICIT% upgrade icons.''' '''Kylo Ren's Shuttle''': text: '''<span class="card-restriction">Upsilon-class Shuttle only.</span>%LINEBREAK%At the end of the Combat phase, choose an unstressed enemy ship at Range 1-2. Its owner must assign a stress token to it or assign a stress token to another ship at Range 1-2 of you that that player controls.''' '''Pivot Wing''': text: '''<span class="card-restriction">U-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong> Increase your agility by 1.%LINEBREAK%After you execute a maneuver, you may flip this card.%LINEBREAK%<strong>Side B (Landing):</strong> When you reveal a (0 %STOP%) maneuver, you may rotate your ship 180&deg;.%LINEBREAK%After you execute a maneuver, you may flip this card.''' '''Adaptive Ailerons''': text: '''<span class="card-restriction">TIE Striker only.</span>%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you <strong>must</strong> execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' # C-ROC '''Merchant One''': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%Your upgrade bar 1 additional %CREW% upgrade icon and 1 additional %TEAM% upgrade icon and loses 1 %CARGO% upgrade icon.''' '''"Light Scyk" Interceptor''': text: '''<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%All Damage cards dealt to you are dealt faceup. You may treat all bank maneuvers (%BANKLEFT% or %BANKRIGHT%) as green maneuvers. You cannot equip Modification upgrades.''' '''Insatiable Worrt''': text: '''After you perform the recover action, gain 3 energy.''' '''Broken Horn''': text: '''When defending, if you have a reinforce token, you may add 1 additional %EVADE% result. If you do, after defending, discard your reinforce token.''' 'Havoc': text: '''<span class="card-restriction">Scurrg H-6 Bomber only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %SALVAGEDASTROMECH% icons and loses the %CREW% upgrade icon.%LINEBREAK%You cannot equip non-unique %SALVAGEDASTROMECH% Upgrade cards.''' 'Vaksai': text: '''<span class="card-restriction">Kihraxz Fighter only.</span>%LINEBREAK%The squad point cost of each of your equipped upgrades is reduced by 1 (to a minimum of 0).%LINEBREAK%You may equip up to 3 different Modification upgrades.''' 'StarViper Mk. II': text: '''<span class="card-restriction">StarViper only.</span>%LINEBREAK%You may equip up to 2 different title Upgrades.%LINEBREAK%When performing a barrel roll action, you <strong>must</strong> use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.''' 'XG-1 Assault Configuration': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains 2 %CANNON% icons.%LINEBREAK%You may perform attacks with %CANNON% secondary weapons that cost 2 or fewer points even while you have a weapons disabled token.''' 'Enforcer': text: '''<span class="card-restriction">M12-L Kimogila Fighter only.</span>%LINEBREAK%After defending, if the attacker is inside your bullseye firing arc, the attacker receives 1 stress token.''' 'Ghost (Phantom II)': text: '''<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom II</em> title card to a friendly <em>Sheathipede</em>-class shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.''' 'Phantom II': text: '''While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc.%LINEBREAK%While you are docked, at the end of the Activation phase, the <em>Ghost</em> may perform a free coordinate action.''' 'First Order Vanguard': text: '''<span class="card-restriction">TIE Silencer only.</span>%LINEBREAK%When attacking, if the defender is the only ship in your firing arc at Range 1-3, you may reroll 1 attack die.%LINEBREAK%When defending, you may discard this card to reroll all of your defense dice.''' 'Os-1 Arsenal Loadout': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% and %MISSILE% icons.%LINEBREAK%You may perform attacks with %TORPEDO% and %MISSILE% secondary weapons against ships you have locked even while you have a weapons disabled token.''' 'Crossfire Formation': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When defending, if there is at least 1 other friendly Resistance ship at Range 1-2 of the attacker with the Crossfire Formation Upgrade card, you may add 1 %FOCUS% result to your roll.''' 'Advanced Ailerons': text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' condition_translations = '''I'll Show You the Dark Side''': text: '''When this card is assigned, if it is not already in play, the player who dealt it searches the Damage deck for 1 Damage card with the <strong><em>Pilot</em></strong> trait and may place it faceup on this card. Then shuffle the damage deck.%LINEBREAK%When you suffer critical damage from an attack, you are instead dealt the chosen faceup Damage card.%LINEBREAK%When there is no Damage card on this card, remove it.''' 'Suppressive Fire': text: '''When attacking a ship other than "Captain Rex," roll 1 fewer attack die.%LINEBREAK% When you declare an attack targeting "Captain Rex" or when "Captain Rex" is destroyed, remove this card.%LINEBREAK%At the end of the Combat phase, if "Captain Rex" did not perform an attack this phase, remove this card.''' 'Fanatical Devotion': text: '''When defending, you cannot spend focus tokens.%LINEBREAK%When attacking, if you spend a focus token to change all %FOCUS% results to %HIT% results, set aside the first %FOCUS% result that you change. The set-aside %HIT% result cannot be canceled by defense dice, but the defender may cancel %CRIT% results before it.%LINEBREAK%During the End phase, remove this card.''' 'A Debt to Pay': text: '''When attacking a ship that has the "A Score to Settle" Upgrade card equipped, you may change 1 %FOCUS% result to a %CRIT% result.''' 'Shadowed': text: '''"Thweek" is treated as having the pilot skill value you had after setup.%LINEBREAK%The pilot skill value of "Thweek" does not change if your pilot skill value changes or you are destroyed.''' 'Mimicked': text: '''"Thweek" is treated as having your pilot ability.%LINEBREAK%"Thweek" cannot apply a Condition card by using your pilot ability.%LINEBREAK%"Thweek" does not lose your pilot ability if you are destroyed.''' 'Harpooned!': text: '''When you are hit by an attack, if there is at least 1 uncanceled %CRIT% result, each other ship at Range 1 suffers 1 damage. Then discard this card and receive 1 facedown Damage card.%LINEBREAK%When you are destroyed, each ship at Range 1 suffers 1 damage.%LINEBREAK%<strong>Action:</strong> Discard this card. Then roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.''' 'Rattled': text: '''When you suffer damage from a bomb, you suffer 1 additional critical damage. Then, remove this card.%LINEBREAK%<strong>Action:</strong> Roll 1 attack die. On a %FOCUS% or %HIT% result, remove this card.''' 'Scrambled': text: '''When attacking a ship at Range 1 that is equipped with the "Targeting Scrambler" upgrade, you cannot modify attack dice.%LINEBREAK%At the end of the combat phase, remove this card.''' 'Optimized Prototype': text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "Director Krennic" Upgrade card may acquire a target lock on the defender.''' exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
41314
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.pl = 'Polski' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations['Polski'] = action : "Barrel Roll": "Beczka" "Boost": "Dopalacz" "Evade": "Unik" "Focus": "Skupienie" "Target Lock": "Namierzenie celu" "Recover": "Naprawa" "Reinforce": "Umocnienie" "Jam": "Zakłócanie" "Coordinate": "Koordynacja" "Cloak": "Maskowanie" slot: "Astromech": "Astromech" "Bomb": "Bomba" "Cannon": "Działo" "Crew": "Załoga" "Elite": "Talent elitarny" "Missile": "Rakiety" "System": "System" "Torpedo": "Torpedy" "Turret": "Wieżyczka" "Cargo": "Ładunek" "Hardpoint": "Punkt konstrukcyjny" "Team": "Drużyna" "Illicit": "Kontrabanda" "Salvaged Astromech": "Złomowane astromechy" sources: # needed? "Core": "Zestaw Podstawowy" "A-Wing Expansion Pack": "Zestaw dodatkowy A-Wing" "B-Wing Expansion Pack": "Zestaw dodatkowy B-Wing" "X-Wing Expansion Pack": "Zestaw dodatkowy X-Wing" "Y-Wing Expansion Pack": "Zestaw dodatkowy Y-Wing" "Millennium Falcon Expansion Pack": "Zestaw dodatkowy Sokół Millennium" "HWK-290 Expansion Pack": "Zestaw dodatkowy HWK-290" "TIE Fighter Expansion Pack": "Zestaw dodatkowy Myśliwiec TIE" "TIE Interceptor Expansion Pack": "Zestaw dodatkowy TIE Interceptor" "TIE Bomber Expansion Pack": "Zestaw dodatkowy Bombowiec TIE" "TIE Advanced Expansion Pack": "Zestaw dodatkowy TIE Advanced" "Lambda-Class Shuttle Expansion Pack": "Zestaw dodatkowy Prom typu Lambda" "Slave I Expansion Pack": "Zestaw dodatkowy Slave I" "Imperial Aces Expansion Pack": "Zestaw dodatkowy Asy Imperium" "Rebel Transport Expansion Pack": "Zestaw dodatkowy Rebeliancki transportowiec" "Z-95 Headhunter Expansion Pack": "Zestaw dodatkowy Z-95 Łowca Głów" "TIE Defender Expansion Pack": "Zestaw dodatkowy TIE Defender" "E-Wing Expansion Pack": "Zestaw dodatkowy E-Wing" "TIE Phantom Expansion Pack": "Zestaw dodatkowy TIE Phantom" "Tantive IV Expansion Pack": "Zestaw dodatkowy Tantive IV" "Rebel Aces Expansion Pack": "Zestaw dodatkowy Asy Rebelii" "YT-2400 Freighter Expansion Pack": "Zestaw dodatkowy YT-2400" "VT-49 Decimator Expansion Pack": "Zestaw dodatkowy Decimator VT-49" "StarViper Expansion Pack": "Zestaw dodatkowy StarViper" "M3-A Interceptor Expansion Pack": "Zestaw dodatkowy M3-A Interceptor" "IG-2000 Expansion Pack": "Zestaw dodatkowy IG-2000" "Most Wanted Expansion Pack": "Zestaw dodatkowy Poszukiwani" "Imperial Raider Expansion Pack": "Zestaw dodatkowy Imperialny Patrolowiec" "The Force Awakens Core Set": "The Force Awakens Core Set" ui: shipSelectorPlaceholder: "Wybór statków" pilotSelectorPlaceholder: "Wybór pilotów" upgradePlaceholder: (translator, language, slot) -> "#{translator language, 'slot', slot}" modificationPlaceholder: "Modyfikacje" titlePlaceholder: "Tytuł" upgradeHeader: (translator, language, slot) -> "Amélioration #{translator language, 'slot', slot}" unreleased: "niewydane" epic: "epickie" byCSSSelector: # Warnings '.unreleased-content-used .translated': 'This squad uses unreleased content!</span>' '.epic-content-used .translated': 'This squad uses Epic content!' '.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!' '.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!' '.collection-invalid .translated': 'You cannot field this list with your collection!' # Type selector '.game-type-selector option[value="standard"]': 'Standard' '.game-type-selector option[value="custom"]': 'Custom' '.game-type-selector option[value="epic"]': 'Epic' '.game-type-selector option[value="team-epic"]': 'Team Epic' # Card browser '.xwing-card-browser .translate.sort-cards-by': 'Sortuj karty po' '.xwing-card-browser option[value="name"]': 'nazwie' '.xwing-card-browser option[value="source"]': 'źródle' '.xwing-card-browser option[value="type-by-points"]': 'typie (po punktach)' '.xwing-card-browser option[value="type-by-name"]': 'typie (po nazwie)' '.xwing-card-browser .translate.select-a-card': 'Wybierz kartę z listy po prawej' '.xwing-card-browser .info-range td': 'Zasięg’' # Info well '.info-well .info-ship td.info-header': 'Statek' '.info-well .info-skill td.info-header': 'Umiejętność pilota' '.info-well .info-actions td.info-header': 'Akcje' '.info-well .info-upgrades td.info-header': 'Ulepszenia' '.info-well .info-range td.info-header': 'Zasięg' # Squadron edit buttons '.clear-squad' : 'Wyczyść eskadrę' '.save-list' : 'Zapisz' '.save-list-as' : 'Zapisz jako ...' '.delete-list' : 'Usuń' '.backend-list-my-squads' : 'Lista eskadr' '.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i>&nbsp;Drukuj \ Wyświetl jako </span>Tekst' '.randomize' : 'randomizuj' '.randomize-options' : 'Opcje ...' '.notes-container > span' : 'Squad Notes' # Print/View modal '.bbcode-list' : 'Skopiuj BBCode poniżej i wklej go do swojego posta.<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.html-list' : '<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.vertical-space-checkbox' : """Dodaj miejsce na karty ulepszeń \ uszkodzeń podczas drukowania <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Wydrukuj w kolorze <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="fa fa-print"></i>&nbsp;Drukuj' # Randomizer options '.do-randomize' : 'Generuj' # Top tab bar '#empireTab' : 'Imperium Galaktyczne' '#rebelTab' : 'Sojusz Rebeliancki' '#scumTab' : 'Szumowiny i Nikczemnicy' '#browserTab' : 'Przeglądarka kart' '#aboutTab' : 'O stronie' singular: 'pilots': 'Pilot' 'modifications': 'Modyfikacja' 'titles': 'Tytuł' types: 'Pilot': 'Pilot' 'Modification': 'Modyfikacja' 'Title': 'Tytuł' exportObj.cardLoaders ?= {} exportObj.cardLoaders['Polski'] = () -> exportObj.cardLanguage = 'Polski' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Rename ships exportObj.renameShip 'TIE Fighter', 'Myśliwiec TIE' exportObj.renameShip 'TIE Bomber', 'Bombowiec TIE' exportObj.renameShip 'Lambda-Class Shuttle', 'Prom typu Lambda' exportObj.renameShip 'VT-49 Decimator', 'Decimator VT-49' exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Łowca głów' exportObj.renameShip 'CR90 Corvette (Aft)', 'Korweta CR90 (rufa)' exportObj.renameShip 'CR90 Corvette (Fore)', 'Corvette CR90 (dziób)' exportObj.renameShip 'GR-75 Medium Transport', 'Średni transportowiec GR-75' # Names don't need updating, but text needs to be set pilot_translations = # Empire # Myśliwiec TIE "Academy Pilot": ship: "Myśliwiec TIE" name: "Pilot z Akademii" "Obsidian Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry Obsydianowych" "Black Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry C<NAME>" '"<NAME>"': name: "<NAME>" ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" '"Night Beast"': name: "<NAME>" ship: "Myśliwiec TIE" text: """Po wykonaniu zielonego manewru możesz wykonać darmową akcję skupienia.""" '"Backstabber"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz będąc poza polem rażenia broniącego się statku, rzucasz 1 dodatkową kością ataku.""" '"Dark Curse"': name: "<NAME>" ship: "Myśliwiec TIE" text: """Kiedy się bronisz statki które cię atakują nie mogą wydawać żetonów skupienia ani przerzucać kości ataku.""" '"<NAME>"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, rzucasz 1 dodatkową kością ataku.""" '"Howlrunner"': ship: "Myśliwiec TIE" text: """Kiedy inny przyjazny statek w zasięgu 1 atakuje przy pomocy swojej podstawowej broni, może przerzucić 1 kość ataku.""" # TIE Interceptor "Alpha Squadron Pilot": name: "Pilot <NAME>skad<NAME>" "Avenger Squadron Pilot": name: "Pilot <NAME> M<NAME>" "Saber Squadron Pilot": name: "Pilot <NAME>" "Royal Guard Pilot": name: "Pilot imperialny gwardzista" "\"<NAME>\"": name: "\"<NAME>\"" text: """Zostajesz zniszczony dopiero pod koniec fazy walki, w której liczba kart uszkodzeń przypisanych do ciebie będzie równa, lub wyższa od twojej wartości kadłuba.""" "<NAME>": name: "<NAME>" text: """Kiedy wykonujesz akcję "beczka", możesz otrzymać 1 żeton stresu, aby zamiast wzornika manewru (%STRAIGHT% 1) użyć (%BANKLEFT% 1) lub (%BANKRIGHT% 1).""" "<NAME>": text: """Kiedy atakujesz w Zasięgu 2-3, możesz wydać 1 żeton uników, aby dodać 1 %HIT% do swojego wyniku.""" "<NAME>": text: """Kiedy ujawnisz manewr %UTURN% możesz traktować go tak, jakby jego prędkość wynosiła "1", "3" lub "5".""" "<NAME>": text: """Po wykonaniu ataku możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "<NAME>": text: """Wrogie statki w Zasięgu 1 nie mogą wykonywać akcji "skupienie" oraz "unik", ani wydawać żetonów skupienia i uników.""" "<NAME>": text: """Kiedy otrzymujesz żeton stresu, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Phantom "Sigma Squadron Pilot": name: "Pilot Eskadry Sigma" "Shadow Squadron Pilot": name: "Pilot Eskadry Cieni" '"Echo"': text: """Kiedy się demaskujesz musisz użyć wzornika manewru (%BANKLEFT% 2) lub (%BANKRIGHT% 2) zamiast wzornika (%STRAIGHT% 2).""" '"Whisper"': name: "<NAME>" text: """Po tym jak wykonasz atak, który trafi cel, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Defender "Onyx Squadron Pilot": name: "Pilot Eskadry Onyx" "Delta Squadron Pilot": name: "Pilot Eskadry Delta" "<NAME>": name: "<NAME>" text: """Kiedy atakujesz, zaraz po swoim rzucie kośćmi ataku możesz namierzyć obrońcę, jeśli ma na sobie czerwony żeton namierzonego celu.""" "<NAME>": text: """Po tym jak wykonasz atak, który zada obrońcy co najmniej jedną kartę uszkodzenia, możesz wydać żeton skupienia aby odkryć te karty.""" # Bombowiec TIE "Scimitar Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Sejmitarów" "Gamma Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Gamma" "Capt<NAME>": ship: "Bombowiec TIE" name: "<NAME>" text: "Kiedy inny przyjazny statek w Zasięgu 1 atakuje przy pomocy dodatkowej broni, może przerzucić maksymalnie 2 kości ataku." "Major Rhymer": ship: "Bombowiec TIE" text: "Kiedy atakujesz przy pomocy dodatkowej broni, możesz zwiększyć lub zmniejszyć zasięg broni o 1. Musisz przy tym zachować limit zasięgu 1-3." "Gamma Squadron Veteran": ship: "Bombowiec TIE" # TIE Advanced "Tempest Squadron Pilot": name: "Pilot Eskadry Burzy" "Storm Squadron Pilot": name: "Pilot Eskadry Szturmu" "<NAME>": text: """Kiedy twój atak zadaje obrońcy odkrytą kartę uszkodzenia, wylosuj 3 karty uszkodzeń, wybierz 1 z nich, którą zadajesz, a pozostałe odrzuć.""" "<NAME>": text: """Podczas swojego kroku "Wykonywania akcji" możesz wykonać 2 akcje.""" "<NAME>": name: "<NAME>" text: """Na początku fazy walki możesz namierzyć wrogi statek znajdujący się w Zasięgu 1 od ciebie.""" # Firespray "<NAME>": name:"<NAME>" "<NAME>": text: """Kiedy atakujesz, obrońca otrzymuje 1 żeton stresu, jeśli anuluje co najmniej jeden wynik %CRIT%.""" "<NAME>": text: """Kiedy ujawniasz manewr skrętu (%BANKLEFT% lub %BANKRIGHT%) możesz przestawić swój wskaźnik manewrów na drugi manewr skrętu o tej samej prędkości.""" "<NAME>": text: """Kiedy atakujesz przy pomocy dodatkowej broni, możesz przerzucić 1 kość ataku.""" # Prom typu Lambda "<NAME>": ship: "Prom typu Lambda" name: "<NAME>" text: """Kiedy wrogi statek namierza cel, musi namierzyć twój statek, jeśli to możliwe.""" "<NAME>": name: "<NAME>" ship: "Prom typu Lambda" text: """Na początku fazy walki możesz przypisać 1 ze swoich niebieskich żetonów namierzonego celu do przyjaznego statku w Zasięgu 1, jeśli ten nie ma niebieskiego żetonu namierzonego celu.""" "<NAME>": ship: "Prom typu Lambda" name: "<NAME>" text: """Kiedy inny przyjazny statek w Zasięgu 1-2 ma otrzymać żeton stresu, gdy ty masz 2 lub mniej żetonów stresu, możesz przypisać do siebie ten żeton stresu.""" "Omicron Group Pilot": ship: "Prom typu Lambda" name: "Pilot grupy Omicron" # VT-49 Decimator "<NAME>": ship: "Decimator VT-49" name: "<NAME>" text: """Po wykonaniu manewru, każdy wrogi statek z którym się stykasz, otrzymuje 1 uszkodzenie.""" "<NAME> <NAME>": ship: "Decimator VT-49" name: "<NAME>" text: """Kiedy atakujesz w Zasięgu 1-2, możesz zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Patrol Leader": ship: "Decimator VT-49" name: "<NAME>" "<NAME>": ship: "Decimator VT-49" name: "<NAME>" text: """Jeśli nie masz żadnych osłon i masz przypisaną co najmniej 1 kartę uszkodzenia, wartość twojej zwrotności wzrasta o 1.""" "<NAME>": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "<NAME>": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "<NAME>": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" # Rebels # X-Wing "Red Squadron Pilot": name: "Pilot <NAME>" "<NAME>": name: "<NAME>iedo<NAME> pilot" "<NAME>": text: """Kiedy atakujesz zredukuj wartość zwrotności obrońcy o 1 (do minimum 0).""" "<NAME>": text: """Po tym jak wydasz żeton skupienia możesz umieścić dany żeton na dowolnym innym przyjaznym statku w Zasięgu 1-2 (zamiast go odrzucać).""" "<NAME>": text: """Inne przyjazne statki w Zasięgu 1 nie mogą być wybierane na cel ataku, jeśli atakujący może na cel wybrać ciebie.""" "<NAME>": text: """Kiedy się bronisz, możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %EVADE%.""" "<NAME>": text: """Po wykonaniu ataku możesz usunąć z obrońcy 1 żeton skupienia, uników, lub niebieski żeton namierzonego celu.""" "<NAME>": text: """Kiedy otrzymujesz żeton stresu możesz usunąć go i rzucić 1 kością ataku. Jeśli wypadnie %HIT%, ten statek otrzymuje 1 zakrytą kartę uszkodzenia.""" '"<NAME>" <NAME>': text: """Kiedy zdobywasz lub wydajesz żeton namierzonego celu, możesz usunąć ze swojego statku 1 żeton stresu.""" "<NAME>": text: """Kiedy wrogi statek wybiera cię na cel ataku, możesz namierzyć ten statek.""" # Y-Wing "Gold Squadron Pilot": name: "Pilot <NAME>" "Gray Squadron Pilot": name: "Pilot <NAME>" '"<NAME>" <NAME>': text: """Po namierzeniu celu wybierz przyjazny statek w Zasięgu 1-2. Wybrany statek może natychmiast namierzyć cel.""" "<NAME>": text: """Kiedy atakujesz w Zasięgu 2-3, możesz przerzucić dowolne ze swoich kości, na których wypadły puste ścianki.""" # A-Wing "Green Squadron Pilot": name: "Pilot Esk<NAME> Z<NAME>" "Prototype Pilot": name: "Pilot prototypu" "<NAME>": text: """Możesz wykonywać akcje nawet jeśli posiadasz żetony stresu.""" "<NAME>": text: """Możesz wybrać na cel swojego ataku wrogi statek, z którym się stykasz, jeżeli ten znajduje się w twoim polu rażenia.""" # YT-1300 "Outer Rim Smuggler": name: "<NAME> z <NAME>" "Che<NAME>": text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, natychmiast ją zakryj (bez rozpatrywania jej efektu).""" "<NAME>": text: """Po wykonaniu zielonego manewru wybierz jeden inny przyjazny statek w Zasięgu 1. Statek ten może wykonać 1 darmową akcję przedstawioną na jego pasku akcji.""" "Han Solo": text: """Kiedy atakujesz możesz przerzucić wszystkie swoje kości ataku. Jeśli zdecydujesz się to zrobić musisz przerzucić tyle ze swoich kości, ile możesz.""" # B-Wing "Dagger Squadron Pilot": name: "Pilot Eskadry Sztyletów" "Blue Squadron Pilot": name: "Pilot Eskadry Niebieskich" "Ten Numb": text: """Kiedy atakujesz, 1 z twoich wyników [crt-hit] nie może być anulowany przy pomocy kości obrony.""" "Ibtisam": text: """Kiedy atakujesz lub się bronisz mając co najmniej 1 żeton stresu, możesz przerzucić jedną ze swoich kości.""" # HWK-290 "Rebel Operative": name: "Agent rebeliantów" "<NAME>": text: '''Na początku fazy walki wybierz 1 inny przyjazny statek w zasięgu 1-3. Do końca tej fazy traktuj wartość umiejętności tego pilota jakby wynosiła "12".''' "<NAME>": text: """Na początku fazy walki możesz przypisać 1 ze swoich żetonów skupienia do innego przyjaznego statku w Zasięgu 1-3.""" "<NAME>": text: """Kiedy inny przyjazny statek w Zasięgu 1-3 atakuje, gdy nie masz żadnych żetonów stresu, możesz otrzymać 1 żeton stresu aby umożliwić mu rzut 1 dodatkową kością ataku.""" # Z-95 "Bandit Squadron Pilot": name: "Pilot Eskadry Bandytów" ship: "Z-95 Łowca głów" "Tala Squadron Pilot": name: "Pilot Eskadry <NAME>" ship: "Z-95 Łowca głów" "<NAME>": name: "<NAME>" ship: "Z-95 Łowca głów" text: "Kiedy atakujesz, obrońca zostaje trafiony twoim atakiem nawet jeśli nie otrzymał żadnych uszkodzeń." "<NAME>": ship: "Z-95 Łowca głów" text: """Po wykonaniu ataku możesz wybrać inny przyjazny statek w Zasięgu 1. Dany statek może wykonać 1 darmową akcję.""" # E-Wing "Knave Squadron Pilot": name: "Pilot Eskadry Szelm" "Blackmoon Squadron Pilot": name: "Pilot Eskadry Czarnego Księżyca" "<NAME>": text: """Kiedy wrogi statek w twoim polu rażenia, w Zasięgu 1-3 się broni, atakujący może zmienić 1 z jego wyników %HIT% na wynik %CRIT%.""" "<NAME>": text: """Na początku fazy końcowej możesz wykonać jeden atak. Nie możesz atakować w następnej rundzie.""" # Asy Rebelii "<NAME>": text: """Po tym jak wykonasz akcję skupienia lub zostanie ci przypisany żeton skupienia, możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "<NAME>": text: """Dopóki znajdujesz się w Zasięgu 1 od co najmniej 1 wrogiego statku, zwiększ swoją wartość zwrotności o 1.""" "<NAME>": text: """Kiedy atakujesz możesz usunąć 1 żeton stresu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "<NAME>": text: """Możesz wykonać atak dodatkową bronią %TORPEDO%, skierowany przeciwko wrogim statkom znajdującym się poza twoim polem rażenia.""" # Transportowiec Rebelii "GR-75 Medium Transport": name: "Średni transportowiec GR-75" ship: "Średni transportowiec GR-75" # CR90 "CR90 Corvette (Fore)": ship: "Korweta CR90 (dziób)" name: "Korweta CR90 (dziób)" text: """Kiedy atakujesz przy pomocy swojej głównej broni, możesz wydać 1 żeton energii aby rzucać 1 dodatkową kością ataku.""" "CR90 Corvette (Aft)": ship: "Korweta CR90 (rufa)" name: "Korweta CR90 (rufa)" # YT-2400 "Dash Rendar": text: """Podczas fazy aktywacji i w czasie wykonywania akcji możesz ignorować przeszkody.""" '"Leebo"': text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, dobierz 1 dodatkową kartę uszkodzenia. Rozpatrz jedną z nich a drugą odrzuć.""" "<NAME>": text: """Podczas wykonywania ataku przy pomocy broni podstawowej, którego celem jest statek z żetonem stresu, rzucasz 1 dodatkową kością.""" "Wild Space F<NAME>er": name: "Out<NAME> z <NAME>" # Scum and Villainy # Starviper "<NAME>": name: "<NAME>" text: """Kiedy się bronisz, przyjazny statek w Zasięgu 1 może otrzymać 1 nieanulowany wynik %HIT% lub %CRIT% (zamiast ciebie).""" "<NAME>": text: """Na początku fazy walki, jeśli jesteś w Zasięgu 1 od wrogiego statku, możesz przypisać do swojego statku 1 żeton skupienia.""" "Black Sun Vigo": name: "<NAME>" "Black Sun Enforcer": name: "<NAME>" # Interceptor M3-A "Cartel Spacer": name: "Pilot kartelu" "Tansarii Point Veteran": name: "Weteran Tansarii Point" "<NAME>": text: """Kiedy inny przyjazny statek w Zasięgu 1 się broni, może przerzucić 1 kość obrony.""" "<NAME>": text: "Po tym jak obronisz się przed atakiem, jeśli atak nie trafił, możesz przypisać do swojego statku 1 żeton uniku." # Agressor "IG-88A": text: """Po tym jak wykonasz atak, który zniszczy obrońcę, możesz odzyskać 1 osłonę.""" "IG-88B": text: """Raz na rundę, po tym jak wykonasz atak, który nie trafi w wybrany cel, możesz wykonać atak przy pomocy dodatkowej broni %CANON%, w którą jesteś wyposażony.""" "IG-88C": text: """Po tym jak wykonasz akcję „dopalacz” możesz przypisać do swojego statku 1 żeton uniku.""" "IG-88D": text: """Możesz wykonać manewr (%SLOOPLEFT% 3) lub (%SLOOPRIGHT% 3) używając odpowiednio wzornika (%TURNLEFT% 3) lub (%TURNRIGHT% 3).""" # Firespray "<NAME> (Scum)": name: """<NAME> (Szumowiny)""" text: """Kiedy atakujesz lub się bronisz możesz przerzucić 1 ze swoich kości za każdy wrogi statek w Zasięgu 1.""" "<NAME> (Scum)": name: """<NAME> (Szumowiny)""" text: """Kiedy atakujesz statek znajdujący się w twoim pomocniczym polu rażenia, rzucasz 1 dodatkową kością ataku.""" "<NAME>": text: """Kiedy zrzucasz bombę, możesz użyć wzornika [%TURNLEFT% 3], [%STRAIGHT% 3], lub [%TURNRIGHT% 3] (zamiast wzornika [%STRAIGHT% 1]).""" "<NAME>": name: "<NAME>" # Y-Wing "<NAME>": text: """Kiedy atakujesz statek znajdujący się poza twoim polem rażenia, rzucasz 1 dodatkową kością ataku.""" "<NAME>": text: """Po tym jak wydasz żeton namierzonego celu, możesz otrzymać 1 żeton stresu, aby namierzyć cel.""" "<NAME>" : name: "<NAME>" "<NAME>": name: "<NAME>u" # HWK "<NAME>": text: """Kiedy wrogi statek w Zasięgu 1-3 otrzyma co najmniej jeden żeton jonów, a ty nie masz żetonu stresu, możesz otrzymać 1 żeton stresu aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "<NAME>": text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z wrogiego statku w Zasięgu 1-2 i przypisać go do siebie.""" "<NAME>": text: """Na koniec fazy aktywacji wybierz jeden wrogi statek w Zasięgu 1-2. Do końca fazy walki wartość umiejętności pilota wybranego statku wynosi "0".""" "<NAME>": name: "<NAME>" # Z-95 "Black Sun Soldier": name: "<NAME>" ship: "Z-95 Łowca głów" "Binay<NAME>": name: "<NAME>" ship: "Z-95 Łowca głów" "<NAME>": ship: "Z-95 Łowca głów" text: """Kiedy atakujesz rzucasz 1 dodatkową kością ataku, jeśli w Zasięgu 1-2 nie ma żadnych innych przyjaznych statków.""" "<NAME>": ship: "Z-95 Łowca głów" text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z innego przyjaznego statku w Zasięgu 1-2 i przypisać go do siebie.""" "<NAME>": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "<NAME>": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "<NAME>": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" '"Redline"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"Deathrain"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Moralo Eval": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" 'Gozanti-class Cruiser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"Scourge"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "The Inquisitor": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "Zuckuss": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" # T-70 "<NAME>": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" '"Blue Ace"': text: """When performing a boost action, you may use the (%TURNLEFT% 1) or (%TURNRIGHT% 1) template.""" # TIE/fo '"Omega Ace"': text: """When attacking, you may spend a focus token and a target lock you have on the defender to change all of your results to %CRIT% results.""" '"Epsilon Leader"': text: """At the start of the Combat phase, remove 1 stress token from each friendly ship at Range 1.""" '"Zeta Ace"': text: """When performing a barrel roll you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" '"Red Ace"': text: '''The first time you remove a shield token from your ship each round, assign 1 evade token to your ship.''' '"Omega Leader"': text: '''Enemy ships that you have locked cannot modify any dice when attacking you or defending against your attacks.''' 'Hera Syndulla': text: '''When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.''' '"Youngster"': text: """Friendly TIE fighters at Range 1-3 may perform the action on your equipped %ELITE% Upgrade card.""" '"<NAME>"': text: """When attacking, you may cancel all die results. If you cancel a %CRIT% result, deal 1 facedown Damage card to the defender.""" '"<NAME>"': text: """When another friendly ship at Range 1 spends a focus token, assign a focus token to your ship.""" '<NAME>': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"<NAME>"': text: '''When attacking, if you are not stressed, you may receive 1 stress token to roll 1 additional die.''' '"<NAME>"': text: '''While you do not have any Damage cards, treat your pilot skill value as "12."''' "<NAME>": text: """When an enemy ship at Range 1-2 is attacking, you may spend a focus token. If you do, the attacker rolls 1 fewer attack die.""" '"<NAME>"': text: """At the start of the Combat phase, each enemy ship you are touching receives 1 stress token.""" '<NAME> (Attack Shuttle)': text: """When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.""" '<NAME>': text: """Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.""" '"Z<NAME>" Orrelios': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' '<NAME>': ship: "Bombowiec TIE" text: '''Once per round, after you discard an %ELITE% Upgrade card, flip that card faceup.''' '<NAME>': text: '''While you are not stressed, you may treat your %TROLLLEFT% and %TROLLRIGHT% maneuvers as white maneuvers.''' "<NAME>": text: """After defending, you may perform a free action.""" "4-LOM": text: """At the start of the End phase, you may assign 1 of your stress tokens to another ship at Range 1.""" "<NAME>": text: """The first time you would be destroyed, instead cancel any remaining damage, discard all Damage cards, and deal 4 facedown Damage cards to this ship.""" "<NAME>": text: """At the start of the Combat phase, you may assign all focus, evade, and target lock tokens assigned to you to another friendly ship.""" '"Death<NAME>"': ship: "Bombowiec TIE" text: '''When you reveal your maneuver dial or after you perform an action, you may perform a %BOMB% Upgrade card action as a free action.''' "<NAME> (TIE Defender)": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "<NAME>": text: """When you reveal a %STRAIGHT% maneuver, you may treat it as a %KTURN% maneuver.""" "<NAME> (PS9)": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" "<NAME>": text: """When attacking or defending, if the enemy ship is inside of your firing arc, you may reroll up to 2 of your blank results.""" 'Han <NAME> (TFA)': text: '''When you are placed during setup, you can be placed anywhere in the play area beyond Range 3 of enemy ships.''' 'Che<NAME> (TFA)': text: '''After another friendly ship at Range 1-3 is destroyed (but has not fled the battlefield), you may perform an attack.''' '<NAME>': text: '''When attacking or defending, you may spend a target lock you have on the enemy ship to add 1 %FOCUS% result to your roll.''' '<NAME>': text: '''When another friendly ship at Range 1-2 is attacking, it may treat your blue target lock tokens as its own.''' '<NAME>': text: '''After an enemy ship in your firing arc at Range 1-3 attacks another friendly ship, you may perform a free action.''' '<NAME>': text: '''After you execute a maneuver, you may roll an attack die. On a %HIT% or %CRIT% result, remove 1 stress token from your ship.''' '"Quick<NAME>"': text: '''Once per round, when you lose a shield token, you may perform a primary weapon attack.''' '"Back<NAME>"': text: '''When attacking a ship inside your auxiliary firing arc, you may add 1 %CRIT% result.''' '<NAME>': text: '''When attacking or defending, if the enemy ship is at Range 1, you may roll 1 additional die.''' '<NAME>': text: '''At the start of the Combat phase, you may choose 1 enemy ship at Range 1. If you are inside its firing arc, it discards all focus and evade tokens.''' '<NAME>': text: '''After you execute a red maneuver, assign 2 focus tokens to your ship.''' '<NAME>': text: '''At the start of the Combat phase, you may choose a ship at Range 1. If it is inside your primary <strong>and</strong> mobile firing arcs, assign 1 tractor beam token to it.''' '<NAME>': text: '''At the start of the Combat phase, you may choose a ship at Range 1-2. If it inside your mobile firing arc, assign 1 stress token to it.''' '<NAME> (Scum)': text: '''When defending against an enemy ship inside your mobile firing arc at Range 1-2, you may add 1 %FOCUS% result to your roll.''' '<NAME> (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.''' '"Zeb" Orrelios (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' '<NAME>': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' '<NAME>': text: '''At the end of the Activation phase, you <strong>must</strong> assign a tractor beam token to each ship you are touching.''' '<NAME>': text: '''At the start of the Activation phase, you may remove 1 stress token from 1 other friendly ship at Range 1-2.''' '<NAME>': text: '''When a friendly ship acquires a target lock, that ship can lock onto an enemy ship at Range 1-3 of any friendly ship.''' '<NAME>': text: '''After an enemy ship executes a maneuver that causes it to overlap your ship, you may perform a free action.''' '''"Duchess"''': text: '''While you have the "Adaptive Ailerons" Upgrade card equipped, you may choose to ignore its card ability.''' '''"Pure Sabacc"''': text: '''When attacking, if you have 1 or fewer Damage cards, roll 1 additional attack die.''' '''"Countdown"''': text: '''When defending, if you are not stressed, during the "Compare Results" step, you may suffer 1 damage to cancel all dice results. If you do, receive 1 stress token.''' '<NAME>': text: '''When you receive a stress token, if there is an enemy ship inside your firing arc at Range 1, you may discard that stress token.''' '"Snap" <NAME>': text: '''After you execute a 2-, 3-, or 4-speed maneuver, if you are not touching a ship, you may perform a free boost action.''' '<NAME>': text: '''When attacking or defending, you may reroll 1 of your dice for each other friendly ship at Range 1.''' '<NAME>': ship: 'Myśliwiec TIE' text: '''At the start of the Combat phase, you may spend 1 focus token to choose a friendly ship at Range 1. It may perform 1 free action.''' '<NAME>': ship: 'Myśliwiec TIE' text: '''After you perform an attack, assign the "Suppressive Fire" Condition card to the defender.''' '<NAME>': text: '''For the purpose of your actions and Upgrade cards, you may treat friendly ships at Range 2-3 as being at Range 1.''' '<NAME>': text: '''During setup, friendly ships may placed anywhere in the play area at Range 1-2 of you.''' '<NAME>': text: '''When you reveal a reverse maneuver, you may drop a bomb using your front guides (including a bomb with the "<strong>Action:</strong>" header).''' '<NAME>': text: '''When defending, instead of using your agility value, you may roll a number of defense dice equal to the speed of the maneuver you executed this round.''' "<NAME>": text: """When attacking or defending, double the effect of your range combat bonuses.""" '<NAME>': text: '''After you acquire a target lock, assign focus and evade tokens to your ship until you have the same number of each token as the locked ship.''' '<NAME>': text: '''At the start of the Combat phase, you may receive a weapons disabled token to flip one of your discarded %TORPEDO% or %MISSILE% Upgrade cards faceup.''' '<NAME>': text: '''When attacking or defending, you may spend 1 shield to reroll any number of your dice.''' '<NAME>': text: '''Once per round, after you roll or reroll dice, if you have the same result on each of your dice, add 1 matching result.''' '<NAME>': text: '''When attacking, you may spend 1 focus token to cancel all of the defender's blank and %FOCUS% results.''' '"<NAME>"': text: '''Once per round, after you perform a secondary weapon attack that does not hit, you may perform an attack with a different weapon.''' '<NAME>': text: '''After defending, if you did not roll exactly 2 defense dice, the attacker receives 1 stress token.''' 'Low<NAME>': text: '''When another friendly ship at Range 1 is defending, you may spend 1 reinforce token. If you do, the defender adds 1 %EVADE% result.''' '<NAME>': text: '''When attacking, if you have no shields and at least 1 Damage card assigned to you, roll 1 additional attack die.''' '<NAME>': text: '''If you are not stressed, when you reveal a turn, bank, or Segnor's Loop maneuver, you may instead treat it as a red Tallon Roll maneuver of the same direction (left or right) using the template of the original revealed maneuver.''' '<NAME>': text: '''During setup, before the "Place Forces" step, you may choose 1 enemy ship and assign the "Shadowed" or "Mimicked" Condition card to it.''' '<NAME>': text: '''Once per round, after an enemy ship that is not defending against an attack suffers damage or critical damage, you may perform an attack against that ship.''' '<NAME>': text: '''When defending, if you have a weapons disabled token, roll 1 additional defense die.''' '<NAME>': text: '''When you receive a weapons disabled token, if you are not stressed, you may receive 1 stress token to remove it.''' '<NAME>': text: '''After you perform an attack, each enemy ship inside your bullseye firing arc at Range 1-3 must choose to suffer 1 damage or remove all of its focus and evade tokens.''' '<NAME> (Kimogila)': text: '''At the start of the Combat phase, you may acquire a target lock on an enemy ship inside your bullseye firing arc at Range 1-3 .''' '<NAME> (Sheathipede)': text: '''When an enemy ship inside your firing arc at Range 1-3 becomes the active ship during the Combat phase, if you are not stressed, you may receive 1 stress token. If you do, that ship cannot spend tokens to modify its dice when attacking this round.''' '<NAME> (Sheathipede)': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"Zeb" Orrelios (Sheathipede)': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'AP-5': text: '''When you perform the coordinate action, after you choose a friendly ship and before it performs a free action, you may receive 2 stress tokens to remove 1 stress token from it.''' '"Crimson Leader"': text: '''When attacking, if the defender is inside your firing arc, you may spend 1 %HIT% or %CRIT% result to assign the "Rattled" Condition to the defender.''' '"Crimson Specialist"': text: '''When placing a bomb token you dropped after revealing your maneuver dial, you may place the bomb token anywhere on the play area touching your ship.''' '"Cobalt Leader"': text: '''When attacking, if the defender is at range 1 of a bomb token, the defender rolls 1 fewer defense die, to a minimum of 0.''' '<NAME> (TIE Silencer)': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' 'Test Pilot "Blackout"': text: '''When attacking, if the attack is obstructed, the defender rolls 2 fewer defense dice (to a minimum of 0).''' '<NAME>': text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.''' 'Major Vermeil': text: '''When attacking, if the defender does not have a focus or evade token, you may change one of your blank or %FOCUS% results to a %HIT% result.''' '<NAME>': text: '''After you perform a boost action, you may receive 1 stress token to receive 1 evade token.''' '<NAME>': text: '''When a friendly ship at Range 1-2 attacks, if it is stressed or has at least 1 Damage card, it may reroll 1 attack die.''' 'B<NAME> Two-Tubes': text: '''After you perform a focus action, you may remove 1 of your focus tokens to assign it to a friendly ship at Range 1-2.''' '<NAME>': text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.''' '"<NAME>"': text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.''' '<NAME>': text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.''' '<NAME>-Tubes': text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.''' upgrade_translations = #Elitarna zdolność "Determination": name: "Determinacja" text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia z cechą "Pilot", natychmiast ją odrzuć bez rozpatrywania jej efektu.""" "Swarm Tactics": name: "<NAME>" text: """Na początku fazy walki wybierz 1 przyjazny statek w Zasięgu 1. Do końca tej fazy traktuj wybrany statek, jakby jego wartość umiejętności pilota była równa twojej.""" "Squad Leader": name: "<NAME>" text: """<strong>Akcja:</strong> Wybierz 1 statek w Zasięgu 1-2, który ma niższą wartość umiejętności pilota niż ty. %LINEBREAK% Wybrany statek może natychmiast wykonać 1 darmową akcję.""" "Expert Handling": name: "<NAME>" text: """„<strong>Akcja:</strong> Wykonaj darmową akcję „beczka”. Jeśli nie masz symbolu akcji %BARRELROLL%, otrzymujesz 1 żeton stresu. Następnie możesz usunąć jeden wrogi żeton namierzonego celu znajdujący się na Twoim statku.""" "<NAME>ship": name: "<NAME>" text: """<strong>Akcja:</strong> Kiedy atakujesz w tej rundzie, możesz zamienić 1 swój wynik %FOCUS% na %CRIT%, a wszystkie pozostałe wyniki %FOCUS% na %HIT%.""" "<NAME>": name: "<NAME>" text: """<strong>Akcja:</strong> Wykonaj biały manewr (%TURNLEFT% 1) lub (%TURNRIGHT% 1)". Następnie otrzymujesz żeton stresu. %LINEBREAK% Następnie, jeśli nie masz symbolu akcji %BOOST%, rzuć 2 kośćmi ataku. Otrzymujesz wszystkie wyrzucone uszkodzenia %HIT% i uszkodzenia krytyczne %CRIT%.""" "Elusiveness": name: "<NAME>" text: """Kiedy się bronisz możesz otrzymać 1 żeton stresu, aby wybrać jedną kość ataku. Atakujący musi przerzucić tą kość. Nie możesz skorzystać z tej zdolności, jeśli jeśli masz co najmniej 1 żeton stresu.""" "Push the Limit": name: "Na granicy ryzyka" text: """Raz na rundę po wykonaniu akcji, możesz wykonać 1 darmową akcję przedstawioną na twoim pasku akcji. Następnie otrzymujesz 1 żeton stresu.""" "<NAME>": name: "<NAME>" text: """Możesz traktować nagłówek <strong>"Atak (namierzony cel):"</strong> jako <strong>"Atak (skupienie):"</strong>. %LINEBREAK% Kiedy atak zmusza cię do wydania żetonu namierzonego celu, możesz zamiast niego wydać żeton skupienia.""" "<NAME>": name: "<NAME>" text: """<strong>Akcja:</strong> Do końca rundy zwiększ wartość swojej podstawowej broni o 1 i zmniejsz wartość zwrotności o 1.""" "<NAME>": name: "<NAME>" text: """Na początku fazy walki usuń 1 żeton stresu z innego przyjaznego statku w Zasięgu 1.""" "<NAME>": name: "<NAME>" text: """Na początku fazy walki możesz wybrać 1 przyjazny statek w Zasięgu 1-2. Do końca fazy zamieniasz się z danym statkiem wartościami umiejętności pilota.""" "<NAME>": name: "<NAME>" text: """Kiedy atakujesz statek w swoim polu rażenia, a nie znajdujesz się w polu rażenia danego statku, zmniejsz jego wartość zwrotności o 1 (do minimum 0).""" "<NAME>": name: "<NAME>" text: """Kiedy atakujesz, możesz przerzucić 1 kość ataku. Jeśli wartość umiejętnosci pilota obrońcy wynosi "2" lub mniej, możesz przerzucić maksymalnie 2 kości ataku (zamiast 1).""" "Draw Their Fire": name: "Ści<NAME>" text: """Kiedy przyjazny statek w Zasięgu 1 zostaje trafiony podczas ataku, możesz zamiast niego otrzymać 1 z nie anulowanych %CRIT%.""" "<NAME>": name: "<NAME>" text: """Kiedy ujawnisz czerwony manewr, możesz odrzucić tę kartę, aby do końca fazy aktywacji traktować ten manewr jako biały.""" "Veteran Instincts": name: "<NAME>" text: """Zwiększ swoją wartość umiejętności pilota o 2.""" "Opportunist": name: "<NAME>" text: """Kiedy atakujesz, jeśli obrońca nie ma żadnych żetonów skupienia ani uników, możesz otrzymać 1 żeton stresu aby rzucić 1 dodatkową kością ataku.%LINEBREAK%Nie możesz skorzystać z tej zdolności, jeśli posiadasz żetony stresu.""" "L<NAME>": name : "<NAME>" text: """Jeśli w zasięgu 1-2 nie ma żadnych innych przyjaznych statków, kiedy się bronisz lub atakujesz, możesz przerzucić 1 wynik z pustą ścianką.""" "Stay On Target": name: "U<NAME> cel" text: """Kiedy ujawnisz swój manewr możesz obrócić swój wskaźnik na inny manewr o tej samej prędkości.%LINEBREAK%Traktuj ten manewr jako czerwony.""" "Ruthlessness": name: "Bezwzględność" text: """%PL_IMPERIALONLY%%LINEBREAK% Po tym jak przeprowadzisz atak, który trafi w cel, musisz wybrać 1 inny statek w Zasięgu 1 od obrońcy (nie siebie). Statek ten otrzymuje 1 uszkodzenie.""" "Intimidation": name: "Zastraszenie" text: """Dopóki stykasz się z wrogim statkiem, jego zwrotność zostaje zmniejszona o 1.""" "Calculation": name: "Kalkulacje" text: """Kiedy atakujesz, możesz wydać żeton skupienia, aby zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Bodyguard": name : "<NAME>" text: """%PL_SCUMONLY%%LINEBREAK% Na początku fazy walki możesz wydać żeton skupienia aby wybrać przyjazny statek w Zasięgu 1 o wartości umiejętności pilota wyższej od ciebie. Do końca rundy zwiększ jego wartość zwrotności o 1.""" # Astromechs "R2 Astromech": name: "Astromech R2" text: """Możesz traktować wszystkie manewry o prędkości 1 i 2, jakby były to zielone manewry.""" "R2-D2": text: """Po wykonaniu zielonego manewru możesz odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R2-F2": text: """<strong>Akcja:</strong> Do końca tej rundy zwiększ swoją wartość zwrotności o 1.""" "R5-D8": text: """<strong>Akcja:</strong> Rzuć jedną kością obrony.%LINEBREAK% Jeżeli wypadnie wynik %EVADE% lub %FOCUS%, odrzuć jedną ze swoich zakrytych kart uszkodzeń.""" "R5-K6": text: """Po wydaniu swojego rzetonu namierzonego celu rzuć 1 kością obrony.%LINEBREAK% Jeżeli wypadnie %EVADE% natychmiast zdobywasz żeton namierzonego celu dla tego samego statku. Nie możesz wydać nowego żetonu namierzonego celu podczas tego ataku.""" "R5 Astromech": name: "Astromech R5" text: """Podczas fazy końcowej możesz wybrać 1 ze swoich odkrytych kart z cechą "Statek" i ją zakryć.""" "R7 Astromech": name: "Astromech R7" text: """Raz na rundę kiedy się bronisz, jeśli namierzasz atakującego, możesz wydać żeton namierzonego celu aby wybrać dowolną liczbę kości ataku. Atakujący musi przerzucić wybrane kości.""" "R7-T1": text: """<strong>Akcja:</strong> Wybierz wrogi statek w Zasięgu 1-2. Jeżeli znajdujesz się w polu rażenia wybranego statku, możesz namierzyć dany statek. Następnie możesz wykonać darmową akcję "dopalacz".""" "R4-D6": text: """Kiedy zostaniesz trafiony w wyniku ataku, a pośród wyników rzutu są co najmniej 3 nieaulowalne wyniki %HIT% możesz wybrać i anulować wszystkie poza 2. Za każdy wynik anulowany w ten sposób otrzymujesz 1 żeton stresu.""" "R5-P9": text: """Na koniec fazy walki możesz wydać jeden ze swoich żetonów skupienia, aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R3-A2": text: """Kiedy wybierzesz cel ataku, jeżeli obrońca znajduje się w twoim polu rażenia, możesz otrzymać 1 żeton stresu, aby sprawić żeby obrońca otrzymał 1 żeton stresu.""" "R2-D6": text: """Twój pasek rowinięć zyskuje symbol %ELITE%.%LINEBREAK% Nie możesz przypisać tej karty rozwinięcia do swojego statku jeżeli masz już symbol rozwinięcia %ELITE% lub jeżeli wartość umiejętności pilota wynosi 2 lub mniej.""" # Torpilles "Proton Torpedoes": name: "Torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Advanced Proton Torpedoes": name: "Zaaw. torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić maksymalnie 3 swoje puste ścianki na wyniki %FOCUS%.""" "<NAME>": name: "<NAME>" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Po wykonaniu tego ataku obrońca otrzymuje 1 żeton stresu jeżeli jego wartość kadłuba wynosi 4 lub mniej.""" "Ion Torpedoes": name: "<NAME>" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeżeli ten atak trafi w wybrany cel, obrońca oraz każdy statek w Zasięgu 1 od niego otrzymuje 1 żeton jonów.""" "Bomb Loadout": name: "Ładunek bomb" text: """<span class="card-restriction">Tylko Y-wing. Ograniczenie.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %BOMB%.""" # Tourelles "Ion Cannon Turret": name: "Wieżyczka z działem jonowym" text: """<strong>Atak:</strong> Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Jeśli atak ten trafi w wybrany statek, otrzymuje on 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Blaster Turret": name: "Wieżyczka blasterowa" text: """<strong>Atak (skupienie):</strong> Wydaj 1 żeton skupienia, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" "Autoblaster Turret": name: "Wieżyczka autoblasterowa" text: """<strong>Atak: Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przy pomocy kości obrony. Obrońca może anulować wyniki %CRIT% przed %HIT%.""" # Missiles "Concussion Missiles": name: "Rakiety wstrząsowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników z pustą ścianką na wynik %HIT%.""" "Cluster Missiles": name: "Rakiety kasetonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu o odrzuć tę kartę, aby przeprowadzić ten atak dwukrotnie.""" "Homing Missiles": name: "Rakiety samonaprowadzające" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Podczas tego ataku obrońca nie może wydawać żetonów uniku.""" "Assault Missiles": name: "Rakiety szturmowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi w wybrany cel, każdy inny statek w Zasięgu 1 od obrońcy otrzymuje 1 uszkodzenie.""" "Ion Pulse Missiles": name: "Jon<NAME> pulsacyjne" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi, obrońca otrzymuje 1 uszkodzenie oraz 2 żetony jonów.""" "Chardaan Refit": name: "<NAME>" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Ta karta ma ujemny koszt w punktach eskadry.""" "Proton Rockets": name: "R<NAME>iety protonowe" text: """<strong>Atak (skupienie):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz rzucić dodatkowymi kośćmi ataku w liczbie równej twojej zwrotności (nie wiecej niż 3).""" # Bombes "Seismic Charges": name: "<NAME>" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton ładunku sejsmicznego. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" "Proximity Mines": name: "Miny zbliżeniowe" text: """<strong>Akcja:</strong> odrzuć tę kartę aby zrzucić 1 żeton miny zbliżeniowej. Kiedy statek wykona manewr w wyniku którego podstawka statku lub wzornik manewru będzie nachodzić na ten żeton, żeton ten zostaje zdetonowany.""" "<NAME>": name: "<NAME>" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton bomby protonowej. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" # Canons "Ion Cannon": name: "<NAME>" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi wybrany cel, obrońca otrzymuje 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystie wyniki kości.""" "Heavy Laser Cannon": name: "<NAME>" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Natychmiast po rzucie swoimi kośćmi ataku musisz zmienić wszystkie swoje wyniki %CRIT% na wyniki %HIT%.""" "Autoblaster": text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przez kości obrony. Obrońca może anulować wyniki %CRIT% przed wynikami %HIT%.""" "Flechette Cannon": name: "<NAME>" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi, obrońca otrzymuje 1 uszkodzenie i, jeśli nie jest zestresowany, otrzymuje także 1 żeton stresu. Następnie anuluj wszystkie wyniki kości.""" '"Mangler" Cannon': name: "Działo typu Mangler" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Kiedy atakujesz, możesz zmienić jeden ze swoich wyników %HIT% na wynik %CRIT%.""" # Systèmes "Enhanced Scopes": name: "Wzmocnione radary" text: """Podczas fazy aktywacji traktuj swoją wartość umiejętności pilota jakby wynosiła "0".""" "Fire-Control System": name: "System kontroli ognia" text: """Po tym jak wykonasz atak, możesz namierzyć obroncę.""" "Advanced Sensors": name: "Zaawanswowane sensory" text: """Zaraz przed tym jak ujawnisz swój manewr, możesz wykonać 1 darmową akcję. %LINEBREAK%Jeżeli skorzystawsz z tej zdolności, musisz w tej rundzie pominąć swój krok "Wykonywania akcji".""" "Sensor Jammer": name: "Zakłócacz sensorów" text: """Kiedy się bronisz możesz zmienić 1 z wyników %HIT% atakującego na wynik %FOCUS%. Atakujący nie może przerzucić kości ze zmienionym wynikiem.""" "Accuracy Corrector": name: "Korektor celności" text: """Kiedy atakujesz, możesz anulować wszystkie swoje wyniki kości. Następnie możesz dodać 2 wyniki %HIT%.%LINEBREAK% Podczas tego ataku nie można ponownie modyfikować twoich kości.""" "Advanced Targeting Computer": name: "Zaawansowany komputer celowniczy" text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK% Kiedy atakujesz namierzonego przez siebie przeciwnika przy pomocy broni podstawowej, do wyniku rzutu kośćmi możesz dodać jeden wynik %CRIT%. Jeżeli to zrobisz, podczas tego ataku nie możesz wydać żetonu namierzonego celu.""" # Équipages "<NAME>": name: "<NAME>" text: """Po wykonaniu ataku, który nie trafił w wybrany cel, natychmiast wykonaj atak główną bronią. W tej rundzie nie możesz wykonać kolejnego ataku.""" "<NAME>": name: "<NAME>" text: """Kiedy atakujesz w Zasiegu 3 możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" "Weapons Engineer": name: "<NAME>" text: """Możesz namierzać naraz 2 statki (każdy wrogi statek możesz namierzać tylko raz). %LINEBREAK%Kiedy namierzasz cel, możesz namierzyć 2 różne statki.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Po wykonaniu ataku, który nie trafi w wybrany cel, natychmiast wykonaj atak główną bronią. Możesz zmienić 1 wynik %FOCUS% na %HIT%.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Możesz traktować wszystkie manewry %STRAIGHT%, jakby były to zielone manewry.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Kiedy otrzymujesz kartę uszkodzenia, możesz natychmiast odrzucić tę kartę i odzyskać 1 żeton osłony. Następnie odrzuć tę kartę rozwinięcia.""" "Recon Specialist": name: "<NAME>" text: """Kiedy wykonujesz akcję skupienia, przypisz do swojego statku 1 dodatkowy żeton skupienia.""" "Saboteur": name: "<NAME>" text: """<strong>Akcja:</strong> Wybierz 1 wrogi statek w Zasięgu 1 i rzuć 1 koscią ataku. Jeśli wypadnie %HIT% lub %CRIT%, wylosuj 1 zakrytą kartę uszkodzenia przypisaną do tego statku, odkryj ją i rozpatrz.""" "Intelligence Agent": name: "<NAME> <NAME>" text: """Na początku fazy aktywacji wybierz 1 wrogi statek w zasięgu 1-2. Możesz podejrzeć manewr wybrany przez ten statek.""" "<NAME>": text: """%PL_IMPERIALONLY%%LINEBREAK%Tylko Imperium. Po tym jak wykonasz atak skierowany przeciwko wrogiemu statkowi, możesz otrzymać 2 uszkodzenia, aby zadać temu statkowi 1 krytyczne uszkodzenie.""" "Rebel Captive": name: "<NAME>" text: """%PL_IMPERIALONLY%%LINEBREAK%Raz na rundę, pierwszy statek, który zadeklaruje ciebie jako cel ataku, natychmiast otrzymuje 1 żeton stresu.""" "Flight Instructor": name: "<NAME>" text: """Kiedy się b<NAME>isz, możesz przerzucić 1 ze swoich wyników %FOCUS%. Jeśli wartość umiejętności atakującego pilota wynosi "2" lub mniej, zamiast tego przerzuć 1 ze swoich pustych scianek.%FOCUS%.""" "Navigator": name: "<NAME>" text: """Kiedy ujawnisz swój manewr, możesz obrócić swój wskaźnik na inny manewr tego samego kierunku. %LINEBREAK%Nie możesz przekręcić wskaźnika na czerwony manewr, jeśli posiadasz jakieś żetony stresu.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Rzuć 2 koścmi obrony. Za kazdy uzyskany wynik %FOCUS% przypisz do swojego statku 1 żeton skupienia. Za każdy wynik %EVADE% przypisz do swojego statku 1 żeton uniku.%FOCUS%""" "<NAME>": text: """%PL_IMPERIALONLY%%LINEBREAK% Na koniec fazy walki kazdy wrogi statek w Zasięgu 1, który nie ma żetonu stresu, otrzymuje żeton stresu.""" "Fleet Officer": name: "<NAME>" text: """%PL_IMPERIALONLY%%LINEBREAK%<strong>Akcja:</strong> Wybierz maksymalnie 2 przyjazne statki w Zasięgu 1-2 i do każdego przypisz po 1 żetonie skupienia, następnie otrzymujesz 1 żeton stresu.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Tylko rebelianci. Kiedy atakujesz, jeśli namierzyłeś obrońcę, możesz wydać żeton namierzonego celu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę, aby umożliwić wszystkim przyjaznym statkom, które ujawiniają czerwony manewr, traktowanie do końca fazy tego manewru jako białego.""" "WED-15 Repair Droid": name: "Droid naprawczy WED-15" text: """%PL_HUGESHIPONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj 1 żeton energii aby odrzucić 1 ze swoich zakrytych kart uszkodzeń albo wydaj 3 żetony energii aby odrzucić 1 ze swoich odkrytych kart uszkodzeń.""" "<NAME>": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę aby do końca fazy traktować wartość umiejętności pilota każdego przyjaznego statku jakby wynosiła "12".""" "<NAME>": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Kiedy inny przyjazny statek w Zasięgu 1 wykonuje atak, możesz zmienić 1 z jego wyników %HIT% na %CRIT%.""" "Tactician": name: "<NAME>" text: "Po tym jak wykonasz atak przeciwko statkowi znajdującemu się w twoim polu rażenia w Zasiegu 2, statek ten otrzymuje 1 żeton stresu." "R2-D2 (Crew)": name: "R2-D2 (Załoga)" text: """%PL_REBELONLY%%LINEBREAK%Na koniec fazy końcowej, jeśli nie masz żadnych osłon, możesz odzyskać 1 osłonę i rzucić 1 kością ataku. Jeśli wypadnie %HIT% odkryj 1 losową ze swoich zakrytych kart uszkodzeń i ją rozpatrz.""" "C-3PO": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, zanim wykonasz rzut co najmniej 1 koscią obrony, możesz na głos zgadnąć liczbę wyników %EVADE%. Jeśli wypadło tyle %EVADE% (przed modyfikacjami) dodaj 1 wynik %EVADE%.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Po tym jak usuniesz ze swojego statku żeton stresu, możesz przypisać do swojego statku żeton skupienia.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, kiedy przyjazny statek w Zasięgu 1-3 wykonuje akcję skupienia lub miałby otrzymać żeton skupienia, możesz danemu statkowi przypisać żeton uniku (zamiast skupienia).""" "<NAME>": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj dowolną ilość żetonów energii aby wybrać taką samą liczbę wrogich statków w Zasiegu 1-2. Usuń z wybranych statków wszystkie żetony skupienia, uników i niebieskie żetony namierzonego celu.""" "Targeting Coordinator": name: "<NAME>" text: """<strong>Energia:</strong> Możesz wydać 1 żeton energii aby wybrać 1 przyjazny statek w Zasięgu 1-2. Namierz cel, a następnie przydziel do wybranego statku niebieski żeton namierzonego celu.""" "<NAME>": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji wybierz 1 wrogi statek w Zasięgu 1-3. Możesz podejrzeć manewr wybrany dla tego statku. Jeżeli jest on biały, przydziel do niego 1 żeton stresu.""" '"L<NAME>"': text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> wykonaj darmową akcję "dopalacz". Następnie otrzymujesz 1 żeton jonów.""" "<NAME>": text: """%PL_REBELONLY%%LINEBREAK%Możesz wykonywać ataki kiedy nachodzisz na przeszkodę. %LINEBREAK%Twoje ataki nie mogą być przyblokowane.""" "<NAME>": text: """%PL_IMPERIALONLY%%LINEBREAK%Na początku fazy walki, jeśli nie masz żadnych osłon, a do twojego statku przypisana jest co najmniej 1 karta uszkodzenia, możesz wykonać darmową akcję unik.""" "<NAME>": text: """%PL_IMPERIALONLY%%LINEBREAK%Kiedy otrzymujesz odkrytą kartę uszkodzenia, możesz odrzucić to rozwinięcie lub inną kartę rozwinięcia [crew] aby zakryć tę kartę uszkodzenia (bez rozpatrywania jej efektu).""" "Greedo": text: """%PL_SCUMONLY%%LINEBREAK%Za pierwszym razem kiedy atakujesz lub bronisz sie w każdej rundzie, pierwsza przypisana karta uszkodzenia jest odkryta.""" "Outlaw Tech": name: "Mechanik wyjęty spod prawa" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu czerwonego manewru, możesz przypisać do swojego statku 1 żeton skupienia.""" "K4 Security Droid": name: "Droid ochroniarz K4" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu zielonego manewru możesz namierzyć cel.""" # Soute "Frequency Jammer": name: "Z<NAME>" text: """Kiedy wykonujesz akcję Zakłócanie, wybierz 1 wrogi statek, który nie ma żetonu stresu i znajduje się w Zasięgu 1 od zakłócanego statku. Wybrany statek otrzymuje 1 żeton stresu.""" "Expanded Cargo Hold": ship: "Średni transportowiec GR-75" name: "<NAME>" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Raz na rundę, kiedy masz otrzymać odkrytą kartę uszkodznia, możesz dobrać te kartę z talii uszkodzeń dziobu lub rufy.""" "Comms Booster": name: "<NAME>" text: """<strong>Energia:</strong> Wydaj 1 żeton energii aby usunąć wszystkie żetony stresu z przyjaznego statku w Zasięgu 1-3, następnie przydziel do tego statku 1 żeton skupienia.""" "Slicer Tools": name: "<NAME>" text: """<strong>Akcja:</strong> Wybierz co najmniej 1 wrogi statek w Zasięgu 1-3, na ktorym znajduje się żeton stresu. Za każdy wybrany statek możesz wydać 1 żeton energii aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "Shield Projector": name: "<NAME>" text: """Kiedy wrogi statek stanie się podczas fazy walki, możesz wydać 3 żetony energii aby do końca fazy zmusić go do zaatakowania ciebie, jeśli to możliwe.""" "Tibanna Gas Supplies": name: "<NAME>" text: """<strong>Energia:</strong> Możesz odrzucić tę kartę aby otrzymać 3 żetony energii.""" "Ionization Reactor": name: "<NAME>" text: """<strong>Energia:</strong> Wydaj 5 żetonów energii z tej karty i odrzuć tą kartę aby sprawić żeby każdy statek w Zasięgu 1 otrzymał 1 uszkodzneie i 1 żeton jonów.""" "Engine Booster": name: "<NAME>" text: """Tuż przed tym jak odkryjesz swój wskaźnik manewrów, możesz wydać 1 żeton energii aby wykonać biały manewr (%STRAIGHT% 1). Nie możesz skorzystać z tej zdolności, jeśli w jej wyniku będziesz nachodzić na inny statek.""" "Backup Shield Generator": name: "Zapasowy generator osłon" text: """Na koniec każdej rudny możesz wydać 1 żeton energii aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "EM Emitter": name: "Emiter elektro-magnetyczny" text: """Kiedy przyblokujesz atak, obrońca rzuca 3 dodatkowymi kośmi obrony (zamiast 1).""" # Hardpiont "Ion Cannon Battery": name: "Bateria działa jonowego" text: """<strong>Atak (energia):</strong> Aby wykonać ten atak, wydaj 2 żetony energii z tej karty. Jeżeli atak ten trafi w wybrany statek, otrzymuje on 1 krytyczne uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Single Turbolasers": name: "<NAME>" text: """<strong>Atak (energia):</strong> Wydaj 2 żetony energii z tej karty aby wykonać ten atak. Obronca podwaja swoją wartość zwrotności przeciwko temu atakowi. Możesz zmienić jeden ze swoich wyników %FOCUS% na %HIT%.""" "Quad Laser Cannons": name: "Poczwórne działka laserowe" text: """<strong>Atak (energia):</strong> Wydaj 1 żeton energii z tej karty aby wykonać ten atak. Jeśli ten atak nie trafi, możesz natychmiast wydać 1 żeton energii z tej karty aby ponownie przeprowadzić ten atak.""" # Équipe "Gunnery Team": name: "<NAME>" text: """Raz na rundę kiedy atakujesz przy pomocy daodatkowej broni, możesz wydać 1 żeton energii aby zmienić 1 ze swoich pustych wyników na %HIT%.""" "Sensor Team": name: "<NAME> sensorów" text: """Kiedy namierzasz cel, możesz namierzyć wrogi statek w Zasięgu 1-5 (zamiast Zasięgu 1-3).""" "Engineering Team": name: "<NAME>" text: """Podczas fazy aktywacji, kiedy ujawnisz manewr %STRAIGHT%, otrzymujesz 1 dodatkowy żeton energii podczas kroku Otrzymywania energii.""" # Illégal "Inertial Dampeners": name: "<NAME>" text: """Kiedy ujawniasz swój manewr, możesz odrzucić tę kartę żeby zamiast tego wykonać biały manewr [0%STOP%]. Następnie otrzymujesz 1 żeton stresu.""" "Dead Man's Switch": name: "<NAME>" text: """Kiedy zostajesz zniszczony, każdy statek w Zasięgu 1 otrzymuje 1 uszkodzenie.""" "Feedback Array": name: "System zwrotny" text: """Podczas fazy walki, zamiast wykonywać jakiekolwiek ataki, możesz otrzymać 1 żeton jonów i 1 uszkodzenie aby wybrać wrogi statek w Zasięgu 1. Wybrany statek otrzymuje 1 uszkodzenie.""" '"Hot Shot" Blaster': name: "<NAME>" text: """<strong>Atak:</strong> Odrzuć tę kartę, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" # Astromech récupéré "Salvaged Astromech": name: "Astrome<NAME> z odzysku" text: "Kiedy otrzymujesz kartę uszkodzenia z cechą Statek, natychmiast możesz ją odrzucić (przed rozpatrzeniem efektu). %LINEBREAK%Następnie odrzuć tę kartę rozwinięcia.%LINEBREAK%." '"<NAME>"': name: "<NAME>" text: """Jeśli jesteś wyposażony w bombę, która może zostać zrzucona przed ujawnieniem twojego manewru, zamiast tego możesz ją zrzucić po tym jak wykonasz swój manewr.""" "Unhinged Astromech": name: "<NAME>" text: """Możesz traktować manewry o prędkości 3 jako zielone.""" "R4-B11": text: """Kiedy atakujesz namierzonego przez siebie obrońcę, możesz wydać żeton namierzonego celu aby wybrać dowolne kości obrony (nawet wszystkie). Następnie obrońca musi przerzucić wybrane przez ciebie kości.""" "R4 Agrome<NAME>": name: "<NAME>" text: """Kiedy atakujesz, po wydaniu żetonu skupienia, możesz namierzyć obrońcę.""" "<NAME>": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" '<NAME>': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" "Shield Technician": text: """%HUGESHIPONLY%%LINEBREAK%When you perform a recover action, instead of spending all of your energy, you can choose any amount of energy to spend.""" "Weapons Guidance": text: """When attacking, you may spend a focus token to change 1 of your blank results to a %HIT% result.""" "BB-8": text: """When you reveal a green maneuver, you may perform a free barrel roll action.""" "R5-X3": text: """Before you reveal your maneuver, you may discard this card to ignore obstacles until the end of the round.""" "Wired": text: """When attacking or defending, if you are stressed, you may reroll 1 or more of your %FOCUS% results.""" 'Cool Hand': text: '''When you receive a stress token, you may discard this card to assign 1 focus or evade token to your ship.''' 'Juke': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking, if you have an evade token, you may change 1 of the defender's %EVADE% results into a %FOCUS% result.''' 'Comm Relay': text: '''You cannot have more than 1 evade token.%LINEBREAK%During the End phase, do not remove an unused evade token from your ship.''' 'Dual Laser Turret': text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).''' 'Broadcast Array': text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.''' 'Rear Admiral Chiraneau': text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.''' 'Ordnance Experts': text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.''' 'Docking Clamps': text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.''' '"Zeb" Orrelios': text: """%REBELONLY%%LINEBREAK%Enemy ships inside your firing arc that you are touching are not considered to be touching you when either you or they activate during the Combat phase.""" '<NAME>': text: """%REBELONLY%%LINEBREAK%Once per round, after a friendly ship at Range 1-2 executes a white maneuver, you may remove 1 stress token from that ship.""" 'Reinforced Deflectors': text: """%LARGESHIPONLY%%LINEBREAK%After defending, if you suffered a combination of 3 or more damage and critical damage during the attack, recover 1 shield (up to your shield value).""" 'Dorsal Turret': text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the target of this attack is at Range 1, roll 1 additional attack die.""" 'Targeting Astromech': text: '''After you execute a red maneuver, you may acquire a target lock.''' '<NAME>': text: """%REBELONLY%%LINEBREAK%You may reveal and execute red maneuvers even while you are stressed.""" '<NAME>': text: """%REBELONLY%%LINEBREAK%When attacking, if you are stressed, you may change 1 of your %FOCUS% results to a %CRIT% result.""" '<NAME>': text: """%REBELONLY%%LINEBREAK%Your upgrade bar gains the %BOMB% upgrade icon. Once per round, before a friendly bomb token is removed, choose 1 enemy ship at Range 1 of that token. That ship suffers 1 damage.""" '"Chopper"': text: """%REBELONLY%%LINEBREAK%You may perform actions even while you are stressed.%LINEBREAK%After you perform an action while you are stressed, suffer 1 damage.""" 'Construction Droid': text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.''' 'Cluster Bombs': text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.''' "Adaptability": text: """<span class="card-restriction">Dual card.</span>%LINEBREAK%<strong>Side A:</strong> Increase your pilot skill value by 1.%LINEBREAK%<strong>Side B:</strong> Decrease your pilot skill value by 1.""" "Electronic Baffle": text: """When you receive a stress token or an ion token, you may suffer 1 damage to discard that token.""" "4-LOM": text: """%SCUMONLY%%LINEBREAK%When attacking, during the "Modify Attack Dice" step, you may receive 1 ion token to choose 1 of the defender's focus or evade tokens. That token cannot be spent during this attack.""" "Zuckuss": text: """%SCUMONLY%%LINEBREAK%When attacking, you may receive any number of stress tokens to choose an equal number of defense dice. The defender must reroll those dice.""" 'Rage': text: """<strong>Action:</strong> Assign 1 focus token to your ship and receive 2 stress tokens. Until the end of the round, when attacking, you may reroll up to 3 attack dice.""" "Attanni Mindlink": text: """%SCUMONLY%%LINEBREAK%Each time you are assigned a focus or stress token, each other friendly ship with Attanni Mindlink must also be assigned the same type of token if it does not already have one.""" "<NAME>": text: """%SCUMONLY%%LINEBREAK%After performing an attack, if the defender was dealt a faceup Damage card, you may discard this card to choose and discard 1 of the defender's Upgrade cards.""" "<NAME>": text: """%SCUMONLY%%LINEBREAK%When attacking, you may reroll 1 attack die. If the defender is a unique pilot, you may instead reroll up to 2 attack dice.""" '"<NAME>"': text: """%SCUMONLY%%LINEBREAK%<strong>Action:</strong> Place 1 shield token on this card.%LINEBREAK%<strong>Action:</strong> Remove 1 shield token from this card to recover 1 shield (up to your shield value).""" "R5-P8": text: """Once per round, after defending, you may roll 1 attack die. On a %HIT% result, the attacker suffers 1 damage. On a %CRIT% result, you and the attacker each suffer 1 damage.""" 'Thermal Detonators': text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 thermal detonator token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Thermal Detonator Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage and receives 1 stress token. Then discard this token.""" "Overclocked R4": text: """During the Combat phase, when you spend a focus token, you may receive 1 stress token to assign 1 focus token to your ship.""" 'Systems Officer': text: '''%IMPERIALONLY%%LINEBREAK%After you execute a green maneuver, choose another friendly ship at Range 1. That ship may acquire a target lock.''' 'Tail Gunner': text: '''When attacking from your rear-facing auxiliary firing arc, reduce the defender's agility by 1 (to a minimum of "0").''' 'R3 Astromech': text: '''Once per round, when attacking with a primary weapon, you may cancel 1 of your %FOCUS% results during the "Modify Attack Dice" step to assign 1 evade token to your ship.''' 'Collision Detector': text: '''When performing a boost, barrel roll, or decloak, your ship and maneuver template can overlap obstacles.%LINEBREAK%When rolling for obstacle damage, ignore all %CRIT% results.''' 'Sensor Cluster': text: '''When defending, you may spend a focus token to change 1 of your blank results to an %EVADE% result.''' 'Fearlessness': text: '''%SCUMONLY%%LINEBREAK%When attacking, if you are inside the defender's firing arc at Range 1 and the defender is inside your firing arc, you may add 1 %HIT% result to your roll.''' '<NAME>': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may choose 1 ship in your firing arc at Range 1-2. That ship does not remove its tractor beam tokens.''' '<NAME>': text: '''%SCUMONLY%%LINEBREAK%When defending, you may remove 1 stress token from the attacker to add 1 %EVADE% result to your roll.''' 'IG-88D': text: '''%SCUMONLY%%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).''' 'Rigged Cargo Chute': text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Discard this card to <strong>drop</strong> one cargo token.''' 'Seismic Torpedo': text: '''<strong>Action:</strong> Discard this card to choose an obstacle at Range 1-2 and inside your primary firing arc. Each ship at Range 1 of the obstacle rolls 1 attack die and suffers any damage (%HIT%) or critical damage (%CRIT%) rolled. Then remove the obstacle.''' 'Black Market Slicer Tools': text: '''<strong>Action:</strong> Choose a stressed enemy ship at Range 1-2 and roll 1 attack die. On a (%HIT%) or (%CRIT%) result, remove 1 stress token and deal it 1 facedown Damage card.''' # Wave X '<NAME>': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Assign the "I'll Show You the Dark Side" Condition card to an enemy ship at Range 1-3.''' '<NAME>': text: '''%SCUMONLY%%LINEBREAK%After executing a maneuver that causes you to overlap an enemy ship, you may suffer 1 damage to perform 1 free action.''' 'A Score to Settle': text: '''During setup, before the "Place Forces" step, choose 1 enemy ship and deal the "A Debt to Pay" Condition card to it.%LINEBREAK%Wehn attacking a ship that has the "A Debt to Pay" Condition card, you may change 1 %FOCUS% result to a %CRIT% result.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%<strong>Action:</strong> Choose 1 friendly ship at Range 1-2. Assign 1 focus token to that ship for each enemy ship inside your firing arc at Range 1-3. You cannot assign more than 3 focus tokens in this way.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%At the end of the Planning phase, you may choose an enemy ship at Range 1-2. Guess aloud that ship's bearing and speed, then look at its dial. If you are correct, you may rotate your dial to another maneuver.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%When attacking with a primary weapon or defending, if the enemy ship is inside your firing arc, you may add 1 blank result to your roll.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%At the start of the End phase, you may place 1 of your ship's focus tokens on this card. At the start of the Combat phase, you may assign 1 of those tokens to your ship.''' 'Burnout SLAM': text: '''%LARGESHIPONLY%%LINEBREAK%Your action bar gains the %SLAM% action icon.%LINEBREAK%After you perform a SLAM action, discard this card.''' 'Primed Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Stress tokens do not prevent you from performing boost or barrel roll actions unless you have 3 or more stress tokens.''' 'Pattern Analyzer': text: '''When executing a maneuver, you may resolve the "Check Pilot Stress" step after the "Perform Action" step (instead of before that step).''' 'Snap Shot': text: '''After an enemy ship executes a maneuver, you may perform this attack against that ship. <strong>Attack:</strong> Attack 1 ship. You cannot modify your attack dice and cannot attack again this phase.''' 'M9-G8': text: '''%REBELONLY%%LINEBREAK%When a ship you have locked is attacking, you may choose 1 attack die. The attacker must reroll that die.%LINEBREAK%You can acquire target locks on other friendly ships.''' 'EMP Device': text: '''During the Combat phase, instead of performing any attacks, you may discard this card to assign 2 ion tokens to each ship at Range 1.''' 'Captain Rex': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may assign 1 focus token to your ship.''' 'General Hux': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 3 friendly ships at Range 1-2. Assign 1 focus token to each and assign the "Fanatical Devotion" Condition card to 1 of them. Then receive 1 stress token.''' 'Operations Specialist': text: '''%LIMITED%%LINEBREAK%After a friendly ship at Range 1-2 performs an attack that does not hit, you may assign 1 focus token to a friendly ship at Range 1-3 of the attacker.''' 'Targeting Synchronizer': text: '''When a friendly ship at Range 1-2 is attacking a ship you have locked, the friendly ship treats the "<strong>Attack (target lock):</strong> header as "<strong>Attack:</strong>." If a game effect instructs you to spend a target lock, it may spend your target lock instead.''' 'Hyperwave Comm Scanner': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0," "6," or "12" until the end of the step.%LINEBREAK%During setup, after another friendly ship is placed at Range 1-2, you may assign 1 focus or evade token to it.''' 'Trick Shot': text: '''When attacking, if the attack is obstructed, you may roll 1 additional attack die.''' 'Hotshot Co-pilot': text: '''When attacking with a primary weapon, the defender must spend 1 focus token if able.%LINEBREAK%When defending, the attacker must spend 1 focus token if able.''' '''Scavenger Crane''': text: '''After a ship at Range 1-2 is destroyed, you may choose a discarded %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, or Modification Upgrade card that was equipped to your ship and flip it faceup. Then roll 1 attack die. On a blank result, discard Scavenger Crane.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%When you acquire a target lock, you can lock onto an enemy ship at Range 1-3 of any friendly ship.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack against a different ship. You cannot perform another attack this round.''' 'Inspiring Recruit': text: '''Once per round, when a friendly ship at Range 1-2 removes a stress token, it may remove 1 additional stress token.''' 'Swarm Leader': text: '''When performing a primary weapon attack, choose up to 2 other friendly ships that have the defender inside their firing arcs at Range 1-3. Remove 1 evade token from each chosen ship to roll 1 additional attack die for each token removed.''' 'Bistan': text: '''%REBELONLY%%LINEBREAK%When attacking Range 1-2, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Expertise': text: '''When attacking, if you are not stressed, you may change all of your %FOCUS% results to %HIT% results.''' 'BoShek': text: '''When a ship you are touching activates, you may look at its chosen maneuver. If you do, its owner <strong>must</strong> rotate the dial to an adjacent maneuver. The ship can reveal and execute that maneuver even while stressed.''' # C-ROC 'Heavy Laser Turret': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack against 1 ship (even a ship outside of your firing arc).''' '<NAME>': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may discard this card to replace a faceup %ILLICIT% or %CARGO% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Azmorigan': text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%At the start of the End phase, you may spend 1 energy to replace a faceup %CREW% or %TEAM% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Quick-release Cargo Locks': text: '''%LINEBREAK%At the end of the Activation phase, you may discard this card to <strong>place</strong> 1 container token.''' 'Supercharged Power Cells': text: '''When attacking, you may discard this card to roll 2 additional attack dice.''' 'ARC Caster': text: '''<span class="card-restriction">Rebel and Scum only.</span>%DUALCARD%%LINEBREAK%<strong>Side A:</strong>%LINEBREAK%<strong>Attack:</strong> Attack 1 ship. If this attack hits, you must choose 1 other ship at Range 1 of the defender to suffer 1 damage.%LINEBREAK%Then flip this card.%LINEBREAK%<strong>Side B:</strong>%LINEBREAK%(Recharging) At the start of the Combat phase, you may receive a weapons disabled token to flip this card.''' 'W<NAME>': text: '''When attacking, you may reroll your %FOCUS% results.''' 'Synced Turret': text: '''<strong>Attack (Target Lock):</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the defender is inside your primary firing arc, you may reroll a number of attack dice up to your primary weapon value.''' 'Unguided Rockets': text: '''<strong>Attack (focus):</strong> Attack 1 Ship.%LINEBREAK%Your attack dice can be modified only by spending a focus token for its standard effect.''' 'Intensity': text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Side A:</strong> After you perform a boost or barrel roll action, you may assign 1 focus or evade token to your ship. If you do, flip this card.%LINEBREAK%<strong>Side B:</strong> (Exhausted) At the end of the Combat phase, you may spend 1 focus or evade token to flip this card.''' '<NAME>': text: '''%SCUMONLY%%LINEBREAK%When you equip this card, place 1 illicit token on each %ILLICIT% Upgrade card in your squad. When you are instructed to discard an Upgrade card, you may discard 1 illicit token on that card instead.''' 'IG-RM Thug Droids': text: '''When attacking, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Selflessness': text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%When a friendly ship at Range 1 is hit by an attack, you may discard this card to suffer all uncanceled %HIT% results instead of the target ship.''' 'Breach Specialist': text: '''When you are dealt a faceup Damage card, you may spend 1 reinforce token to flip it facedown (without resolving its effect). If you do, until the end of the round, when you are dealt a faceup Damage card, flip it facedown (without resolving its effect).''' 'R4-E1': text: '''You can perform actions on your %TORPEDO% and %BOMB% Upgrade cards even if you are stressed. After you perform an action in this way, you may discard this card to remove 1 stress token from your ship.''' 'Cruise Missiles': text: '''<strong>Attack (Target Lock):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to the speed of the manuever you performed this round, to a maximum of 4 additional dice.''' 'Ion Dischargers': text: '''After you receive an ion token, you may choose an enemy ship at Range 1. If you do, remove that ion token. Then that ship may choose to receive 1 ion token. If it does, discard this card.''' 'Harpoon Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, assign the "Harpooned!" Condition to the defender.''' 'Ordnance Silos': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When you equip this card, place 3 ordnance tokens on each other equipped %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.''' 'Trajectory Simulator': text: '''You may launch bombs using the (%STRAIGHT% 5) template instead of dropping them. You cannot launch bombs with the "<strong>Action:</strong>" header in this way.''' 'Jamming Beam': text: '''<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, assign the defender 1 jam token. Then cancel <strong>all</strong> dice results.''' 'Linked Battery': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking with a primary or %CANNON% secondary weapon, you may reroll 1 attack die.''' 'Saturation Salvo': text: '''After you perform an attack with a %TORPEDO% or %MISSILE% secondary weapon that does not hit, each ship at Range 1 of the defender with an agility value lower than the squad point cost of the %TORPEDO% or %MISSILE% Upgrade card must roll 1 attack die and suffer any damage (%HIT%) or critical damage (%CRIT%) rolled.''' 'Contraband Cybernetics': text: '''When you become the active ship during the Activation phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, you may perform actions and red maneuvers even while you are stressed.''' 'Maul': text: '''%SCUMONLY% <span class="card-restriction">Ignore this restriction if your squad contains "Ezra Bridger."</span>%LINEBREAK%When attacking, if you are not stressed, you may receive any number of stress tokens to reroll that many attack dice.%LINEBREAK%After performing an attack that hits, you may remove 1 of your stress tokens.''' 'Courier Droid': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0" or "8" until the end of the step.''' '"Chopper" (Astromech)': text: '''<strong>Action: </strong>Discard 1 other equipped Upgrade card to recover 1 shield.''' 'Flight-Assist Astromech': text: '''You cannot attack ships outside your firing arc.%LINEBREAK%After you execute a maneuver, if you did not overlap a ship or obstacle and there are no enemy ships inside your firing arc at Range 1-3, you may perform a free boost or barrel roll action.''' 'Advanced Optics': text: '''You cannot have more than 1 focus token.%LINEBREAK%During the End phase, do not remove an unused focus token from your ship.''' 'Scrambler Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each other ship at Range 1 receives 1 jam token. Then cancel <strong>all</strong> results.''' 'R5-TK': text: '''You can acquire target locks on friendly ships.%LINEBREAK%You can attack friendly ships.''' 'Threat Tracker': text: '''%SMALLSHIPONLY%%LINEBREAK%When an enemy ship inside your firing arc at Range 1-2 becomes thee active ship during the Combat phase, you may spend your target lock on that ship to perform a free boost or barrell roll action if that action is on your action bar.''' '<NAME>': text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Assign 1 evade token to your ship for each obstacle at Range 1, to a maximum of 2 evade tokens.''' 'Targeting Scrambler': text: '''At the start of the Planning phase, you may receive a weapons disabled token to choose a ship at Range 1-3 and assign it the "Scrambled" Condition.''' 'Death Troopers': text: '''After another friendly ship at range 1 becomes the defender, if you are inside the attacker's firing arc at range 1-3, the attacker receives 1 stress token.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%When attacking, you may suffer 1 damage to change all of your %FOCUS% results to %CRIT% results.''' '<NAME>': text: '''During setup, before the "Place Forces" step, assign the "Optimized Prototype" condition to a friendly Galactic Empire ship with 3 or fewer shields.''' '<NAME>': text: '''%REBELONLY%%LINEBREAK%After defending, you may acquire a target lock on the attacker.''' 'Renegade Refit': text: '''<span class="card-restriction">T-65 X-Wing and U-Wing only.</span>%LINEBREAK%You can equip up to two different Modification upgrades.%LINEBREAK%The squad point cost of each of your equipped %ELITE% upgrades is reduced by 1 (to a minimum of 0).''' 'Tactical Officer': text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.''' 'ISB Slicer': text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.''' 'Thrust Corrector': text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.''' modification_translations = "Shield Upgrade": name: "Ulepszenie osłon" text: """Zwiększ wartość swoich osłon o 1.""" "Advanced Cloaking Device": name: "Zaawansowany system maskowania" text: """<span class="card-restriction">Tylko TIE Phantom.</span>%LINEBREAK%Po tym jak wykonasz atak, możesz wykonać darmową akcję maskowanie.""" ship: "TIE Phantom" "Stealth Device": name: "Urządzenie maskujące" text: """Zwiększ wartość swojej zwrotności o 1. Jeśli zostaniesz trafiony podczas ataku, odrzuć tę kartę.""" "Engine Upgrade": name : "Ulepszenie silnika" text: """Twój pasek rozwinięć zyskuje symbol akcji %BOOST%.""" "Anti-Pursuit Lasers": name: "Lasery antypościg<NAME>" text: """%PL_LARGESHIPONLY%Po tym jak wrogi statek wykona manewr, który sprawi że będzie zachodzić na ciebie, rzuć 1 kością ataku. Jeśli wypadnie %HIT% lub %CRIT%, wrogi statek otrzymuje 1 uszkodzenie.""" "Targeting Computer": name: "Komputer celowniczy" text: """Twój pasek akcji zyskuje symbol akcji %TARGETLOCK%.""" "Hull Upgrade": name: "Ulepszenie kadłuba" text: """Zwiększ wartość swojego kadłuba o 1.""" "Munitions Failsafe": name: "Zabezpieczenie amunicji" text: """Kiedy atakujesz przy pomocy broni dodatkowej, która nakazuje odrzucenie karty po wykonaniu ataku, nie odrzucasz jej jeśli atak nie trafi.""" "Stygium Particle Accelerator": name: "Akcelerator cząsteczek stygium" text: """Kiedy się demaskujesz lub wykonasz akcję maskowanie, możesz wykonać darmową akcję unik.""" "Combat Retrofit": name: "Modyfikacja bojowa" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Zwiększ wartość swojego kadłuba o 2 i wartość swoich osłon o 1.""" ship: "Transport moyen GR-75" "B-Wing/E2": text: """<span class="card-restriction">Tylko B-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %CREW%.""" "Countermeasures": name: "Środki profilaktyczne" text: """%PL_LARGESHIPONLY%%LINEBREAK%Na początku fazy walki możesz odrzucić tę kartę, aby do końca rundy zwiększyć swoją zwrotność o 1. Następnie możesz usunąć ze swojego statku 1 wrogi żeton namierzonego celu.""" "Experimental Interface": name: "Eksperymentalny interfejs" text: """Raz na rundę. Po tym jak wykonasz akcję możesz wykonać 1 darmową akcję z karty rozwinięcia z nagłówkiem <strong>Akcja:</strong>, w którą jesteś wyposażony. Następnie otrzymujesz 1 żeton stresu.""" "Tactical Jammer": name: "<NAME>" text: """%PL_LARGESHIPONLY%%LINEBREAK%Twój statek może przyblokowywać wrogie ataki.""" "Autothrusters": name: "<NAME>" text: """Kiedy się bronisz, jeśli jesteś poza Zasięgiem 2 albo znajdujesz się poza polem rażenia atakującego, możesz zmienić 1 ze swoich pustych wyników na %EVADE%. Możesz wyposażyć swój statek w tę kartę tylko jeśli masz symbol akcji %BOOST%.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" 'Integrated Astromech': text: '''<span class="card-restriction">X-wing only.</span>%LINEBREAK%When you are dealt a Damage card, you may discard 1 of your %ASTROMECH% Upgrade cards to discard that Damage card.''' 'Optimized Generators': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, when you assign energy to an equipped Upgrade card, gain 2 energy.''' 'Automated Protocols': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, after you perform an action that is not a recover or reinforce action, you may spend 1 energy to perform a free recover or reinforce action.''' 'Ordnance Tubes': text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.''' 'Long-Range Scanners': text: '''You can acquire target locks on ships at Range 3 and beyond. You cannot acquire target locks on ships at Range 1-2. You can equip this card only if you have %TORPEDO% and %MISSILE% in your upgrade bar.''' "Guidance Chips": text: """Once per round, when attacking with a %TORPEDO% or %MISSILE% secondary weapon, you may change 1 die result to a %HIT% result (or a %CRIT% result if your primary weapon value is "3" or higher).""" 'Vectored Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Your action bar gains the %BARRELROLL% action icon.''' 'Smuggling Compartment': text: '''<span class="card-restriction">YT-1300 and YT-2400 only.</span>%LINEBREAK%Your upgrade bar gains the %ILLICIT% upgrade icon.%LINEBREAK%You may equip 1 additional Modification upgrade that costs 3 or fewer squad points.''' 'Gyroscopic Targeting': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%At the end of the Combat phase, if you executed a 3-, 4-, or 5-speed maneuver this round, you may rotate your mobile firing arc.''' 'Captured TIE': text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Enemy ships with a pilot skill value lower than yours cannot declare you as the target of an attack. After you perform an attack or when you are the only remaining friendly ship, discard this card.''' 'Spacetug Tractor Array': text: '''<span class="card-restriction">Quadjumper only.</span>%LINEBREAK%<strong>Action:</strong> Choose a ship inside your firing arc at Range 1 and assign a tractor beam token to it. If it is a friendly ship, resolve the effect of the tractor beam token as though it were an enemy ship.''' 'Lightweight Frame': text: '''<span class="card-restriction">TIE only.</span>%LINEBREAK%When defending, after rolling defense dice, if there are more attack dice than defense dice, roll 1 additional defense die.%LINEBREAK%You cannot equip this card if your agility value is "3" or higher.''' 'Pulsed Ray Shield': text: '''<span class="card-restriction">Rebel and Scum only.</span>%LINEBREAK%During the End phase, you may receive 1 ion token to recover 1 shield (up to your shield value). You can equip this card only if your shield value is "1."''' 'Deflective Plating': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When a friendly bomb token detonates, you may choose not to suffer its effects. If you do, roll an attack die. On a %HIT% result, discard this card.''' 'Servomotor S-Foils': text: '''<span class="card-restriction">T-65 X-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong>Your action bar gains %BARRELROLL%. If you are not stressed, when you reveal a (%TURNLEFT% 3) or (3 %TURNRIGHT%) maneuver, you may treat it as a red (%TROLLLEFT% 3) or (%TROLLRIGHT% 3) in the same direction.%LINEBREAK%At the start of the Activation phase, you may flip this card.%LINEBREAK%<strong>Side B (Closed):</strong>Reduce your primary attack value by 1. Your action bar gains %BOOST%. Treat your (%BANKLEFT% 2) and (%BANKRIGHT% 2 ) as green.%LINEBREAK%At the start of the Activation phase, you may flip this card.''' 'Multi-spectral Camouflage': text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.''' title_translations = "Slave I": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %TORPEDO%.""" "M<NAME>ium <NAME>": name: "<NAME>" text: """<span class="card-restriction">Tylko YT-1300.</span>%LINEBREAK% Twój pasek akcji zyskuje symbol akcji %EVADE%.""" "<NAME>": text: """<span class="card-restriction">Tylko HWK-290.</span>%LINEBREAK%Podczas fazy końcowej nie usuwaj ze swojego statku niewykorzystanych żetonów skupienia.""" "ST-321": ship: "Prom typu Lambda" text: """<span class="card-restriction">Navette de classe <em>Lambda</em> uniquement.</span>%LINEBREAK%Quand vous verrouillez une cible, vous pouvez verrouiller n'importe quel vaisseau ennemi situé dans la zone de jeu.""" "Royal Guard TIE": ship: "TIE Interceptor" name: "<NAME>" text: """<span class="card-restriction">Tylko TIE Interceptor.</span>%LINEBREAK%Możesz dołączyć do swojego statku maksymalnie 2 różne karty Modyfikacji (zamiast 1). Nie możesz dołączyć tej karty do swojego statku, jeśli wartość umiejętności pilota wynosi "4" lub mniej.""" "Dod<NAME>'s Pride": name: "<NAME>" ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy wykonujesz akcję "Koordynacja", możesz wybrać 2 przyjazne statki (zamiast 1). Statki te mogą wykonać po 1 darmowej akcji.""" "A-Wing Test Pilot": name: "Pilot testowy A-winga" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %ELITE%. Nie możesz wyposażyć się w 2 takie same karty rozwinięcia [elite talent]. Nie możesz wyposażyć się w tę kartę, jeśli twoja wartość umiejętności pilota wynosi "1" lub mniej.""" "Tantive IV": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Twój pasek rozwinięć sekcji dziobowej zyskuje po 1 symbolu rozwinięcia %CREW% i %TEAM%.""" "Bright Hope": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Żetony wsparcia przypisane do twojej sekcji dziobowej dostają 2 wyniki %EVADE% (zamiast 1).""" "Quantum Storm": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Na początku fazy końcowej, jeśli masz nie więcej niż 1 żeton energi, otrzymujesz 1 żeton energii.""" "Dutyfree": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Kiedy wykonujesz akcję Zakłócenie, możesz wybrać wrogi statek w Zasięgu 1-3 (zamiast Zasięgu 1-2).""" "Jaina's Light": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy się bronisz, raz na atak, jeśli otrzymujesz odkrytą kartę uszkodzenia, możesz ją odrzucić i dobrać nową odkrytą kartę uszkodzenia.""" "Outrider": text: """<span class="card-restriction">Tylko YT-2400.</span>%LINEBREAK%Dopóki jesteś wyposażony w kartę rozwinięcia [cannon], nie możesz wykonywać ataków bronią podstawową. Przy pomocy dodatkowej broni [cannon] możesz wykonywać ataki skierowane przeciwko statkom znajdujacym się poza twoim polem rażenia. """ "Dauntless": ship: 'Decimator VT-49' text: """<span class="card-restriction">Tylko Decimator VT-49.</span>%LINEBREAK%Po tym jak wykonasz manewr, który sprawi że będziesz nachodzić na inny statek, możesz wykonać 1 darmową akcję. Następnie otrzymujesz 1 żeton stresu.""" "<NAME>": text: """<span class="card-restriction">Tylko StarViper.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbole rozwinięć %SYSTEM% i %ILLICIT%. Nie możesz wyposażyć swojego statku w tę kartę jeśli wartość umiejętności twojego pilota wynosi „3” lub mniej.""" '"Heavy Scyk" Interceptor (Cannon)': name: 'Interceptor typu Heavy Scyk (Działo)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Torpedo)': name: 'Interceptor typu Heavy Scyk (Torpeda)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Missile)': name: 'Intercepteur "<NAME>" (Rakieta)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" "IG-2000": text: """<span class="card-restriction">Tylko Aggressor.</span>%LINEBREAK%Masz zdolność pilota każdego innego przyjaznego statku z kartą ulepszenia IG-2000 (jako dodatek do swojej zdolności pilota).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Tylko Y-wing.</span>%LINEBREAK%Nie możesz atakować statków znajdujących się poza twoim polem rażenia. Po wykonaniu ataku przy pomocy broni podstawowej, możesz natychmiast wykonać atak przy pomocy dodatkowej broni %TURRET%.""" "Andrasta": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje dwa symbole %BOMB%.""" "TIE/x1": text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %SYSTEM%. %LINEBREAK%Koszt przypisanej do tego statku karty rozwinięcia %SYSTEM% jest obniżony o 4 punkty (do minimum 0).""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "<NAME>": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "Punishing One": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" "Assailer": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%When defending, if the targeted section has a reinforce token, you may change 1 %FOCUS% result to a %EVADE% result.""" "Instigator": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform a recover action, recover 1 additional shield.""" "Impetuous": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform an attack that destroys an enemy ship, you may acquire a target lock.""" 'TIE/x7': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Your upgrade bar loses the %CANNON% and %MISSILE% upgrade icons.%LINEBREAK%After executing a 3-, 4-, or 5-speed maneuver, you may assign 1 evade token to your ship.''' 'TIE/D': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Once per round, after you perform an attack with a %CANNON% secondary weapon that costs 3 or fewer squad points, you may perform a primary weapon attack.''' 'TIE Shuttle': ship: 'Bombowiec TIE' text: '''<span class="card-restriction">TIE Bomber only.</span>%LINEBREAK%Your upgrade bar loses all %TORPEDO%, %MISSILE%, and %BOMB% upgrade icons and gains 2 %CREW% upgrade icons. You cannot equip a %CREW% Upgrade card that costs more than 4 squad points.''' 'Requiem': text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.''' 'Vector': text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).''' 'Suppressor': text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.''' 'Black One': text: '''After you perform a boost or barrel roll action, you may remove 1 enemy target lock from a friendly ship at Range 1. You cannot equip this card if your pilot skill is "6" or lower.''' 'Millennium Falcon (TFA)': text: '''After you execute a 3-speed bank maneuver (%BANKLEFT% or %BANKRIGHT%), if you are not touching another ship and you are not stressed, you may receive 1 stress token to rotate your ship 180&deg;.''' 'Alliance Overhaul': text: '''<span class="card-restriction">ARC-170 only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. When attacking from your auxiliary firing arc, you may change 1 of your %FOCUS% results to a %CRIT% result.''' 'Special Ops Training': text: '''<span class="card-restriction">TIE/sf only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. If you do not, you may perform an additional attack from your auxiliary firing arc.''' 'Concord Dawn Protector': text: '''<span class="card-restriction">Protectorate Starfighter only.</span>%LINEBREAK%When defending, if you are inside the attacker's firing arc and at Range 1 and the attacker is inside your firing arc, add 1 %EVADE% result.''' 'Shadow Caster': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%After you perform an attack that hits, if the defender is inside your mobile firing arc and at Range 1-2, you may assign the defender 1 tractor beam token.''' # Wave X '''Sabine's Masterpiece''': ship: 'Myśliwiec TIE' text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Your upgrade bar gains the %CREW% and %ILLICIT% upgrade icons.''' '''Kylo Ren's Shuttle''': text: '''<span class="card-restriction">Upsilon-class Shuttle only.</span>%LINEBREAK%At the end of the Combat phase, choose an unstressed enemy ship at Range 1-2. Its owner must assign a stress token to it or assign a stress token to another ship at Range 1-2 of you that that player controls.''' '''Pivot Wing''': text: '''<span class="card-restriction">U-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong> Increase your agility by 1.%LINEBREAK%After you execute a maneuver, you may flip this card.%LINEBREAK%<strong>Side B (Landing):</strong> When you reveal a (0 %STOP%) maneuver, you may rotate your ship 180&deg;.%LINEBREAK%After you execute a maneuver, you may flip this card.''' '''Adaptive Ailerons''': text: '''<span class="card-restriction">TIE Striker only.</span>%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you <strong>must</strong> execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' # C-ROC '''Merchant One''': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%Your upgrade bar 1 additional %CREW% upgrade icon and 1 additional %TEAM% upgrade icon and loses 1 %CARGO% upgrade icon.''' '''"Light Scyk" Interceptor''': text: '''<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%All Damage cards dealt to you are dealt faceup. You may treat all bank maneuvers (%BANKLEFT% or %BANKRIGHT%) as green maneuvers. You cannot equip Modification upgrades.''' '''Insatiable Worrt''': text: '''After you perform the recover action, gain 3 energy.''' '''Broken Horn''': text: '''When defending, if you have a reinforce token, you may add 1 additional %EVADE% result. If you do, after defending, discard your reinforce token.''' 'Havoc': text: '''<span class="card-restriction">Scurrg H-6 Bomber only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %SALVAGEDASTROMECH% icons and loses the %CREW% upgrade icon.%LINEBREAK%You cannot equip non-unique %SALVAGEDASTROMECH% Upgrade cards.''' 'Vaksai': text: '''<span class="card-restriction">Kihraxz Fighter only.</span>%LINEBREAK%The squad point cost of each of your equipped upgrades is reduced by 1 (to a minimum of 0).%LINEBREAK%You may equip up to 3 different Modification upgrades.''' 'StarViper Mk. II': text: '''<span class="card-restriction">StarViper only.</span>%LINEBREAK%You may equip up to 2 different title Upgrades.%LINEBREAK%When performing a barrel roll action, you <strong>must</strong> use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.''' 'XG-1 Assault Configuration': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains 2 %CANNON% icons.%LINEBREAK%You may perform attacks with %CANNON% secondary weapons that cost 2 or fewer points even while you have a weapons disabled token.''' 'Enforcer': text: '''<span class="card-restriction">M12-L Kimogila Fighter only.</span>%LINEBREAK%After defending, if the attacker is inside your bullseye firing arc, the attacker receives 1 stress token.''' 'Ghost (Phantom II)': text: '''<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom II</em> title card to a friendly <em>Sheathipede</em>-class shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.''' 'Phantom II': text: '''While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc.%LINEBREAK%While you are docked, at the end of the Activation phase, the <em>Ghost</em> may perform a free coordinate action.''' 'First Order Vanguard': text: '''<span class="card-restriction">TIE Silencer only.</span>%LINEBREAK%When attacking, if the defender is the only ship in your firing arc at Range 1-3, you may reroll 1 attack die.%LINEBREAK%When defending, you may discard this card to reroll all of your defense dice.''' 'Os-1 Arsenal Loadout': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% and %MISSILE% icons.%LINEBREAK%You may perform attacks with %TORPEDO% and %MISSILE% secondary weapons against ships you have locked even while you have a weapons disabled token.''' 'Crossfire Formation': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When defending, if there is at least 1 other friendly Resistance ship at Range 1-2 of the attacker with the Crossfire Formation Upgrade card, you may add 1 %FOCUS% result to your roll.''' 'Advanced Ailerons': text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' condition_translations = '''I'll Show You the Dark Side''': text: '''When this card is assigned, if it is not already in play, the player who dealt it searches the Damage deck for 1 Damage card with the <strong><em>Pilot</em></strong> trait and may place it faceup on this card. Then shuffle the damage deck.%LINEBREAK%When you suffer critical damage from an attack, you are instead dealt the chosen faceup Damage card.%LINEBREAK%When there is no Damage card on this card, remove it.''' 'Suppressive Fire': text: '''When attacking a ship other than "Captain Rex," roll 1 fewer attack die.%LINEBREAK% When you declare an attack targeting "Captain Rex" or when "Captain Rex" is destroyed, remove this card.%LINEBREAK%At the end of the Combat phase, if "Captain Rex" did not perform an attack this phase, remove this card.''' 'Fanatical Devotion': text: '''When defending, you cannot spend focus tokens.%LINEBREAK%When attacking, if you spend a focus token to change all %FOCUS% results to %HIT% results, set aside the first %FOCUS% result that you change. The set-aside %HIT% result cannot be canceled by defense dice, but the defender may cancel %CRIT% results before it.%LINEBREAK%During the End phase, remove this card.''' 'A Debt to Pay': text: '''When attacking a ship that has the "A Score to Settle" Upgrade card equipped, you may change 1 %FOCUS% result to a %CRIT% result.''' 'Shadowed': text: '''"Thweek" is treated as having the pilot skill value you had after setup.%LINEBREAK%The pilot skill value of "Thweek" does not change if your pilot skill value changes or you are destroyed.''' 'Mimicked': text: '''"Thweek" is treated as having your pilot ability.%LINEBREAK%"Thweek" cannot apply a Condition card by using your pilot ability.%LINEBREAK%"Thweek" does not lose your pilot ability if you are destroyed.''' 'Harpooned!': text: '''When you are hit by an attack, if there is at least 1 uncanceled %CRIT% result, each other ship at Range 1 suffers 1 damage. Then discard this card and receive 1 facedown Damage card.%LINEBREAK%When you are destroyed, each ship at Range 1 suffers 1 damage.%LINEBREAK%<strong>Action:</strong> Discard this card. Then roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.''' 'Rattled': text: '''When you suffer damage from a bomb, you suffer 1 additional critical damage. Then, remove this card.%LINEBREAK%<strong>Action:</strong> Roll 1 attack die. On a %FOCUS% or %HIT% result, remove this card.''' 'Scrambled': text: '''When attacking a ship at Range 1 that is equipped with the "Targeting Scrambler" upgrade, you cannot modify attack dice.%LINEBREAK%At the end of the combat phase, remove this card.''' 'Optimized Prototype': text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "<NAME>" Upgrade card may acquire a target lock on the defender.''' exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
true
exportObj = exports ? this exportObj.codeToLanguage ?= {} exportObj.codeToLanguage.pl = 'Polski' exportObj.translations ?= {} # This is here mostly as a template for other languages. exportObj.translations['Polski'] = action : "Barrel Roll": "Beczka" "Boost": "Dopalacz" "Evade": "Unik" "Focus": "Skupienie" "Target Lock": "Namierzenie celu" "Recover": "Naprawa" "Reinforce": "Umocnienie" "Jam": "Zakłócanie" "Coordinate": "Koordynacja" "Cloak": "Maskowanie" slot: "Astromech": "Astromech" "Bomb": "Bomba" "Cannon": "Działo" "Crew": "Załoga" "Elite": "Talent elitarny" "Missile": "Rakiety" "System": "System" "Torpedo": "Torpedy" "Turret": "Wieżyczka" "Cargo": "Ładunek" "Hardpoint": "Punkt konstrukcyjny" "Team": "Drużyna" "Illicit": "Kontrabanda" "Salvaged Astromech": "Złomowane astromechy" sources: # needed? "Core": "Zestaw Podstawowy" "A-Wing Expansion Pack": "Zestaw dodatkowy A-Wing" "B-Wing Expansion Pack": "Zestaw dodatkowy B-Wing" "X-Wing Expansion Pack": "Zestaw dodatkowy X-Wing" "Y-Wing Expansion Pack": "Zestaw dodatkowy Y-Wing" "Millennium Falcon Expansion Pack": "Zestaw dodatkowy Sokół Millennium" "HWK-290 Expansion Pack": "Zestaw dodatkowy HWK-290" "TIE Fighter Expansion Pack": "Zestaw dodatkowy Myśliwiec TIE" "TIE Interceptor Expansion Pack": "Zestaw dodatkowy TIE Interceptor" "TIE Bomber Expansion Pack": "Zestaw dodatkowy Bombowiec TIE" "TIE Advanced Expansion Pack": "Zestaw dodatkowy TIE Advanced" "Lambda-Class Shuttle Expansion Pack": "Zestaw dodatkowy Prom typu Lambda" "Slave I Expansion Pack": "Zestaw dodatkowy Slave I" "Imperial Aces Expansion Pack": "Zestaw dodatkowy Asy Imperium" "Rebel Transport Expansion Pack": "Zestaw dodatkowy Rebeliancki transportowiec" "Z-95 Headhunter Expansion Pack": "Zestaw dodatkowy Z-95 Łowca Głów" "TIE Defender Expansion Pack": "Zestaw dodatkowy TIE Defender" "E-Wing Expansion Pack": "Zestaw dodatkowy E-Wing" "TIE Phantom Expansion Pack": "Zestaw dodatkowy TIE Phantom" "Tantive IV Expansion Pack": "Zestaw dodatkowy Tantive IV" "Rebel Aces Expansion Pack": "Zestaw dodatkowy Asy Rebelii" "YT-2400 Freighter Expansion Pack": "Zestaw dodatkowy YT-2400" "VT-49 Decimator Expansion Pack": "Zestaw dodatkowy Decimator VT-49" "StarViper Expansion Pack": "Zestaw dodatkowy StarViper" "M3-A Interceptor Expansion Pack": "Zestaw dodatkowy M3-A Interceptor" "IG-2000 Expansion Pack": "Zestaw dodatkowy IG-2000" "Most Wanted Expansion Pack": "Zestaw dodatkowy Poszukiwani" "Imperial Raider Expansion Pack": "Zestaw dodatkowy Imperialny Patrolowiec" "The Force Awakens Core Set": "The Force Awakens Core Set" ui: shipSelectorPlaceholder: "Wybór statków" pilotSelectorPlaceholder: "Wybór pilotów" upgradePlaceholder: (translator, language, slot) -> "#{translator language, 'slot', slot}" modificationPlaceholder: "Modyfikacje" titlePlaceholder: "Tytuł" upgradeHeader: (translator, language, slot) -> "Amélioration #{translator language, 'slot', slot}" unreleased: "niewydane" epic: "epickie" byCSSSelector: # Warnings '.unreleased-content-used .translated': 'This squad uses unreleased content!</span>' '.epic-content-used .translated': 'This squad uses Epic content!' '.illegal-epic-too-many-small-ships .translated': 'You may not field more than 12 of the same type Small ship!' '.illegal-epic-too-many-large-ships .translated': 'You may not field more than 6 of the same type Large ship!' '.collection-invalid .translated': 'You cannot field this list with your collection!' # Type selector '.game-type-selector option[value="standard"]': 'Standard' '.game-type-selector option[value="custom"]': 'Custom' '.game-type-selector option[value="epic"]': 'Epic' '.game-type-selector option[value="team-epic"]': 'Team Epic' # Card browser '.xwing-card-browser .translate.sort-cards-by': 'Sortuj karty po' '.xwing-card-browser option[value="name"]': 'nazwie' '.xwing-card-browser option[value="source"]': 'źródle' '.xwing-card-browser option[value="type-by-points"]': 'typie (po punktach)' '.xwing-card-browser option[value="type-by-name"]': 'typie (po nazwie)' '.xwing-card-browser .translate.select-a-card': 'Wybierz kartę z listy po prawej' '.xwing-card-browser .info-range td': 'Zasięg’' # Info well '.info-well .info-ship td.info-header': 'Statek' '.info-well .info-skill td.info-header': 'Umiejętność pilota' '.info-well .info-actions td.info-header': 'Akcje' '.info-well .info-upgrades td.info-header': 'Ulepszenia' '.info-well .info-range td.info-header': 'Zasięg' # Squadron edit buttons '.clear-squad' : 'Wyczyść eskadrę' '.save-list' : 'Zapisz' '.save-list-as' : 'Zapisz jako ...' '.delete-list' : 'Usuń' '.backend-list-my-squads' : 'Lista eskadr' '.view-as-text' : '<span class="hidden-phone"><i class="fa fa-print"></i>&nbsp;Drukuj \ Wyświetl jako </span>Tekst' '.randomize' : 'randomizuj' '.randomize-options' : 'Opcje ...' '.notes-container > span' : 'Squad Notes' # Print/View modal '.bbcode-list' : 'Skopiuj BBCode poniżej i wklej go do swojego posta.<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.html-list' : '<textarea></textarea><button class="btn btn-copy">Skopiuj</button>' '.vertical-space-checkbox' : """Dodaj miejsce na karty ulepszeń \ uszkodzeń podczas drukowania <input type="checkbox" class="toggle-vertical-space" />""" '.color-print-checkbox' : """Wydrukuj w kolorze <input type="checkbox" class="toggle-color-print" />""" '.print-list' : '<i class="fa fa-print"></i>&nbsp;Drukuj' # Randomizer options '.do-randomize' : 'Generuj' # Top tab bar '#empireTab' : 'Imperium Galaktyczne' '#rebelTab' : 'Sojusz Rebeliancki' '#scumTab' : 'Szumowiny i Nikczemnicy' '#browserTab' : 'Przeglądarka kart' '#aboutTab' : 'O stronie' singular: 'pilots': 'Pilot' 'modifications': 'Modyfikacja' 'titles': 'Tytuł' types: 'Pilot': 'Pilot' 'Modification': 'Modyfikacja' 'Title': 'Tytuł' exportObj.cardLoaders ?= {} exportObj.cardLoaders['Polski'] = () -> exportObj.cardLanguage = 'Polski' # Assumes cards-common has been loaded basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards # English names are loaded by default, so no update is needed exportObj.ships = basic_cards.ships # Rename ships exportObj.renameShip 'TIE Fighter', 'Myśliwiec TIE' exportObj.renameShip 'TIE Bomber', 'Bombowiec TIE' exportObj.renameShip 'Lambda-Class Shuttle', 'Prom typu Lambda' exportObj.renameShip 'VT-49 Decimator', 'Decimator VT-49' exportObj.renameShip 'Z-95 Headhunter', 'Z-95 Łowca głów' exportObj.renameShip 'CR90 Corvette (Aft)', 'Korweta CR90 (rufa)' exportObj.renameShip 'CR90 Corvette (Fore)', 'Corvette CR90 (dziób)' exportObj.renameShip 'GR-75 Medium Transport', 'Średni transportowiec GR-75' # Names don't need updating, but text needs to be set pilot_translations = # Empire # Myśliwiec TIE "Academy Pilot": ship: "Myśliwiec TIE" name: "Pilot z Akademii" "Obsidian Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry Obsydianowych" "Black Squadron Pilot": ship: "Myśliwiec TIE" name: "Pilot Eskadry CPI:NAME:<NAME>END_PI" '"PI:NAME:<NAME>END_PI"': name: "PI:NAME:<NAME>END_PI" ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" '"Night Beast"': name: "PI:NAME:<NAME>END_PI" ship: "Myśliwiec TIE" text: """Po wykonaniu zielonego manewru możesz wykonać darmową akcję skupienia.""" '"Backstabber"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz będąc poza polem rażenia broniącego się statku, rzucasz 1 dodatkową kością ataku.""" '"Dark Curse"': name: "PI:NAME:<NAME>END_PI" ship: "Myśliwiec TIE" text: """Kiedy się bronisz statki które cię atakują nie mogą wydawać żetonów skupienia ani przerzucać kości ataku.""" '"PI:NAME:<NAME>END_PI"': ship: "Myśliwiec TIE" text: """Kiedy atakujesz w Zasięgu 1, rzucasz 1 dodatkową kością ataku.""" '"Howlrunner"': ship: "Myśliwiec TIE" text: """Kiedy inny przyjazny statek w zasięgu 1 atakuje przy pomocy swojej podstawowej broni, może przerzucić 1 kość ataku.""" # TIE Interceptor "Alpha Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PIskadPI:NAME:<NAME>END_PI" "Avenger Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PI MPI:NAME:<NAME>END_PI" "Saber Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PI" "Royal Guard Pilot": name: "Pilot imperialny gwardzista" "\"PI:NAME:<NAME>END_PI\"": name: "\"PI:NAME:<NAME>END_PI\"" text: """Zostajesz zniszczony dopiero pod koniec fazy walki, w której liczba kart uszkodzeń przypisanych do ciebie będzie równa, lub wyższa od twojej wartości kadłuba.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy wykonujesz akcję "beczka", możesz otrzymać 1 żeton stresu, aby zamiast wzornika manewru (%STRAIGHT% 1) użyć (%BANKLEFT% 1) lub (%BANKRIGHT% 1).""" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz w Zasięgu 2-3, możesz wydać 1 żeton uników, aby dodać 1 %HIT% do swojego wyniku.""" "PI:NAME:<NAME>END_PI": text: """Kiedy ujawnisz manewr %UTURN% możesz traktować go tak, jakby jego prędkość wynosiła "1", "3" lub "5".""" "PI:NAME:<NAME>END_PI": text: """Po wykonaniu ataku możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "PI:NAME:<NAME>END_PI": text: """Wrogie statki w Zasięgu 1 nie mogą wykonywać akcji "skupienie" oraz "unik", ani wydawać żetonów skupienia i uników.""" "PI:NAME:<NAME>END_PI": text: """Kiedy otrzymujesz żeton stresu, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Phantom "Sigma Squadron Pilot": name: "Pilot Eskadry Sigma" "Shadow Squadron Pilot": name: "Pilot Eskadry Cieni" '"Echo"': text: """Kiedy się demaskujesz musisz użyć wzornika manewru (%BANKLEFT% 2) lub (%BANKRIGHT% 2) zamiast wzornika (%STRAIGHT% 2).""" '"Whisper"': name: "PI:NAME:<NAME>END_PI" text: """Po tym jak wykonasz atak, który trafi cel, możesz przypisać do swojego statku 1 żeton skupienia.""" # TIE Defender "Onyx Squadron Pilot": name: "Pilot Eskadry Onyx" "Delta Squadron Pilot": name: "Pilot Eskadry Delta" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz, zaraz po swoim rzucie kośćmi ataku możesz namierzyć obrońcę, jeśli ma na sobie czerwony żeton namierzonego celu.""" "PI:NAME:<NAME>END_PI": text: """Po tym jak wykonasz atak, który zada obrońcy co najmniej jedną kartę uszkodzenia, możesz wydać żeton skupienia aby odkryć te karty.""" # Bombowiec TIE "Scimitar Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Sejmitarów" "Gamma Squadron Pilot": ship: "Bombowiec TIE" name: "Pilot Eskadry Gamma" "CaptPI:NAME:<NAME>END_PI": ship: "Bombowiec TIE" name: "PI:NAME:<NAME>END_PI" text: "Kiedy inny przyjazny statek w Zasięgu 1 atakuje przy pomocy dodatkowej broni, może przerzucić maksymalnie 2 kości ataku." "Major Rhymer": ship: "Bombowiec TIE" text: "Kiedy atakujesz przy pomocy dodatkowej broni, możesz zwiększyć lub zmniejszyć zasięg broni o 1. Musisz przy tym zachować limit zasięgu 1-3." "Gamma Squadron Veteran": ship: "Bombowiec TIE" # TIE Advanced "Tempest Squadron Pilot": name: "Pilot Eskadry Burzy" "Storm Squadron Pilot": name: "Pilot Eskadry Szturmu" "PI:NAME:<NAME>END_PI": text: """Kiedy twój atak zadaje obrońcy odkrytą kartę uszkodzenia, wylosuj 3 karty uszkodzeń, wybierz 1 z nich, którą zadajesz, a pozostałe odrzuć.""" "PI:NAME:<NAME>END_PI": text: """Podczas swojego kroku "Wykonywania akcji" możesz wykonać 2 akcje.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Na początku fazy walki możesz namierzyć wrogi statek znajdujący się w Zasięgu 1 od ciebie.""" # Firespray "PI:NAME:<NAME>END_PI": name:"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz, obrońca otrzymuje 1 żeton stresu, jeśli anuluje co najmniej jeden wynik %CRIT%.""" "PI:NAME:<NAME>END_PI": text: """Kiedy ujawniasz manewr skrętu (%BANKLEFT% lub %BANKRIGHT%) możesz przestawić swój wskaźnik manewrów na drugi manewr skrętu o tej samej prędkości.""" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz przy pomocy dodatkowej broni, możesz przerzucić 1 kość ataku.""" # Prom typu Lambda "PI:NAME:<NAME>END_PI": ship: "Prom typu Lambda" name: "PI:NAME:<NAME>END_PI" text: """Kiedy wrogi statek namierza cel, musi namierzyć twój statek, jeśli to możliwe.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" ship: "Prom typu Lambda" text: """Na początku fazy walki możesz przypisać 1 ze swoich niebieskich żetonów namierzonego celu do przyjaznego statku w Zasięgu 1, jeśli ten nie ma niebieskiego żetonu namierzonego celu.""" "PI:NAME:<NAME>END_PI": ship: "Prom typu Lambda" name: "PI:NAME:<NAME>END_PI" text: """Kiedy inny przyjazny statek w Zasięgu 1-2 ma otrzymać żeton stresu, gdy ty masz 2 lub mniej żetonów stresu, możesz przypisać do siebie ten żeton stresu.""" "Omicron Group Pilot": ship: "Prom typu Lambda" name: "Pilot grupy Omicron" # VT-49 Decimator "PI:NAME:<NAME>END_PI": ship: "Decimator VT-49" name: "PI:NAME:<NAME>END_PI" text: """Po wykonaniu manewru, każdy wrogi statek z którym się stykasz, otrzymuje 1 uszkodzenie.""" "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI": ship: "Decimator VT-49" name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz w Zasięgu 1-2, możesz zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Patrol Leader": ship: "Decimator VT-49" name: "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI": ship: "Decimator VT-49" name: "PI:NAME:<NAME>END_PI" text: """Jeśli nie masz żadnych osłon i masz przypisaną co najmniej 1 kartę uszkodzenia, wartość twojej zwrotności wzrasta o 1.""" "PI:NAME:<NAME>END_PI": text: """When you reveal your maneuver, you may increase or decrease its speed by 1 (to a minimum of 1).""" "PI:NAME:<NAME>END_PI": text: """Enemy ships at Range 1 cannot add their range combat bonus when attacking.""" "PI:NAME:<NAME>END_PI": text: """At the start of the End phase, you may spend a target lock you have on an enemy ship to flip 1 random facedown Damage card assigned to it faceup.""" # Rebels # X-Wing "Red Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PIiedoPI:NAME:<NAME>END_PI pilot" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz zredukuj wartość zwrotności obrońcy o 1 (do minimum 0).""" "PI:NAME:<NAME>END_PI": text: """Po tym jak wydasz żeton skupienia możesz umieścić dany żeton na dowolnym innym przyjaznym statku w Zasięgu 1-2 (zamiast go odrzucać).""" "PI:NAME:<NAME>END_PI": text: """Inne przyjazne statki w Zasięgu 1 nie mogą być wybierane na cel ataku, jeśli atakujący może na cel wybrać ciebie.""" "PI:NAME:<NAME>END_PI": text: """Kiedy się bronisz, możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %EVADE%.""" "PI:NAME:<NAME>END_PI": text: """Po wykonaniu ataku możesz usunąć z obrońcy 1 żeton skupienia, uników, lub niebieski żeton namierzonego celu.""" "PI:NAME:<NAME>END_PI": text: """Kiedy otrzymujesz żeton stresu możesz usunąć go i rzucić 1 kością ataku. Jeśli wypadnie %HIT%, ten statek otrzymuje 1 zakrytą kartę uszkodzenia.""" '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI': text: """Kiedy zdobywasz lub wydajesz żeton namierzonego celu, możesz usunąć ze swojego statku 1 żeton stresu.""" "PI:NAME:<NAME>END_PI": text: """Kiedy wrogi statek wybiera cię na cel ataku, możesz namierzyć ten statek.""" # Y-Wing "Gold Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PI" "Gray Squadron Pilot": name: "Pilot PI:NAME:<NAME>END_PI" '"PI:NAME:<NAME>END_PI" PI:NAME:<NAME>END_PI': text: """Po namierzeniu celu wybierz przyjazny statek w Zasięgu 1-2. Wybrany statek może natychmiast namierzyć cel.""" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz w Zasięgu 2-3, możesz przerzucić dowolne ze swoich kości, na których wypadły puste ścianki.""" # A-Wing "Green Squadron Pilot": name: "Pilot EskPI:NAME:<NAME>END_PI ZPI:NAME:<NAME>END_PI" "Prototype Pilot": name: "Pilot prototypu" "PI:NAME:<NAME>END_PI": text: """Możesz wykonywać akcje nawet jeśli posiadasz żetony stresu.""" "PI:NAME:<NAME>END_PI": text: """Możesz wybrać na cel swojego ataku wrogi statek, z którym się stykasz, jeżeli ten znajduje się w twoim polu rażenia.""" # YT-1300 "Outer Rim Smuggler": name: "PI:NAME:<NAME>END_PI z PI:NAME:<NAME>END_PI" "ChePI:NAME:<NAME>END_PI": text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, natychmiast ją zakryj (bez rozpatrywania jej efektu).""" "PI:NAME:<NAME>END_PI": text: """Po wykonaniu zielonego manewru wybierz jeden inny przyjazny statek w Zasięgu 1. Statek ten może wykonać 1 darmową akcję przedstawioną na jego pasku akcji.""" "Han Solo": text: """Kiedy atakujesz możesz przerzucić wszystkie swoje kości ataku. Jeśli zdecydujesz się to zrobić musisz przerzucić tyle ze swoich kości, ile możesz.""" # B-Wing "Dagger Squadron Pilot": name: "Pilot Eskadry Sztyletów" "Blue Squadron Pilot": name: "Pilot Eskadry Niebieskich" "Ten Numb": text: """Kiedy atakujesz, 1 z twoich wyników [crt-hit] nie może być anulowany przy pomocy kości obrony.""" "Ibtisam": text: """Kiedy atakujesz lub się bronisz mając co najmniej 1 żeton stresu, możesz przerzucić jedną ze swoich kości.""" # HWK-290 "Rebel Operative": name: "Agent rebeliantów" "PI:NAME:<NAME>END_PI": text: '''Na początku fazy walki wybierz 1 inny przyjazny statek w zasięgu 1-3. Do końca tej fazy traktuj wartość umiejętności tego pilota jakby wynosiła "12".''' "PI:NAME:<NAME>END_PI": text: """Na początku fazy walki możesz przypisać 1 ze swoich żetonów skupienia do innego przyjaznego statku w Zasięgu 1-3.""" "PI:NAME:<NAME>END_PI": text: """Kiedy inny przyjazny statek w Zasięgu 1-3 atakuje, gdy nie masz żadnych żetonów stresu, możesz otrzymać 1 żeton stresu aby umożliwić mu rzut 1 dodatkową kością ataku.""" # Z-95 "Bandit Squadron Pilot": name: "Pilot Eskadry Bandytów" ship: "Z-95 Łowca głów" "Tala Squadron Pilot": name: "Pilot Eskadry PI:NAME:<NAME>END_PI" ship: "Z-95 Łowca głów" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" ship: "Z-95 Łowca głów" text: "Kiedy atakujesz, obrońca zostaje trafiony twoim atakiem nawet jeśli nie otrzymał żadnych uszkodzeń." "PI:NAME:<NAME>END_PI": ship: "Z-95 Łowca głów" text: """Po wykonaniu ataku możesz wybrać inny przyjazny statek w Zasięgu 1. Dany statek może wykonać 1 darmową akcję.""" # E-Wing "Knave Squadron Pilot": name: "Pilot Eskadry Szelm" "Blackmoon Squadron Pilot": name: "Pilot Eskadry Czarnego Księżyca" "PI:NAME:<NAME>END_PI": text: """Kiedy wrogi statek w twoim polu rażenia, w Zasięgu 1-3 się broni, atakujący może zmienić 1 z jego wyników %HIT% na wynik %CRIT%.""" "PI:NAME:<NAME>END_PI": text: """Na początku fazy końcowej możesz wykonać jeden atak. Nie możesz atakować w następnej rundzie.""" # Asy Rebelii "PI:NAME:<NAME>END_PI": text: """Po tym jak wykonasz akcję skupienia lub zostanie ci przypisany żeton skupienia, możesz wykonać darmową akcję "dopalacz" lub "beczka".""" "PI:NAME:<NAME>END_PI": text: """Dopóki znajdujesz się w Zasięgu 1 od co najmniej 1 wrogiego statku, zwiększ swoją wartość zwrotności o 1.""" "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz możesz usunąć 1 żeton stresu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "PI:NAME:<NAME>END_PI": text: """Możesz wykonać atak dodatkową bronią %TORPEDO%, skierowany przeciwko wrogim statkom znajdującym się poza twoim polem rażenia.""" # Transportowiec Rebelii "GR-75 Medium Transport": name: "Średni transportowiec GR-75" ship: "Średni transportowiec GR-75" # CR90 "CR90 Corvette (Fore)": ship: "Korweta CR90 (dziób)" name: "Korweta CR90 (dziób)" text: """Kiedy atakujesz przy pomocy swojej głównej broni, możesz wydać 1 żeton energii aby rzucać 1 dodatkową kością ataku.""" "CR90 Corvette (Aft)": ship: "Korweta CR90 (rufa)" name: "Korweta CR90 (rufa)" # YT-2400 "Dash Rendar": text: """Podczas fazy aktywacji i w czasie wykonywania akcji możesz ignorować przeszkody.""" '"Leebo"': text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia, dobierz 1 dodatkową kartę uszkodzenia. Rozpatrz jedną z nich a drugą odrzuć.""" "PI:NAME:<NAME>END_PI": text: """Podczas wykonywania ataku przy pomocy broni podstawowej, którego celem jest statek z żetonem stresu, rzucasz 1 dodatkową kością.""" "Wild Space FPI:NAME:<NAME>END_PIer": name: "OutPI:NAME:<NAME>END_PI z PI:NAME:<NAME>END_PI" # Scum and Villainy # Starviper "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy się bronisz, przyjazny statek w Zasięgu 1 może otrzymać 1 nieanulowany wynik %HIT% lub %CRIT% (zamiast ciebie).""" "PI:NAME:<NAME>END_PI": text: """Na początku fazy walki, jeśli jesteś w Zasięgu 1 od wrogiego statku, możesz przypisać do swojego statku 1 żeton skupienia.""" "Black Sun Vigo": name: "PI:NAME:<NAME>END_PI" "Black Sun Enforcer": name: "PI:NAME:<NAME>END_PI" # Interceptor M3-A "Cartel Spacer": name: "Pilot kartelu" "Tansarii Point Veteran": name: "Weteran Tansarii Point" "PI:NAME:<NAME>END_PI": text: """Kiedy inny przyjazny statek w Zasięgu 1 się broni, może przerzucić 1 kość obrony.""" "PI:NAME:<NAME>END_PI": text: "Po tym jak obronisz się przed atakiem, jeśli atak nie trafił, możesz przypisać do swojego statku 1 żeton uniku." # Agressor "IG-88A": text: """Po tym jak wykonasz atak, który zniszczy obrońcę, możesz odzyskać 1 osłonę.""" "IG-88B": text: """Raz na rundę, po tym jak wykonasz atak, który nie trafi w wybrany cel, możesz wykonać atak przy pomocy dodatkowej broni %CANON%, w którą jesteś wyposażony.""" "IG-88C": text: """Po tym jak wykonasz akcję „dopalacz” możesz przypisać do swojego statku 1 żeton uniku.""" "IG-88D": text: """Możesz wykonać manewr (%SLOOPLEFT% 3) lub (%SLOOPRIGHT% 3) używając odpowiednio wzornika (%TURNLEFT% 3) lub (%TURNRIGHT% 3).""" # Firespray "PI:NAME:<NAME>END_PI (Scum)": name: """PI:NAME:<NAME>END_PI (Szumowiny)""" text: """Kiedy atakujesz lub się bronisz możesz przerzucić 1 ze swoich kości za każdy wrogi statek w Zasięgu 1.""" "PI:NAME:<NAME>END_PI (Scum)": name: """PI:NAME:<NAME>END_PI (Szumowiny)""" text: """Kiedy atakujesz statek znajdujący się w twoim pomocniczym polu rażenia, rzucasz 1 dodatkową kością ataku.""" "PI:NAME:<NAME>END_PI": text: """Kiedy zrzucasz bombę, możesz użyć wzornika [%TURNLEFT% 3], [%STRAIGHT% 3], lub [%TURNRIGHT% 3] (zamiast wzornika [%STRAIGHT% 1]).""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" # Y-Wing "PI:NAME:<NAME>END_PI": text: """Kiedy atakujesz statek znajdujący się poza twoim polem rażenia, rzucasz 1 dodatkową kością ataku.""" "PI:NAME:<NAME>END_PI": text: """Po tym jak wydasz żeton namierzonego celu, możesz otrzymać 1 żeton stresu, aby namierzyć cel.""" "PI:NAME:<NAME>END_PI" : name: "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PIu" # HWK "PI:NAME:<NAME>END_PI": text: """Kiedy wrogi statek w Zasięgu 1-3 otrzyma co najmniej jeden żeton jonów, a ty nie masz żetonu stresu, możesz otrzymać 1 żeton stresu aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "PI:NAME:<NAME>END_PI": text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z wrogiego statku w Zasięgu 1-2 i przypisać go do siebie.""" "PI:NAME:<NAME>END_PI": text: """Na koniec fazy aktywacji wybierz jeden wrogi statek w Zasięgu 1-2. Do końca fazy walki wartość umiejętności pilota wybranego statku wynosi "0".""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" # Z-95 "Black Sun Soldier": name: "PI:NAME:<NAME>END_PI" ship: "Z-95 Łowca głów" "BinayPI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" ship: "Z-95 Łowca głów" "PI:NAME:<NAME>END_PI": ship: "Z-95 Łowca głów" text: """Kiedy atakujesz rzucasz 1 dodatkową kością ataku, jeśli w Zasięgu 1-2 nie ma żadnych innych przyjaznych statków.""" "PI:NAME:<NAME>END_PI": ship: "Z-95 Łowca głów" text: """Na początku fazy walki możesz usunąć 1 żeton skupienia lub uników z innego przyjaznego statku w Zasięgu 1-2 i przypisać go do siebie.""" "PI:NAME:<NAME>END_PI": text: """When a friendly ship declares an attack, you may spend a target lock you have on the defender to reduce its agility by 1 for that attack.""" "PI:NAME:<NAME>END_PI": text: """When defending, if the attacker is inside your firing arc, roll 1 additional defense die.""" "PI:NAME:<NAME>END_PI": text: """When another friendly ship at Range 1-2 is attacking, it may treat your focus tokens as its own.""" '"Redline"': text: """You may maintain 2 target locks on the same ship. When you acquire a target lock, you may acquire a second lock on that ship.""" '"Deathrain"': text: """When dropping a bomb, you may use the front guides of your ship. After dropping a bomb, you may perform a free barrel roll action.""" "Moralo Eval": text: """You can perform %CANNON% secondary attacks against ships inside your auxiliary firing arc.""" 'Gozanti-class Cruiser': text: """After you execute a maneuver, you may deploy up to 2 attached ships.""" '"Scourge"': text: """When attacking a defender that has 1 or more Damage cards, roll 1 additional attack die.""" "The Inquisitor": text: """When attacking with your primary weapon at Range 2-3, treat the range of the attack as Range 1.""" "Zuckuss": text: """When attacking, you may roll 1 additional attack die. If you do, the defender rolls 1 additional defense die.""" "Dengar": text: """Once per round after defending, if the attacker is inside your firing arc, you may perform an attack against the that ship.""" # T-70 "PI:NAME:<NAME>END_PI": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" '"Blue Ace"': text: """When performing a boost action, you may use the (%TURNLEFT% 1) or (%TURNRIGHT% 1) template.""" # TIE/fo '"Omega Ace"': text: """When attacking, you may spend a focus token and a target lock you have on the defender to change all of your results to %CRIT% results.""" '"Epsilon Leader"': text: """At the start of the Combat phase, remove 1 stress token from each friendly ship at Range 1.""" '"Zeta Ace"': text: """When performing a barrel roll you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" '"Red Ace"': text: '''The first time you remove a shield token from your ship each round, assign 1 evade token to your ship.''' '"Omega Leader"': text: '''Enemy ships that you have locked cannot modify any dice when attacking you or defending against your attacks.''' 'Hera Syndulla': text: '''When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.''' '"Youngster"': text: """Friendly TIE fighters at Range 1-3 may perform the action on your equipped %ELITE% Upgrade card.""" '"PI:NAME:<NAME>END_PI"': text: """When attacking, you may cancel all die results. If you cancel a %CRIT% result, deal 1 facedown Damage card to the defender.""" '"PI:NAME:<NAME>END_PI"': text: """When another friendly ship at Range 1 spends a focus token, assign a focus token to your ship.""" 'PI:NAME:<NAME>END_PI': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"PI:NAME:<NAME>END_PI"': text: '''When attacking, if you are not stressed, you may receive 1 stress token to roll 1 additional die.''' '"PI:NAME:<NAME>END_PI"': text: '''While you do not have any Damage cards, treat your pilot skill value as "12."''' "PI:NAME:<NAME>END_PI": text: """When an enemy ship at Range 1-2 is attacking, you may spend a focus token. If you do, the attacker rolls 1 fewer attack die.""" '"PI:NAME:<NAME>END_PI"': text: """At the start of the Combat phase, each enemy ship you are touching receives 1 stress token.""" 'PI:NAME:<NAME>END_PI (Attack Shuttle)': text: """When you reveal a green or red maneuver, you may rotate your dial to another maneuver of the same difficulty.""" 'PI:NAME:<NAME>END_PI': text: """Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.""" '"ZPI:NAME:<NAME>END_PI" Orrelios': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'PI:NAME:<NAME>END_PI': ship: "Bombowiec TIE" text: '''Once per round, after you discard an %ELITE% Upgrade card, flip that card faceup.''' 'PI:NAME:<NAME>END_PI': text: '''While you are not stressed, you may treat your %TROLLLEFT% and %TROLLRIGHT% maneuvers as white maneuvers.''' "PI:NAME:<NAME>END_PI": text: """After defending, you may perform a free action.""" "4-LOM": text: """At the start of the End phase, you may assign 1 of your stress tokens to another ship at Range 1.""" "PI:NAME:<NAME>END_PI": text: """The first time you would be destroyed, instead cancel any remaining damage, discard all Damage cards, and deal 4 facedown Damage cards to this ship.""" "PI:NAME:<NAME>END_PI": text: """At the start of the Combat phase, you may assign all focus, evade, and target lock tokens assigned to you to another friendly ship.""" '"DeathPI:NAME:<NAME>END_PI"': ship: "Bombowiec TIE" text: '''When you reveal your maneuver dial or after you perform an action, you may perform a %BOMB% Upgrade card action as a free action.''' "PI:NAME:<NAME>END_PI (TIE Defender)": text: """When your attack deals a faceup Damage card to the defender, instead draw 3 Damage cards, choose 1 to deal, and discard the others.""" "PI:NAME:<NAME>END_PI": text: """When you reveal a %STRAIGHT% maneuver, you may treat it as a %KTURN% maneuver.""" "PI:NAME:<NAME>END_PI (PS9)": text: """When attacking or defending, if you have a focus token, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.""" "PI:NAME:<NAME>END_PI": text: """When attacking or defending, if the enemy ship is inside of your firing arc, you may reroll up to 2 of your blank results.""" 'Han PI:NAME:<NAME>END_PI (TFA)': text: '''When you are placed during setup, you can be placed anywhere in the play area beyond Range 3 of enemy ships.''' 'ChePI:NAME:<NAME>END_PI (TFA)': text: '''After another friendly ship at Range 1-3 is destroyed (but has not fled the battlefield), you may perform an attack.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking or defending, you may spend a target lock you have on the enemy ship to add 1 %FOCUS% result to your roll.''' 'PI:NAME:<NAME>END_PI': text: '''When another friendly ship at Range 1-2 is attacking, it may treat your blue target lock tokens as its own.''' 'PI:NAME:<NAME>END_PI': text: '''After an enemy ship in your firing arc at Range 1-3 attacks another friendly ship, you may perform a free action.''' 'PI:NAME:<NAME>END_PI': text: '''After you execute a maneuver, you may roll an attack die. On a %HIT% or %CRIT% result, remove 1 stress token from your ship.''' '"QuickPI:NAME:<NAME>END_PI"': text: '''Once per round, when you lose a shield token, you may perform a primary weapon attack.''' '"BackPI:NAME:<NAME>END_PI"': text: '''When attacking a ship inside your auxiliary firing arc, you may add 1 %CRIT% result.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking or defending, if the enemy ship is at Range 1, you may roll 1 additional die.''' 'PI:NAME:<NAME>END_PI': text: '''At the start of the Combat phase, you may choose 1 enemy ship at Range 1. If you are inside its firing arc, it discards all focus and evade tokens.''' 'PI:NAME:<NAME>END_PI': text: '''After you execute a red maneuver, assign 2 focus tokens to your ship.''' 'PI:NAME:<NAME>END_PI': text: '''At the start of the Combat phase, you may choose a ship at Range 1. If it is inside your primary <strong>and</strong> mobile firing arcs, assign 1 tractor beam token to it.''' 'PI:NAME:<NAME>END_PI': text: '''At the start of the Combat phase, you may choose a ship at Range 1-2. If it inside your mobile firing arc, assign 1 stress token to it.''' 'PI:NAME:<NAME>END_PI (Scum)': text: '''When defending against an enemy ship inside your mobile firing arc at Range 1-2, you may add 1 %FOCUS% result to your roll.''' 'PI:NAME:<NAME>END_PI (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''Immediately before you reveal your maneuver, you may perform a free boost or barrel roll action.''' '"Zeb" Orrelios (TIE Fighter)': ship: 'Myśliwiec TIE' text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'PI:NAME:<NAME>END_PI': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' 'PI:NAME:<NAME>END_PI': text: '''At the end of the Activation phase, you <strong>must</strong> assign a tractor beam token to each ship you are touching.''' 'PI:NAME:<NAME>END_PI': text: '''At the start of the Activation phase, you may remove 1 stress token from 1 other friendly ship at Range 1-2.''' 'PI:NAME:<NAME>END_PI': text: '''When a friendly ship acquires a target lock, that ship can lock onto an enemy ship at Range 1-3 of any friendly ship.''' 'PI:NAME:<NAME>END_PI': text: '''After an enemy ship executes a maneuver that causes it to overlap your ship, you may perform a free action.''' '''"Duchess"''': text: '''While you have the "Adaptive Ailerons" Upgrade card equipped, you may choose to ignore its card ability.''' '''"Pure Sabacc"''': text: '''When attacking, if you have 1 or fewer Damage cards, roll 1 additional attack die.''' '''"Countdown"''': text: '''When defending, if you are not stressed, during the "Compare Results" step, you may suffer 1 damage to cancel all dice results. If you do, receive 1 stress token.''' 'PI:NAME:<NAME>END_PI': text: '''When you receive a stress token, if there is an enemy ship inside your firing arc at Range 1, you may discard that stress token.''' '"Snap" PI:NAME:<NAME>END_PI': text: '''After you execute a 2-, 3-, or 4-speed maneuver, if you are not touching a ship, you may perform a free boost action.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking or defending, you may reroll 1 of your dice for each other friendly ship at Range 1.''' 'PI:NAME:<NAME>END_PI': ship: 'Myśliwiec TIE' text: '''At the start of the Combat phase, you may spend 1 focus token to choose a friendly ship at Range 1. It may perform 1 free action.''' 'PI:NAME:<NAME>END_PI': ship: 'Myśliwiec TIE' text: '''After you perform an attack, assign the "Suppressive Fire" Condition card to the defender.''' 'PI:NAME:<NAME>END_PI': text: '''For the purpose of your actions and Upgrade cards, you may treat friendly ships at Range 2-3 as being at Range 1.''' 'PI:NAME:<NAME>END_PI': text: '''During setup, friendly ships may placed anywhere in the play area at Range 1-2 of you.''' 'PI:NAME:<NAME>END_PI': text: '''When you reveal a reverse maneuver, you may drop a bomb using your front guides (including a bomb with the "<strong>Action:</strong>" header).''' 'PI:NAME:<NAME>END_PI': text: '''When defending, instead of using your agility value, you may roll a number of defense dice equal to the speed of the maneuver you executed this round.''' "PI:NAME:<NAME>END_PI": text: """When attacking or defending, double the effect of your range combat bonuses.""" 'PI:NAME:<NAME>END_PI': text: '''After you acquire a target lock, assign focus and evade tokens to your ship until you have the same number of each token as the locked ship.''' 'PI:NAME:<NAME>END_PI': text: '''At the start of the Combat phase, you may receive a weapons disabled token to flip one of your discarded %TORPEDO% or %MISSILE% Upgrade cards faceup.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking or defending, you may spend 1 shield to reroll any number of your dice.''' 'PI:NAME:<NAME>END_PI': text: '''Once per round, after you roll or reroll dice, if you have the same result on each of your dice, add 1 matching result.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking, you may spend 1 focus token to cancel all of the defender's blank and %FOCUS% results.''' '"PI:NAME:<NAME>END_PI"': text: '''Once per round, after you perform a secondary weapon attack that does not hit, you may perform an attack with a different weapon.''' 'PI:NAME:<NAME>END_PI': text: '''After defending, if you did not roll exactly 2 defense dice, the attacker receives 1 stress token.''' 'LowPI:NAME:<NAME>END_PI': text: '''When another friendly ship at Range 1 is defending, you may spend 1 reinforce token. If you do, the defender adds 1 %EVADE% result.''' 'PI:NAME:<NAME>END_PI': text: '''When attacking, if you have no shields and at least 1 Damage card assigned to you, roll 1 additional attack die.''' 'PI:NAME:<NAME>END_PI': text: '''If you are not stressed, when you reveal a turn, bank, or Segnor's Loop maneuver, you may instead treat it as a red Tallon Roll maneuver of the same direction (left or right) using the template of the original revealed maneuver.''' 'PI:NAME:<NAME>END_PI': text: '''During setup, before the "Place Forces" step, you may choose 1 enemy ship and assign the "Shadowed" or "Mimicked" Condition card to it.''' 'PI:NAME:<NAME>END_PI': text: '''Once per round, after an enemy ship that is not defending against an attack suffers damage or critical damage, you may perform an attack against that ship.''' 'PI:NAME:<NAME>END_PI': text: '''When defending, if you have a weapons disabled token, roll 1 additional defense die.''' 'PI:NAME:<NAME>END_PI': text: '''When you receive a weapons disabled token, if you are not stressed, you may receive 1 stress token to remove it.''' 'PI:NAME:<NAME>END_PI': text: '''After you perform an attack, each enemy ship inside your bullseye firing arc at Range 1-3 must choose to suffer 1 damage or remove all of its focus and evade tokens.''' 'PI:NAME:<NAME>END_PI (Kimogila)': text: '''At the start of the Combat phase, you may acquire a target lock on an enemy ship inside your bullseye firing arc at Range 1-3 .''' 'PI:NAME:<NAME>END_PI (Sheathipede)': text: '''When an enemy ship inside your firing arc at Range 1-3 becomes the active ship during the Combat phase, if you are not stressed, you may receive 1 stress token. If you do, that ship cannot spend tokens to modify its dice when attacking this round.''' 'PI:NAME:<NAME>END_PI (Sheathipede)': text: """When defending, if you are stressed, you may change up to 2 of your %FOCUS% results to %EVADE% results.""" '"Zeb" Orrelios (Sheathipede)': text: '''When defending, you may cancel %CRIT% results before %HIT% results.''' 'AP-5': text: '''When you perform the coordinate action, after you choose a friendly ship and before it performs a free action, you may receive 2 stress tokens to remove 1 stress token from it.''' '"Crimson Leader"': text: '''When attacking, if the defender is inside your firing arc, you may spend 1 %HIT% or %CRIT% result to assign the "Rattled" Condition to the defender.''' '"Crimson Specialist"': text: '''When placing a bomb token you dropped after revealing your maneuver dial, you may place the bomb token anywhere on the play area touching your ship.''' '"Cobalt Leader"': text: '''When attacking, if the defender is at range 1 of a bomb token, the defender rolls 1 fewer defense die, to a minimum of 0.''' 'PI:NAME:<NAME>END_PI (TIE Silencer)': text: '''The first time you are hit by an attack each round, deal the "I'll Show You the Dark Side" Condition card to the attacker.''' 'Test Pilot "Blackout"': text: '''When attacking, if the attack is obstructed, the defender rolls 2 fewer defense dice (to a minimum of 0).''' 'PI:NAME:<NAME>END_PI': text: '''After you perform a boost or barrel roll action, you may flip your equipped "Servomotor S-foils" upgrade card.''' 'Major Vermeil': text: '''When attacking, if the defender does not have a focus or evade token, you may change one of your blank or %FOCUS% results to a %HIT% result.''' 'PI:NAME:<NAME>END_PI': text: '''After you perform a boost action, you may receive 1 stress token to receive 1 evade token.''' 'PI:NAME:<NAME>END_PI': text: '''When a friendly ship at Range 1-2 attacks, if it is stressed or has at least 1 Damage card, it may reroll 1 attack die.''' 'BPI:NAME:<NAME>END_PI Two-Tubes': text: '''After you perform a focus action, you may remove 1 of your focus tokens to assign it to a friendly ship at Range 1-2.''' 'PI:NAME:<NAME>END_PI': text: '''When defending, if the attacker is jammed, add 1 %EVADE% result to your roll.''' '"PI:NAME:<NAME>END_PI"': text: '''After a friendly ship executes a 1-speed maneuver, if it is at Range 1 and did not overlap a ship, you may assign 1 of your focus or evade tokens to it.''' 'PI:NAME:<NAME>END_PI': text: '''When another friendly ship at Range 1-2 is defending, the attacker cannot reroll more than 1 attack die.''' 'PI:NAME:<NAME>END_PI-Tubes': text: '''When you become the active ship during the Activation phase, if you have 1 or more focus tokens, you may perform a free action.''' upgrade_translations = #Elitarna zdolność "Determination": name: "Determinacja" text: """Kiedy otrzymujesz odkrytą kartę uszkodzenia z cechą "Pilot", natychmiast ją odrzuć bez rozpatrywania jej efektu.""" "Swarm Tactics": name: "PI:NAME:<NAME>END_PI" text: """Na początku fazy walki wybierz 1 przyjazny statek w Zasięgu 1. Do końca tej fazy traktuj wybrany statek, jakby jego wartość umiejętności pilota była równa twojej.""" "Squad Leader": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Wybierz 1 statek w Zasięgu 1-2, który ma niższą wartość umiejętności pilota niż ty. %LINEBREAK% Wybrany statek może natychmiast wykonać 1 darmową akcję.""" "Expert Handling": name: "PI:NAME:<NAME>END_PI" text: """„<strong>Akcja:</strong> Wykonaj darmową akcję „beczka”. Jeśli nie masz symbolu akcji %BARRELROLL%, otrzymujesz 1 żeton stresu. Następnie możesz usunąć jeden wrogi żeton namierzonego celu znajdujący się na Twoim statku.""" "PI:NAME:<NAME>END_PIship": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Kiedy atakujesz w tej rundzie, możesz zamienić 1 swój wynik %FOCUS% na %CRIT%, a wszystkie pozostałe wyniki %FOCUS% na %HIT%.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Wykonaj biały manewr (%TURNLEFT% 1) lub (%TURNRIGHT% 1)". Następnie otrzymujesz żeton stresu. %LINEBREAK% Następnie, jeśli nie masz symbolu akcji %BOOST%, rzuć 2 kośćmi ataku. Otrzymujesz wszystkie wyrzucone uszkodzenia %HIT% i uszkodzenia krytyczne %CRIT%.""" "Elusiveness": name: "PI:NAME:<NAME>END_PI" text: """Kiedy się bronisz możesz otrzymać 1 żeton stresu, aby wybrać jedną kość ataku. Atakujący musi przerzucić tą kość. Nie możesz skorzystać z tej zdolności, jeśli jeśli masz co najmniej 1 żeton stresu.""" "Push the Limit": name: "Na granicy ryzyka" text: """Raz na rundę po wykonaniu akcji, możesz wykonać 1 darmową akcję przedstawioną na twoim pasku akcji. Następnie otrzymujesz 1 żeton stresu.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Możesz traktować nagłówek <strong>"Atak (namierzony cel):"</strong> jako <strong>"Atak (skupienie):"</strong>. %LINEBREAK% Kiedy atak zmusza cię do wydania żetonu namierzonego celu, możesz zamiast niego wydać żeton skupienia.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Do końca rundy zwiększ wartość swojej podstawowej broni o 1 i zmniejsz wartość zwrotności o 1.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Na początku fazy walki usuń 1 żeton stresu z innego przyjaznego statku w Zasięgu 1.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Na początku fazy walki możesz wybrać 1 przyjazny statek w Zasięgu 1-2. Do końca fazy zamieniasz się z danym statkiem wartościami umiejętności pilota.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz statek w swoim polu rażenia, a nie znajdujesz się w polu rażenia danego statku, zmniejsz jego wartość zwrotności o 1 (do minimum 0).""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz, możesz przerzucić 1 kość ataku. Jeśli wartość umiejętnosci pilota obrońcy wynosi "2" lub mniej, możesz przerzucić maksymalnie 2 kości ataku (zamiast 1).""" "Draw Their Fire": name: "ŚciPI:NAME:<NAME>END_PI" text: """Kiedy przyjazny statek w Zasięgu 1 zostaje trafiony podczas ataku, możesz zamiast niego otrzymać 1 z nie anulowanych %CRIT%.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy ujawnisz czerwony manewr, możesz odrzucić tę kartę, aby do końca fazy aktywacji traktować ten manewr jako biały.""" "Veteran Instincts": name: "PI:NAME:<NAME>END_PI" text: """Zwiększ swoją wartość umiejętności pilota o 2.""" "Opportunist": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz, jeśli obrońca nie ma żadnych żetonów skupienia ani uników, możesz otrzymać 1 żeton stresu aby rzucić 1 dodatkową kością ataku.%LINEBREAK%Nie możesz skorzystać z tej zdolności, jeśli posiadasz żetony stresu.""" "LPI:NAME:<NAME>END_PI": name : "PI:NAME:<NAME>END_PI" text: """Jeśli w zasięgu 1-2 nie ma żadnych innych przyjaznych statków, kiedy się bronisz lub atakujesz, możesz przerzucić 1 wynik z pustą ścianką.""" "Stay On Target": name: "UPI:NAME:<NAME>END_PI cel" text: """Kiedy ujawnisz swój manewr możesz obrócić swój wskaźnik na inny manewr o tej samej prędkości.%LINEBREAK%Traktuj ten manewr jako czerwony.""" "Ruthlessness": name: "Bezwzględność" text: """%PL_IMPERIALONLY%%LINEBREAK% Po tym jak przeprowadzisz atak, który trafi w cel, musisz wybrać 1 inny statek w Zasięgu 1 od obrońcy (nie siebie). Statek ten otrzymuje 1 uszkodzenie.""" "Intimidation": name: "Zastraszenie" text: """Dopóki stykasz się z wrogim statkiem, jego zwrotność zostaje zmniejszona o 1.""" "Calculation": name: "Kalkulacje" text: """Kiedy atakujesz, możesz wydać żeton skupienia, aby zmienić jeden ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Bodyguard": name : "PI:NAME:<NAME>END_PI" text: """%PL_SCUMONLY%%LINEBREAK% Na początku fazy walki możesz wydać żeton skupienia aby wybrać przyjazny statek w Zasięgu 1 o wartości umiejętności pilota wyższej od ciebie. Do końca rundy zwiększ jego wartość zwrotności o 1.""" # Astromechs "R2 Astromech": name: "Astromech R2" text: """Możesz traktować wszystkie manewry o prędkości 1 i 2, jakby były to zielone manewry.""" "R2-D2": text: """Po wykonaniu zielonego manewru możesz odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R2-F2": text: """<strong>Akcja:</strong> Do końca tej rundy zwiększ swoją wartość zwrotności o 1.""" "R5-D8": text: """<strong>Akcja:</strong> Rzuć jedną kością obrony.%LINEBREAK% Jeżeli wypadnie wynik %EVADE% lub %FOCUS%, odrzuć jedną ze swoich zakrytych kart uszkodzeń.""" "R5-K6": text: """Po wydaniu swojego rzetonu namierzonego celu rzuć 1 kością obrony.%LINEBREAK% Jeżeli wypadnie %EVADE% natychmiast zdobywasz żeton namierzonego celu dla tego samego statku. Nie możesz wydać nowego żetonu namierzonego celu podczas tego ataku.""" "R5 Astromech": name: "Astromech R5" text: """Podczas fazy końcowej możesz wybrać 1 ze swoich odkrytych kart z cechą "Statek" i ją zakryć.""" "R7 Astromech": name: "Astromech R7" text: """Raz na rundę kiedy się bronisz, jeśli namierzasz atakującego, możesz wydać żeton namierzonego celu aby wybrać dowolną liczbę kości ataku. Atakujący musi przerzucić wybrane kości.""" "R7-T1": text: """<strong>Akcja:</strong> Wybierz wrogi statek w Zasięgu 1-2. Jeżeli znajdujesz się w polu rażenia wybranego statku, możesz namierzyć dany statek. Następnie możesz wykonać darmową akcję "dopalacz".""" "R4-D6": text: """Kiedy zostaniesz trafiony w wyniku ataku, a pośród wyników rzutu są co najmniej 3 nieaulowalne wyniki %HIT% możesz wybrać i anulować wszystkie poza 2. Za każdy wynik anulowany w ten sposób otrzymujesz 1 żeton stresu.""" "R5-P9": text: """Na koniec fazy walki możesz wydać jeden ze swoich żetonów skupienia, aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "R3-A2": text: """Kiedy wybierzesz cel ataku, jeżeli obrońca znajduje się w twoim polu rażenia, możesz otrzymać 1 żeton stresu, aby sprawić żeby obrońca otrzymał 1 żeton stresu.""" "R2-D6": text: """Twój pasek rowinięć zyskuje symbol %ELITE%.%LINEBREAK% Nie możesz przypisać tej karty rozwinięcia do swojego statku jeżeli masz już symbol rozwinięcia %ELITE% lub jeżeli wartość umiejętności pilota wynosi 2 lub mniej.""" # Torpilles "Proton Torpedoes": name: "Torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników %FOCUS% na wynik %CRIT%.""" "Advanced Proton Torpedoes": name: "Zaaw. torpedy protonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić maksymalnie 3 swoje puste ścianki na wyniki %FOCUS%.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Po wykonaniu tego ataku obrońca otrzymuje 1 żeton stresu jeżeli jego wartość kadłuba wynosi 4 lub mniej.""" "Ion Torpedoes": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeżeli ten atak trafi w wybrany cel, obrońca oraz każdy statek w Zasięgu 1 od niego otrzymuje 1 żeton jonów.""" "Bomb Loadout": name: "Ładunek bomb" text: """<span class="card-restriction">Tylko Y-wing. Ograniczenie.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %BOMB%.""" # Tourelles "Ion Cannon Turret": name: "Wieżyczka z działem jonowym" text: """<strong>Atak:</strong> Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Jeśli atak ten trafi w wybrany statek, otrzymuje on 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Blaster Turret": name: "Wieżyczka blasterowa" text: """<strong>Atak (skupienie):</strong> Wydaj 1 żeton skupienia, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" "Autoblaster Turret": name: "Wieżyczka autoblasterowa" text: """<strong>Atak: Zaatakuj 1 statek (nawet poza twoim polem rażenia). %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przy pomocy kości obrony. Obrońca może anulować wyniki %CRIT% przed %HIT%.""" # Missiles "Concussion Missiles": name: "Rakiety wstrząsowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz zmienić 1 ze swoich wyników z pustą ścianką na wynik %HIT%.""" "Cluster Missiles": name: "Rakiety kasetonowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu o odrzuć tę kartę, aby przeprowadzić ten atak dwukrotnie.""" "Homing Missiles": name: "Rakiety samonaprowadzające" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Podczas tego ataku obrońca nie może wydawać żetonów uniku.""" "Assault Missiles": name: "Rakiety szturmowe" text: """<strong>Atak (namierzony cel):</strong> Wydaj swój żeton namierzonego celu i odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi w wybrany cel, każdy inny statek w Zasięgu 1 od obrońcy otrzymuje 1 uszkodzenie.""" "Ion Pulse Missiles": name: "JonPI:NAME:<NAME>END_PI pulsacyjne" text: """<strong>Atak (namierzony cel):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Jeśli ten atak trafi, obrońca otrzymuje 1 uszkodzenie oraz 2 żetony jonów.""" "Chardaan Refit": name: "PI:NAME:<NAME>END_PI" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Ta karta ma ujemny koszt w punktach eskadry.""" "Proton Rockets": name: "RPI:NAME:<NAME>END_PIiety protonowe" text: """<strong>Atak (skupienie):</strong> Odrzuć tę kartę, aby wykonać ten atak. %LINEBREAK%Możesz rzucić dodatkowymi kośćmi ataku w liczbie równej twojej zwrotności (nie wiecej niż 3).""" # Bombes "Seismic Charges": name: "PI:NAME:<NAME>END_PI" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton ładunku sejsmicznego. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" "Proximity Mines": name: "Miny zbliżeniowe" text: """<strong>Akcja:</strong> odrzuć tę kartę aby zrzucić 1 żeton miny zbliżeniowej. Kiedy statek wykona manewr w wyniku którego podstawka statku lub wzornik manewru będzie nachodzić na ten żeton, żeton ten zostaje zdetonowany.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy odkrywasz swój wskaźnik manewrów, możesz odrzucić tą kartę aby zrzucić 1 żeton bomby protonowej. %LINEBREAK%Żeton ten zostanie zdetonowany na koniec fazy aktywacji.""" # Canons "Ion Cannon": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi wybrany cel, obrońca otrzymuje 1 uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystie wyniki kości.""" "Heavy Laser Cannon": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Natychmiast po rzucie swoimi kośćmi ataku musisz zmienić wszystkie swoje wyniki %CRIT% na wyniki %HIT%.""" "Autoblaster": text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Twoje wyniki %HIT% nie mogą być anulowane przez kości obrony. Obrońca może anulować wyniki %CRIT% przed wynikami %HIT%.""" "Flechette Cannon": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Jeżeli ten atak trafi, obrońca otrzymuje 1 uszkodzenie i, jeśli nie jest zestresowany, otrzymuje także 1 żeton stresu. Następnie anuluj wszystkie wyniki kości.""" '"Mangler" Cannon': name: "Działo typu Mangler" text: """<strong>Atak: Zaatakuj 1 statek. %LINEBREAK%Kiedy atakujesz, możesz zmienić jeden ze swoich wyników %HIT% na wynik %CRIT%.""" # Systèmes "Enhanced Scopes": name: "Wzmocnione radary" text: """Podczas fazy aktywacji traktuj swoją wartość umiejętności pilota jakby wynosiła "0".""" "Fire-Control System": name: "System kontroli ognia" text: """Po tym jak wykonasz atak, możesz namierzyć obroncę.""" "Advanced Sensors": name: "Zaawanswowane sensory" text: """Zaraz przed tym jak ujawnisz swój manewr, możesz wykonać 1 darmową akcję. %LINEBREAK%Jeżeli skorzystawsz z tej zdolności, musisz w tej rundzie pominąć swój krok "Wykonywania akcji".""" "Sensor Jammer": name: "Zakłócacz sensorów" text: """Kiedy się bronisz możesz zmienić 1 z wyników %HIT% atakującego na wynik %FOCUS%. Atakujący nie może przerzucić kości ze zmienionym wynikiem.""" "Accuracy Corrector": name: "Korektor celności" text: """Kiedy atakujesz, możesz anulować wszystkie swoje wyniki kości. Następnie możesz dodać 2 wyniki %HIT%.%LINEBREAK% Podczas tego ataku nie można ponownie modyfikować twoich kości.""" "Advanced Targeting Computer": name: "Zaawansowany komputer celowniczy" text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK% Kiedy atakujesz namierzonego przez siebie przeciwnika przy pomocy broni podstawowej, do wyniku rzutu kośćmi możesz dodać jeden wynik %CRIT%. Jeżeli to zrobisz, podczas tego ataku nie możesz wydać żetonu namierzonego celu.""" # Équipages "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Po wykonaniu ataku, który nie trafił w wybrany cel, natychmiast wykonaj atak główną bronią. W tej rundzie nie możesz wykonać kolejnego ataku.""" "PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz w Zasiegu 3 możesz zmienić 1 ze swoich wyników %HIT% na wynik %CRIT%.""" "Weapons Engineer": name: "PI:NAME:<NAME>END_PI" text: """Możesz namierzać naraz 2 statki (każdy wrogi statek możesz namierzać tylko raz). %LINEBREAK%Kiedy namierzasz cel, możesz namierzyć 2 różne statki.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Po wykonaniu ataku, który nie trafi w wybrany cel, natychmiast wykonaj atak główną bronią. Możesz zmienić 1 wynik %FOCUS% na %HIT%.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Możesz traktować wszystkie manewry %STRAIGHT%, jakby były to zielone manewry.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Kiedy otrzymujesz kartę uszkodzenia, możesz natychmiast odrzucić tę kartę i odzyskać 1 żeton osłony. Następnie odrzuć tę kartę rozwinięcia.""" "Recon Specialist": name: "PI:NAME:<NAME>END_PI" text: """Kiedy wykonujesz akcję skupienia, przypisz do swojego statku 1 dodatkowy żeton skupienia.""" "Saboteur": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Wybierz 1 wrogi statek w Zasięgu 1 i rzuć 1 koscią ataku. Jeśli wypadnie %HIT% lub %CRIT%, wylosuj 1 zakrytą kartę uszkodzenia przypisaną do tego statku, odkryj ją i rozpatrz.""" "Intelligence Agent": name: "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" text: """Na początku fazy aktywacji wybierz 1 wrogi statek w zasięgu 1-2. Możesz podejrzeć manewr wybrany przez ten statek.""" "PI:NAME:<NAME>END_PI": text: """%PL_IMPERIALONLY%%LINEBREAK%Tylko Imperium. Po tym jak wykonasz atak skierowany przeciwko wrogiemu statkowi, możesz otrzymać 2 uszkodzenia, aby zadać temu statkowi 1 krytyczne uszkodzenie.""" "Rebel Captive": name: "PI:NAME:<NAME>END_PI" text: """%PL_IMPERIALONLY%%LINEBREAK%Raz na rundę, pierwszy statek, który zadeklaruje ciebie jako cel ataku, natychmiast otrzymuje 1 żeton stresu.""" "Flight Instructor": name: "PI:NAME:<NAME>END_PI" text: """Kiedy się bPI:NAME:<NAME>END_PIisz, możesz przerzucić 1 ze swoich wyników %FOCUS%. Jeśli wartość umiejętności atakującego pilota wynosi "2" lub mniej, zamiast tego przerzuć 1 ze swoich pustych scianek.%FOCUS%.""" "Navigator": name: "PI:NAME:<NAME>END_PI" text: """Kiedy ujawnisz swój manewr, możesz obrócić swój wskaźnik na inny manewr tego samego kierunku. %LINEBREAK%Nie możesz przekręcić wskaźnika na czerwony manewr, jeśli posiadasz jakieś żetony stresu.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Rzuć 2 koścmi obrony. Za kazdy uzyskany wynik %FOCUS% przypisz do swojego statku 1 żeton skupienia. Za każdy wynik %EVADE% przypisz do swojego statku 1 żeton uniku.%FOCUS%""" "PI:NAME:<NAME>END_PI": text: """%PL_IMPERIALONLY%%LINEBREAK% Na koniec fazy walki kazdy wrogi statek w Zasięgu 1, który nie ma żetonu stresu, otrzymuje żeton stresu.""" "Fleet Officer": name: "PI:NAME:<NAME>END_PI" text: """%PL_IMPERIALONLY%%LINEBREAK%<strong>Akcja:</strong> Wybierz maksymalnie 2 przyjazne statki w Zasięgu 1-2 i do każdego przypisz po 1 żetonie skupienia, następnie otrzymujesz 1 żeton stresu.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Tylko rebelianci. Kiedy atakujesz, jeśli namierzyłeś obrońcę, możesz wydać żeton namierzonego celu aby zmienić wszystkie swoje wyniki %FOCUS% na %HIT%.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę, aby umożliwić wszystkim przyjaznym statkom, które ujawiniają czerwony manewr, traktowanie do końca fazy tego manewru jako białego.""" "WED-15 Repair Droid": name: "Droid naprawczy WED-15" text: """%PL_HUGESHIPONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj 1 żeton energii aby odrzucić 1 ze swoich zakrytych kart uszkodzeń albo wydaj 3 żetony energii aby odrzucić 1 ze swoich odkrytych kart uszkodzeń.""" "PI:NAME:<NAME>END_PI": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji możesz odrzucić tę kartę aby do końca fazy traktować wartość umiejętności pilota każdego przyjaznego statku jakby wynosiła "12".""" "PI:NAME:<NAME>END_PI": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Kiedy inny przyjazny statek w Zasięgu 1 wykonuje atak, możesz zmienić 1 z jego wyników %HIT% na %CRIT%.""" "Tactician": name: "PI:NAME:<NAME>END_PI" text: "Po tym jak wykonasz atak przeciwko statkowi znajdującemu się w twoim polu rażenia w Zasiegu 2, statek ten otrzymuje 1 żeton stresu." "R2-D2 (Crew)": name: "R2-D2 (Załoga)" text: """%PL_REBELONLY%%LINEBREAK%Na koniec fazy końcowej, jeśli nie masz żadnych osłon, możesz odzyskać 1 osłonę i rzucić 1 kością ataku. Jeśli wypadnie %HIT% odkryj 1 losową ze swoich zakrytych kart uszkodzeń i ją rozpatrz.""" "C-3PO": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, zanim wykonasz rzut co najmniej 1 koscią obrony, możesz na głos zgadnąć liczbę wyników %EVADE%. Jeśli wypadło tyle %EVADE% (przed modyfikacjami) dodaj 1 wynik %EVADE%.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Po tym jak usuniesz ze swojego statku żeton stresu, możesz przypisać do swojego statku żeton skupienia.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Raz na rundę, kiedy przyjazny statek w Zasięgu 1-3 wykonuje akcję skupienia lub miałby otrzymać żeton skupienia, możesz danemu statkowi przypisać żeton uniku (zamiast skupienia).""" "PI:NAME:<NAME>END_PI": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> Wydaj dowolną ilość żetonów energii aby wybrać taką samą liczbę wrogich statków w Zasiegu 1-2. Usuń z wybranych statków wszystkie żetony skupienia, uników i niebieskie żetony namierzonego celu.""" "Targeting Coordinator": name: "PI:NAME:<NAME>END_PI" text: """<strong>Energia:</strong> Możesz wydać 1 żeton energii aby wybrać 1 przyjazny statek w Zasięgu 1-2. Namierz cel, a następnie przydziel do wybranego statku niebieski żeton namierzonego celu.""" "PI:NAME:<NAME>END_PI": text: """%PL_HUGESHIPONLY% %PL_REBELONLY%%LINEBREAK%Na początku fazy aktywacji wybierz 1 wrogi statek w Zasięgu 1-3. Możesz podejrzeć manewr wybrany dla tego statku. Jeżeli jest on biały, przydziel do niego 1 żeton stresu.""" '"LPI:NAME:<NAME>END_PI"': text: """%PL_REBELONLY%%LINEBREAK%<strong>Akcja:</strong> wykonaj darmową akcję "dopalacz". Następnie otrzymujesz 1 żeton jonów.""" "PI:NAME:<NAME>END_PI": text: """%PL_REBELONLY%%LINEBREAK%Możesz wykonywać ataki kiedy nachodzisz na przeszkodę. %LINEBREAK%Twoje ataki nie mogą być przyblokowane.""" "PI:NAME:<NAME>END_PI": text: """%PL_IMPERIALONLY%%LINEBREAK%Na początku fazy walki, jeśli nie masz żadnych osłon, a do twojego statku przypisana jest co najmniej 1 karta uszkodzenia, możesz wykonać darmową akcję unik.""" "PI:NAME:<NAME>END_PI": text: """%PL_IMPERIALONLY%%LINEBREAK%Kiedy otrzymujesz odkrytą kartę uszkodzenia, możesz odrzucić to rozwinięcie lub inną kartę rozwinięcia [crew] aby zakryć tę kartę uszkodzenia (bez rozpatrywania jej efektu).""" "Greedo": text: """%PL_SCUMONLY%%LINEBREAK%Za pierwszym razem kiedy atakujesz lub bronisz sie w każdej rundzie, pierwsza przypisana karta uszkodzenia jest odkryta.""" "Outlaw Tech": name: "Mechanik wyjęty spod prawa" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu czerwonego manewru, możesz przypisać do swojego statku 1 żeton skupienia.""" "K4 Security Droid": name: "Droid ochroniarz K4" text: """%PL_SCUMONLY%%LINEBREAK%Po wykonaniu zielonego manewru możesz namierzyć cel.""" # Soute "Frequency Jammer": name: "ZPI:NAME:<NAME>END_PI" text: """Kiedy wykonujesz akcję Zakłócanie, wybierz 1 wrogi statek, który nie ma żetonu stresu i znajduje się w Zasięgu 1 od zakłócanego statku. Wybrany statek otrzymuje 1 żeton stresu.""" "Expanded Cargo Hold": ship: "Średni transportowiec GR-75" name: "PI:NAME:<NAME>END_PI" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Raz na rundę, kiedy masz otrzymać odkrytą kartę uszkodznia, możesz dobrać te kartę z talii uszkodzeń dziobu lub rufy.""" "Comms Booster": name: "PI:NAME:<NAME>END_PI" text: """<strong>Energia:</strong> Wydaj 1 żeton energii aby usunąć wszystkie żetony stresu z przyjaznego statku w Zasięgu 1-3, następnie przydziel do tego statku 1 żeton skupienia.""" "Slicer Tools": name: "PI:NAME:<NAME>END_PI" text: """<strong>Akcja:</strong> Wybierz co najmniej 1 wrogi statek w Zasięgu 1-3, na ktorym znajduje się żeton stresu. Za każdy wybrany statek możesz wydać 1 żeton energii aby sprawić, żeby dany statek otrzymał 1 uszkodzenie.""" "Shield Projector": name: "PI:NAME:<NAME>END_PI" text: """Kiedy wrogi statek stanie się podczas fazy walki, możesz wydać 3 żetony energii aby do końca fazy zmusić go do zaatakowania ciebie, jeśli to możliwe.""" "Tibanna Gas Supplies": name: "PI:NAME:<NAME>END_PI" text: """<strong>Energia:</strong> Możesz odrzucić tę kartę aby otrzymać 3 żetony energii.""" "Ionization Reactor": name: "PI:NAME:<NAME>END_PI" text: """<strong>Energia:</strong> Wydaj 5 żetonów energii z tej karty i odrzuć tą kartę aby sprawić żeby każdy statek w Zasięgu 1 otrzymał 1 uszkodzneie i 1 żeton jonów.""" "Engine Booster": name: "PI:NAME:<NAME>END_PI" text: """Tuż przed tym jak odkryjesz swój wskaźnik manewrów, możesz wydać 1 żeton energii aby wykonać biały manewr (%STRAIGHT% 1). Nie możesz skorzystać z tej zdolności, jeśli w jej wyniku będziesz nachodzić na inny statek.""" "Backup Shield Generator": name: "Zapasowy generator osłon" text: """Na koniec każdej rudny możesz wydać 1 żeton energii aby odzyskać 1 osłonę (nie przekraczając swojej wartości osłon).""" "EM Emitter": name: "Emiter elektro-magnetyczny" text: """Kiedy przyblokujesz atak, obrońca rzuca 3 dodatkowymi kośmi obrony (zamiast 1).""" # Hardpiont "Ion Cannon Battery": name: "Bateria działa jonowego" text: """<strong>Atak (energia):</strong> Aby wykonać ten atak, wydaj 2 żetony energii z tej karty. Jeżeli atak ten trafi w wybrany statek, otrzymuje on 1 krytyczne uszkodzenie oraz 1 żeton jonów. Następnie anuluj wszystkie wyniki kości.""" "Single Turbolasers": name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak (energia):</strong> Wydaj 2 żetony energii z tej karty aby wykonać ten atak. Obronca podwaja swoją wartość zwrotności przeciwko temu atakowi. Możesz zmienić jeden ze swoich wyników %FOCUS% na %HIT%.""" "Quad Laser Cannons": name: "Poczwórne działka laserowe" text: """<strong>Atak (energia):</strong> Wydaj 1 żeton energii z tej karty aby wykonać ten atak. Jeśli ten atak nie trafi, możesz natychmiast wydać 1 żeton energii z tej karty aby ponownie przeprowadzić ten atak.""" # Équipe "Gunnery Team": name: "PI:NAME:<NAME>END_PI" text: """Raz na rundę kiedy atakujesz przy pomocy daodatkowej broni, możesz wydać 1 żeton energii aby zmienić 1 ze swoich pustych wyników na %HIT%.""" "Sensor Team": name: "PI:NAME:<NAME>END_PI sensorów" text: """Kiedy namierzasz cel, możesz namierzyć wrogi statek w Zasięgu 1-5 (zamiast Zasięgu 1-3).""" "Engineering Team": name: "PI:NAME:<NAME>END_PI" text: """Podczas fazy aktywacji, kiedy ujawnisz manewr %STRAIGHT%, otrzymujesz 1 dodatkowy żeton energii podczas kroku Otrzymywania energii.""" # Illégal "Inertial Dampeners": name: "PI:NAME:<NAME>END_PI" text: """Kiedy ujawniasz swój manewr, możesz odrzucić tę kartę żeby zamiast tego wykonać biały manewr [0%STOP%]. Następnie otrzymujesz 1 żeton stresu.""" "Dead Man's Switch": name: "PI:NAME:<NAME>END_PI" text: """Kiedy zostajesz zniszczony, każdy statek w Zasięgu 1 otrzymuje 1 uszkodzenie.""" "Feedback Array": name: "System zwrotny" text: """Podczas fazy walki, zamiast wykonywać jakiekolwiek ataki, możesz otrzymać 1 żeton jonów i 1 uszkodzenie aby wybrać wrogi statek w Zasięgu 1. Wybrany statek otrzymuje 1 uszkodzenie.""" '"Hot Shot" Blaster': name: "PI:NAME:<NAME>END_PI" text: """<strong>Atak:</strong> Odrzuć tę kartę, aby zaatakować 1 statek (nawet poza twoim polem rażenia).""" # Astromech récupéré "Salvaged Astromech": name: "AstromePI:NAME:<NAME>END_PI z odzysku" text: "Kiedy otrzymujesz kartę uszkodzenia z cechą Statek, natychmiast możesz ją odrzucić (przed rozpatrzeniem efektu). %LINEBREAK%Następnie odrzuć tę kartę rozwinięcia.%LINEBREAK%." '"PI:NAME:<NAME>END_PI"': name: "PI:NAME:<NAME>END_PI" text: """Jeśli jesteś wyposażony w bombę, która może zostać zrzucona przed ujawnieniem twojego manewru, zamiast tego możesz ją zrzucić po tym jak wykonasz swój manewr.""" "Unhinged Astromech": name: "PI:NAME:<NAME>END_PI" text: """Możesz traktować manewry o prędkości 3 jako zielone.""" "R4-B11": text: """Kiedy atakujesz namierzonego przez siebie obrońcę, możesz wydać żeton namierzonego celu aby wybrać dowolne kości obrony (nawet wszystkie). Następnie obrońca musi przerzucić wybrane przez ciebie kości.""" "R4 AgromePI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """Kiedy atakujesz, po wydaniu żetonu skupienia, możesz namierzyć obrońcę.""" "PI:NAME:<NAME>END_PI": text: """%IMPERIALONLY%%LINEBREAK%Once per round, you may change a friendly ship's die result to any other die result. That die result cannot be modified again.""" "Bossk": text: """%SCUMONLY%%LINEBREAK%After you perform an attack that does not hit, if you are not stressed, you <strong>must</strong> receive 1 stress token. Then assign 1 focus token to your ship and acquire a target lock on the defender.""" "Lightning Reflexes": text: """%SMALLSHIPONLY%%LINEBREAK%After you execute a white or green maneuver on your dial, you may discard this card to rotate your ship 180&deg;. Then receive 1 stress token <strong>after</strong> the "Check Pilot Stress" step.""" "Twin Laser Turret": text: """<strong>Attack:</strong> Perform this attack <strong>twice</strong> (even against a ship outside your firing arc).<br /><br />Each time this attack hits, the defender suffers 1 damage. Then cancel <strong>all</strong> dice results.""" "Plasma Torpedoes": text: """<strong>Attack (target lock):</strong> Spend your target lock and discard this card to perform this attack.<br /><br />If this attack hits, after dealing damage, remove 1 shield token from the defender.""" "Ion Bombs": text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 ion bomb token.<br /><br />This token <strong>detonates</strong> at the end of the Activation phase.<br /><br /><strong>Ion Bombs Token:</strong> When this bomb token detonates, each ship at Range 1 of the token receives 2 ion tokens. Then discard this token.""" "Conner Net": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 1 Conner Net token.<br /><br />When a ship's base or maneuver template overlaps this token, this token <strong>detonates</strong>.<br /><br /><strong>Conner Net Token:</strong> When this bomb token detonates, the ship that moved through or overlapped this token suffers 1 damage, receives 2 ion tokens, and skips its "Perform Action" step. Then discard this token.""" "Bombardier": text: """When dropping a bomb, you may use the (%STRAIGHT% 2) template instead of the (%STRAIGHT% 1) template.""" "Cluster Mines": text: """<strong>Action:</strong> Discard this card to <strong>drop</strong> 3 cluster mine tokens.<br /><br />When a ship's base or maneuver template overlaps a cluster mine token, that token <strong>detonates</strong>.<br /><br /><strong>Cluster Mines Tokens:</strong> When one of these bomb tokens detonates, the ship that moved through or overlapped this token rolls 2 attack dice and suffers all damage (%HIT%) rolled. Then discard this token.""" 'Crack Shot': text: '''When attacking a ship inside your firing arc, you may discard this card to cancel 1 of the defender's %EVADE% results.''' "Advanced Homing Missiles": text: """<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, deal 1 faceup Damage card to the defender. Then cancel <strong>all</strong> dice results.""" 'PI:NAME:<NAME>END_PI': text: '''%IMPERIALONLY%%LINEBREAK%At the start of the first round, choose 1 enemy small or large ship. When attacking or defending against that ship, you may change 1 of your %FOCUS% results to a %HIT% or %EVADE% result.''' 'XX-23 S-Thread Tracers': text: """<strong>Attack (focus):</strong> Discard this card to perform this attack. If this attack hits, each friendly ship at Range 1-2 of you may acquire a target lock on the defender. Then cancel <strong>all</strong> dice results.""" "Tractor Beam": text: """<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, the defender receives 1 tractor beam token. Then cancel <strong>all</strong> dice results.""" "Cloaking Device": text: """%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Perform a free cloak action.%LINEBREAK%At the end of each round, if you are cloaked, roll 1 attack die. On a %FOCUS% result, discard this card, then decloak or discard your cloak token.""" "Shield Technician": text: """%HUGESHIPONLY%%LINEBREAK%When you perform a recover action, instead of spending all of your energy, you can choose any amount of energy to spend.""" "Weapons Guidance": text: """When attacking, you may spend a focus token to change 1 of your blank results to a %HIT% result.""" "BB-8": text: """When you reveal a green maneuver, you may perform a free barrel roll action.""" "R5-X3": text: """Before you reveal your maneuver, you may discard this card to ignore obstacles until the end of the round.""" "Wired": text: """When attacking or defending, if you are stressed, you may reroll 1 or more of your %FOCUS% results.""" 'Cool Hand': text: '''When you receive a stress token, you may discard this card to assign 1 focus or evade token to your ship.''' 'Juke': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking, if you have an evade token, you may change 1 of the defender's %EVADE% results into a %FOCUS% result.''' 'Comm Relay': text: '''You cannot have more than 1 evade token.%LINEBREAK%During the End phase, do not remove an unused evade token from your ship.''' 'Dual Laser Turret': text: '''%GOZANTIONLY%%LINEBREAK%<strong>Attack (energy):</strong> Spend 1 energy from this card to perform this attack against 1 ship (even a ship outside your firing arc).''' 'Broadcast Array': text: '''%GOZANTIONLY%%LINEBREAK%Your action bar gains the %JAM% action icon.''' 'Rear Admiral Chiraneau': text: '''%HUGESHIPONLY% %IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Execute a white (%STRAIGHT% 1) maneuver.''' 'Ordnance Experts': text: '''Once per round, when a friendly ship at Range 1-3 performs an attack with a %TORPEDO% or %MISSILE% secondary weapon, it may change 1 of its blank results to a %HIT% result.''' 'Docking Clamps': text: '''%GOZANTIONLY% %LIMITED%%LINEBREAK%You may attach 4 up to TIE fighters, TIE interceptors, TIE bombers, or TIE Advanced to this ship. All attached ships must have the same ship type.''' '"Zeb" Orrelios': text: """%REBELONLY%%LINEBREAK%Enemy ships inside your firing arc that you are touching are not considered to be touching you when either you or they activate during the Combat phase.""" 'PI:NAME:<NAME>END_PI': text: """%REBELONLY%%LINEBREAK%Once per round, after a friendly ship at Range 1-2 executes a white maneuver, you may remove 1 stress token from that ship.""" 'Reinforced Deflectors': text: """%LARGESHIPONLY%%LINEBREAK%After defending, if you suffered a combination of 3 or more damage and critical damage during the attack, recover 1 shield (up to your shield value).""" 'Dorsal Turret': text: """<strong>Attack:</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the target of this attack is at Range 1, roll 1 additional attack die.""" 'Targeting Astromech': text: '''After you execute a red maneuver, you may acquire a target lock.''' 'PI:NAME:<NAME>END_PI': text: """%REBELONLY%%LINEBREAK%You may reveal and execute red maneuvers even while you are stressed.""" 'PI:NAME:<NAME>END_PI': text: """%REBELONLY%%LINEBREAK%When attacking, if you are stressed, you may change 1 of your %FOCUS% results to a %CRIT% result.""" 'PI:NAME:<NAME>END_PI': text: """%REBELONLY%%LINEBREAK%Your upgrade bar gains the %BOMB% upgrade icon. Once per round, before a friendly bomb token is removed, choose 1 enemy ship at Range 1 of that token. That ship suffers 1 damage.""" '"Chopper"': text: """%REBELONLY%%LINEBREAK%You may perform actions even while you are stressed.%LINEBREAK%After you perform an action while you are stressed, suffer 1 damage.""" 'Construction Droid': text: '''%HUGESHIPONLY% %LIMITED%%LINEBREAK%When you perform a recover action, you may spend 1 energy to discard 1 facedown Damage card.''' 'Cluster Bombs': text: '''After defending, you may discard this card. If you do, each other ship at Range 1 of the defending section rolls 2 attack dice, suffering all damage (%HIT%) and critical damage (%CRIT%) rolled.''' "Adaptability": text: """<span class="card-restriction">Dual card.</span>%LINEBREAK%<strong>Side A:</strong> Increase your pilot skill value by 1.%LINEBREAK%<strong>Side B:</strong> Decrease your pilot skill value by 1.""" "Electronic Baffle": text: """When you receive a stress token or an ion token, you may suffer 1 damage to discard that token.""" "4-LOM": text: """%SCUMONLY%%LINEBREAK%When attacking, during the "Modify Attack Dice" step, you may receive 1 ion token to choose 1 of the defender's focus or evade tokens. That token cannot be spent during this attack.""" "Zuckuss": text: """%SCUMONLY%%LINEBREAK%When attacking, you may receive any number of stress tokens to choose an equal number of defense dice. The defender must reroll those dice.""" 'Rage': text: """<strong>Action:</strong> Assign 1 focus token to your ship and receive 2 stress tokens. Until the end of the round, when attacking, you may reroll up to 3 attack dice.""" "Attanni Mindlink": text: """%SCUMONLY%%LINEBREAK%Each time you are assigned a focus or stress token, each other friendly ship with Attanni Mindlink must also be assigned the same type of token if it does not already have one.""" "PI:NAME:<NAME>END_PI": text: """%SCUMONLY%%LINEBREAK%After performing an attack, if the defender was dealt a faceup Damage card, you may discard this card to choose and discard 1 of the defender's Upgrade cards.""" "PI:NAME:<NAME>END_PI": text: """%SCUMONLY%%LINEBREAK%When attacking, you may reroll 1 attack die. If the defender is a unique pilot, you may instead reroll up to 2 attack dice.""" '"PI:NAME:<NAME>END_PI"': text: """%SCUMONLY%%LINEBREAK%<strong>Action:</strong> Place 1 shield token on this card.%LINEBREAK%<strong>Action:</strong> Remove 1 shield token from this card to recover 1 shield (up to your shield value).""" "R5-P8": text: """Once per round, after defending, you may roll 1 attack die. On a %HIT% result, the attacker suffers 1 damage. On a %CRIT% result, you and the attacker each suffer 1 damage.""" 'Thermal Detonators': text: """When you reveal your maneuver dial, you may discard this card to <strong>drop</strong> 1 thermal detonator token.%LINEBREAK%This token <strong>detonates</strong> at the end of the Activation phase.%LINEBREAK%<strong>Thermal Detonator Token:</strong> When this bomb token detonates, each ship at Range 1 of the token suffers 1 damage and receives 1 stress token. Then discard this token.""" "Overclocked R4": text: """During the Combat phase, when you spend a focus token, you may receive 1 stress token to assign 1 focus token to your ship.""" 'Systems Officer': text: '''%IMPERIALONLY%%LINEBREAK%After you execute a green maneuver, choose another friendly ship at Range 1. That ship may acquire a target lock.''' 'Tail Gunner': text: '''When attacking from your rear-facing auxiliary firing arc, reduce the defender's agility by 1 (to a minimum of "0").''' 'R3 Astromech': text: '''Once per round, when attacking with a primary weapon, you may cancel 1 of your %FOCUS% results during the "Modify Attack Dice" step to assign 1 evade token to your ship.''' 'Collision Detector': text: '''When performing a boost, barrel roll, or decloak, your ship and maneuver template can overlap obstacles.%LINEBREAK%When rolling for obstacle damage, ignore all %CRIT% results.''' 'Sensor Cluster': text: '''When defending, you may spend a focus token to change 1 of your blank results to an %EVADE% result.''' 'Fearlessness': text: '''%SCUMONLY%%LINEBREAK%When attacking, if you are inside the defender's firing arc at Range 1 and the defender is inside your firing arc, you may add 1 %HIT% result to your roll.''' 'PI:NAME:<NAME>END_PI': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may choose 1 ship in your firing arc at Range 1-2. That ship does not remove its tractor beam tokens.''' 'PI:NAME:<NAME>END_PI': text: '''%SCUMONLY%%LINEBREAK%When defending, you may remove 1 stress token from the attacker to add 1 %EVADE% result to your roll.''' 'IG-88D': text: '''%SCUMONLY%%LINEBREAK%You have the pilot ability of each other friendly ship with the <em>IG-2000</em> Upgrade card (in addition to your own pilot ability).''' 'Rigged Cargo Chute': text: '''%LARGESHIPONLY%%LINEBREAK%<strong>Action:</strong> Discard this card to <strong>drop</strong> one cargo token.''' 'Seismic Torpedo': text: '''<strong>Action:</strong> Discard this card to choose an obstacle at Range 1-2 and inside your primary firing arc. Each ship at Range 1 of the obstacle rolls 1 attack die and suffers any damage (%HIT%) or critical damage (%CRIT%) rolled. Then remove the obstacle.''' 'Black Market Slicer Tools': text: '''<strong>Action:</strong> Choose a stressed enemy ship at Range 1-2 and roll 1 attack die. On a (%HIT%) or (%CRIT%) result, remove 1 stress token and deal it 1 facedown Damage card.''' # Wave X 'PI:NAME:<NAME>END_PI': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Assign the "I'll Show You the Dark Side" Condition card to an enemy ship at Range 1-3.''' 'PI:NAME:<NAME>END_PI': text: '''%SCUMONLY%%LINEBREAK%After executing a maneuver that causes you to overlap an enemy ship, you may suffer 1 damage to perform 1 free action.''' 'A Score to Settle': text: '''During setup, before the "Place Forces" step, choose 1 enemy ship and deal the "A Debt to Pay" Condition card to it.%LINEBREAK%Wehn attacking a ship that has the "A Debt to Pay" Condition card, you may change 1 %FOCUS% result to a %CRIT% result.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%<strong>Action:</strong> Choose 1 friendly ship at Range 1-2. Assign 1 focus token to that ship for each enemy ship inside your firing arc at Range 1-3. You cannot assign more than 3 focus tokens in this way.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%At the end of the Planning phase, you may choose an enemy ship at Range 1-2. Guess aloud that ship's bearing and speed, then look at its dial. If you are correct, you may rotate your dial to another maneuver.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%When attacking with a primary weapon or defending, if the enemy ship is inside your firing arc, you may add 1 blank result to your roll.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%At the start of the End phase, you may place 1 of your ship's focus tokens on this card. At the start of the Combat phase, you may assign 1 of those tokens to your ship.''' 'Burnout SLAM': text: '''%LARGESHIPONLY%%LINEBREAK%Your action bar gains the %SLAM% action icon.%LINEBREAK%After you perform a SLAM action, discard this card.''' 'Primed Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Stress tokens do not prevent you from performing boost or barrel roll actions unless you have 3 or more stress tokens.''' 'Pattern Analyzer': text: '''When executing a maneuver, you may resolve the "Check Pilot Stress" step after the "Perform Action" step (instead of before that step).''' 'Snap Shot': text: '''After an enemy ship executes a maneuver, you may perform this attack against that ship. <strong>Attack:</strong> Attack 1 ship. You cannot modify your attack dice and cannot attack again this phase.''' 'M9-G8': text: '''%REBELONLY%%LINEBREAK%When a ship you have locked is attacking, you may choose 1 attack die. The attacker must reroll that die.%LINEBREAK%You can acquire target locks on other friendly ships.''' 'EMP Device': text: '''During the Combat phase, instead of performing any attacks, you may discard this card to assign 2 ion tokens to each ship at Range 1.''' 'Captain Rex': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may assign 1 focus token to your ship.''' 'General Hux': text: '''%IMPERIALONLY%%LINEBREAK%<strong>Action:</strong> Choose up to 3 friendly ships at Range 1-2. Assign 1 focus token to each and assign the "Fanatical Devotion" Condition card to 1 of them. Then receive 1 stress token.''' 'Operations Specialist': text: '''%LIMITED%%LINEBREAK%After a friendly ship at Range 1-2 performs an attack that does not hit, you may assign 1 focus token to a friendly ship at Range 1-3 of the attacker.''' 'Targeting Synchronizer': text: '''When a friendly ship at Range 1-2 is attacking a ship you have locked, the friendly ship treats the "<strong>Attack (target lock):</strong> header as "<strong>Attack:</strong>." If a game effect instructs you to spend a target lock, it may spend your target lock instead.''' 'Hyperwave Comm Scanner': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0," "6," or "12" until the end of the step.%LINEBREAK%During setup, after another friendly ship is placed at Range 1-2, you may assign 1 focus or evade token to it.''' 'Trick Shot': text: '''When attacking, if the attack is obstructed, you may roll 1 additional attack die.''' 'Hotshot Co-pilot': text: '''When attacking with a primary weapon, the defender must spend 1 focus token if able.%LINEBREAK%When defending, the attacker must spend 1 focus token if able.''' '''Scavenger Crane''': text: '''After a ship at Range 1-2 is destroyed, you may choose a discarded %TORPEDO%, %MISSILE%, %BOMB%, %CANNON%, %TURRET%, or Modification Upgrade card that was equipped to your ship and flip it faceup. Then roll 1 attack die. On a blank result, discard Scavenger Crane.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%When you acquire a target lock, you can lock onto an enemy ship at Range 1-3 of any friendly ship.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%After you perform an attack that does not hit, you may immediately perform a primary weapon attack against a different ship. You cannot perform another attack this round.''' 'Inspiring Recruit': text: '''Once per round, when a friendly ship at Range 1-2 removes a stress token, it may remove 1 additional stress token.''' 'Swarm Leader': text: '''When performing a primary weapon attack, choose up to 2 other friendly ships that have the defender inside their firing arcs at Range 1-3. Remove 1 evade token from each chosen ship to roll 1 additional attack die for each token removed.''' 'Bistan': text: '''%REBELONLY%%LINEBREAK%When attacking Range 1-2, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Expertise': text: '''When attacking, if you are not stressed, you may change all of your %FOCUS% results to %HIT% results.''' 'BoShek': text: '''When a ship you are touching activates, you may look at its chosen maneuver. If you do, its owner <strong>must</strong> rotate the dial to an adjacent maneuver. The ship can reveal and execute that maneuver even while stressed.''' # C-ROC 'Heavy Laser Turret': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%<strong>Attack (energy):</strong> Spend 2 energy from this card to perform this attack against 1 ship (even a ship outside of your firing arc).''' 'PI:NAME:<NAME>END_PI': text: '''%SCUMONLY%%LINEBREAK%At the start of the End phase, you may discard this card to replace a faceup %ILLICIT% or %CARGO% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Azmorigan': text: '''%HUGESHIPONLY% %SCUMONLY%%LINEBREAK%At the start of the End phase, you may spend 1 energy to replace a faceup %CREW% or %TEAM% Upgrade card you have equipped with another Upgrade card of the same type of equal or fewer squad points.''' 'Quick-release Cargo Locks': text: '''%LINEBREAK%At the end of the Activation phase, you may discard this card to <strong>place</strong> 1 container token.''' 'Supercharged Power Cells': text: '''When attacking, you may discard this card to roll 2 additional attack dice.''' 'ARC Caster': text: '''<span class="card-restriction">Rebel and Scum only.</span>%DUALCARD%%LINEBREAK%<strong>Side A:</strong>%LINEBREAK%<strong>Attack:</strong> Attack 1 ship. If this attack hits, you must choose 1 other ship at Range 1 of the defender to suffer 1 damage.%LINEBREAK%Then flip this card.%LINEBREAK%<strong>Side B:</strong>%LINEBREAK%(Recharging) At the start of the Combat phase, you may receive a weapons disabled token to flip this card.''' 'WPI:NAME:<NAME>END_PI': text: '''When attacking, you may reroll your %FOCUS% results.''' 'Synced Turret': text: '''<strong>Attack (Target Lock):</strong> Attack 1 ship (even a ship outside your firing arc).%LINEBREAK%If the defender is inside your primary firing arc, you may reroll a number of attack dice up to your primary weapon value.''' 'Unguided Rockets': text: '''<strong>Attack (focus):</strong> Attack 1 Ship.%LINEBREAK%Your attack dice can be modified only by spending a focus token for its standard effect.''' 'Intensity': text: '''%SMALLSHIPONLY% %DUALCARD%%LINEBREAK%<strong>Side A:</strong> After you perform a boost or barrel roll action, you may assign 1 focus or evade token to your ship. If you do, flip this card.%LINEBREAK%<strong>Side B:</strong> (Exhausted) At the end of the Combat phase, you may spend 1 focus or evade token to flip this card.''' 'PI:NAME:<NAME>END_PI': text: '''%SCUMONLY%%LINEBREAK%When you equip this card, place 1 illicit token on each %ILLICIT% Upgrade card in your squad. When you are instructed to discard an Upgrade card, you may discard 1 illicit token on that card instead.''' 'IG-RM Thug Droids': text: '''When attacking, you may change 1 of your %HIT% results to a %CRIT% result.''' 'Selflessness': text: '''%SMALLSHIPONLY% %REBELONLY%%LINEBREAK%When a friendly ship at Range 1 is hit by an attack, you may discard this card to suffer all uncanceled %HIT% results instead of the target ship.''' 'Breach Specialist': text: '''When you are dealt a faceup Damage card, you may spend 1 reinforce token to flip it facedown (without resolving its effect). If you do, until the end of the round, when you are dealt a faceup Damage card, flip it facedown (without resolving its effect).''' 'R4-E1': text: '''You can perform actions on your %TORPEDO% and %BOMB% Upgrade cards even if you are stressed. After you perform an action in this way, you may discard this card to remove 1 stress token from your ship.''' 'Cruise Missiles': text: '''<strong>Attack (Target Lock):</strong> Discard this card to perform this attack.%LINEBREAK%You may roll additional attack dice equal to the speed of the manuever you performed this round, to a maximum of 4 additional dice.''' 'Ion Dischargers': text: '''After you receive an ion token, you may choose an enemy ship at Range 1. If you do, remove that ion token. Then that ship may choose to receive 1 ion token. If it does, discard this card.''' 'Harpoon Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, assign the "Harpooned!" Condition to the defender.''' 'Ordnance Silos': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When you equip this card, place 3 ordnance tokens on each other equipped %BOMB% Upgrade card. When you are instructed to discard an Upgrade card, you may discard 1 ordnance token on that card instead.''' 'Trajectory Simulator': text: '''You may launch bombs using the (%STRAIGHT% 5) template instead of dropping them. You cannot launch bombs with the "<strong>Action:</strong>" header in this way.''' 'Jamming Beam': text: '''<strong>Attack:</strong> Attack 1 ship.%LINEBREAK%If this attack hits, assign the defender 1 jam token. Then cancel <strong>all</strong> dice results.''' 'Linked Battery': text: '''%SMALLSHIPONLY%%LINEBREAK%When attacking with a primary or %CANNON% secondary weapon, you may reroll 1 attack die.''' 'Saturation Salvo': text: '''After you perform an attack with a %TORPEDO% or %MISSILE% secondary weapon that does not hit, each ship at Range 1 of the defender with an agility value lower than the squad point cost of the %TORPEDO% or %MISSILE% Upgrade card must roll 1 attack die and suffer any damage (%HIT%) or critical damage (%CRIT%) rolled.''' 'Contraband Cybernetics': text: '''When you become the active ship during the Activation phase, you may discard this card and receive 1 stress token. If you do, until the end of the round, you may perform actions and red maneuvers even while you are stressed.''' 'Maul': text: '''%SCUMONLY% <span class="card-restriction">Ignore this restriction if your squad contains "Ezra Bridger."</span>%LINEBREAK%When attacking, if you are not stressed, you may receive any number of stress tokens to reroll that many attack dice.%LINEBREAK%After performing an attack that hits, you may remove 1 of your stress tokens.''' 'Courier Droid': text: '''At the start of the "Place Forces" step, you may choose to treat your pilot skill value as "0" or "8" until the end of the step.''' '"Chopper" (Astromech)': text: '''<strong>Action: </strong>Discard 1 other equipped Upgrade card to recover 1 shield.''' 'Flight-Assist Astromech': text: '''You cannot attack ships outside your firing arc.%LINEBREAK%After you execute a maneuver, if you did not overlap a ship or obstacle and there are no enemy ships inside your firing arc at Range 1-3, you may perform a free boost or barrel roll action.''' 'Advanced Optics': text: '''You cannot have more than 1 focus token.%LINEBREAK%During the End phase, do not remove an unused focus token from your ship.''' 'Scrambler Missiles': text: '''<strong>Attack (target lock):</strong> Discard this card to perform this attack.%LINEBREAK%If this attack hits, the defender and each other ship at Range 1 receives 1 jam token. Then cancel <strong>all</strong> results.''' 'R5-TK': text: '''You can acquire target locks on friendly ships.%LINEBREAK%You can attack friendly ships.''' 'Threat Tracker': text: '''%SMALLSHIPONLY%%LINEBREAK%When an enemy ship inside your firing arc at Range 1-2 becomes thee active ship during the Combat phase, you may spend your target lock on that ship to perform a free boost or barrell roll action if that action is on your action bar.''' 'PI:NAME:<NAME>END_PI': text: '''%SMALLSHIPONLY%%LINEBREAK%<strong>Action:</strong> Assign 1 evade token to your ship for each obstacle at Range 1, to a maximum of 2 evade tokens.''' 'Targeting Scrambler': text: '''At the start of the Planning phase, you may receive a weapons disabled token to choose a ship at Range 1-3 and assign it the "Scrambled" Condition.''' 'Death Troopers': text: '''After another friendly ship at range 1 becomes the defender, if you are inside the attacker's firing arc at range 1-3, the attacker receives 1 stress token.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%When attacking, you may suffer 1 damage to change all of your %FOCUS% results to %CRIT% results.''' 'PI:NAME:<NAME>END_PI': text: '''During setup, before the "Place Forces" step, assign the "Optimized Prototype" condition to a friendly Galactic Empire ship with 3 or fewer shields.''' 'PI:NAME:<NAME>END_PI': text: '''%REBELONLY%%LINEBREAK%After defending, you may acquire a target lock on the attacker.''' 'Renegade Refit': text: '''<span class="card-restriction">T-65 X-Wing and U-Wing only.</span>%LINEBREAK%You can equip up to two different Modification upgrades.%LINEBREAK%The squad point cost of each of your equipped %ELITE% upgrades is reduced by 1 (to a minimum of 0).''' 'Tactical Officer': text: '''%IMPERIALONLY%%LINEBREAK%Your action bar gains %COORDINATE%.''' 'ISB Slicer': text: '''After you perform a jam action against an enemy ship, you may choose a ship at Range 1 of that ship that is not jammed and assign it 1 jam token.''' 'Thrust Corrector': text: '''When defending, if you have 3 or fewer stress tokens, you may receive 1 stress token to cancel all of your dice results. If you do, add 1 %EVADE% result to your roll. Your dice cannot be modified again during this attack.%LINEBREAK%You can equip this Upgrade only if your hull value is "4" or lower.''' modification_translations = "Shield Upgrade": name: "Ulepszenie osłon" text: """Zwiększ wartość swoich osłon o 1.""" "Advanced Cloaking Device": name: "Zaawansowany system maskowania" text: """<span class="card-restriction">Tylko TIE Phantom.</span>%LINEBREAK%Po tym jak wykonasz atak, możesz wykonać darmową akcję maskowanie.""" ship: "TIE Phantom" "Stealth Device": name: "Urządzenie maskujące" text: """Zwiększ wartość swojej zwrotności o 1. Jeśli zostaniesz trafiony podczas ataku, odrzuć tę kartę.""" "Engine Upgrade": name : "Ulepszenie silnika" text: """Twój pasek rozwinięć zyskuje symbol akcji %BOOST%.""" "Anti-Pursuit Lasers": name: "Lasery antypościgPI:NAME:<NAME>END_PI" text: """%PL_LARGESHIPONLY%Po tym jak wrogi statek wykona manewr, który sprawi że będzie zachodzić na ciebie, rzuć 1 kością ataku. Jeśli wypadnie %HIT% lub %CRIT%, wrogi statek otrzymuje 1 uszkodzenie.""" "Targeting Computer": name: "Komputer celowniczy" text: """Twój pasek akcji zyskuje symbol akcji %TARGETLOCK%.""" "Hull Upgrade": name: "Ulepszenie kadłuba" text: """Zwiększ wartość swojego kadłuba o 1.""" "Munitions Failsafe": name: "Zabezpieczenie amunicji" text: """Kiedy atakujesz przy pomocy broni dodatkowej, która nakazuje odrzucenie karty po wykonaniu ataku, nie odrzucasz jej jeśli atak nie trafi.""" "Stygium Particle Accelerator": name: "Akcelerator cząsteczek stygium" text: """Kiedy się demaskujesz lub wykonasz akcję maskowanie, możesz wykonać darmową akcję unik.""" "Combat Retrofit": name: "Modyfikacja bojowa" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Zwiększ wartość swojego kadłuba o 2 i wartość swoich osłon o 1.""" ship: "Transport moyen GR-75" "B-Wing/E2": text: """<span class="card-restriction">Tylko B-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %CREW%.""" "Countermeasures": name: "Środki profilaktyczne" text: """%PL_LARGESHIPONLY%%LINEBREAK%Na początku fazy walki możesz odrzucić tę kartę, aby do końca rundy zwiększyć swoją zwrotność o 1. Następnie możesz usunąć ze swojego statku 1 wrogi żeton namierzonego celu.""" "Experimental Interface": name: "Eksperymentalny interfejs" text: """Raz na rundę. Po tym jak wykonasz akcję możesz wykonać 1 darmową akcję z karty rozwinięcia z nagłówkiem <strong>Akcja:</strong>, w którą jesteś wyposażony. Następnie otrzymujesz 1 żeton stresu.""" "Tactical Jammer": name: "PI:NAME:<NAME>END_PI" text: """%PL_LARGESHIPONLY%%LINEBREAK%Twój statek może przyblokowywać wrogie ataki.""" "Autothrusters": name: "PI:NAME:<NAME>END_PI" text: """Kiedy się bronisz, jeśli jesteś poza Zasięgiem 2 albo znajdujesz się poza polem rażenia atakującego, możesz zmienić 1 ze swoich pustych wyników na %EVADE%. Możesz wyposażyć swój statek w tę kartę tylko jeśli masz symbol akcji %BOOST%.""" "Twin Ion Engine Mk. II": text: """You may treat all bank maneuvers (%BANKLEFT% and %BANKRIGHT%) as green maneuvers.""" "Maneuvering Fins": text: """<span class="card-restriction">YV-666 only.</span>%LINEBREAK%When you reveal a turn maneuver (%TURNLEFT% or %TURNRIGHT%), you may rotate your dial to the corresponding bank maneuver (%BANKLEFT% or %BANKRIGHT%) of the same speed.""" "Ion Projector": text: """%LARGESHIPONLY%%LINEBREAK%After an enemy ship executes a maneuver that causes it to overlap your ship, roll 1 attack die. On a %HIT% or %CRIT% result, the enemy ship receives 1 ion token.""" 'Integrated Astromech': text: '''<span class="card-restriction">X-wing only.</span>%LINEBREAK%When you are dealt a Damage card, you may discard 1 of your %ASTROMECH% Upgrade cards to discard that Damage card.''' 'Optimized Generators': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, when you assign energy to an equipped Upgrade card, gain 2 energy.''' 'Automated Protocols': text: '''%HUGESHIPONLY%%LINEBREAK%Once per round, after you perform an action that is not a recover or reinforce action, you may spend 1 energy to perform a free recover or reinforce action.''' 'Ordnance Tubes': text: '''%HUGESHIPONLY%%LINEBREAK%You may treat each of your %HARDPOINT% upgrade icons as a %TORPEDO% or %MISSILE% icon.%LINEBREAK%When you are instructed to discard a %TORPEDO% or %MISSILE% Upgrade card, do not discard it.''' 'Long-Range Scanners': text: '''You can acquire target locks on ships at Range 3 and beyond. You cannot acquire target locks on ships at Range 1-2. You can equip this card only if you have %TORPEDO% and %MISSILE% in your upgrade bar.''' "Guidance Chips": text: """Once per round, when attacking with a %TORPEDO% or %MISSILE% secondary weapon, you may change 1 die result to a %HIT% result (or a %CRIT% result if your primary weapon value is "3" or higher).""" 'Vectored Thrusters': text: '''%SMALLSHIPONLY%%LINEBREAK%Your action bar gains the %BARRELROLL% action icon.''' 'Smuggling Compartment': text: '''<span class="card-restriction">YT-1300 and YT-2400 only.</span>%LINEBREAK%Your upgrade bar gains the %ILLICIT% upgrade icon.%LINEBREAK%You may equip 1 additional Modification upgrade that costs 3 or fewer squad points.''' 'Gyroscopic Targeting': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%At the end of the Combat phase, if you executed a 3-, 4-, or 5-speed maneuver this round, you may rotate your mobile firing arc.''' 'Captured TIE': text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Enemy ships with a pilot skill value lower than yours cannot declare you as the target of an attack. After you perform an attack or when you are the only remaining friendly ship, discard this card.''' 'Spacetug Tractor Array': text: '''<span class="card-restriction">Quadjumper only.</span>%LINEBREAK%<strong>Action:</strong> Choose a ship inside your firing arc at Range 1 and assign a tractor beam token to it. If it is a friendly ship, resolve the effect of the tractor beam token as though it were an enemy ship.''' 'Lightweight Frame': text: '''<span class="card-restriction">TIE only.</span>%LINEBREAK%When defending, after rolling defense dice, if there are more attack dice than defense dice, roll 1 additional defense die.%LINEBREAK%You cannot equip this card if your agility value is "3" or higher.''' 'Pulsed Ray Shield': text: '''<span class="card-restriction">Rebel and Scum only.</span>%LINEBREAK%During the End phase, you may receive 1 ion token to recover 1 shield (up to your shield value). You can equip this card only if your shield value is "1."''' 'Deflective Plating': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When a friendly bomb token detonates, you may choose not to suffer its effects. If you do, roll an attack die. On a %HIT% result, discard this card.''' 'Servomotor S-Foils': text: '''<span class="card-restriction">T-65 X-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong>Your action bar gains %BARRELROLL%. If you are not stressed, when you reveal a (%TURNLEFT% 3) or (3 %TURNRIGHT%) maneuver, you may treat it as a red (%TROLLLEFT% 3) or (%TROLLRIGHT% 3) in the same direction.%LINEBREAK%At the start of the Activation phase, you may flip this card.%LINEBREAK%<strong>Side B (Closed):</strong>Reduce your primary attack value by 1. Your action bar gains %BOOST%. Treat your (%BANKLEFT% 2) and (%BANKRIGHT% 2 ) as green.%LINEBREAK%At the start of the Activation phase, you may flip this card.''' 'Multi-spectral Camouflage': text: '''%SMALLSHIPONLY%%LINEBREAK%After you receive a red target lock token, if you have only 1 red target lock token, roll 1 defense die. On an %EVADE% result, remove 1 red target lock token.''' title_translations = "Slave I": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol %TORPEDO%.""" "MPI:NAME:<NAME>END_PIium PI:NAME:<NAME>END_PI": name: "PI:NAME:<NAME>END_PI" text: """<span class="card-restriction">Tylko YT-1300.</span>%LINEBREAK% Twój pasek akcji zyskuje symbol akcji %EVADE%.""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">Tylko HWK-290.</span>%LINEBREAK%Podczas fazy końcowej nie usuwaj ze swojego statku niewykorzystanych żetonów skupienia.""" "ST-321": ship: "Prom typu Lambda" text: """<span class="card-restriction">Navette de classe <em>Lambda</em> uniquement.</span>%LINEBREAK%Quand vous verrouillez une cible, vous pouvez verrouiller n'importe quel vaisseau ennemi situé dans la zone de jeu.""" "Royal Guard TIE": ship: "TIE Interceptor" name: "PI:NAME:<NAME>END_PI" text: """<span class="card-restriction">Tylko TIE Interceptor.</span>%LINEBREAK%Możesz dołączyć do swojego statku maksymalnie 2 różne karty Modyfikacji (zamiast 1). Nie możesz dołączyć tej karty do swojego statku, jeśli wartość umiejętności pilota wynosi "4" lub mniej.""" "DodPI:NAME:<NAME>END_PI's Pride": name: "PI:NAME:<NAME>END_PI" ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy wykonujesz akcję "Koordynacja", możesz wybrać 2 przyjazne statki (zamiast 1). Statki te mogą wykonać po 1 darmowej akcji.""" "A-Wing Test Pilot": name: "Pilot testowy A-winga" text: """<span class="card-restriction">Tylko A-wing.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %ELITE%. Nie możesz wyposażyć się w 2 takie same karty rozwinięcia [elite talent]. Nie możesz wyposażyć się w tę kartę, jeśli twoja wartość umiejętności pilota wynosi "1" lub mniej.""" "Tantive IV": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Twój pasek rozwinięć sekcji dziobowej zyskuje po 1 symbolu rozwinięcia %CREW% i %TEAM%.""" "Bright Hope": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Żetony wsparcia przypisane do twojej sekcji dziobowej dostają 2 wyniki %EVADE% (zamiast 1).""" "Quantum Storm": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Na początku fazy końcowej, jeśli masz nie więcej niż 1 żeton energi, otrzymujesz 1 żeton energii.""" "Dutyfree": ship: "Średni transportowiec GR-75" text: """<span class="card-restriction">Tylko GR-75.</span>%LINEBREAK%Kiedy wykonujesz akcję Zakłócenie, możesz wybrać wrogi statek w Zasięgu 1-3 (zamiast Zasięgu 1-2).""" "Jaina's Light": ship: "Korweta CR90 (dziób)" text: """<span class="card-restriction">Tylko sekcja dziobowa CR90.</span>%LINEBREAK%Kiedy się bronisz, raz na atak, jeśli otrzymujesz odkrytą kartę uszkodzenia, możesz ją odrzucić i dobrać nową odkrytą kartę uszkodzenia.""" "Outrider": text: """<span class="card-restriction">Tylko YT-2400.</span>%LINEBREAK%Dopóki jesteś wyposażony w kartę rozwinięcia [cannon], nie możesz wykonywać ataków bronią podstawową. Przy pomocy dodatkowej broni [cannon] możesz wykonywać ataki skierowane przeciwko statkom znajdujacym się poza twoim polem rażenia. """ "Dauntless": ship: 'Decimator VT-49' text: """<span class="card-restriction">Tylko Decimator VT-49.</span>%LINEBREAK%Po tym jak wykonasz manewr, który sprawi że będziesz nachodzić na inny statek, możesz wykonać 1 darmową akcję. Następnie otrzymujesz 1 żeton stresu.""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">Tylko StarViper.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbole rozwinięć %SYSTEM% i %ILLICIT%. Nie możesz wyposażyć swojego statku w tę kartę jeśli wartość umiejętności twojego pilota wynosi „3” lub mniej.""" '"Heavy Scyk" Interceptor (Cannon)': name: 'Interceptor typu Heavy Scyk (Działo)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Torpedo)': name: 'Interceptor typu Heavy Scyk (Torpeda)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" '"Heavy Scyk" Interceptor (Missile)': name: 'Intercepteur "PI:NAME:<NAME>END_PI" (Rakieta)' text: """<span class="card-restriction">Tylko Interceptor M3-A.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje jeden z symboli rozwinięć: %CANNON%, %TORPEDO% lub %MISSILE%.""" "IG-2000": text: """<span class="card-restriction">Tylko Aggressor.</span>%LINEBREAK%Masz zdolność pilota każdego innego przyjaznego statku z kartą ulepszenia IG-2000 (jako dodatek do swojej zdolności pilota).""" "BTL-A4 Y-Wing": text: """<span class="card-restriction">Tylko Y-wing.</span>%LINEBREAK%Nie możesz atakować statków znajdujących się poza twoim polem rażenia. Po wykonaniu ataku przy pomocy broni podstawowej, możesz natychmiast wykonać atak przy pomocy dodatkowej broni %TURRET%.""" "Andrasta": text: """<span class="card-restriction">Tylko Firespray-31.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje dwa symbole %BOMB%.""" "TIE/x1": text: """<span class="card-restriction">Tylko TIE Advanced.</span>%LINEBREAK%Twój pasek rozwinięć zyskuje symbol rozwinięcia %SYSTEM%. %LINEBREAK%Koszt przypisanej do tego statku karty rozwinięcia %SYSTEM% jest obniżony o 4 punkty (do minimum 0).""" "Ghost": text: """<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom</em> title card to a friendly Attack Shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.""" "Phantom": text: """While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc, and, at the end of the Combat phase, it may perform an additional attack with an equipped %TURRET%. If it performs this attack, it cannot attack again this round.""" "TIE/v1": text: """<span class="card-restriction">TIE Advanced Prototype only.</span>%LINEBREAK%After you acquire a target lock, you may perform a free evade action.""" "PI:NAME:<NAME>END_PI": text: """<span class="card-restriction">G-1A starfighter only.</span>%LINEBREAK%Your upgrade bar gains the %BARRELROLL% Upgrade icon.%LINEBREAK%You <strong>must</strong> equip 1 "Tractor Beam" Upgrade card (paying its squad point cost as normal).""" "Punishing One": text: """<span class="card-restriction">JumpMaster 5000 only.</span>%LINEBREAK%Increase your primary weapon value by 1.""" "Assailer": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%When defending, if the targeted section has a reinforce token, you may change 1 %FOCUS% result to a %EVADE% result.""" "Instigator": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform a recover action, recover 1 additional shield.""" "Impetuous": text: """<span class="card-restriction"><em>Raider</em>-class corvette aft section only.</span>%LINEBREAK%After you perform an attack that destroys an enemy ship, you may acquire a target lock.""" 'TIE/x7': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Your upgrade bar loses the %CANNON% and %MISSILE% upgrade icons.%LINEBREAK%After executing a 3-, 4-, or 5-speed maneuver, you may assign 1 evade token to your ship.''' 'TIE/D': text: '''<span class="card-restriction">TIE Defender only.</span>%LINEBREAK%Once per round, after you perform an attack with a %CANNON% secondary weapon that costs 3 or fewer squad points, you may perform a primary weapon attack.''' 'TIE Shuttle': ship: 'Bombowiec TIE' text: '''<span class="card-restriction">TIE Bomber only.</span>%LINEBREAK%Your upgrade bar loses all %TORPEDO%, %MISSILE%, and %BOMB% upgrade icons and gains 2 %CREW% upgrade icons. You cannot equip a %CREW% Upgrade card that costs more than 4 squad points.''' 'Requiem': text: '''%GOZANTIONLY%%LINEBREAK%When you deploy a ship, treat its pilot skill value as "8" until the end of the round.''' 'Vector': text: '''%GOZANTIONLY%%LINEBREAK%After you execute a maneuver, you may deploy up to 4 attached ships (instead of 2).''' 'Suppressor': text: '''%GOZANTIONLY%%LINEBREAK%Once per round, after you acquire a target lock, you may remove 1 focus, evade, or blue target lock token from that ship.''' 'Black One': text: '''After you perform a boost or barrel roll action, you may remove 1 enemy target lock from a friendly ship at Range 1. You cannot equip this card if your pilot skill is "6" or lower.''' 'Millennium Falcon (TFA)': text: '''After you execute a 3-speed bank maneuver (%BANKLEFT% or %BANKRIGHT%), if you are not touching another ship and you are not stressed, you may receive 1 stress token to rotate your ship 180&deg;.''' 'Alliance Overhaul': text: '''<span class="card-restriction">ARC-170 only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. When attacking from your auxiliary firing arc, you may change 1 of your %FOCUS% results to a %CRIT% result.''' 'Special Ops Training': text: '''<span class="card-restriction">TIE/sf only.</span>%LINEBREAK%When attacking with a primary weapon from your primary firing arc, you may roll 1 additional attack die. If you do not, you may perform an additional attack from your auxiliary firing arc.''' 'Concord Dawn Protector': text: '''<span class="card-restriction">Protectorate Starfighter only.</span>%LINEBREAK%When defending, if you are inside the attacker's firing arc and at Range 1 and the attacker is inside your firing arc, add 1 %EVADE% result.''' 'Shadow Caster': text: '''<span class="card-restriction">Lancer-class Pursuit Craft only.</span>%LINEBREAK%After you perform an attack that hits, if the defender is inside your mobile firing arc and at Range 1-2, you may assign the defender 1 tractor beam token.''' # Wave X '''Sabine's Masterpiece''': ship: 'Myśliwiec TIE' text: '''<span class="card-restriction">TIE Fighter only.</span>%REBELONLY%%LINEBREAK%Your upgrade bar gains the %CREW% and %ILLICIT% upgrade icons.''' '''Kylo Ren's Shuttle''': text: '''<span class="card-restriction">Upsilon-class Shuttle only.</span>%LINEBREAK%At the end of the Combat phase, choose an unstressed enemy ship at Range 1-2. Its owner must assign a stress token to it or assign a stress token to another ship at Range 1-2 of you that that player controls.''' '''Pivot Wing''': text: '''<span class="card-restriction">U-Wing only.</span> %DUALCARD%%LINEBREAK%<strong>Side A (Attack):</strong> Increase your agility by 1.%LINEBREAK%After you execute a maneuver, you may flip this card.%LINEBREAK%<strong>Side B (Landing):</strong> When you reveal a (0 %STOP%) maneuver, you may rotate your ship 180&deg;.%LINEBREAK%After you execute a maneuver, you may flip this card.''' '''Adaptive Ailerons''': text: '''<span class="card-restriction">TIE Striker only.</span>%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you <strong>must</strong> execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' # C-ROC '''Merchant One''': text: '''<span class="card-restriction">C-ROC Cruiser only.</span>%LINEBREAK%Your upgrade bar 1 additional %CREW% upgrade icon and 1 additional %TEAM% upgrade icon and loses 1 %CARGO% upgrade icon.''' '''"Light Scyk" Interceptor''': text: '''<span class="card-restriction">M3-A Interceptor only.</span>%LINEBREAK%All Damage cards dealt to you are dealt faceup. You may treat all bank maneuvers (%BANKLEFT% or %BANKRIGHT%) as green maneuvers. You cannot equip Modification upgrades.''' '''Insatiable Worrt''': text: '''After you perform the recover action, gain 3 energy.''' '''Broken Horn''': text: '''When defending, if you have a reinforce token, you may add 1 additional %EVADE% result. If you do, after defending, discard your reinforce token.''' 'Havoc': text: '''<span class="card-restriction">Scurrg H-6 Bomber only.</span>%LINEBREAK%Your upgrade bar gains the %SYSTEM% and %SALVAGEDASTROMECH% icons and loses the %CREW% upgrade icon.%LINEBREAK%You cannot equip non-unique %SALVAGEDASTROMECH% Upgrade cards.''' 'Vaksai': text: '''<span class="card-restriction">Kihraxz Fighter only.</span>%LINEBREAK%The squad point cost of each of your equipped upgrades is reduced by 1 (to a minimum of 0).%LINEBREAK%You may equip up to 3 different Modification upgrades.''' 'StarViper Mk. II': text: '''<span class="card-restriction">StarViper only.</span>%LINEBREAK%You may equip up to 2 different title Upgrades.%LINEBREAK%When performing a barrel roll action, you <strong>must</strong> use the (%BANKLEFT% 1) or (%BANKRIGHT% 1) template instead of the (%STRAIGHT% 1) template.''' 'XG-1 Assault Configuration': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains 2 %CANNON% icons.%LINEBREAK%You may perform attacks with %CANNON% secondary weapons that cost 2 or fewer points even while you have a weapons disabled token.''' 'Enforcer': text: '''<span class="card-restriction">M12-L Kimogila Fighter only.</span>%LINEBREAK%After defending, if the attacker is inside your bullseye firing arc, the attacker receives 1 stress token.''' 'Ghost (Phantom II)': text: '''<span class="card-restriction">VCX-100 only.</span>%LINEBREAK%Equip the <em>Phantom II</em> title card to a friendly <em>Sheathipede</em>-class shuttle and dock it to this ship.%LINEBREAK%After you execute a maneuver, you may deploy it from your rear guides.''' 'Phantom II': text: '''While you are docked, the <em>Ghost</em> can perform primary weapon attacks from its special firing arc.%LINEBREAK%While you are docked, at the end of the Activation phase, the <em>Ghost</em> may perform a free coordinate action.''' 'First Order Vanguard': text: '''<span class="card-restriction">TIE Silencer only.</span>%LINEBREAK%When attacking, if the defender is the only ship in your firing arc at Range 1-3, you may reroll 1 attack die.%LINEBREAK%When defending, you may discard this card to reroll all of your defense dice.''' 'Os-1 Arsenal Loadout': text: '''<span class="card-restriction">Alpha-class Star Wing only.</span>%LINEBREAK%Your upgrade bar gains the %TORPEDO% and %MISSILE% icons.%LINEBREAK%You may perform attacks with %TORPEDO% and %MISSILE% secondary weapons against ships you have locked even while you have a weapons disabled token.''' 'Crossfire Formation': text: '''<span class="card-restriction">B/SF-17 Bomber only.</span>%LINEBREAK%When defending, if there is at least 1 other friendly Resistance ship at Range 1-2 of the attacker with the Crossfire Formation Upgrade card, you may add 1 %FOCUS% result to your roll.''' 'Advanced Ailerons': text: '''<span class="card-restriction">TIE Reaper only.</span>%LINEBREAK%Treat your (%BANKLEFT% 3) and (%BANKRIGHT% 3) maneuvers as white.%LINEBREAK%Immediately before you reveal your dial, if you are not stressed, you must execute a white (%BANKLEFT% 1), (%STRAIGHT% 1), or (%BANKRIGHT% 1) maneuver.''' condition_translations = '''I'll Show You the Dark Side''': text: '''When this card is assigned, if it is not already in play, the player who dealt it searches the Damage deck for 1 Damage card with the <strong><em>Pilot</em></strong> trait and may place it faceup on this card. Then shuffle the damage deck.%LINEBREAK%When you suffer critical damage from an attack, you are instead dealt the chosen faceup Damage card.%LINEBREAK%When there is no Damage card on this card, remove it.''' 'Suppressive Fire': text: '''When attacking a ship other than "Captain Rex," roll 1 fewer attack die.%LINEBREAK% When you declare an attack targeting "Captain Rex" or when "Captain Rex" is destroyed, remove this card.%LINEBREAK%At the end of the Combat phase, if "Captain Rex" did not perform an attack this phase, remove this card.''' 'Fanatical Devotion': text: '''When defending, you cannot spend focus tokens.%LINEBREAK%When attacking, if you spend a focus token to change all %FOCUS% results to %HIT% results, set aside the first %FOCUS% result that you change. The set-aside %HIT% result cannot be canceled by defense dice, but the defender may cancel %CRIT% results before it.%LINEBREAK%During the End phase, remove this card.''' 'A Debt to Pay': text: '''When attacking a ship that has the "A Score to Settle" Upgrade card equipped, you may change 1 %FOCUS% result to a %CRIT% result.''' 'Shadowed': text: '''"Thweek" is treated as having the pilot skill value you had after setup.%LINEBREAK%The pilot skill value of "Thweek" does not change if your pilot skill value changes or you are destroyed.''' 'Mimicked': text: '''"Thweek" is treated as having your pilot ability.%LINEBREAK%"Thweek" cannot apply a Condition card by using your pilot ability.%LINEBREAK%"Thweek" does not lose your pilot ability if you are destroyed.''' 'Harpooned!': text: '''When you are hit by an attack, if there is at least 1 uncanceled %CRIT% result, each other ship at Range 1 suffers 1 damage. Then discard this card and receive 1 facedown Damage card.%LINEBREAK%When you are destroyed, each ship at Range 1 suffers 1 damage.%LINEBREAK%<strong>Action:</strong> Discard this card. Then roll 1 attack die. On a %HIT% or %CRIT% result, suffer 1 damage.''' 'Rattled': text: '''When you suffer damage from a bomb, you suffer 1 additional critical damage. Then, remove this card.%LINEBREAK%<strong>Action:</strong> Roll 1 attack die. On a %FOCUS% or %HIT% result, remove this card.''' 'Scrambled': text: '''When attacking a ship at Range 1 that is equipped with the "Targeting Scrambler" upgrade, you cannot modify attack dice.%LINEBREAK%At the end of the combat phase, remove this card.''' 'Optimized Prototype': text: '''Increase your shield value by 1.%LINEBREAK%Once per round, when performing a primary weapon attack, you may spend 1 die result to remove 1 shield from the defender.%LINEBREAK%After you perform a primary weapon attack, a friendly ship at Range 1-2 equipped with the "PI:NAME:<NAME>END_PI" Upgrade card may acquire a target lock on the defender.''' exportObj.setupCardData basic_cards, pilot_translations, upgrade_translations, modification_translations, title_translations, condition_translations
[ { "context": "m_utf8 'this be the top secret key! shit yeah! sdf3 234 092i34 092i34 0923i'\ninput = WordArray.from_u", "end": 471, "score": 0.8340457677841187, "start": 470, "tag": "KEY", "value": "3" }, { "context": "utf8 'this be the top secret key! shit yeah! sdf3 234 092i34 092i34 0923i'\ninput = WordArray.from_utf8 ", "end": 475, "score": 0.7688056826591492, "start": 472, "tag": "KEY", "value": "234" }, { "context": "'this be the top secret key! shit yeah! sdf3 234 092i34 092i34 0923i'\ninput = WordArray.from_utf8 'this be", "end": 482, "score": 0.7423381805419922, "start": 477, "tag": "KEY", "value": "92i34" }, { "context": "e the top secret key! shit yeah! sdf3 234 092i34 092i34 0923i'\ninput = WordArray.from_utf8 'this be the message", "end": 495, "score": 0.8472409844398499, "start": 484, "tag": "KEY", "value": "92i34 0923i" } ]
dev/hmax.iced
CyberFlameGO/triplesec
274
{HMAX} = require '../src/hmax' {WordArray} = require '../src/wordarray' {SHA512} = require '../src/sha512' {HMAC} = require '../src/hmac' #-------- class NullHash constructor : -> @output_size : SHA512.output_size output_size : NullHash.output_size @blockSize : SHA512.blockSize blockSize : NullHash.blockSize update : -> finalize : -> new WordArray [], 0 reset : -> @ #-------- key = WordArray.from_utf8 'this be the top secret key! shit yeah! sdf3 234 092i34 092i34 0923i' input = WordArray.from_utf8 'this be the message dawg' hmax = new HMAX key, [ SHA512, NullHash ], { skip_compose : 0 } hmax2 = new HMAX key, [ NullHash, SHA512 ], { skip_compose : 1 } hmac = new HMAC key, SHA512 hmax.finalize(input) hmax2.finalize(input) hmac.finalize(input)
98786
{HMAX} = require '../src/hmax' {WordArray} = require '../src/wordarray' {SHA512} = require '../src/sha512' {HMAC} = require '../src/hmac' #-------- class NullHash constructor : -> @output_size : SHA512.output_size output_size : NullHash.output_size @blockSize : SHA512.blockSize blockSize : NullHash.blockSize update : -> finalize : -> new WordArray [], 0 reset : -> @ #-------- key = WordArray.from_utf8 'this be the top secret key! shit yeah! sdf<KEY> <KEY> 0<KEY> 0<KEY>' input = WordArray.from_utf8 'this be the message dawg' hmax = new HMAX key, [ SHA512, NullHash ], { skip_compose : 0 } hmax2 = new HMAX key, [ NullHash, SHA512 ], { skip_compose : 1 } hmac = new HMAC key, SHA512 hmax.finalize(input) hmax2.finalize(input) hmac.finalize(input)
true
{HMAX} = require '../src/hmax' {WordArray} = require '../src/wordarray' {SHA512} = require '../src/sha512' {HMAC} = require '../src/hmac' #-------- class NullHash constructor : -> @output_size : SHA512.output_size output_size : NullHash.output_size @blockSize : SHA512.blockSize blockSize : NullHash.blockSize update : -> finalize : -> new WordArray [], 0 reset : -> @ #-------- key = WordArray.from_utf8 'this be the top secret key! shit yeah! sdfPI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI 0PI:KEY:<KEY>END_PI 0PI:KEY:<KEY>END_PI' input = WordArray.from_utf8 'this be the message dawg' hmax = new HMAX key, [ SHA512, NullHash ], { skip_compose : 0 } hmax2 = new HMAX key, [ NullHash, SHA512 ], { skip_compose : 1 } hmac = new HMAC key, SHA512 hmax.finalize(input) hmax2.finalize(input) hmac.finalize(input)
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998409748077393, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999282360076904, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/semantic/icontrols.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {Formular} = require "./formular" # This is a formular implementation that provides standard controls # shipped within the Semantic UI framework. It contains most of the # shipped controls (fields and inputs) covered in a Semantic manual. # Plese refer to the implementation for the usage information. Also, # see the methods to get the idea of what is available and what not. # Reference the `Formular` abstraction for the internal information. module.exports.InputControls = cc -> class InputControls extends Formular # Group the two previously created fields (passed by either as # direct object or the selectors) into a one horizontal field # that is going to equally share the space between two fields. # This method is going to internally insert the grouper right # before the first field and them move both fields to grouper. group: (fieldOne, fieldTwo, fieldAdd) -> selectorOne = fieldOne and _.isString fieldOne selectorTwo = fieldTwo and _.isString fieldTwo selectorAdd = fieldAdd and _.isString fieldAdd fieldOne = ".field.#{fieldOne}" if selectorOne fieldTwo = ".field.#{fieldTwo}" if selectorTwo fieldAdd = ".field.#{fieldAdd}" if selectorAdd fieldOne = @element.find fieldOne if selectorOne fieldTwo = @element.find fieldTwo if selectorTwo fieldAdd = @element.find fieldAdd if selectorAdd assert fieldOne.length > 0, "invalid obj A given" assert fieldTwo.length > 0, "invalid obj B given" assert q = try if fieldAdd then "three" else "two" assert union = try $ "<div>", class: "#{q} fields" union.insertBefore fieldOne # place before A field fieldOne.appendTo union; fieldTwo.appendTo union fieldAdd.appendTo union if (try fieldAdd.length) # Create a field that is typically would be used to enter the # password or similar information that should not be displayed # while it is being typed in. The field has the asterisk to it # and can optionally attach an icon to the field (recommended). # In other ways, it is structurally equal to `starred` field. # Please refer to `Widget` class for reference on subwidgets. @subwidget hidden: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "password" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create a regular textual field that is however marked by star # (astetisk) on its right, that usually indicated the field is # either required or has some remarks to it or simply indicates # an elevated attention to the field. Oterwise, it is a simple # textual field that can optionally be tagged with a left icon. # Please refer to `Widget` class for reference on subwidgets. @subwidget starred: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create an inlined checkbox field that looks like a checkbox # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget checkbox: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox" # wrapping sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a sliding # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget sliding: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox slider" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a toggling # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget toggling: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox toggle" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # This method creates the most basic textual field. It does not # contain anything other that the field itself. Optionally this # can be tagged by an icon on the left side of the field. It is # a good idea to use such a field for inputting sorts data that # is not strictly required, but is usually optional, as example. # Please refer to `Widget` class for reference on subwidgets. @subwidget regular: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; input.appendTo wrap if icon then wrap.append icon else no; field
209673
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {Formular} = require "./formular" # This is a formular implementation that provides standard controls # shipped within the Semantic UI framework. It contains most of the # shipped controls (fields and inputs) covered in a Semantic manual. # Plese refer to the implementation for the usage information. Also, # see the methods to get the idea of what is available and what not. # Reference the `Formular` abstraction for the internal information. module.exports.InputControls = cc -> class InputControls extends Formular # Group the two previously created fields (passed by either as # direct object or the selectors) into a one horizontal field # that is going to equally share the space between two fields. # This method is going to internally insert the grouper right # before the first field and them move both fields to grouper. group: (fieldOne, fieldTwo, fieldAdd) -> selectorOne = fieldOne and _.isString fieldOne selectorTwo = fieldTwo and _.isString fieldTwo selectorAdd = fieldAdd and _.isString fieldAdd fieldOne = ".field.#{fieldOne}" if selectorOne fieldTwo = ".field.#{fieldTwo}" if selectorTwo fieldAdd = ".field.#{fieldAdd}" if selectorAdd fieldOne = @element.find fieldOne if selectorOne fieldTwo = @element.find fieldTwo if selectorTwo fieldAdd = @element.find fieldAdd if selectorAdd assert fieldOne.length > 0, "invalid obj A given" assert fieldTwo.length > 0, "invalid obj B given" assert q = try if fieldAdd then "three" else "two" assert union = try $ "<div>", class: "#{q} fields" union.insertBefore fieldOne # place before A field fieldOne.appendTo union; fieldTwo.appendTo union fieldAdd.appendTo union if (try fieldAdd.length) # Create a field that is typically would be used to enter the # password or similar information that should not be displayed # while it is being typed in. The field has the asterisk to it # and can optionally attach an icon to the field (recommended). # In other ways, it is structurally equal to `starred` field. # Please refer to `Widget` class for reference on subwidgets. @subwidget hidden: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "password" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create a regular textual field that is however marked by star # (astetisk) on its right, that usually indicated the field is # either required or has some remarks to it or simply indicates # an elevated attention to the field. Oterwise, it is a simple # textual field that can optionally be tagged with a left icon. # Please refer to `Widget` class for reference on subwidgets. @subwidget starred: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create an inlined checkbox field that looks like a checkbox # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget checkbox: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox" # wrapping sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a sliding # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget sliding: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox slider" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a toggling # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget toggling: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox toggle" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # This method creates the most basic textual field. It does not # contain anything other that the field itself. Optionally this # can be tagged by an icon on the left side of the field. It is # a good idea to use such a field for inputting sorts data that # is not strictly required, but is usually optional, as example. # Please refer to `Widget` class for reference on subwidgets. @subwidget regular: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; input.appendTo wrap if icon then wrap.append icon else no; field
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" assert = require "assert" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {Formular} = require "./formular" # This is a formular implementation that provides standard controls # shipped within the Semantic UI framework. It contains most of the # shipped controls (fields and inputs) covered in a Semantic manual. # Plese refer to the implementation for the usage information. Also, # see the methods to get the idea of what is available and what not. # Reference the `Formular` abstraction for the internal information. module.exports.InputControls = cc -> class InputControls extends Formular # Group the two previously created fields (passed by either as # direct object or the selectors) into a one horizontal field # that is going to equally share the space between two fields. # This method is going to internally insert the grouper right # before the first field and them move both fields to grouper. group: (fieldOne, fieldTwo, fieldAdd) -> selectorOne = fieldOne and _.isString fieldOne selectorTwo = fieldTwo and _.isString fieldTwo selectorAdd = fieldAdd and _.isString fieldAdd fieldOne = ".field.#{fieldOne}" if selectorOne fieldTwo = ".field.#{fieldTwo}" if selectorTwo fieldAdd = ".field.#{fieldAdd}" if selectorAdd fieldOne = @element.find fieldOne if selectorOne fieldTwo = @element.find fieldTwo if selectorTwo fieldAdd = @element.find fieldAdd if selectorAdd assert fieldOne.length > 0, "invalid obj A given" assert fieldTwo.length > 0, "invalid obj B given" assert q = try if fieldAdd then "three" else "two" assert union = try $ "<div>", class: "#{q} fields" union.insertBefore fieldOne # place before A field fieldOne.appendTo union; fieldTwo.appendTo union fieldAdd.appendTo union if (try fieldAdd.length) # Create a field that is typically would be used to enter the # password or similar information that should not be displayed # while it is being typed in. The field has the asterisk to it # and can optionally attach an icon to the field (recommended). # In other ways, it is structurally equal to `starred` field. # Please refer to `Widget` class for reference on subwidgets. @subwidget hidden: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "password" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create a regular textual field that is however marked by star # (astetisk) on its right, that usually indicated the field is # either required or has some remarks to it or simply indicates # an elevated attention to the field. Oterwise, it is a simple # textual field that can optionally be tagged with a left icon. # Please refer to `Widget` class for reference on subwidgets. @subwidget starred: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" assert corner = $ "<div>", class: "ui corner label" assert asterisk = $ "<i>", class: "icon asterisk" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; corner.append asterisk wrap.append input, icon or null, corner; field # Create an inlined checkbox field that looks like a checkbox # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget checkbox: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox" # wrapping sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a sliding # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget sliding: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox slider" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # Create an inlined checkbox field that looks like a toggling # with a text string attached next to it (on the right side). # It is usually a good idea for indicating options selection # or agreement to some legal terms and conditions. The field # that it creates is rendered as inline (see semantic man). # Please refer to `Widget` class for reference on subwidgets. @subwidget toggling: (identity, synopsis, onpos, onneg) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isString what = "ui checkbox toggle" # wrap sel assert _.isObject label = $ "<label>", class: "label" assert _.isObject input = $ "<input>", type: "checkbox" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: what; field.addClass "inline" input.on "input", -> do -> field.removeClass "error" try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity input.appendTo wrap; field.append wrap.append label $(wrap).checkbox onEnable: onpos, onDisable: onneg label.text synopsis.toString(); return field # This method creates the most basic textual field. It does not # contain anything other that the field itself. Optionally this # can be tagged by an icon on the left side of the field. It is # a good idea to use such a field for inputting sorts data that # is not strictly required, but is usually optional, as example. # Please refer to `Widget` class for reference on subwidgets. @subwidget regular: (identity, synopsis, icon) -> assert _.isString(identity), "invalid field identity" assert _.isString(synopsis), "invalid field synopsis" assert _.isObject input = $ "<input>", type: "text" assert _.isObject label = $ "<label>", class: "label" assert _.isObject input.attr name: identity.toString() field = $("<div>", class: "field").appendTo @element wrap = $ "<div>", class: "icon input ui left labeled" input.on "input", -> do -> field.removeClass "error" sic = try _.isString(icon) and not _.isEmpty(icon) assert icon = $ "<i>", class: "icon #{icon}" if sic assert input.attr placeholder: synopsis.toString() try $(field).data "identity", identity.toString() field.addClass try identity.toString() if identity field.append label, wrap; input.appendTo wrap if icon then wrap.append icon else no; field
[ { "context": "================\n#\n# Generic Utilities\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#=================================", "end": 118, "score": 0.9998693466186523, "start": 100, "tag": "NAME", "value": "Matthew Wagerfield" }, { "context": "# Generic Utilities\n#\n# @author Matthew Wagerfield @mwagerfield\n#\n#==============================================", "end": 131, "score": 0.9986572265625, "start": 119, "tag": "USERNAME", "value": "@mwagerfield" } ]
development/production/source/assets/scripts/coffee/core/Utils.coffee
wagerfield/cinnamon
2
### #============================================================ # # Generic Utilities # # @author Matthew Wagerfield @mwagerfield # #============================================================ ### class Utils ### # Browser vendor prefixes. ### @VENDORS = ['O','ms','Moz','webkit',null] ### # Generates a GUID. # @param {number} length The length of the guid. # @param {string} prefix String to prefix the GUID with. # @return {string} The generated GUID. ### @guid = (length = 8, prefix = 'mw') -> guid = ((Math.random().toFixed 1).substr 2 for i in [0...length]) guid = "#{prefix}#{guid.join ''}" return guid ### # Adds a tap class to an array of elements and removes it after the wait delay. # @requires underscore.js # @see http://underscorejs.org/ # @param {jQuery} $elements jQuery selection. # @param {string} selection String selection for live elements. # @param {number} wait The delay before removing the tap class. ### @tap = ($elements, selection, wait = 400) -> if !!selection $elements.on 'tap', selection, (event) -> $target = $ event.currentTarget debounce = $target.data 'debounce' if !debounce debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $target.data 'debounce', debounce $target.addClass 'tap' debounce $target else $elements.each (index, element) -> debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $(element).on 'tap', (event) -> $target = $ event.currentTarget $target.addClass 'tap' debounce $target return ### # Scrolls the window to 0 to hide the browser menu bar. ### @scrollTop = () -> setTimeout ( -> window.scrollTo 0, 0), 0 ### # Scrolls the window to 0 to hide the browser menu bar. # @param {DOM} element DOM element. # @param {string} property Property to set. # @param {value} value Property value. ### @css = (element, property, value, vendors = @VENDORS) -> element.style[if vendor? then @camelCase "#{vendor}-#{property}" else property] = value for vendor in vendors ### # Converts a hyphenated string to camel case. # @param {string} value The string to process. ### @camelCase = (value) -> return value.replace /-+(.)?/g, (match, character) -> if character then character.toUpperCase() else ''
144853
### #============================================================ # # Generic Utilities # # @author <NAME> @mwagerfield # #============================================================ ### class Utils ### # Browser vendor prefixes. ### @VENDORS = ['O','ms','Moz','webkit',null] ### # Generates a GUID. # @param {number} length The length of the guid. # @param {string} prefix String to prefix the GUID with. # @return {string} The generated GUID. ### @guid = (length = 8, prefix = 'mw') -> guid = ((Math.random().toFixed 1).substr 2 for i in [0...length]) guid = "#{prefix}#{guid.join ''}" return guid ### # Adds a tap class to an array of elements and removes it after the wait delay. # @requires underscore.js # @see http://underscorejs.org/ # @param {jQuery} $elements jQuery selection. # @param {string} selection String selection for live elements. # @param {number} wait The delay before removing the tap class. ### @tap = ($elements, selection, wait = 400) -> if !!selection $elements.on 'tap', selection, (event) -> $target = $ event.currentTarget debounce = $target.data 'debounce' if !debounce debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $target.data 'debounce', debounce $target.addClass 'tap' debounce $target else $elements.each (index, element) -> debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $(element).on 'tap', (event) -> $target = $ event.currentTarget $target.addClass 'tap' debounce $target return ### # Scrolls the window to 0 to hide the browser menu bar. ### @scrollTop = () -> setTimeout ( -> window.scrollTo 0, 0), 0 ### # Scrolls the window to 0 to hide the browser menu bar. # @param {DOM} element DOM element. # @param {string} property Property to set. # @param {value} value Property value. ### @css = (element, property, value, vendors = @VENDORS) -> element.style[if vendor? then @camelCase "#{vendor}-#{property}" else property] = value for vendor in vendors ### # Converts a hyphenated string to camel case. # @param {string} value The string to process. ### @camelCase = (value) -> return value.replace /-+(.)?/g, (match, character) -> if character then character.toUpperCase() else ''
true
### #============================================================ # # Generic Utilities # # @author PI:NAME:<NAME>END_PI @mwagerfield # #============================================================ ### class Utils ### # Browser vendor prefixes. ### @VENDORS = ['O','ms','Moz','webkit',null] ### # Generates a GUID. # @param {number} length The length of the guid. # @param {string} prefix String to prefix the GUID with. # @return {string} The generated GUID. ### @guid = (length = 8, prefix = 'mw') -> guid = ((Math.random().toFixed 1).substr 2 for i in [0...length]) guid = "#{prefix}#{guid.join ''}" return guid ### # Adds a tap class to an array of elements and removes it after the wait delay. # @requires underscore.js # @see http://underscorejs.org/ # @param {jQuery} $elements jQuery selection. # @param {string} selection String selection for live elements. # @param {number} wait The delay before removing the tap class. ### @tap = ($elements, selection, wait = 400) -> if !!selection $elements.on 'tap', selection, (event) -> $target = $ event.currentTarget debounce = $target.data 'debounce' if !debounce debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $target.data 'debounce', debounce $target.addClass 'tap' debounce $target else $elements.each (index, element) -> debounce = _.debounce (($element) -> $element.removeClass 'tap'), wait $(element).on 'tap', (event) -> $target = $ event.currentTarget $target.addClass 'tap' debounce $target return ### # Scrolls the window to 0 to hide the browser menu bar. ### @scrollTop = () -> setTimeout ( -> window.scrollTo 0, 0), 0 ### # Scrolls the window to 0 to hide the browser menu bar. # @param {DOM} element DOM element. # @param {string} property Property to set. # @param {value} value Property value. ### @css = (element, property, value, vendors = @VENDORS) -> element.style[if vendor? then @camelCase "#{vendor}-#{property}" else property] = value for vendor in vendors ### # Converts a hyphenated string to camel case. # @param {string} value The string to process. ### @camelCase = (value) -> return value.replace /-+(.)?/g, (match, character) -> if character then character.toUpperCase() else ''
[ { "context": " , done\n\n beforeEach (done) ->\n auth = new Buffer('some-user:some-pass').toString('base64')\n e", "end": 1518, "score": 0.645983874797821, "start": 1512, "tag": "KEY", "value": "Buffer" }, { "context": " beforeEach (done) ->\n auth = new Buffer('some-user:some-pass').toString('base64')\n expectedExpires = moment.unix(@currentTim", "end": 1558, "score": 0.7883912324905396, "start": 1520, "tag": "KEY", "value": "some-user:some-pass').toString('base64" }, { "context": "eforeEach (done) ->\n auth = new Buffer('some-user:some-pass').toString('base64')\n expectedExpi", "end": 2589, "score": 0.5453042387962341, "start": 2585, "tag": "PASSWORD", "value": "user" }, { "context": "beforeEach (done) ->\n auth = new Buffer('some-user:some-pass').toString('base64')\n expectedExpi", "end": 3649, "score": 0.7598649263381958, "start": 3645, "tag": "PASSWORD", "value": "user" }, { "context": "eforeEach (done) ->\n auth = new Buffer('some-user:some-pass').toString('base64')\n expectedExpi", "end": 4358, "score": 0.42346057295799255, "start": 4354, "tag": "USERNAME", "value": "user" } ]
test/worker-spec.coffee
octoblu/queue-length-verifier
0
async = require 'async' UUID = require 'uuid' shmock = require '@octoblu/shmock' moment = require 'moment' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' enableDestroy = require 'server-destroy' Worker = require '../src/worker' Env = require '../src/env' describe 'QueueLengthWorker', -> beforeEach (done) -> @env = new Env({ REDIS_URI: 'localhost' NAMESPACE: "test-worker-#{UUID.v1()}" QUEUE_NAME: 'some-queue' QUEUE_MAX_LENGTH: 10 LOG_URL: "http://some-user:some-pass@localhost:#{0xd00d}/verifications/test" }).get() redisClient = new Redis @env.REDIS_URI, dropBufferSupport: true @client = new RedisNS @env.NAMESPACE, redisClient @client.ping (error) => @client.once 'error', done done error return # dumb redis promise fix beforeEach -> @verifierService = shmock 0xd00d enableDestroy @verifierService @currentTime = moment().unix() @consoleLog = sinon.spy() @consoleError = sinon.spy() @sut = new Worker { @client, @env, @currentTime, @consoleLog, @consoleError } afterEach -> @verifierService.destroy() describe 'when the queue length is greater than the max', -> beforeEach (done) -> async.times 12, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 12 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 12 >= 10' describe 'when the queue length is equal to the max', -> beforeEach (done) -> async.times 10, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 10 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 10 >= 10' describe 'when the queue length is less than the max', -> beforeEach (done) -> async.times 9, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok' describe 'when the queue length is zero', -> beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok'
208783
async = require 'async' UUID = require 'uuid' shmock = require '@octoblu/shmock' moment = require 'moment' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' enableDestroy = require 'server-destroy' Worker = require '../src/worker' Env = require '../src/env' describe 'QueueLengthWorker', -> beforeEach (done) -> @env = new Env({ REDIS_URI: 'localhost' NAMESPACE: "test-worker-#{UUID.v1()}" QUEUE_NAME: 'some-queue' QUEUE_MAX_LENGTH: 10 LOG_URL: "http://some-user:some-pass@localhost:#{0xd00d}/verifications/test" }).get() redisClient = new Redis @env.REDIS_URI, dropBufferSupport: true @client = new RedisNS @env.NAMESPACE, redisClient @client.ping (error) => @client.once 'error', done done error return # dumb redis promise fix beforeEach -> @verifierService = shmock 0xd00d enableDestroy @verifierService @currentTime = moment().unix() @consoleLog = sinon.spy() @consoleError = sinon.spy() @sut = new Worker { @client, @env, @currentTime, @consoleLog, @consoleError } afterEach -> @verifierService.destroy() describe 'when the queue length is greater than the max', -> beforeEach (done) -> async.times 12, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new <KEY>('<KEY>') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 12 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 12 >= 10' describe 'when the queue length is equal to the max', -> beforeEach (done) -> async.times 10, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-<PASSWORD>:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 10 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 10 >= 10' describe 'when the queue length is less than the max', -> beforeEach (done) -> async.times 9, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-<PASSWORD>:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok' describe 'when the queue length is zero', -> beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok'
true
async = require 'async' UUID = require 'uuid' shmock = require '@octoblu/shmock' moment = require 'moment' Redis = require 'ioredis' RedisNS = require '@octoblu/redis-ns' enableDestroy = require 'server-destroy' Worker = require '../src/worker' Env = require '../src/env' describe 'QueueLengthWorker', -> beforeEach (done) -> @env = new Env({ REDIS_URI: 'localhost' NAMESPACE: "test-worker-#{UUID.v1()}" QUEUE_NAME: 'some-queue' QUEUE_MAX_LENGTH: 10 LOG_URL: "http://some-user:some-pass@localhost:#{0xd00d}/verifications/test" }).get() redisClient = new Redis @env.REDIS_URI, dropBufferSupport: true @client = new RedisNS @env.NAMESPACE, redisClient @client.ping (error) => @client.once 'error', done done error return # dumb redis promise fix beforeEach -> @verifierService = shmock 0xd00d enableDestroy @verifierService @currentTime = moment().unix() @consoleLog = sinon.spy() @consoleError = sinon.spy() @sut = new Worker { @client, @env, @currentTime, @consoleLog, @consoleError } afterEach -> @verifierService.destroy() describe 'when the queue length is greater than the max', -> beforeEach (done) -> async.times 12, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new PI:KEY:<KEY>END_PI('PI:KEY:<KEY>END_PI') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 12 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 12 >= 10' describe 'when the queue length is equal to the max', -> beforeEach (done) -> async.times 10, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-PI:PASSWORD:<PASSWORD>END_PI:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: false expires: expectedExpires error: { message: 'Queue length exceeded max 10 >= 10' } } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.error failure', -> expect(@consoleError).to.have.been.calledWith 'queue-length failure', 'Error: Queue length exceeded max 10 >= 10' describe 'when the queue length is less than the max', -> beforeEach (done) -> async.times 9, (n, next) => data = JSON.stringify { foo: 'bar', n } @client.lpush @env.QUEUE_NAME, data, next return # dumb redis promise fix , done beforeEach (done) -> auth = new Buffer('some-PI:PASSWORD:<PASSWORD>END_PI:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok' describe 'when the queue length is zero', -> beforeEach (done) -> auth = new Buffer('some-user:some-pass').toString('base64') expectedExpires = moment.unix(@currentTime).add(@env.LOG_EXPIRATION, 'seconds').utc().format() @verifyFailure = @verifierService .post '/verifications/test' .set 'Authorization', "Basic #{auth}" .send { success: true expires: expectedExpires } .reply 201 @sut.do (error) => done error it 'should send a failure to the verifications endpoint', -> @verifyFailure.done() it 'should console.log ok', -> expect(@consoleLog).to.have.been.calledWith 'queue-length ok'
[ { "context": "#\n# longdouble.js, https://github.com/ofmlabs/longdouble.js\n# \n# By Jens Nockert of OFMLabs\n#\n#", "end": 45, "score": 0.9980672001838684, "start": 38, "tag": "USERNAME", "value": "ofmlabs" }, { "context": ", https://github.com/ofmlabs/longdouble.js\n# \n# By Jens Nockert of OFMLabs\n#\n# Lemma 1. Let a and b be two p-bit ", "end": 80, "score": 0.999858558177948, "start": 68, "tag": "NAME", "value": "Jens Nockert" } ]
src/longdouble.coffee
audiocogs/longdouble.js
12
# # longdouble.js, https://github.com/ofmlabs/longdouble.js # # By Jens Nockert of OFMLabs # # Lemma 1. Let a and b be two p-bit floating point numbers such that |a| ≥ |b|. # Then |err(a + b)| ≤ |b| ≤ |a|. # Lemma 2. Let a and b be two p-bit floating point numbers. # Then err(a + b) = (a + b) − fl(a + b) is representable as a p-bit # floating point number. # Algorithm 4. The following algorithm computes # s = fl(a + b) # e = err(a + b). # This algorithm uses three more floating point operations instead # of a branch. # # Note. I should look into if it is faster to use (3) with a branch. two_sum = (a, b) -> s = a + b e = s - a return [s, (a - (s - e)) + (b - e)] # Algorithm 3. The following algorithm computes # s = fl(a + b) # e = err(a + b), # assuming |a| ≥ |b|. quick_two_sum = (a, b) -> s = a + b return [s, b - (s - a)] # Algorithm 5. The following algorithm splits a 53-bit IEEE double precision # floating point number into ahi and alo, each with 26 bits of # significand, such that a = ahi + alo. ahi will contain the first # 26 bits, while alo will contain the lower 26 bits. # # Note. There is additional stuff in the code, that is not available in # the paper, I need to look into when it is needed. # # Ideas: Handles denormals? SPLITTER = 134217729.0 # = 2^27 + 1 split = (a) -> temp = SPLITTER * a hi = temp - (temp - a) lo = a - hi return [hi, lo] # Algorithm 6. The following algorithm computes # p = fl(a × b) # e = err(a × b). if (!Math.fma) # Only my special build of Firefox supports FMA yet. two_prod = (a, b) -> p = a * b [a_hi, a_lo] = split(a) [b_hi, b_lo] = split(b) error = ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo return [p, error] else # Algorithm 7. The following algorithm computes # p = fl(a × b) # e = err(a × b) # on a browser with FMA support. # # Note: FMA is never implemented in JS, but I will probably add it to # Spidermonkey soon, this would probably make this method much # faster, even without hardware support. two_prod = (a, b) -> p = a * b return [p, Math.fma(a, b, -p)] # Note: The same as (4), but with b replaced by -b. two_diff = (a, b) -> s = a - b e = s - a return [s, (a - (s - e)) - (b + e)] # Note: The same as (3), but with b replaced by -b. quick_two_diff = (a, b) -> s = a - b return [s, (a - s) - b] # TODO: Implement a sane constructor class CSLongDouble constructor: (@hi, @lo) -> # # Imp 1: Since a long-double is a sum of two doubles, just changing the # sign of both the high and the low part, we change the sign of # the sum itself. # negate: () -> return new CSLongDouble(-@hi, -@lo) # # Imp 2: To add a and b, we use the general structure to apply the # operation to first the high parts (s_hi, s_lo) and the low parts # (t_hi, t_lo) in separation, then we merge the results, first # t_hi, then t_lo. # add: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo); # # Imp 3: The fast versions have lower precision, since it only merges in # the high part (t_hi) of the lower parts. # addFast: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) s_lo = (s_lo + @lo) + other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 4: Essentially equivalent to the addFast method, but with some # optimizations due to the other.lo being 0. # addDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (2), but with the other replaced by -other. # That is, the first two two_sum operations in the network are # replaced by two_diff, the merging is done in the same way. # sub: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (3), but with the other replaced by -other. # That is, the first two_sum operation in the network is # replaced by two_diff, and the optimized second add is replaced # by a difference. # subFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) s_lo = (s_lo + @lo) - other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 6: Equivalent to (4), but with the other replaced by -other. # That is, the first two_sum operation is replaced by two_diff, # and just like in (5), but since the low part of other is 0, we # do not need the second difference. # subDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 7: Multiplication uses a similar network to the fast # implementations, due to the nature of floating point. # We know that the a_lo * b_lo will never end up in the final # product, which allows us to do some optimizations. # mul: (other) -> [p_hi, p_lo] = two_prod(@hi, other.hi) p_lo += (@hi * other.lo + other.hi * @lo) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 8: The same as (7), but since b_lo is 0, we can optimize a bit. # mulDouble: (other) -> [p_hi, p_lo] = two_prod(@hi, other) p_lo += (@lo * other) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 9: Implementing division is # div: (other) -> q_hi = @hi / other.hi r = this.sub(other.mulDouble(q_hi)) q_lo = r.hi / other.hi r.decrement(other.mulDouble(q_lo)) q_vlo = r.hi / other.hi [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) r = new CSLongDouble(q_hi, q_lo) return r.addDouble(q_vlo) # Imp 10: TODO divFast: (other) -> q_hi = @hi / other.hi r = other.mulDouble(q_hi) [s_hi, s_lo] = two_diff(@hi, r.hi) s_lo = (s_lo - r.lo) + @lo q_lo = (s_hi + s_lo) / other.hi [r.hi, r.lo] = quick_two_sum(q_hi, q_lo) return r # Imp 11: The same as (10), but with b_lo being 0. # divDouble: (other) -> q_hi = @hi / other [p_hi, p_lo] = two_prod(q_hi, other) [s_hi, s_lo] = two_diff(@hi, p_hi) s_lo = (s_lo + @lo) - p_lo q_lo = (s_hi + s_lo) / other [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) return new CSLongDouble(q_hi, q_lo) # Imp 12: See (2). # increment: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_hi += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_hi += t_lo; [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 13: See (3). # incrementFast: (other) -> [s_hi, s_lo] = two_sum(@sum, other.sum) s_lo = (s_lo + @lo) - other.lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 14: See (4). # incrementDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 15: See (5). # decrement: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 16: See (6). # decrementFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.lo) lo = (s_lo + @lo) - other.lo [@sum, @error] = quick_two_sum(s_hi, s_lo) return this # Imp 17: See (7). # decrementDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 18: Trivial # equal: (other) -> return @hi == other.hi && @lo == other.lo # Imp 19: Trivial # equalDouble: (other) -> return @hi == other && @lo == 0.0 # Imp 20: Trivial # notEqual: (other) -> return @hi != other.hi || @lo != other.lo # Imp 21: Trivial # notEqualDouble: (other) -> return @hi != other || @lo != 0.0 # Imp 22: Trivial # greaterThan: (other) -> return @hi > other.hi || (@hi == other.hi && @lo > other.lo) # Imp 23: Trivial # greaterThanDouble: (other) -> return @hi > other || (@hi == other && @lo > 0.0) # Imp 24: Trivial # greaterEqualThan: (other) -> return @hi >= other.hi || (@hi == other.hi && @lo >= other.lo) # Imp 25: Trivial # greaterEqualThanDouble: (other) -> return @hi >= other || (@hi == other && @lo >= 0.0) # Imp 26: Trivial # lessThan: (other) -> return @hi < other.hi || (@hi == other.hi && @lo < other.lo) # Imp 27: Trivial # lessThanDouble: (other) -> return @hi < other || (@hi == other && @lo < 0.0) # Imp 28: Trivial # lessEqualThan: (other) -> return @hi <= other.hi || (@hi == other.hi && @lo <= other.lo) # Imp 29: Trivial # lessEqualThanDouble: (other) -> return @hi <= other || (@hi == other && @lo <= 0.0) # Imp 30: Trivial # abs: () -> if this.lessThanDouble(0.0) return this.negate() else return new CSLongDouble(@hi, @lo) # Imp 31: TODO but trivial # pow: (n) -> if n == 0 if this.zero() return new CSLongDouble(0.0 / 0.0, 0.0 / 0.0) return new CSLongDouble(1.0, 0.0) r = new CSLongDouble(@hi, @lo) s = new CSLongDouble(1.0, 0.0) p = Math.abs(n) if p > 1.0 while p > 0.0 if p % 2 == 1 s = s.mul(r) p = p / 2.0 if p > 0.0 r = r.mul(r) else s = r if n < 0.0 return new CSLongDouble(1.0, 0.0).div(s) else return s # Helper 1: Trivial # zero: () -> return @hi == 0.0 && @lo == 0.0 # Helper 2: Trivial # notZero: () -> return @hi != 0.0 || @lo != 0.0 # Helper 3: Trivial # one: () -> return @hi == 1.0 && @lo == 0.0 window.CSLongDouble = CSLongDouble
112078
# # longdouble.js, https://github.com/ofmlabs/longdouble.js # # By <NAME> of OFMLabs # # Lemma 1. Let a and b be two p-bit floating point numbers such that |a| ≥ |b|. # Then |err(a + b)| ≤ |b| ≤ |a|. # Lemma 2. Let a and b be two p-bit floating point numbers. # Then err(a + b) = (a + b) − fl(a + b) is representable as a p-bit # floating point number. # Algorithm 4. The following algorithm computes # s = fl(a + b) # e = err(a + b). # This algorithm uses three more floating point operations instead # of a branch. # # Note. I should look into if it is faster to use (3) with a branch. two_sum = (a, b) -> s = a + b e = s - a return [s, (a - (s - e)) + (b - e)] # Algorithm 3. The following algorithm computes # s = fl(a + b) # e = err(a + b), # assuming |a| ≥ |b|. quick_two_sum = (a, b) -> s = a + b return [s, b - (s - a)] # Algorithm 5. The following algorithm splits a 53-bit IEEE double precision # floating point number into ahi and alo, each with 26 bits of # significand, such that a = ahi + alo. ahi will contain the first # 26 bits, while alo will contain the lower 26 bits. # # Note. There is additional stuff in the code, that is not available in # the paper, I need to look into when it is needed. # # Ideas: Handles denormals? SPLITTER = 134217729.0 # = 2^27 + 1 split = (a) -> temp = SPLITTER * a hi = temp - (temp - a) lo = a - hi return [hi, lo] # Algorithm 6. The following algorithm computes # p = fl(a × b) # e = err(a × b). if (!Math.fma) # Only my special build of Firefox supports FMA yet. two_prod = (a, b) -> p = a * b [a_hi, a_lo] = split(a) [b_hi, b_lo] = split(b) error = ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo return [p, error] else # Algorithm 7. The following algorithm computes # p = fl(a × b) # e = err(a × b) # on a browser with FMA support. # # Note: FMA is never implemented in JS, but I will probably add it to # Spidermonkey soon, this would probably make this method much # faster, even without hardware support. two_prod = (a, b) -> p = a * b return [p, Math.fma(a, b, -p)] # Note: The same as (4), but with b replaced by -b. two_diff = (a, b) -> s = a - b e = s - a return [s, (a - (s - e)) - (b + e)] # Note: The same as (3), but with b replaced by -b. quick_two_diff = (a, b) -> s = a - b return [s, (a - s) - b] # TODO: Implement a sane constructor class CSLongDouble constructor: (@hi, @lo) -> # # Imp 1: Since a long-double is a sum of two doubles, just changing the # sign of both the high and the low part, we change the sign of # the sum itself. # negate: () -> return new CSLongDouble(-@hi, -@lo) # # Imp 2: To add a and b, we use the general structure to apply the # operation to first the high parts (s_hi, s_lo) and the low parts # (t_hi, t_lo) in separation, then we merge the results, first # t_hi, then t_lo. # add: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo); # # Imp 3: The fast versions have lower precision, since it only merges in # the high part (t_hi) of the lower parts. # addFast: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) s_lo = (s_lo + @lo) + other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 4: Essentially equivalent to the addFast method, but with some # optimizations due to the other.lo being 0. # addDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (2), but with the other replaced by -other. # That is, the first two two_sum operations in the network are # replaced by two_diff, the merging is done in the same way. # sub: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (3), but with the other replaced by -other. # That is, the first two_sum operation in the network is # replaced by two_diff, and the optimized second add is replaced # by a difference. # subFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) s_lo = (s_lo + @lo) - other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 6: Equivalent to (4), but with the other replaced by -other. # That is, the first two_sum operation is replaced by two_diff, # and just like in (5), but since the low part of other is 0, we # do not need the second difference. # subDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 7: Multiplication uses a similar network to the fast # implementations, due to the nature of floating point. # We know that the a_lo * b_lo will never end up in the final # product, which allows us to do some optimizations. # mul: (other) -> [p_hi, p_lo] = two_prod(@hi, other.hi) p_lo += (@hi * other.lo + other.hi * @lo) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 8: The same as (7), but since b_lo is 0, we can optimize a bit. # mulDouble: (other) -> [p_hi, p_lo] = two_prod(@hi, other) p_lo += (@lo * other) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 9: Implementing division is # div: (other) -> q_hi = @hi / other.hi r = this.sub(other.mulDouble(q_hi)) q_lo = r.hi / other.hi r.decrement(other.mulDouble(q_lo)) q_vlo = r.hi / other.hi [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) r = new CSLongDouble(q_hi, q_lo) return r.addDouble(q_vlo) # Imp 10: TODO divFast: (other) -> q_hi = @hi / other.hi r = other.mulDouble(q_hi) [s_hi, s_lo] = two_diff(@hi, r.hi) s_lo = (s_lo - r.lo) + @lo q_lo = (s_hi + s_lo) / other.hi [r.hi, r.lo] = quick_two_sum(q_hi, q_lo) return r # Imp 11: The same as (10), but with b_lo being 0. # divDouble: (other) -> q_hi = @hi / other [p_hi, p_lo] = two_prod(q_hi, other) [s_hi, s_lo] = two_diff(@hi, p_hi) s_lo = (s_lo + @lo) - p_lo q_lo = (s_hi + s_lo) / other [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) return new CSLongDouble(q_hi, q_lo) # Imp 12: See (2). # increment: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_hi += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_hi += t_lo; [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 13: See (3). # incrementFast: (other) -> [s_hi, s_lo] = two_sum(@sum, other.sum) s_lo = (s_lo + @lo) - other.lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 14: See (4). # incrementDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 15: See (5). # decrement: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 16: See (6). # decrementFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.lo) lo = (s_lo + @lo) - other.lo [@sum, @error] = quick_two_sum(s_hi, s_lo) return this # Imp 17: See (7). # decrementDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 18: Trivial # equal: (other) -> return @hi == other.hi && @lo == other.lo # Imp 19: Trivial # equalDouble: (other) -> return @hi == other && @lo == 0.0 # Imp 20: Trivial # notEqual: (other) -> return @hi != other.hi || @lo != other.lo # Imp 21: Trivial # notEqualDouble: (other) -> return @hi != other || @lo != 0.0 # Imp 22: Trivial # greaterThan: (other) -> return @hi > other.hi || (@hi == other.hi && @lo > other.lo) # Imp 23: Trivial # greaterThanDouble: (other) -> return @hi > other || (@hi == other && @lo > 0.0) # Imp 24: Trivial # greaterEqualThan: (other) -> return @hi >= other.hi || (@hi == other.hi && @lo >= other.lo) # Imp 25: Trivial # greaterEqualThanDouble: (other) -> return @hi >= other || (@hi == other && @lo >= 0.0) # Imp 26: Trivial # lessThan: (other) -> return @hi < other.hi || (@hi == other.hi && @lo < other.lo) # Imp 27: Trivial # lessThanDouble: (other) -> return @hi < other || (@hi == other && @lo < 0.0) # Imp 28: Trivial # lessEqualThan: (other) -> return @hi <= other.hi || (@hi == other.hi && @lo <= other.lo) # Imp 29: Trivial # lessEqualThanDouble: (other) -> return @hi <= other || (@hi == other && @lo <= 0.0) # Imp 30: Trivial # abs: () -> if this.lessThanDouble(0.0) return this.negate() else return new CSLongDouble(@hi, @lo) # Imp 31: TODO but trivial # pow: (n) -> if n == 0 if this.zero() return new CSLongDouble(0.0 / 0.0, 0.0 / 0.0) return new CSLongDouble(1.0, 0.0) r = new CSLongDouble(@hi, @lo) s = new CSLongDouble(1.0, 0.0) p = Math.abs(n) if p > 1.0 while p > 0.0 if p % 2 == 1 s = s.mul(r) p = p / 2.0 if p > 0.0 r = r.mul(r) else s = r if n < 0.0 return new CSLongDouble(1.0, 0.0).div(s) else return s # Helper 1: Trivial # zero: () -> return @hi == 0.0 && @lo == 0.0 # Helper 2: Trivial # notZero: () -> return @hi != 0.0 || @lo != 0.0 # Helper 3: Trivial # one: () -> return @hi == 1.0 && @lo == 0.0 window.CSLongDouble = CSLongDouble
true
# # longdouble.js, https://github.com/ofmlabs/longdouble.js # # By PI:NAME:<NAME>END_PI of OFMLabs # # Lemma 1. Let a and b be two p-bit floating point numbers such that |a| ≥ |b|. # Then |err(a + b)| ≤ |b| ≤ |a|. # Lemma 2. Let a and b be two p-bit floating point numbers. # Then err(a + b) = (a + b) − fl(a + b) is representable as a p-bit # floating point number. # Algorithm 4. The following algorithm computes # s = fl(a + b) # e = err(a + b). # This algorithm uses three more floating point operations instead # of a branch. # # Note. I should look into if it is faster to use (3) with a branch. two_sum = (a, b) -> s = a + b e = s - a return [s, (a - (s - e)) + (b - e)] # Algorithm 3. The following algorithm computes # s = fl(a + b) # e = err(a + b), # assuming |a| ≥ |b|. quick_two_sum = (a, b) -> s = a + b return [s, b - (s - a)] # Algorithm 5. The following algorithm splits a 53-bit IEEE double precision # floating point number into ahi and alo, each with 26 bits of # significand, such that a = ahi + alo. ahi will contain the first # 26 bits, while alo will contain the lower 26 bits. # # Note. There is additional stuff in the code, that is not available in # the paper, I need to look into when it is needed. # # Ideas: Handles denormals? SPLITTER = 134217729.0 # = 2^27 + 1 split = (a) -> temp = SPLITTER * a hi = temp - (temp - a) lo = a - hi return [hi, lo] # Algorithm 6. The following algorithm computes # p = fl(a × b) # e = err(a × b). if (!Math.fma) # Only my special build of Firefox supports FMA yet. two_prod = (a, b) -> p = a * b [a_hi, a_lo] = split(a) [b_hi, b_lo] = split(b) error = ((a_hi * b_hi - p) + a_hi * b_lo + a_lo * b_hi) + a_lo * b_lo return [p, error] else # Algorithm 7. The following algorithm computes # p = fl(a × b) # e = err(a × b) # on a browser with FMA support. # # Note: FMA is never implemented in JS, but I will probably add it to # Spidermonkey soon, this would probably make this method much # faster, even without hardware support. two_prod = (a, b) -> p = a * b return [p, Math.fma(a, b, -p)] # Note: The same as (4), but with b replaced by -b. two_diff = (a, b) -> s = a - b e = s - a return [s, (a - (s - e)) - (b + e)] # Note: The same as (3), but with b replaced by -b. quick_two_diff = (a, b) -> s = a - b return [s, (a - s) - b] # TODO: Implement a sane constructor class CSLongDouble constructor: (@hi, @lo) -> # # Imp 1: Since a long-double is a sum of two doubles, just changing the # sign of both the high and the low part, we change the sign of # the sum itself. # negate: () -> return new CSLongDouble(-@hi, -@lo) # # Imp 2: To add a and b, we use the general structure to apply the # operation to first the high parts (s_hi, s_lo) and the low parts # (t_hi, t_lo) in separation, then we merge the results, first # t_hi, then t_lo. # add: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo); # # Imp 3: The fast versions have lower precision, since it only merges in # the high part (t_hi) of the lower parts. # addFast: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) s_lo = (s_lo + @lo) + other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 4: Essentially equivalent to the addFast method, but with some # optimizations due to the other.lo being 0. # addDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (2), but with the other replaced by -other. # That is, the first two two_sum operations in the network are # replaced by two_diff, the merging is done in the same way. # sub: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 5: Equivalent to (3), but with the other replaced by -other. # That is, the first two_sum operation in the network is # replaced by two_diff, and the optimized second add is replaced # by a difference. # subFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) s_lo = (s_lo + @lo) - other.lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 6: Equivalent to (4), but with the other replaced by -other. # That is, the first two_sum operation is replaced by two_diff, # and just like in (5), but since the low part of other is 0, we # do not need the second difference. # subDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) return new CSLongDouble(s_hi, s_lo) # Imp 7: Multiplication uses a similar network to the fast # implementations, due to the nature of floating point. # We know that the a_lo * b_lo will never end up in the final # product, which allows us to do some optimizations. # mul: (other) -> [p_hi, p_lo] = two_prod(@hi, other.hi) p_lo += (@hi * other.lo + other.hi * @lo) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 8: The same as (7), but since b_lo is 0, we can optimize a bit. # mulDouble: (other) -> [p_hi, p_lo] = two_prod(@hi, other) p_lo += (@lo * other) [p_hi, p_lo] = quick_two_sum(p_hi, p_lo) return new CSLongDouble(p_hi, p_lo) # Imp 9: Implementing division is # div: (other) -> q_hi = @hi / other.hi r = this.sub(other.mulDouble(q_hi)) q_lo = r.hi / other.hi r.decrement(other.mulDouble(q_lo)) q_vlo = r.hi / other.hi [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) r = new CSLongDouble(q_hi, q_lo) return r.addDouble(q_vlo) # Imp 10: TODO divFast: (other) -> q_hi = @hi / other.hi r = other.mulDouble(q_hi) [s_hi, s_lo] = two_diff(@hi, r.hi) s_lo = (s_lo - r.lo) + @lo q_lo = (s_hi + s_lo) / other.hi [r.hi, r.lo] = quick_two_sum(q_hi, q_lo) return r # Imp 11: The same as (10), but with b_lo being 0. # divDouble: (other) -> q_hi = @hi / other [p_hi, p_lo] = two_prod(q_hi, other) [s_hi, s_lo] = two_diff(@hi, p_hi) s_lo = (s_lo + @lo) - p_lo q_lo = (s_hi + s_lo) / other [q_hi, q_lo] = quick_two_sum(q_hi, q_lo) return new CSLongDouble(q_hi, q_lo) # Imp 12: See (2). # increment: (other) -> [s_hi, s_lo] = two_sum(@hi, other.hi) [t_hi, t_lo] = two_sum(@lo, other.lo) s_hi += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_hi += t_lo; [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 13: See (3). # incrementFast: (other) -> [s_hi, s_lo] = two_sum(@sum, other.sum) s_lo = (s_lo + @lo) - other.lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 14: See (4). # incrementDouble: (other) -> [s_hi, s_lo] = two_sum(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 15: See (5). # decrement: (other) -> [s_hi, s_lo] = two_diff(@hi, other.hi) [t_hi, t_lo] = two_diff(@lo, other.lo) s_lo += t_hi [s_hi, s_lo] = quick_two_sum(s_hi, s_lo) s_lo += t_lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 16: See (6). # decrementFast: (other) -> [s_hi, s_lo] = two_diff(@hi, other.lo) lo = (s_lo + @lo) - other.lo [@sum, @error] = quick_two_sum(s_hi, s_lo) return this # Imp 17: See (7). # decrementDouble: (other) -> [s_hi, s_lo] = two_diff(@hi, other) s_lo += @lo [@hi, @lo] = quick_two_sum(s_hi, s_lo) return this # Imp 18: Trivial # equal: (other) -> return @hi == other.hi && @lo == other.lo # Imp 19: Trivial # equalDouble: (other) -> return @hi == other && @lo == 0.0 # Imp 20: Trivial # notEqual: (other) -> return @hi != other.hi || @lo != other.lo # Imp 21: Trivial # notEqualDouble: (other) -> return @hi != other || @lo != 0.0 # Imp 22: Trivial # greaterThan: (other) -> return @hi > other.hi || (@hi == other.hi && @lo > other.lo) # Imp 23: Trivial # greaterThanDouble: (other) -> return @hi > other || (@hi == other && @lo > 0.0) # Imp 24: Trivial # greaterEqualThan: (other) -> return @hi >= other.hi || (@hi == other.hi && @lo >= other.lo) # Imp 25: Trivial # greaterEqualThanDouble: (other) -> return @hi >= other || (@hi == other && @lo >= 0.0) # Imp 26: Trivial # lessThan: (other) -> return @hi < other.hi || (@hi == other.hi && @lo < other.lo) # Imp 27: Trivial # lessThanDouble: (other) -> return @hi < other || (@hi == other && @lo < 0.0) # Imp 28: Trivial # lessEqualThan: (other) -> return @hi <= other.hi || (@hi == other.hi && @lo <= other.lo) # Imp 29: Trivial # lessEqualThanDouble: (other) -> return @hi <= other || (@hi == other && @lo <= 0.0) # Imp 30: Trivial # abs: () -> if this.lessThanDouble(0.0) return this.negate() else return new CSLongDouble(@hi, @lo) # Imp 31: TODO but trivial # pow: (n) -> if n == 0 if this.zero() return new CSLongDouble(0.0 / 0.0, 0.0 / 0.0) return new CSLongDouble(1.0, 0.0) r = new CSLongDouble(@hi, @lo) s = new CSLongDouble(1.0, 0.0) p = Math.abs(n) if p > 1.0 while p > 0.0 if p % 2 == 1 s = s.mul(r) p = p / 2.0 if p > 0.0 r = r.mul(r) else s = r if n < 0.0 return new CSLongDouble(1.0, 0.0).div(s) else return s # Helper 1: Trivial # zero: () -> return @hi == 0.0 && @lo == 0.0 # Helper 2: Trivial # notZero: () -> return @hi != 0.0 || @lo != 0.0 # Helper 3: Trivial # one: () -> return @hi == 1.0 && @lo == 0.0 window.CSLongDouble = CSLongDouble
[ { "context": "l.service\n user: config.mail.username\n pass: config.mail.password\n authMethod: \"LOGIN\"\n smtpTransport\n", "end": 4122, "score": 0.9976469278335571, "start": 4102, "tag": "PASSWORD", "value": "config.mail.password" } ]
server/auth.coffee
flauta/codecombat
0
passport = require('passport') winston = require('winston') LocalStrategy = require('passport-local').Strategy User = require('./models/User') UserHandler = require('./handlers/user') config = require '../server_config' nodemailer = require 'nodemailer' errors = require './errors' module.exports.setupRoutes = (app) -> passport.serializeUser((user, done) -> done(null, user._id)) passport.deserializeUser((id, done) -> User.findById(id, (err, user) -> done(err, user))) passport.use(new LocalStrategy( (username, password, done) -> User.findOne({emailLower:username.toLowerCase()}).exec((err, user) -> return done(err) if err return done(null, false, {message:'not found', property:'email'}) if not user passwordReset = (user.get('passwordReset') or '').toLowerCase() if passwordReset and password.toLowerCase() is passwordReset User.update {_id: user.get('_id')}, {passwordReset: ''}, {}, -> return done(null, user) hash = User.hashPassword(password) unless user.get('passwordHash') is hash return done(null, false, {message:'is wrong, wrong, wrong', property:'password'}) return done(null, user) ) )) app.post('/auth/login', (req, res, next) -> passport.authenticate('local', (err, user, info) -> return next(err) if err if not user return errors.unauthorized(res, [{message:info.message, property:info.property}]) req.logIn(user, (err) -> return next(err) if (err) res.send(UserHandler.formatEntity(req, req.user)) return res.end() ) )(req, res, next) ) app.get('/auth/whoami', (req, res) -> res.setHeader('Content-Type', 'text/json'); res.send(UserHandler.formatEntity(req, req.user)) res.end() ) app.post('/auth/logout', (req, res) -> req.logout() res.end() ) app.post('/auth/reset', (req, res) -> unless req.body.email return errors.badInput(res, [{message:'Need an email specified.', property:email}]) User.findOne({emailLower:req.body.email.toLowerCase()}).exec((err, user) -> if not user return errors.notFound(res, [{message:'not found.', property:'email'}]) user.set('passwordReset', Math.random().toString(36).slice(2,7).toUpperCase()) user.save (err) => return errors.serverError(res) if err if config.isProduction transport = createSMTPTransport() options = createMailOptions req.body.email, user.get('passwordReset') transport.sendMail options, (error, response) -> if error console.error "Error sending mail: #{error.message or error}" return errors.serverError(res) if err else return res.end() else console.log 'new password is', user.get('passwordReset') return res.end() ) ) app.get '/auth/unsubscribe', (req, res) -> email = req.query.email unless req.query.email return errors.badInput res, 'No email provided to unsubscribe.' User.findOne({emailLower:req.query.email.toLowerCase()}).exec (err, user) -> if not user return errors.notFound res, "No user found with email '#{req.query.email}'" user.set('emailSubscriptions', []) user.save (err) => return errors.serverError res, 'Database failure.' if err res.send "Unsubscribed #{req.query.email} from all CodeCombat emails. Sorry to see you go! <p><a href='/account/settings'>Account settings</a></p>" res.end() createMailOptions = (receiver, password) -> # TODO: use email templates here options = from: config.mail.username to: receiver replyTo: config.mail.username subject: "[CodeCombat] Password Reset" text: "You can log into your account with: #{password}" #html: message.replace '\n', '<br>\n' createSMTPTransport = -> return smtpTransport if smtpTransport smtpTransport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: config.mail.password authMethod: "LOGIN" smtpTransport
49929
passport = require('passport') winston = require('winston') LocalStrategy = require('passport-local').Strategy User = require('./models/User') UserHandler = require('./handlers/user') config = require '../server_config' nodemailer = require 'nodemailer' errors = require './errors' module.exports.setupRoutes = (app) -> passport.serializeUser((user, done) -> done(null, user._id)) passport.deserializeUser((id, done) -> User.findById(id, (err, user) -> done(err, user))) passport.use(new LocalStrategy( (username, password, done) -> User.findOne({emailLower:username.toLowerCase()}).exec((err, user) -> return done(err) if err return done(null, false, {message:'not found', property:'email'}) if not user passwordReset = (user.get('passwordReset') or '').toLowerCase() if passwordReset and password.toLowerCase() is passwordReset User.update {_id: user.get('_id')}, {passwordReset: ''}, {}, -> return done(null, user) hash = User.hashPassword(password) unless user.get('passwordHash') is hash return done(null, false, {message:'is wrong, wrong, wrong', property:'password'}) return done(null, user) ) )) app.post('/auth/login', (req, res, next) -> passport.authenticate('local', (err, user, info) -> return next(err) if err if not user return errors.unauthorized(res, [{message:info.message, property:info.property}]) req.logIn(user, (err) -> return next(err) if (err) res.send(UserHandler.formatEntity(req, req.user)) return res.end() ) )(req, res, next) ) app.get('/auth/whoami', (req, res) -> res.setHeader('Content-Type', 'text/json'); res.send(UserHandler.formatEntity(req, req.user)) res.end() ) app.post('/auth/logout', (req, res) -> req.logout() res.end() ) app.post('/auth/reset', (req, res) -> unless req.body.email return errors.badInput(res, [{message:'Need an email specified.', property:email}]) User.findOne({emailLower:req.body.email.toLowerCase()}).exec((err, user) -> if not user return errors.notFound(res, [{message:'not found.', property:'email'}]) user.set('passwordReset', Math.random().toString(36).slice(2,7).toUpperCase()) user.save (err) => return errors.serverError(res) if err if config.isProduction transport = createSMTPTransport() options = createMailOptions req.body.email, user.get('passwordReset') transport.sendMail options, (error, response) -> if error console.error "Error sending mail: #{error.message or error}" return errors.serverError(res) if err else return res.end() else console.log 'new password is', user.get('passwordReset') return res.end() ) ) app.get '/auth/unsubscribe', (req, res) -> email = req.query.email unless req.query.email return errors.badInput res, 'No email provided to unsubscribe.' User.findOne({emailLower:req.query.email.toLowerCase()}).exec (err, user) -> if not user return errors.notFound res, "No user found with email '#{req.query.email}'" user.set('emailSubscriptions', []) user.save (err) => return errors.serverError res, 'Database failure.' if err res.send "Unsubscribed #{req.query.email} from all CodeCombat emails. Sorry to see you go! <p><a href='/account/settings'>Account settings</a></p>" res.end() createMailOptions = (receiver, password) -> # TODO: use email templates here options = from: config.mail.username to: receiver replyTo: config.mail.username subject: "[CodeCombat] Password Reset" text: "You can log into your account with: #{password}" #html: message.replace '\n', '<br>\n' createSMTPTransport = -> return smtpTransport if smtpTransport smtpTransport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: <PASSWORD> authMethod: "LOGIN" smtpTransport
true
passport = require('passport') winston = require('winston') LocalStrategy = require('passport-local').Strategy User = require('./models/User') UserHandler = require('./handlers/user') config = require '../server_config' nodemailer = require 'nodemailer' errors = require './errors' module.exports.setupRoutes = (app) -> passport.serializeUser((user, done) -> done(null, user._id)) passport.deserializeUser((id, done) -> User.findById(id, (err, user) -> done(err, user))) passport.use(new LocalStrategy( (username, password, done) -> User.findOne({emailLower:username.toLowerCase()}).exec((err, user) -> return done(err) if err return done(null, false, {message:'not found', property:'email'}) if not user passwordReset = (user.get('passwordReset') or '').toLowerCase() if passwordReset and password.toLowerCase() is passwordReset User.update {_id: user.get('_id')}, {passwordReset: ''}, {}, -> return done(null, user) hash = User.hashPassword(password) unless user.get('passwordHash') is hash return done(null, false, {message:'is wrong, wrong, wrong', property:'password'}) return done(null, user) ) )) app.post('/auth/login', (req, res, next) -> passport.authenticate('local', (err, user, info) -> return next(err) if err if not user return errors.unauthorized(res, [{message:info.message, property:info.property}]) req.logIn(user, (err) -> return next(err) if (err) res.send(UserHandler.formatEntity(req, req.user)) return res.end() ) )(req, res, next) ) app.get('/auth/whoami', (req, res) -> res.setHeader('Content-Type', 'text/json'); res.send(UserHandler.formatEntity(req, req.user)) res.end() ) app.post('/auth/logout', (req, res) -> req.logout() res.end() ) app.post('/auth/reset', (req, res) -> unless req.body.email return errors.badInput(res, [{message:'Need an email specified.', property:email}]) User.findOne({emailLower:req.body.email.toLowerCase()}).exec((err, user) -> if not user return errors.notFound(res, [{message:'not found.', property:'email'}]) user.set('passwordReset', Math.random().toString(36).slice(2,7).toUpperCase()) user.save (err) => return errors.serverError(res) if err if config.isProduction transport = createSMTPTransport() options = createMailOptions req.body.email, user.get('passwordReset') transport.sendMail options, (error, response) -> if error console.error "Error sending mail: #{error.message or error}" return errors.serverError(res) if err else return res.end() else console.log 'new password is', user.get('passwordReset') return res.end() ) ) app.get '/auth/unsubscribe', (req, res) -> email = req.query.email unless req.query.email return errors.badInput res, 'No email provided to unsubscribe.' User.findOne({emailLower:req.query.email.toLowerCase()}).exec (err, user) -> if not user return errors.notFound res, "No user found with email '#{req.query.email}'" user.set('emailSubscriptions', []) user.save (err) => return errors.serverError res, 'Database failure.' if err res.send "Unsubscribed #{req.query.email} from all CodeCombat emails. Sorry to see you go! <p><a href='/account/settings'>Account settings</a></p>" res.end() createMailOptions = (receiver, password) -> # TODO: use email templates here options = from: config.mail.username to: receiver replyTo: config.mail.username subject: "[CodeCombat] Password Reset" text: "You can log into your account with: #{password}" #html: message.replace '\n', '<br>\n' createSMTPTransport = -> return smtpTransport if smtpTransport smtpTransport = nodemailer.createTransport "SMTP", service: config.mail.service user: config.mail.username pass: PI:PASSWORD:<PASSWORD>END_PI authMethod: "LOGIN" smtpTransport
[ { "context": "#\n# Document level hooks\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\n$ ->\n $('.lui-tabs').forEach (element)->\n u", "end": 65, "score": 0.9998852610588074, "start": 48, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/tabs/src/document.coffee
lovely-io/lovely.io-stl
2
# # Document level hooks # # Copyright (C) 2012 Nikolay Nemshilov # $ -> $('.lui-tabs').forEach (element)-> unless element instanceof Tabs new Tabs(element._)
43322
# # Document level hooks # # Copyright (C) 2012 <NAME> # $ -> $('.lui-tabs').forEach (element)-> unless element instanceof Tabs new Tabs(element._)
true
# # Document level hooks # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # $ -> $('.lui-tabs').forEach (element)-> unless element instanceof Tabs new Tabs(element._)
[ { "context": "'.remove', @el).hide() if @model.get('email') is 'admin@voxe.org'\n\n @\n\n removeAdmin: ->\n @model.removeAdmin", "end": 366, "score": 0.999911367893219, "start": 352, "tag": "EMAIL", "value": "admin@voxe.org" } ]
app/assets/javascripts/admin/views/admins/admin_view.js.coffee
JulienGuizot/voxe
5
class Admin.Views.Admins.AdminView extends Backbone.View tagName: 'tr' template: JST['admin/templates/admins/admin'] events: 'click .remove': 'removeAdmin' initialize: -> @model.bind 'change', => @trigger 'adminChanged' render: -> $(@el).html @template(@model.toJSON()) $('.remove', @el).hide() if @model.get('email') is 'admin@voxe.org' @ removeAdmin: -> @model.removeAdmin()
106991
class Admin.Views.Admins.AdminView extends Backbone.View tagName: 'tr' template: JST['admin/templates/admins/admin'] events: 'click .remove': 'removeAdmin' initialize: -> @model.bind 'change', => @trigger 'adminChanged' render: -> $(@el).html @template(@model.toJSON()) $('.remove', @el).hide() if @model.get('email') is '<EMAIL>' @ removeAdmin: -> @model.removeAdmin()
true
class Admin.Views.Admins.AdminView extends Backbone.View tagName: 'tr' template: JST['admin/templates/admins/admin'] events: 'click .remove': 'removeAdmin' initialize: -> @model.bind 'change', => @trigger 'adminChanged' render: -> $(@el).html @template(@model.toJSON()) $('.remove', @el).hide() if @model.get('email') is 'PI:EMAIL:<EMAIL>END_PI' @ removeAdmin: -> @model.removeAdmin()
[ { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos@gmail.com>\n https://raithos.github.io", "end": 48, "score": 0.9996595978736877, "start": 37, "tag": "NAME", "value": "Stephen Kim" }, { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos@gmail.com>\n https://raithos.github.io\n###\n\nexportObj = e", "end": 67, "score": 0.9999297857284546, "start": 50, "tag": "EMAIL", "value": "raithos@gmail.com" }, { "context": " builder.current_squad.name = new_name\n builder.current_squad.dir", "end": 38456, "score": 0.80942702293396, "start": 38448, "tag": "NAME", "value": "new_name" } ]
coffeescripts/system/backend.coffee
danrs/xwing
0
### X-Wing Squad Builder 2.0 Stephen Kim <raithos@gmail.com> https://raithos.github.io ### exportObj = exports ? this class exportObj.SquadBuilderBackend ### Usage: rebel_builder = new SquadBuilder faction: 'Rebel Alliance' ... empire_builder = new SquadBuilder faction: 'Galactic Empire' ... backend = new SquadBuilderBackend server: 'https://xwing.example.com' builders: [ rebel_builder, empire_builder ] login_logout_button: '#login-logout' auth_status: '#auth-status' ### constructor: (args) -> # Might as well do this right away $.ajaxSetup dataType: "json" # Because Firefox sucks for some reason xhrFields: withCredentials: true # args @server = args.server @builders = args.builders @login_logout_button = $ args.login_logout_button @auth_status = $ args.auth_status @authenticated = false @ui_ready = false @oauth_window = null @method_metadata = google_oauth2: icon: 'fab fa-google' text: 'Google' facebook: icon: 'fab fa-facebook' text: 'Facebook' twitter: icon: 'fab fa-twitter' text: 'Twitter' discord: icon: 'fab fa-discord' text: 'Discord' @squad_display_mode = 'all' @show_archived = false @collection_save_timer = null @setupHandlers() @setupUI() # Check initial authentication status @authenticate () => @auth_status.hide() @login_logout_button.removeClass 'd-none' # Finally, hook up the builders for builder in @builders builder.setBackend this @updateAuthenticationVisibility() updateAuthenticationVisibility: () -> if @authenticated $('.show-authenticated').show() $('.hide-authenticated').hide() else $('.show-authenticated').hide() $('.hide-authenticated').show() save: (serialized, id=null, name, faction, additional_data={}, cb) -> if serialized == "" cb id: null success: false error: "You cannot save an empty squad" else if $.trim(name) == "" cb id: null success: false error: "Squad name cannot be empty" else if not faction? or faction == "" throw "Faction unspecified to save()" else post_args = name: $.trim(name) faction: $.trim(faction) serialized: serialized additional_data: additional_data if id? post_url = "#{@server}/squads/#{id}" else post_url = "#{@server}/squads/new" post_args['_method'] = 'put' $.post post_url, post_args, (data, textStatus, jqXHR) => cb id: data.id success: data.success error: data.error delete: (id, cb) -> post_args = '_method': 'delete' $.post "#{@server}/squads/#{id}", post_args, (data, textStatus, jqXHR) => cb success: data.success error: data.error archive: (data, faction, cb) -> data.additional_data["archived"] = true @save(data.serialized, data.id, data.name, faction, data.additional_data, cb) list: (builder) -> # TODO: Pagination @squad_list_modal.find('.modal-header .squad-list-header-placeholder').text(exportObj.translate('ui', "yourXYsquads", builder.faction)) list_ul = $ @squad_list_modal.find('ul.squad-list') list_ul.text '' list_ul.hide() loading_pane = $ @squad_list_modal.find('p.squad-list-loading') loading_pane.show() @show_all_squads_button.click() @squad_list_modal.modal 'show' # This counter keeps tracked of the number of squads marked to be deleted (to hide the delete-selected button if none is selected) @number_of_selected_squads_to_be_deleted = 0 #setup tag list tag_list = [] url = "#{@server}/squads/list" $.get url, (data, textStatus, jqXHR) => hasNotArchivedSquads = false for squad in data[builder.faction] li = $ document.createElement('LI') li.addClass 'squad-summary' li.data 'squad', squad li.data 'builder', builder li.data 'selectedForDeletion', false list_ul.append li if squad.additional_data?.tag? and (squad.additional_data?.tag != "") and (tag_list.indexOf(squad.additional_data.tag) == -1) tag_array = squad.additional_data?.tag.split(",") for tag_entry in tag_array tag_list.push tag_entry if squad.additional_data?.archived? li.hide() else hasNotArchivedSquads = true li.append $.trim """ <div class="row"> <div class="col-md-9"> <h4>#{squad.name}</h4> </div> <div class="col-md-3"> <h5>#{squad.additional_data?.points} #{exportObj.translate('ui', "Points")}</h5> </div> </div> <div class="row squad-description"> <div class="col-md-9"> #{squad.additional_data?.description} </div> <div class="squad-buttons col-md-3"> <button class="btn btn-modal convert-squad"><i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i></button> &nbsp; <button class="btn btn-modal load-squad"><i class="fa fa-download"></i></button> &nbsp; <button class="btn btn-danger delete-squad"><i class="fa fa-times"></i></button> </div> </div> <div class="row squad-convert-confirm"> <div class="col-md-9 translated" defaultText="Convert to Extended?"> </div> <div class="squad-buttons col-md-3"> <button class="btn btn-danger confirm-convert-squad translated" defaultText="Convert"></button> &nbsp; <button class="btn btn-modal cancel-convert-squad translated" defaultText="Cancel"></button> </div> </div> <div class="row squad-delete-confirm"> <div class="col-md-9"> #{exportObj.translate('ui', 'reallyDeleteSquadXY', "<em>#{squad.name}</em>")} </div> <div class="col-md-3"> <button class="btn btn-danger confirm-delete-squad translated" defaultText="Delete"></button> &nbsp; <button class="btn btn-modal cancel-delete-squad translated" defaultText="Cancel"></button> </div> </div> """ li.find('.squad-convert-confirm').hide() li.find('.squad-delete-confirm').hide() if squad.serialized.search(/v\d+Zh/) == -1 li.find('button.convert-squad').hide() li.find('button.convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-convert-confirm').fadeIn 'fast' li.find('button.cancel-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', false do (li) => li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.confirm-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-convert-squad').fadeOut 'fast' li.find('.confirm-convert-squad').addClass 'disabled' li.find('.confirm-convert-squad').text 'Converting...' new_serialized = li.data('squad').serialized.replace('Zh','Zs') @save new_serialized, li.data('squad').id, li.data('squad').name, li.data('builder').faction, li.data('squad').additional_data, (results) => if results.success li.data('squad').serialized = new_serialized li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.convert-squad').fadeOut 'fast' else li.html $.trim """ Error converting #{li.data('squad').name}: <em>#{results.error}</em> """ li.find('button.load-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, () -> builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') else builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') li.find('button.delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' # show delete multiple section if not yet shown if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').show() # increment counter @number_of_selected_squads_to_be_deleted += 1 li.find('button.cancel-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', false # decrement counter @number_of_selected_squads_to_be_deleted -= 1 do (li) => li.find('.squad-delete-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() li.find('button.confirm-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text 'Deleting...' @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ if not hasNotArchivedSquads list_ul.append $.trim """ <li class="translated" defaultText="No saved squads"></li> """ #setup Tags @squad_list_tags.empty() for tag in tag_list tagclean = tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') @squad_list_tags.append $.trim """ <button class="btn #{tagclean}">#{tag}</button> """ tag_button = $ @squad_list_tags.find(".#{tagclean}") tag_button.click (e) => button = $ e.target buttontag = button.attr('class').replace('btn ','').replace('btn-inverse ','') @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> if $(elem).data().squad.additional_data.tag? tag_array = $(elem).data().squad.additional_data.tag.split(",") found_tag = false for tag in tag_array if buttontag == tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') then found_tag = true if found_tag then $(elem).show() else $(elem).hide() else $(elem).hide() # some of the created html needs translation (e.g. buttons). Do that now. exportObj.translateUIElements(list_ul) loading_pane.fadeOut 'fast' list_ul.fadeIn 'fast' authenticate: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Checking auth status...') @auth_status.show() old_auth_state = @authenticated $.ajax url: "#{@server}/ping" success: (data) => if data?.success @authenticated = true else @authenticated = false @maybeAuthenticationChanged old_auth_state, cb error: (jqXHR, textStatus, errorThrown) => @authenticated = false @maybeAuthenticationChanged old_auth_state, cb maybeAuthenticationChanged: (old_auth_state, cb) => if old_auth_state != @authenticated $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @oauth_window = null @auth_status.hide() cb @authenticated @authenticated login: () -> # Display login dialog. if @ui_ready @login_modal.modal 'show' logout: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Logging out...') @auth_status.show() $.get "#{@server}/auth/logout", (data, textStatus, jqXHR) => @authenticated = false $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @auth_status.hide() cb() showSaveAsModal: (builder) -> @save_as_modal.data 'builder', builder @save_as_input.val builder.current_squad.name @save_as_save_button.addClass 'disabled' @nameCheck() @save_as_modal.modal 'show' showDeleteModal: (builder) -> @delete_modal.data 'builder', builder @delete_name_container.text builder.current_squad.name @delete_modal.modal 'show' nameCheck: () => window.clearInterval @save_as_modal.data('timer') # trivial check name = $.trim(@save_as_input.val()) if name.length == 0 @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "name required")} """ else $.post "#{@server}/squads/namecheck", { name: name }, (data) => @name_availability_container.text '' if data.available @name_availability_container.append $.trim """ <i class="fa fa-thumbs-up"></i> #{exportObj.translate('ui', "Name is available")} """ @save_as_save_button.removeClass 'disabled' else @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "Name in use")} """ @save_as_save_button.addClass 'disabled' warnUnsaved: (builder, action) -> @unsaved_modal.data 'builder', builder @unsaved_modal.data 'callback', action @unsaved_modal.modal 'show' setupUI: () -> @auth_status.addClass 'disabled' @auth_status.click (e) => false @login_modal = $ document.createElement('DIV') @login_modal.addClass 'modal fade d-print-none' @login_modal.tabindex = "-1" @login_modal.role = "dialog" $(document.body).append @login_modal @login_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Log in with OAuth"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p> <span class="translated" defaultText="select OAuth provider"></span> <a class="login-help translated" href="#" defaultText="What's this?"></a> </p> <div class="well well-small oauth-explanation"> <span class="translated" defaultText="OAuth explanation"></span> <button class="btn btn-modal translated" defaultText="Got it!"></button> </div> <ul class="login-providers inline"></ul> <p class="translated" defaultText="Continue to OAuth provider"></p> <p class="translated" defaultText="iOS requires cross-site control"></p> <p class="login-in-progress"> <em class="translated" defaultText="login in progress"></em> </p> </div> </div> </div> """ oauth_explanation = $ @login_modal.find('.oauth-explanation') oauth_explanation.hide() @login_modal.find('.login-in-progress').hide() @login_modal.find('a.login-help').click (e) => e.preventDefault() unless oauth_explanation.is ':visible' oauth_explanation.slideDown 'fast' oauth_explanation.find('button').click (e) => e.preventDefault() oauth_explanation.slideUp 'fast' $.get "#{@server}/methods", (data, textStatus, jqXHR) => methods_ul = $ @login_modal.find('ul.login-providers') for method in data.methods a = $ document.createElement('A') a.addClass 'btn btn-modal' a.data 'url', "#{@server}/auth/#{method}" a.append """<i class="#{@method_metadata[method].icon}"></i>&nbsp;#{@method_metadata[method].text}""" a.click (e) => e.preventDefault() methods_ul.slideUp 'fast' @login_modal.find('.login-in-progress').slideDown 'fast' @oauth_window = window.open $(e.target).data('url'), "xwing_login" li = $ document.createElement('LI') li.append a methods_ul.append li @ui_ready = true # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@login_modal) @reload_done_modal = $ document.createElement('DIV') @reload_done_modal.addClass 'modal fade d-print-none' @reload_done_modal.tabindex = "-1" @reload_done_modal.role = "dialog" $(document.body).append @reload_done_modal @reload_done_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Reload Done</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Squads reloaded"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Well done!"></button> </div> </div> </div> """ # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@reload_done_modal) @squad_list_modal = $ document.createElement('DIV') @squad_list_modal.addClass 'modal fade d-print-none squad-list' @squad_list_modal.tabindex = "-1" @squad_list_modal.role = "dialog" $(document.body).append @squad_list_modal @squad_list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="squad-list-header-placeholder d-none d-lg-block"></h3> <h4 class="squad-list-header-placeholder d-lg-none"></h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <ul class="squad-list"></ul> <p class="pagination-centered squad-list-loading"> <i class="fa fa-spinner fa-spin fa-3x"></i> <br /> <span class="translated" defaultText="Fetching squads..."></span> </p> </div> <div class="modal-footer"> <div class="btn-group delete-multiple-squads full-row"> <button class="btn btn-modal select-all translated" defaultText="Select All"></button> <button class="btn btn-modal archive-selected translated" defaultText="Archive Selected"></button> <button class="btn btn-modal btn-danger delete-selected translated" defaultText="Delete Selected"></button> </div> <div class="btn-group squad-display-mode full-row"> <button class="btn btn-modal btn-inverse show-all-squads translated" defaultText="All"></button> <button class="btn btn-modal show-standard-squads"><span class="d-none d-lg-block translated" defaultText="Standard"></span><span class="d-lg-none translated" defaultText="Hyper"></span></button> <button class="btn btn-modal show-extended-squads"><span class="d-none d-lg-block translated" defaultText="Extended"></span><span class="d-lg-none translated" defaultText="Ext"></span></button> <button class="btn btn-modal show-quickbuild-squads"><span class="d-none d-lg-block translated" defaultText="Quickbuild"></span><span class="d-lg-none translated" defaultText="QB"></span></button> <button class="btn btn-modal show-epic-squads translated" defaultText="Epic"></button> <button class="btn btn-modal show-archived-squads translated" defaultText="Archived"></button> <button class="btn btn-modal reload-all translated" defaultText="Recalculate Points"></button> </div> <div class="btn-group tags-display full-row"> </div> </div> </div> </div> """ @squad_list_modal.find('ul.squad-list').hide() @squad_list_tags = $ @squad_list_modal.find('div.tags-display') # The delete multiple section only appeares, when somebody hits the delete button of one squad. @squad_list_modal.find('div.delete-multiple-squads').hide() # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_selected_button = $ @squad_list_modal.find('button.delete-selected') @delete_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Deleting...') @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ @archive_selected_button = $ @squad_list_modal.find('button.archive-selected') @archive_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Archiving...') @archive li.data('squad'), li.data('builder').faction, (results) => if results.success li.slideUp 'fast', -> $(li).hide() $(li).find('.confirm-delete-squad').removeClass 'disabled' $(li).find('.confirm-delete-squad').text exportObj.translate('ui', 'Delete') $(li).data 'selectedForDeletion', false $(li).find('.squad-delete-confirm').fadeOut 'fast', -> $(li).find('.squad-description').fadeIn 'fast' # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error archiving #{li.data('squad').name}: <em>#{results.error}</em> """ @squad_list_modal.find('button.reload-all').click (e) => ul = @squad_list_modal.find('ul.squad-list') squadProcessingStack = [ () => @reload_done_modal.modal 'show' ] squadDataStack = [] for li in ul.find('li') li = $ li squadDataStack.push li.data('squad') builder = li.data('builder') squadProcessingStack.push () => sqd = squadDataStack.pop() # console.log("loading " + sqd.name) builder.container.trigger 'xwing-backend:squadLoadRequested', [ sqd, () => additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.notes.val().substr(0, 1024) obstacles: builder.getObstacles() tag: builder.tag.val().substr(0, 1024) # console.log("saving " + builder.current_squad.name) @save builder.serialize(), builder.current_squad.id, builder.current_squad.name, builder.faction, additional_data, squadProcessingStack.pop() ] @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, squadProcessingStack.pop() else squadProcessingStack.pop()() @select_all_button = $ @squad_list_modal.find('button.select-all') @select_all_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if not li.data 'selectedForDeletion' li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' @number_of_selected_squads_to_be_deleted += 1 @show_all_squads_button = $ @squad_list_modal.find('.show-all-squads') @show_all_squads_button.click (e) => unless @squad_display_mode == 'all' @squad_display_mode = 'all' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_all_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').show() @show_extended_squads_button = $ @squad_list_modal.find('.show-extended-squads') @show_extended_squads_button.click (e) => unless @squad_display_mode == 'extended' @squad_display_mode = 'extended' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_extended_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zs/) != -1 @show_epic_squads_button = $ @squad_list_modal.find('.show-epic-squads') @show_epic_squads_button.click (e) => unless @squad_display_mode == 'epic' @squad_display_mode = 'epic' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_epic_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Ze/) != -1 @show_standard_squads_button = $ @squad_list_modal.find('.show-standard-squads') @show_standard_squads_button.click (e) => unless @squad_display_mode == 'standard' @squad_display_mode = 'standard' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_standard_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zh/) != -1 @show_quickbuild_squads_button = $ @squad_list_modal.find('.show-quickbuild-squads') @show_quickbuild_squads_button.click (e) => unless @squad_display_mode == 'quickbuild' @squad_display_mode = 'quickbuild' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_quickbuild_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zq/) != -1 @show_archived_squads_button = $ @squad_list_modal.find('.show-archived-squads') @show_archived_squads_button.click (e) => @show_archived = not @show_archived if @show_archived @show_archived_squads_button.addClass 'btn-inverse' else @show_archived_squads_button.removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) => $(elem).toggle (($(elem).data().squad.additional_data.archived?) == @show_archived) @save_as_modal = $ document.createElement('DIV') @save_as_modal.addClass 'modal fade d-print-none' @save_as_modal.tabindex = "-1" @save_as_modal.role = "dialog" $(document.body).append @save_as_modal @save_as_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Save Squad As..."></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label for="xw-be-squad-save-as"> <span class="translated" defaultText="New Squad Name"></span> <input id="xw-be-squad-save-as"></input> </label> <span class="name-availability"></span> </div> <div class="modal-footer"> <button class="btn btn-primary save translated" aria-hidden="true" defaultText="Save"></button> </div> </div> </div> """ @save_as_modal.on 'shown', () => # Because Firefox handles this badly window.setTimeout () => @save_as_input.focus() @save_as_input.select() , 100 @save_as_save_button = @save_as_modal.find('button.save') @save_as_save_button.click (e) => e.preventDefault() unless @save_as_save_button.hasClass('disabled') timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.modal 'hide' builder = @save_as_modal.data 'builder' additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.getNotes() obstacles: builder.getObstacles() tag: builder.getTag() builder.backend_save_list_as_button.addClass 'disabled' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', 'Saving squad...')} """ builder.backend_status.show() new_name = $.trim @save_as_input.val() @save builder.serialize(), null, new_name, builder.faction, additional_data, (results) => if results.success builder.current_squad.id = results.id builder.current_squad.name = new_name builder.current_squad.dirty = false builder.container.trigger 'xwing-backend:squadNameChanged' builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', 'New squad saved successfully.')} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ builder.backend_save_list_as_button.removeClass 'disabled' @save_as_input = $ @save_as_modal.find('input') @save_as_input.keypress (e) => if e.which == 13 @save_as_save_button.click() false else @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-spin fa-spinner"></i> #{exportObj.translate('ui', 'Checking name availability...')} """ timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.data 'timer', window.setInterval(@nameCheck, 500) @name_availability_container = $ @save_as_modal.find('.name-availability') # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_modal = $ document.createElement('DIV') @delete_modal.addClass 'modal fade d-print-none' @delete_modal.tabindex = "-1" @delete_modal.role = "dialog" $(document.body).append @delete_modal @delete_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3><span class="translated" defaultText="Really Delete"></span> <span class="squad-name-placeholder"></span>?</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Sure to delete?"></p> </div> <div class="modal-footer"> <button class="btn btn-danger delete" aria-hidden="true"><span class="translated" defaultText="Yes, Delete"></span> <i class="squad-name-placeholder"></i></button> <button class="btn btn-modal translated" data-dismiss="modal" aria-hidden="true" defaultText="Never Mind"></button> </div> </div> </div> """ @delete_name_container = $ @delete_modal.find('.squad-name-placeholder') @delete_button = $ @delete_modal.find('button.delete') @delete_button.click (e) => e.preventDefault() builder = @delete_modal.data 'builder' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', "Deleting squad...")} """ builder.backend_status.show() builder.backend_delete_list_button.addClass 'disabled' @delete_modal.modal 'hide' @delete builder.current_squad.id, (results) => if results.success builder.resetCurrentSquad() builder.current_squad.dirty = true builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', "Squad deleted.")} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ # Failed, so offer chance to delete again builder.backend_delete_list_button.removeClass 'disabled' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@delete_modal) @unsaved_modal = $ document.createElement('DIV') @unsaved_modal.addClass 'modal fade d-print-none' @unsaved_modal.tabindex = "-1" @unsaved_modal.role = "dialog" $(document.body).append @unsaved_modal @unsaved_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Unsaved Changes"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Unsaved Changes Warning"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Go Back"></button> <button class="btn btn-danger discard translated" aria-hidden="true" defaultText="Discard Changes"></button> </div> </div> </div> """ @unsaved_discard_button = $ @unsaved_modal.find('button.discard') @unsaved_discard_button.click (e) => e.preventDefault() @unsaved_modal.data('builder').current_squad.dirty = false @unsaved_modal.data('callback')() @unsaved_modal.modal 'hide' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@unsaved_modal) setupHandlers: () -> $(window).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => @updateAuthenticationVisibility() if authenticated @loadCollection() @login_logout_button.click (e) => e.preventDefault() if @authenticated @logout() else @login() $(window).on 'message', (e) => ev = e.originalEvent if ev.origin == @server switch ev.data?.command when 'auth_successful' @authenticate() @login_modal.modal 'hide' @login_modal.find('.login-in-progress').hide() @login_modal.find('ul.login-providers').show() ev.source.close() else console.log "Unexpected command #{ev.data?.command}" else console.log "Message received from unapproved origin #{ev.origin}" window.last_ev = e .on 'xwing-collection:changed', (e, collection) => clearTimeout(@collection_save_timer) if @collection_save_timer? @collection_save_timer = setTimeout => @saveCollection collection, (res) -> if res $(window).trigger 'xwing-collection:saved', collection , 1000 getSettings: (cb=$.noop) -> $.get("#{@server}/settings").done (data, textStatus, jqXHR) => cb data.settings set: (setting, value, cb=$.noop) -> post_args = "_method": "PUT" post_args[setting] = value $.post("#{@server}/settings", post_args).done (data, textStatus, jqXHR) => cb data.set deleteSetting: (setting, cb=$.noop) -> $.post("#{@server}/settings/#{setting}", {"_method": "DELETE"}).done (data, textStatus, jqXHR) => cb data.deleted getHeaders: (cb=$.noop) -> $.get("#{@server}/headers").done (data, textStatus, jqXHR) => cb data.headers getLanguagePreference: (settings, cb=$.noop) => # check if user provided a language preference. If yes, this will override the browser preference queried in translate.coffee if settings?.language? # we found a language, provide it with priority 10 cb settings.language, 10 # otherwise we may parse a language out of the headers else await @getHeaders defer(headers) if headers?.HTTP_ACCEPT_LANGUAGE? # Need to parse out language preferences console.log "#{headers.HTTP_ACCEPT_LANGUAGE}" for language_range in headers.HTTP_ACCEPT_LANGUAGE.split(',') [ language_tag, quality ] = language_range.split ';' console.log "#{language_tag}, #{quality}" if language_tag == '*' # let's give that half priority cb 'English', -0.5 else language_code = language_tag.split('-')[0] # check if the language code is available if langc of exportObj.codeToLanguage # yep - use as language with reasonable priority cb(exportObj.codeToLanguage[language_code], 8) else # bullshit priority - we can't support what the user wants # (maybe he gave another option though in his browser settings) cb 'English', -1 break else # no headers, callback with bullshit priority cb 'English', -1 getCollectionCheck: (settings, cb=$.noop) => if settings?.collectioncheck? cb settings.collectioncheck else @collectioncheck = true cb true saveCollection: (collection, cb=$.noop) -> post_args = expansions: collection.expansions singletons: collection.singletons checks: collection.checks $.post("#{@server}/collection", post_args).done (data, textStatus, jqXHR) -> cb data.success loadCollection: -> # Backend provides an empty collection if none exists yet for the user. $.get("#{@server}/collection").done (data, textStatus, jqXHR) -> collection = data.collection new exportObj.Collection expansions: collection.expansions singletons: collection.singletons checks: collection.checks
122005
### X-Wing Squad Builder 2.0 <NAME> <<EMAIL>> https://raithos.github.io ### exportObj = exports ? this class exportObj.SquadBuilderBackend ### Usage: rebel_builder = new SquadBuilder faction: 'Rebel Alliance' ... empire_builder = new SquadBuilder faction: 'Galactic Empire' ... backend = new SquadBuilderBackend server: 'https://xwing.example.com' builders: [ rebel_builder, empire_builder ] login_logout_button: '#login-logout' auth_status: '#auth-status' ### constructor: (args) -> # Might as well do this right away $.ajaxSetup dataType: "json" # Because Firefox sucks for some reason xhrFields: withCredentials: true # args @server = args.server @builders = args.builders @login_logout_button = $ args.login_logout_button @auth_status = $ args.auth_status @authenticated = false @ui_ready = false @oauth_window = null @method_metadata = google_oauth2: icon: 'fab fa-google' text: 'Google' facebook: icon: 'fab fa-facebook' text: 'Facebook' twitter: icon: 'fab fa-twitter' text: 'Twitter' discord: icon: 'fab fa-discord' text: 'Discord' @squad_display_mode = 'all' @show_archived = false @collection_save_timer = null @setupHandlers() @setupUI() # Check initial authentication status @authenticate () => @auth_status.hide() @login_logout_button.removeClass 'd-none' # Finally, hook up the builders for builder in @builders builder.setBackend this @updateAuthenticationVisibility() updateAuthenticationVisibility: () -> if @authenticated $('.show-authenticated').show() $('.hide-authenticated').hide() else $('.show-authenticated').hide() $('.hide-authenticated').show() save: (serialized, id=null, name, faction, additional_data={}, cb) -> if serialized == "" cb id: null success: false error: "You cannot save an empty squad" else if $.trim(name) == "" cb id: null success: false error: "Squad name cannot be empty" else if not faction? or faction == "" throw "Faction unspecified to save()" else post_args = name: $.trim(name) faction: $.trim(faction) serialized: serialized additional_data: additional_data if id? post_url = "#{@server}/squads/#{id}" else post_url = "#{@server}/squads/new" post_args['_method'] = 'put' $.post post_url, post_args, (data, textStatus, jqXHR) => cb id: data.id success: data.success error: data.error delete: (id, cb) -> post_args = '_method': 'delete' $.post "#{@server}/squads/#{id}", post_args, (data, textStatus, jqXHR) => cb success: data.success error: data.error archive: (data, faction, cb) -> data.additional_data["archived"] = true @save(data.serialized, data.id, data.name, faction, data.additional_data, cb) list: (builder) -> # TODO: Pagination @squad_list_modal.find('.modal-header .squad-list-header-placeholder').text(exportObj.translate('ui', "yourXYsquads", builder.faction)) list_ul = $ @squad_list_modal.find('ul.squad-list') list_ul.text '' list_ul.hide() loading_pane = $ @squad_list_modal.find('p.squad-list-loading') loading_pane.show() @show_all_squads_button.click() @squad_list_modal.modal 'show' # This counter keeps tracked of the number of squads marked to be deleted (to hide the delete-selected button if none is selected) @number_of_selected_squads_to_be_deleted = 0 #setup tag list tag_list = [] url = "#{@server}/squads/list" $.get url, (data, textStatus, jqXHR) => hasNotArchivedSquads = false for squad in data[builder.faction] li = $ document.createElement('LI') li.addClass 'squad-summary' li.data 'squad', squad li.data 'builder', builder li.data 'selectedForDeletion', false list_ul.append li if squad.additional_data?.tag? and (squad.additional_data?.tag != "") and (tag_list.indexOf(squad.additional_data.tag) == -1) tag_array = squad.additional_data?.tag.split(",") for tag_entry in tag_array tag_list.push tag_entry if squad.additional_data?.archived? li.hide() else hasNotArchivedSquads = true li.append $.trim """ <div class="row"> <div class="col-md-9"> <h4>#{squad.name}</h4> </div> <div class="col-md-3"> <h5>#{squad.additional_data?.points} #{exportObj.translate('ui', "Points")}</h5> </div> </div> <div class="row squad-description"> <div class="col-md-9"> #{squad.additional_data?.description} </div> <div class="squad-buttons col-md-3"> <button class="btn btn-modal convert-squad"><i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i></button> &nbsp; <button class="btn btn-modal load-squad"><i class="fa fa-download"></i></button> &nbsp; <button class="btn btn-danger delete-squad"><i class="fa fa-times"></i></button> </div> </div> <div class="row squad-convert-confirm"> <div class="col-md-9 translated" defaultText="Convert to Extended?"> </div> <div class="squad-buttons col-md-3"> <button class="btn btn-danger confirm-convert-squad translated" defaultText="Convert"></button> &nbsp; <button class="btn btn-modal cancel-convert-squad translated" defaultText="Cancel"></button> </div> </div> <div class="row squad-delete-confirm"> <div class="col-md-9"> #{exportObj.translate('ui', 'reallyDeleteSquadXY', "<em>#{squad.name}</em>")} </div> <div class="col-md-3"> <button class="btn btn-danger confirm-delete-squad translated" defaultText="Delete"></button> &nbsp; <button class="btn btn-modal cancel-delete-squad translated" defaultText="Cancel"></button> </div> </div> """ li.find('.squad-convert-confirm').hide() li.find('.squad-delete-confirm').hide() if squad.serialized.search(/v\d+Zh/) == -1 li.find('button.convert-squad').hide() li.find('button.convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-convert-confirm').fadeIn 'fast' li.find('button.cancel-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', false do (li) => li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.confirm-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-convert-squad').fadeOut 'fast' li.find('.confirm-convert-squad').addClass 'disabled' li.find('.confirm-convert-squad').text 'Converting...' new_serialized = li.data('squad').serialized.replace('Zh','Zs') @save new_serialized, li.data('squad').id, li.data('squad').name, li.data('builder').faction, li.data('squad').additional_data, (results) => if results.success li.data('squad').serialized = new_serialized li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.convert-squad').fadeOut 'fast' else li.html $.trim """ Error converting #{li.data('squad').name}: <em>#{results.error}</em> """ li.find('button.load-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, () -> builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') else builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') li.find('button.delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' # show delete multiple section if not yet shown if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').show() # increment counter @number_of_selected_squads_to_be_deleted += 1 li.find('button.cancel-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', false # decrement counter @number_of_selected_squads_to_be_deleted -= 1 do (li) => li.find('.squad-delete-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() li.find('button.confirm-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text 'Deleting...' @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ if not hasNotArchivedSquads list_ul.append $.trim """ <li class="translated" defaultText="No saved squads"></li> """ #setup Tags @squad_list_tags.empty() for tag in tag_list tagclean = tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') @squad_list_tags.append $.trim """ <button class="btn #{tagclean}">#{tag}</button> """ tag_button = $ @squad_list_tags.find(".#{tagclean}") tag_button.click (e) => button = $ e.target buttontag = button.attr('class').replace('btn ','').replace('btn-inverse ','') @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> if $(elem).data().squad.additional_data.tag? tag_array = $(elem).data().squad.additional_data.tag.split(",") found_tag = false for tag in tag_array if buttontag == tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') then found_tag = true if found_tag then $(elem).show() else $(elem).hide() else $(elem).hide() # some of the created html needs translation (e.g. buttons). Do that now. exportObj.translateUIElements(list_ul) loading_pane.fadeOut 'fast' list_ul.fadeIn 'fast' authenticate: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Checking auth status...') @auth_status.show() old_auth_state = @authenticated $.ajax url: "#{@server}/ping" success: (data) => if data?.success @authenticated = true else @authenticated = false @maybeAuthenticationChanged old_auth_state, cb error: (jqXHR, textStatus, errorThrown) => @authenticated = false @maybeAuthenticationChanged old_auth_state, cb maybeAuthenticationChanged: (old_auth_state, cb) => if old_auth_state != @authenticated $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @oauth_window = null @auth_status.hide() cb @authenticated @authenticated login: () -> # Display login dialog. if @ui_ready @login_modal.modal 'show' logout: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Logging out...') @auth_status.show() $.get "#{@server}/auth/logout", (data, textStatus, jqXHR) => @authenticated = false $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @auth_status.hide() cb() showSaveAsModal: (builder) -> @save_as_modal.data 'builder', builder @save_as_input.val builder.current_squad.name @save_as_save_button.addClass 'disabled' @nameCheck() @save_as_modal.modal 'show' showDeleteModal: (builder) -> @delete_modal.data 'builder', builder @delete_name_container.text builder.current_squad.name @delete_modal.modal 'show' nameCheck: () => window.clearInterval @save_as_modal.data('timer') # trivial check name = $.trim(@save_as_input.val()) if name.length == 0 @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "name required")} """ else $.post "#{@server}/squads/namecheck", { name: name }, (data) => @name_availability_container.text '' if data.available @name_availability_container.append $.trim """ <i class="fa fa-thumbs-up"></i> #{exportObj.translate('ui', "Name is available")} """ @save_as_save_button.removeClass 'disabled' else @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "Name in use")} """ @save_as_save_button.addClass 'disabled' warnUnsaved: (builder, action) -> @unsaved_modal.data 'builder', builder @unsaved_modal.data 'callback', action @unsaved_modal.modal 'show' setupUI: () -> @auth_status.addClass 'disabled' @auth_status.click (e) => false @login_modal = $ document.createElement('DIV') @login_modal.addClass 'modal fade d-print-none' @login_modal.tabindex = "-1" @login_modal.role = "dialog" $(document.body).append @login_modal @login_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Log in with OAuth"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p> <span class="translated" defaultText="select OAuth provider"></span> <a class="login-help translated" href="#" defaultText="What's this?"></a> </p> <div class="well well-small oauth-explanation"> <span class="translated" defaultText="OAuth explanation"></span> <button class="btn btn-modal translated" defaultText="Got it!"></button> </div> <ul class="login-providers inline"></ul> <p class="translated" defaultText="Continue to OAuth provider"></p> <p class="translated" defaultText="iOS requires cross-site control"></p> <p class="login-in-progress"> <em class="translated" defaultText="login in progress"></em> </p> </div> </div> </div> """ oauth_explanation = $ @login_modal.find('.oauth-explanation') oauth_explanation.hide() @login_modal.find('.login-in-progress').hide() @login_modal.find('a.login-help').click (e) => e.preventDefault() unless oauth_explanation.is ':visible' oauth_explanation.slideDown 'fast' oauth_explanation.find('button').click (e) => e.preventDefault() oauth_explanation.slideUp 'fast' $.get "#{@server}/methods", (data, textStatus, jqXHR) => methods_ul = $ @login_modal.find('ul.login-providers') for method in data.methods a = $ document.createElement('A') a.addClass 'btn btn-modal' a.data 'url', "#{@server}/auth/#{method}" a.append """<i class="#{@method_metadata[method].icon}"></i>&nbsp;#{@method_metadata[method].text}""" a.click (e) => e.preventDefault() methods_ul.slideUp 'fast' @login_modal.find('.login-in-progress').slideDown 'fast' @oauth_window = window.open $(e.target).data('url'), "xwing_login" li = $ document.createElement('LI') li.append a methods_ul.append li @ui_ready = true # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@login_modal) @reload_done_modal = $ document.createElement('DIV') @reload_done_modal.addClass 'modal fade d-print-none' @reload_done_modal.tabindex = "-1" @reload_done_modal.role = "dialog" $(document.body).append @reload_done_modal @reload_done_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Reload Done</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Squads reloaded"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Well done!"></button> </div> </div> </div> """ # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@reload_done_modal) @squad_list_modal = $ document.createElement('DIV') @squad_list_modal.addClass 'modal fade d-print-none squad-list' @squad_list_modal.tabindex = "-1" @squad_list_modal.role = "dialog" $(document.body).append @squad_list_modal @squad_list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="squad-list-header-placeholder d-none d-lg-block"></h3> <h4 class="squad-list-header-placeholder d-lg-none"></h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <ul class="squad-list"></ul> <p class="pagination-centered squad-list-loading"> <i class="fa fa-spinner fa-spin fa-3x"></i> <br /> <span class="translated" defaultText="Fetching squads..."></span> </p> </div> <div class="modal-footer"> <div class="btn-group delete-multiple-squads full-row"> <button class="btn btn-modal select-all translated" defaultText="Select All"></button> <button class="btn btn-modal archive-selected translated" defaultText="Archive Selected"></button> <button class="btn btn-modal btn-danger delete-selected translated" defaultText="Delete Selected"></button> </div> <div class="btn-group squad-display-mode full-row"> <button class="btn btn-modal btn-inverse show-all-squads translated" defaultText="All"></button> <button class="btn btn-modal show-standard-squads"><span class="d-none d-lg-block translated" defaultText="Standard"></span><span class="d-lg-none translated" defaultText="Hyper"></span></button> <button class="btn btn-modal show-extended-squads"><span class="d-none d-lg-block translated" defaultText="Extended"></span><span class="d-lg-none translated" defaultText="Ext"></span></button> <button class="btn btn-modal show-quickbuild-squads"><span class="d-none d-lg-block translated" defaultText="Quickbuild"></span><span class="d-lg-none translated" defaultText="QB"></span></button> <button class="btn btn-modal show-epic-squads translated" defaultText="Epic"></button> <button class="btn btn-modal show-archived-squads translated" defaultText="Archived"></button> <button class="btn btn-modal reload-all translated" defaultText="Recalculate Points"></button> </div> <div class="btn-group tags-display full-row"> </div> </div> </div> </div> """ @squad_list_modal.find('ul.squad-list').hide() @squad_list_tags = $ @squad_list_modal.find('div.tags-display') # The delete multiple section only appeares, when somebody hits the delete button of one squad. @squad_list_modal.find('div.delete-multiple-squads').hide() # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_selected_button = $ @squad_list_modal.find('button.delete-selected') @delete_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Deleting...') @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ @archive_selected_button = $ @squad_list_modal.find('button.archive-selected') @archive_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Archiving...') @archive li.data('squad'), li.data('builder').faction, (results) => if results.success li.slideUp 'fast', -> $(li).hide() $(li).find('.confirm-delete-squad').removeClass 'disabled' $(li).find('.confirm-delete-squad').text exportObj.translate('ui', 'Delete') $(li).data 'selectedForDeletion', false $(li).find('.squad-delete-confirm').fadeOut 'fast', -> $(li).find('.squad-description').fadeIn 'fast' # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error archiving #{li.data('squad').name}: <em>#{results.error}</em> """ @squad_list_modal.find('button.reload-all').click (e) => ul = @squad_list_modal.find('ul.squad-list') squadProcessingStack = [ () => @reload_done_modal.modal 'show' ] squadDataStack = [] for li in ul.find('li') li = $ li squadDataStack.push li.data('squad') builder = li.data('builder') squadProcessingStack.push () => sqd = squadDataStack.pop() # console.log("loading " + sqd.name) builder.container.trigger 'xwing-backend:squadLoadRequested', [ sqd, () => additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.notes.val().substr(0, 1024) obstacles: builder.getObstacles() tag: builder.tag.val().substr(0, 1024) # console.log("saving " + builder.current_squad.name) @save builder.serialize(), builder.current_squad.id, builder.current_squad.name, builder.faction, additional_data, squadProcessingStack.pop() ] @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, squadProcessingStack.pop() else squadProcessingStack.pop()() @select_all_button = $ @squad_list_modal.find('button.select-all') @select_all_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if not li.data 'selectedForDeletion' li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' @number_of_selected_squads_to_be_deleted += 1 @show_all_squads_button = $ @squad_list_modal.find('.show-all-squads') @show_all_squads_button.click (e) => unless @squad_display_mode == 'all' @squad_display_mode = 'all' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_all_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').show() @show_extended_squads_button = $ @squad_list_modal.find('.show-extended-squads') @show_extended_squads_button.click (e) => unless @squad_display_mode == 'extended' @squad_display_mode = 'extended' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_extended_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zs/) != -1 @show_epic_squads_button = $ @squad_list_modal.find('.show-epic-squads') @show_epic_squads_button.click (e) => unless @squad_display_mode == 'epic' @squad_display_mode = 'epic' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_epic_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Ze/) != -1 @show_standard_squads_button = $ @squad_list_modal.find('.show-standard-squads') @show_standard_squads_button.click (e) => unless @squad_display_mode == 'standard' @squad_display_mode = 'standard' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_standard_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zh/) != -1 @show_quickbuild_squads_button = $ @squad_list_modal.find('.show-quickbuild-squads') @show_quickbuild_squads_button.click (e) => unless @squad_display_mode == 'quickbuild' @squad_display_mode = 'quickbuild' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_quickbuild_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zq/) != -1 @show_archived_squads_button = $ @squad_list_modal.find('.show-archived-squads') @show_archived_squads_button.click (e) => @show_archived = not @show_archived if @show_archived @show_archived_squads_button.addClass 'btn-inverse' else @show_archived_squads_button.removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) => $(elem).toggle (($(elem).data().squad.additional_data.archived?) == @show_archived) @save_as_modal = $ document.createElement('DIV') @save_as_modal.addClass 'modal fade d-print-none' @save_as_modal.tabindex = "-1" @save_as_modal.role = "dialog" $(document.body).append @save_as_modal @save_as_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Save Squad As..."></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label for="xw-be-squad-save-as"> <span class="translated" defaultText="New Squad Name"></span> <input id="xw-be-squad-save-as"></input> </label> <span class="name-availability"></span> </div> <div class="modal-footer"> <button class="btn btn-primary save translated" aria-hidden="true" defaultText="Save"></button> </div> </div> </div> """ @save_as_modal.on 'shown', () => # Because Firefox handles this badly window.setTimeout () => @save_as_input.focus() @save_as_input.select() , 100 @save_as_save_button = @save_as_modal.find('button.save') @save_as_save_button.click (e) => e.preventDefault() unless @save_as_save_button.hasClass('disabled') timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.modal 'hide' builder = @save_as_modal.data 'builder' additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.getNotes() obstacles: builder.getObstacles() tag: builder.getTag() builder.backend_save_list_as_button.addClass 'disabled' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', 'Saving squad...')} """ builder.backend_status.show() new_name = $.trim @save_as_input.val() @save builder.serialize(), null, new_name, builder.faction, additional_data, (results) => if results.success builder.current_squad.id = results.id builder.current_squad.name = <NAME> builder.current_squad.dirty = false builder.container.trigger 'xwing-backend:squadNameChanged' builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', 'New squad saved successfully.')} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ builder.backend_save_list_as_button.removeClass 'disabled' @save_as_input = $ @save_as_modal.find('input') @save_as_input.keypress (e) => if e.which == 13 @save_as_save_button.click() false else @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-spin fa-spinner"></i> #{exportObj.translate('ui', 'Checking name availability...')} """ timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.data 'timer', window.setInterval(@nameCheck, 500) @name_availability_container = $ @save_as_modal.find('.name-availability') # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_modal = $ document.createElement('DIV') @delete_modal.addClass 'modal fade d-print-none' @delete_modal.tabindex = "-1" @delete_modal.role = "dialog" $(document.body).append @delete_modal @delete_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3><span class="translated" defaultText="Really Delete"></span> <span class="squad-name-placeholder"></span>?</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Sure to delete?"></p> </div> <div class="modal-footer"> <button class="btn btn-danger delete" aria-hidden="true"><span class="translated" defaultText="Yes, Delete"></span> <i class="squad-name-placeholder"></i></button> <button class="btn btn-modal translated" data-dismiss="modal" aria-hidden="true" defaultText="Never Mind"></button> </div> </div> </div> """ @delete_name_container = $ @delete_modal.find('.squad-name-placeholder') @delete_button = $ @delete_modal.find('button.delete') @delete_button.click (e) => e.preventDefault() builder = @delete_modal.data 'builder' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', "Deleting squad...")} """ builder.backend_status.show() builder.backend_delete_list_button.addClass 'disabled' @delete_modal.modal 'hide' @delete builder.current_squad.id, (results) => if results.success builder.resetCurrentSquad() builder.current_squad.dirty = true builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', "Squad deleted.")} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ # Failed, so offer chance to delete again builder.backend_delete_list_button.removeClass 'disabled' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@delete_modal) @unsaved_modal = $ document.createElement('DIV') @unsaved_modal.addClass 'modal fade d-print-none' @unsaved_modal.tabindex = "-1" @unsaved_modal.role = "dialog" $(document.body).append @unsaved_modal @unsaved_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Unsaved Changes"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Unsaved Changes Warning"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Go Back"></button> <button class="btn btn-danger discard translated" aria-hidden="true" defaultText="Discard Changes"></button> </div> </div> </div> """ @unsaved_discard_button = $ @unsaved_modal.find('button.discard') @unsaved_discard_button.click (e) => e.preventDefault() @unsaved_modal.data('builder').current_squad.dirty = false @unsaved_modal.data('callback')() @unsaved_modal.modal 'hide' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@unsaved_modal) setupHandlers: () -> $(window).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => @updateAuthenticationVisibility() if authenticated @loadCollection() @login_logout_button.click (e) => e.preventDefault() if @authenticated @logout() else @login() $(window).on 'message', (e) => ev = e.originalEvent if ev.origin == @server switch ev.data?.command when 'auth_successful' @authenticate() @login_modal.modal 'hide' @login_modal.find('.login-in-progress').hide() @login_modal.find('ul.login-providers').show() ev.source.close() else console.log "Unexpected command #{ev.data?.command}" else console.log "Message received from unapproved origin #{ev.origin}" window.last_ev = e .on 'xwing-collection:changed', (e, collection) => clearTimeout(@collection_save_timer) if @collection_save_timer? @collection_save_timer = setTimeout => @saveCollection collection, (res) -> if res $(window).trigger 'xwing-collection:saved', collection , 1000 getSettings: (cb=$.noop) -> $.get("#{@server}/settings").done (data, textStatus, jqXHR) => cb data.settings set: (setting, value, cb=$.noop) -> post_args = "_method": "PUT" post_args[setting] = value $.post("#{@server}/settings", post_args).done (data, textStatus, jqXHR) => cb data.set deleteSetting: (setting, cb=$.noop) -> $.post("#{@server}/settings/#{setting}", {"_method": "DELETE"}).done (data, textStatus, jqXHR) => cb data.deleted getHeaders: (cb=$.noop) -> $.get("#{@server}/headers").done (data, textStatus, jqXHR) => cb data.headers getLanguagePreference: (settings, cb=$.noop) => # check if user provided a language preference. If yes, this will override the browser preference queried in translate.coffee if settings?.language? # we found a language, provide it with priority 10 cb settings.language, 10 # otherwise we may parse a language out of the headers else await @getHeaders defer(headers) if headers?.HTTP_ACCEPT_LANGUAGE? # Need to parse out language preferences console.log "#{headers.HTTP_ACCEPT_LANGUAGE}" for language_range in headers.HTTP_ACCEPT_LANGUAGE.split(',') [ language_tag, quality ] = language_range.split ';' console.log "#{language_tag}, #{quality}" if language_tag == '*' # let's give that half priority cb 'English', -0.5 else language_code = language_tag.split('-')[0] # check if the language code is available if langc of exportObj.codeToLanguage # yep - use as language with reasonable priority cb(exportObj.codeToLanguage[language_code], 8) else # bullshit priority - we can't support what the user wants # (maybe he gave another option though in his browser settings) cb 'English', -1 break else # no headers, callback with bullshit priority cb 'English', -1 getCollectionCheck: (settings, cb=$.noop) => if settings?.collectioncheck? cb settings.collectioncheck else @collectioncheck = true cb true saveCollection: (collection, cb=$.noop) -> post_args = expansions: collection.expansions singletons: collection.singletons checks: collection.checks $.post("#{@server}/collection", post_args).done (data, textStatus, jqXHR) -> cb data.success loadCollection: -> # Backend provides an empty collection if none exists yet for the user. $.get("#{@server}/collection").done (data, textStatus, jqXHR) -> collection = data.collection new exportObj.Collection expansions: collection.expansions singletons: collection.singletons checks: collection.checks
true
### X-Wing Squad Builder 2.0 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> https://raithos.github.io ### exportObj = exports ? this class exportObj.SquadBuilderBackend ### Usage: rebel_builder = new SquadBuilder faction: 'Rebel Alliance' ... empire_builder = new SquadBuilder faction: 'Galactic Empire' ... backend = new SquadBuilderBackend server: 'https://xwing.example.com' builders: [ rebel_builder, empire_builder ] login_logout_button: '#login-logout' auth_status: '#auth-status' ### constructor: (args) -> # Might as well do this right away $.ajaxSetup dataType: "json" # Because Firefox sucks for some reason xhrFields: withCredentials: true # args @server = args.server @builders = args.builders @login_logout_button = $ args.login_logout_button @auth_status = $ args.auth_status @authenticated = false @ui_ready = false @oauth_window = null @method_metadata = google_oauth2: icon: 'fab fa-google' text: 'Google' facebook: icon: 'fab fa-facebook' text: 'Facebook' twitter: icon: 'fab fa-twitter' text: 'Twitter' discord: icon: 'fab fa-discord' text: 'Discord' @squad_display_mode = 'all' @show_archived = false @collection_save_timer = null @setupHandlers() @setupUI() # Check initial authentication status @authenticate () => @auth_status.hide() @login_logout_button.removeClass 'd-none' # Finally, hook up the builders for builder in @builders builder.setBackend this @updateAuthenticationVisibility() updateAuthenticationVisibility: () -> if @authenticated $('.show-authenticated').show() $('.hide-authenticated').hide() else $('.show-authenticated').hide() $('.hide-authenticated').show() save: (serialized, id=null, name, faction, additional_data={}, cb) -> if serialized == "" cb id: null success: false error: "You cannot save an empty squad" else if $.trim(name) == "" cb id: null success: false error: "Squad name cannot be empty" else if not faction? or faction == "" throw "Faction unspecified to save()" else post_args = name: $.trim(name) faction: $.trim(faction) serialized: serialized additional_data: additional_data if id? post_url = "#{@server}/squads/#{id}" else post_url = "#{@server}/squads/new" post_args['_method'] = 'put' $.post post_url, post_args, (data, textStatus, jqXHR) => cb id: data.id success: data.success error: data.error delete: (id, cb) -> post_args = '_method': 'delete' $.post "#{@server}/squads/#{id}", post_args, (data, textStatus, jqXHR) => cb success: data.success error: data.error archive: (data, faction, cb) -> data.additional_data["archived"] = true @save(data.serialized, data.id, data.name, faction, data.additional_data, cb) list: (builder) -> # TODO: Pagination @squad_list_modal.find('.modal-header .squad-list-header-placeholder').text(exportObj.translate('ui', "yourXYsquads", builder.faction)) list_ul = $ @squad_list_modal.find('ul.squad-list') list_ul.text '' list_ul.hide() loading_pane = $ @squad_list_modal.find('p.squad-list-loading') loading_pane.show() @show_all_squads_button.click() @squad_list_modal.modal 'show' # This counter keeps tracked of the number of squads marked to be deleted (to hide the delete-selected button if none is selected) @number_of_selected_squads_to_be_deleted = 0 #setup tag list tag_list = [] url = "#{@server}/squads/list" $.get url, (data, textStatus, jqXHR) => hasNotArchivedSquads = false for squad in data[builder.faction] li = $ document.createElement('LI') li.addClass 'squad-summary' li.data 'squad', squad li.data 'builder', builder li.data 'selectedForDeletion', false list_ul.append li if squad.additional_data?.tag? and (squad.additional_data?.tag != "") and (tag_list.indexOf(squad.additional_data.tag) == -1) tag_array = squad.additional_data?.tag.split(",") for tag_entry in tag_array tag_list.push tag_entry if squad.additional_data?.archived? li.hide() else hasNotArchivedSquads = true li.append $.trim """ <div class="row"> <div class="col-md-9"> <h4>#{squad.name}</h4> </div> <div class="col-md-3"> <h5>#{squad.additional_data?.points} #{exportObj.translate('ui', "Points")}</h5> </div> </div> <div class="row squad-description"> <div class="col-md-9"> #{squad.additional_data?.description} </div> <div class="squad-buttons col-md-3"> <button class="btn btn-modal convert-squad"><i class="xwing-miniatures-font xwing-miniatures-font-first-player-1"></i></button> &nbsp; <button class="btn btn-modal load-squad"><i class="fa fa-download"></i></button> &nbsp; <button class="btn btn-danger delete-squad"><i class="fa fa-times"></i></button> </div> </div> <div class="row squad-convert-confirm"> <div class="col-md-9 translated" defaultText="Convert to Extended?"> </div> <div class="squad-buttons col-md-3"> <button class="btn btn-danger confirm-convert-squad translated" defaultText="Convert"></button> &nbsp; <button class="btn btn-modal cancel-convert-squad translated" defaultText="Cancel"></button> </div> </div> <div class="row squad-delete-confirm"> <div class="col-md-9"> #{exportObj.translate('ui', 'reallyDeleteSquadXY', "<em>#{squad.name}</em>")} </div> <div class="col-md-3"> <button class="btn btn-danger confirm-delete-squad translated" defaultText="Delete"></button> &nbsp; <button class="btn btn-modal cancel-delete-squad translated" defaultText="Cancel"></button> </div> </div> """ li.find('.squad-convert-confirm').hide() li.find('.squad-delete-confirm').hide() if squad.serialized.search(/v\d+Zh/) == -1 li.find('button.convert-squad').hide() li.find('button.convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-convert-confirm').fadeIn 'fast' li.find('button.cancel-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedToConvert', false do (li) => li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.confirm-convert-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-convert-squad').fadeOut 'fast' li.find('.confirm-convert-squad').addClass 'disabled' li.find('.confirm-convert-squad').text 'Converting...' new_serialized = li.data('squad').serialized.replace('Zh','Zs') @save new_serialized, li.data('squad').id, li.data('squad').name, li.data('builder').faction, li.data('squad').additional_data, (results) => if results.success li.data('squad').serialized = new_serialized li.find('.squad-convert-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' li.find('button.convert-squad').fadeOut 'fast' else li.html $.trim """ Error converting #{li.data('squad').name}: <em>#{results.error}</em> """ li.find('button.load-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, () -> builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') else builder.container.trigger 'xwing-backend:squadLoadRequested', li.data('squad') li.find('button.delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' # show delete multiple section if not yet shown if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').show() # increment counter @number_of_selected_squads_to_be_deleted += 1 li.find('button.cancel-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.data 'selectedForDeletion', false # decrement counter @number_of_selected_squads_to_be_deleted -= 1 do (li) => li.find('.squad-delete-confirm').fadeOut 'fast', -> li.find('.squad-description').fadeIn 'fast' # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() li.find('button.confirm-delete-squad').click (e) => e.preventDefault() button = $ e.target li = button.closest 'li' builder = li.data('builder') li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text 'Deleting...' @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ if not hasNotArchivedSquads list_ul.append $.trim """ <li class="translated" defaultText="No saved squads"></li> """ #setup Tags @squad_list_tags.empty() for tag in tag_list tagclean = tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') @squad_list_tags.append $.trim """ <button class="btn #{tagclean}">#{tag}</button> """ tag_button = $ @squad_list_tags.find(".#{tagclean}") tag_button.click (e) => button = $ e.target buttontag = button.attr('class').replace('btn ','').replace('btn-inverse ','') @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> if $(elem).data().squad.additional_data.tag? tag_array = $(elem).data().squad.additional_data.tag.split(",") found_tag = false for tag in tag_array if buttontag == tag.toLowerCase().replace(/[^a-z0-9]/g, '').replace(/\s+/g, '-') then found_tag = true if found_tag then $(elem).show() else $(elem).hide() else $(elem).hide() # some of the created html needs translation (e.g. buttons). Do that now. exportObj.translateUIElements(list_ul) loading_pane.fadeOut 'fast' list_ul.fadeIn 'fast' authenticate: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Checking auth status...') @auth_status.show() old_auth_state = @authenticated $.ajax url: "#{@server}/ping" success: (data) => if data?.success @authenticated = true else @authenticated = false @maybeAuthenticationChanged old_auth_state, cb error: (jqXHR, textStatus, errorThrown) => @authenticated = false @maybeAuthenticationChanged old_auth_state, cb maybeAuthenticationChanged: (old_auth_state, cb) => if old_auth_state != @authenticated $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @oauth_window = null @auth_status.hide() cb @authenticated @authenticated login: () -> # Display login dialog. if @ui_ready @login_modal.modal 'show' logout: (cb=$.noop) -> $(@auth_status.find('.payload')).text exportObj.translate('ui', 'Logging out...') @auth_status.show() $.get "#{@server}/auth/logout", (data, textStatus, jqXHR) => @authenticated = false $(window).trigger 'xwing-backend:authenticationChanged', [ @authenticated, this ] @auth_status.hide() cb() showSaveAsModal: (builder) -> @save_as_modal.data 'builder', builder @save_as_input.val builder.current_squad.name @save_as_save_button.addClass 'disabled' @nameCheck() @save_as_modal.modal 'show' showDeleteModal: (builder) -> @delete_modal.data 'builder', builder @delete_name_container.text builder.current_squad.name @delete_modal.modal 'show' nameCheck: () => window.clearInterval @save_as_modal.data('timer') # trivial check name = $.trim(@save_as_input.val()) if name.length == 0 @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "name required")} """ else $.post "#{@server}/squads/namecheck", { name: name }, (data) => @name_availability_container.text '' if data.available @name_availability_container.append $.trim """ <i class="fa fa-thumbs-up"></i> #{exportObj.translate('ui', "Name is available")} """ @save_as_save_button.removeClass 'disabled' else @name_availability_container.append $.trim """ <i class="fa fa-thumbs-down"></i> #{exportObj.translate('ui', "Name in use")} """ @save_as_save_button.addClass 'disabled' warnUnsaved: (builder, action) -> @unsaved_modal.data 'builder', builder @unsaved_modal.data 'callback', action @unsaved_modal.modal 'show' setupUI: () -> @auth_status.addClass 'disabled' @auth_status.click (e) => false @login_modal = $ document.createElement('DIV') @login_modal.addClass 'modal fade d-print-none' @login_modal.tabindex = "-1" @login_modal.role = "dialog" $(document.body).append @login_modal @login_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Log in with OAuth"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p> <span class="translated" defaultText="select OAuth provider"></span> <a class="login-help translated" href="#" defaultText="What's this?"></a> </p> <div class="well well-small oauth-explanation"> <span class="translated" defaultText="OAuth explanation"></span> <button class="btn btn-modal translated" defaultText="Got it!"></button> </div> <ul class="login-providers inline"></ul> <p class="translated" defaultText="Continue to OAuth provider"></p> <p class="translated" defaultText="iOS requires cross-site control"></p> <p class="login-in-progress"> <em class="translated" defaultText="login in progress"></em> </p> </div> </div> </div> """ oauth_explanation = $ @login_modal.find('.oauth-explanation') oauth_explanation.hide() @login_modal.find('.login-in-progress').hide() @login_modal.find('a.login-help').click (e) => e.preventDefault() unless oauth_explanation.is ':visible' oauth_explanation.slideDown 'fast' oauth_explanation.find('button').click (e) => e.preventDefault() oauth_explanation.slideUp 'fast' $.get "#{@server}/methods", (data, textStatus, jqXHR) => methods_ul = $ @login_modal.find('ul.login-providers') for method in data.methods a = $ document.createElement('A') a.addClass 'btn btn-modal' a.data 'url', "#{@server}/auth/#{method}" a.append """<i class="#{@method_metadata[method].icon}"></i>&nbsp;#{@method_metadata[method].text}""" a.click (e) => e.preventDefault() methods_ul.slideUp 'fast' @login_modal.find('.login-in-progress').slideDown 'fast' @oauth_window = window.open $(e.target).data('url'), "xwing_login" li = $ document.createElement('LI') li.append a methods_ul.append li @ui_ready = true # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@login_modal) @reload_done_modal = $ document.createElement('DIV') @reload_done_modal.addClass 'modal fade d-print-none' @reload_done_modal.tabindex = "-1" @reload_done_modal.role = "dialog" $(document.body).append @reload_done_modal @reload_done_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3>Reload Done</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Squads reloaded"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Well done!"></button> </div> </div> </div> """ # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@reload_done_modal) @squad_list_modal = $ document.createElement('DIV') @squad_list_modal.addClass 'modal fade d-print-none squad-list' @squad_list_modal.tabindex = "-1" @squad_list_modal.role = "dialog" $(document.body).append @squad_list_modal @squad_list_modal.append $.trim """ <div class="modal-dialog modal-lg modal-dialog-scrollable modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="squad-list-header-placeholder d-none d-lg-block"></h3> <h4 class="squad-list-header-placeholder d-lg-none"></h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <ul class="squad-list"></ul> <p class="pagination-centered squad-list-loading"> <i class="fa fa-spinner fa-spin fa-3x"></i> <br /> <span class="translated" defaultText="Fetching squads..."></span> </p> </div> <div class="modal-footer"> <div class="btn-group delete-multiple-squads full-row"> <button class="btn btn-modal select-all translated" defaultText="Select All"></button> <button class="btn btn-modal archive-selected translated" defaultText="Archive Selected"></button> <button class="btn btn-modal btn-danger delete-selected translated" defaultText="Delete Selected"></button> </div> <div class="btn-group squad-display-mode full-row"> <button class="btn btn-modal btn-inverse show-all-squads translated" defaultText="All"></button> <button class="btn btn-modal show-standard-squads"><span class="d-none d-lg-block translated" defaultText="Standard"></span><span class="d-lg-none translated" defaultText="Hyper"></span></button> <button class="btn btn-modal show-extended-squads"><span class="d-none d-lg-block translated" defaultText="Extended"></span><span class="d-lg-none translated" defaultText="Ext"></span></button> <button class="btn btn-modal show-quickbuild-squads"><span class="d-none d-lg-block translated" defaultText="Quickbuild"></span><span class="d-lg-none translated" defaultText="QB"></span></button> <button class="btn btn-modal show-epic-squads translated" defaultText="Epic"></button> <button class="btn btn-modal show-archived-squads translated" defaultText="Archived"></button> <button class="btn btn-modal reload-all translated" defaultText="Recalculate Points"></button> </div> <div class="btn-group tags-display full-row"> </div> </div> </div> </div> """ @squad_list_modal.find('ul.squad-list').hide() @squad_list_tags = $ @squad_list_modal.find('div.tags-display') # The delete multiple section only appeares, when somebody hits the delete button of one squad. @squad_list_modal.find('div.delete-multiple-squads').hide() # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_selected_button = $ @squad_list_modal.find('button.delete-selected') @delete_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.cancel-delete-squad').fadeOut 'fast' li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Deleting...') @delete li.data('squad').id, (results) => if results.success li.slideUp 'fast', -> $(li).remove() # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error deleting #{li.data('squad').name}: <em>#{results.error}</em> """ @archive_selected_button = $ @squad_list_modal.find('button.archive-selected') @archive_selected_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if li.data 'selectedForDeletion' do (li) => li.find('.confirm-delete-squad').addClass 'disabled' li.find('.confirm-delete-squad').text exportObj.translate('ui', 'Archiving...') @archive li.data('squad'), li.data('builder').faction, (results) => if results.success li.slideUp 'fast', -> $(li).hide() $(li).find('.confirm-delete-squad').removeClass 'disabled' $(li).find('.confirm-delete-squad').text exportObj.translate('ui', 'Delete') $(li).data 'selectedForDeletion', false $(li).find('.squad-delete-confirm').fadeOut 'fast', -> $(li).find('.squad-description').fadeIn 'fast' # decrement counter @number_of_selected_squads_to_be_deleted -= 1 # hide delete multiple section if this was the last selected squad if not @number_of_selected_squads_to_be_deleted @squad_list_modal.find('div.delete-multiple-squads').hide() else li.html $.trim """ Error archiving #{li.data('squad').name}: <em>#{results.error}</em> """ @squad_list_modal.find('button.reload-all').click (e) => ul = @squad_list_modal.find('ul.squad-list') squadProcessingStack = [ () => @reload_done_modal.modal 'show' ] squadDataStack = [] for li in ul.find('li') li = $ li squadDataStack.push li.data('squad') builder = li.data('builder') squadProcessingStack.push () => sqd = squadDataStack.pop() # console.log("loading " + sqd.name) builder.container.trigger 'xwing-backend:squadLoadRequested', [ sqd, () => additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.notes.val().substr(0, 1024) obstacles: builder.getObstacles() tag: builder.tag.val().substr(0, 1024) # console.log("saving " + builder.current_squad.name) @save builder.serialize(), builder.current_squad.id, builder.current_squad.name, builder.faction, additional_data, squadProcessingStack.pop() ] @squad_list_modal.modal 'hide' if builder.current_squad.dirty @warnUnsaved builder, squadProcessingStack.pop() else squadProcessingStack.pop()() @select_all_button = $ @squad_list_modal.find('button.select-all') @select_all_button.click (e) => ul = @squad_list_modal.find('ul.squad-list') for li in ul.find('li') li = $ li if not li.data 'selectedForDeletion' li.data 'selectedForDeletion', true do (li) => li.find('.squad-description').fadeOut 'fast', -> li.find('.squad-delete-confirm').fadeIn 'fast' @number_of_selected_squads_to_be_deleted += 1 @show_all_squads_button = $ @squad_list_modal.find('.show-all-squads') @show_all_squads_button.click (e) => unless @squad_display_mode == 'all' @squad_display_mode = 'all' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_all_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').show() @show_extended_squads_button = $ @squad_list_modal.find('.show-extended-squads') @show_extended_squads_button.click (e) => unless @squad_display_mode == 'extended' @squad_display_mode = 'extended' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_extended_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zs/) != -1 @show_epic_squads_button = $ @squad_list_modal.find('.show-epic-squads') @show_epic_squads_button.click (e) => unless @squad_display_mode == 'epic' @squad_display_mode = 'epic' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_epic_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Ze/) != -1 @show_standard_squads_button = $ @squad_list_modal.find('.show-standard-squads') @show_standard_squads_button.click (e) => unless @squad_display_mode == 'standard' @squad_display_mode = 'standard' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_standard_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zh/) != -1 @show_quickbuild_squads_button = $ @squad_list_modal.find('.show-quickbuild-squads') @show_quickbuild_squads_button.click (e) => unless @squad_display_mode == 'quickbuild' @squad_display_mode = 'quickbuild' @squad_list_modal.find('.squad-display-mode .btn').removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @show_quickbuild_squads_button.addClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) -> $(elem).toggle $(elem).data().squad.serialized.search(/v\d+Zq/) != -1 @show_archived_squads_button = $ @squad_list_modal.find('.show-archived-squads') @show_archived_squads_button.click (e) => @show_archived = not @show_archived if @show_archived @show_archived_squads_button.addClass 'btn-inverse' else @show_archived_squads_button.removeClass 'btn-inverse' @squad_list_tags.find('.btn').removeClass 'btn-inverse' @squad_list_modal.find('.squad-list li').each (idx, elem) => $(elem).toggle (($(elem).data().squad.additional_data.archived?) == @show_archived) @save_as_modal = $ document.createElement('DIV') @save_as_modal.addClass 'modal fade d-print-none' @save_as_modal.tabindex = "-1" @save_as_modal.role = "dialog" $(document.body).append @save_as_modal @save_as_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Save Squad As..."></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <label for="xw-be-squad-save-as"> <span class="translated" defaultText="New Squad Name"></span> <input id="xw-be-squad-save-as"></input> </label> <span class="name-availability"></span> </div> <div class="modal-footer"> <button class="btn btn-primary save translated" aria-hidden="true" defaultText="Save"></button> </div> </div> </div> """ @save_as_modal.on 'shown', () => # Because Firefox handles this badly window.setTimeout () => @save_as_input.focus() @save_as_input.select() , 100 @save_as_save_button = @save_as_modal.find('button.save') @save_as_save_button.click (e) => e.preventDefault() unless @save_as_save_button.hasClass('disabled') timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.modal 'hide' builder = @save_as_modal.data 'builder' additional_data = points: builder.total_points description: builder.describeSquad() cards: builder.listCards() notes: builder.getNotes() obstacles: builder.getObstacles() tag: builder.getTag() builder.backend_save_list_as_button.addClass 'disabled' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', 'Saving squad...')} """ builder.backend_status.show() new_name = $.trim @save_as_input.val() @save builder.serialize(), null, new_name, builder.faction, additional_data, (results) => if results.success builder.current_squad.id = results.id builder.current_squad.name = PI:NAME:<NAME>END_PI builder.current_squad.dirty = false builder.container.trigger 'xwing-backend:squadNameChanged' builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', 'New squad saved successfully.')} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ builder.backend_save_list_as_button.removeClass 'disabled' @save_as_input = $ @save_as_modal.find('input') @save_as_input.keypress (e) => if e.which == 13 @save_as_save_button.click() false else @name_availability_container.text '' @name_availability_container.append $.trim """ <i class="fa fa-spin fa-spinner"></i> #{exportObj.translate('ui', 'Checking name availability...')} """ timer = @save_as_modal.data('timer') window.clearInterval(timer) if timer? @save_as_modal.data 'timer', window.setInterval(@nameCheck, 500) @name_availability_container = $ @save_as_modal.find('.name-availability') # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@squad_list_modal) @delete_modal = $ document.createElement('DIV') @delete_modal.addClass 'modal fade d-print-none' @delete_modal.tabindex = "-1" @delete_modal.role = "dialog" $(document.body).append @delete_modal @delete_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3><span class="translated" defaultText="Really Delete"></span> <span class="squad-name-placeholder"></span>?</h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Sure to delete?"></p> </div> <div class="modal-footer"> <button class="btn btn-danger delete" aria-hidden="true"><span class="translated" defaultText="Yes, Delete"></span> <i class="squad-name-placeholder"></i></button> <button class="btn btn-modal translated" data-dismiss="modal" aria-hidden="true" defaultText="Never Mind"></button> </div> </div> </div> """ @delete_name_container = $ @delete_modal.find('.squad-name-placeholder') @delete_button = $ @delete_modal.find('button.delete') @delete_button.click (e) => e.preventDefault() builder = @delete_modal.data 'builder' builder.backend_status.html $.trim """ <i class="fa fa-sync fa-spin"></i>&nbsp;#{exportObj.translate('ui', "Deleting squad...")} """ builder.backend_status.show() builder.backend_delete_list_button.addClass 'disabled' @delete_modal.modal 'hide' @delete builder.current_squad.id, (results) => if results.success builder.resetCurrentSquad() builder.current_squad.dirty = true builder.container.trigger 'xwing-backend:squadDirtinessChanged' builder.backend_status.html $.trim """ <i class="fa fa-check"></i>&nbsp;#{exportObj.translate('ui', "Squad deleted.")} """ else builder.backend_status.html $.trim """ <i class="fa fa-exclamation-circle"></i>&nbsp;#{results.error} """ # Failed, so offer chance to delete again builder.backend_delete_list_button.removeClass 'disabled' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@delete_modal) @unsaved_modal = $ document.createElement('DIV') @unsaved_modal.addClass 'modal fade d-print-none' @unsaved_modal.tabindex = "-1" @unsaved_modal.role = "dialog" $(document.body).append @unsaved_modal @unsaved_modal.append $.trim """ <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h3 class="translated" defaultText="Unsaved Changes"></h3> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p class="translated" defaultText="Unsaved Changes Warning"></p> </div> <div class="modal-footer"> <button class="btn btn-modal btn-primary translated" aria-hidden="true" data-dismiss="modal" defaultText="Go Back"></button> <button class="btn btn-danger discard translated" aria-hidden="true" defaultText="Discard Changes"></button> </div> </div> </div> """ @unsaved_discard_button = $ @unsaved_modal.find('button.discard') @unsaved_discard_button.click (e) => e.preventDefault() @unsaved_modal.data('builder').current_squad.dirty = false @unsaved_modal.data('callback')() @unsaved_modal.modal 'hide' # this is dynamically created UI, so we need to translate it after creation exportObj.translateUIElements(@unsaved_modal) setupHandlers: () -> $(window).on 'xwing-backend:authenticationChanged', (e, authenticated, backend) => @updateAuthenticationVisibility() if authenticated @loadCollection() @login_logout_button.click (e) => e.preventDefault() if @authenticated @logout() else @login() $(window).on 'message', (e) => ev = e.originalEvent if ev.origin == @server switch ev.data?.command when 'auth_successful' @authenticate() @login_modal.modal 'hide' @login_modal.find('.login-in-progress').hide() @login_modal.find('ul.login-providers').show() ev.source.close() else console.log "Unexpected command #{ev.data?.command}" else console.log "Message received from unapproved origin #{ev.origin}" window.last_ev = e .on 'xwing-collection:changed', (e, collection) => clearTimeout(@collection_save_timer) if @collection_save_timer? @collection_save_timer = setTimeout => @saveCollection collection, (res) -> if res $(window).trigger 'xwing-collection:saved', collection , 1000 getSettings: (cb=$.noop) -> $.get("#{@server}/settings").done (data, textStatus, jqXHR) => cb data.settings set: (setting, value, cb=$.noop) -> post_args = "_method": "PUT" post_args[setting] = value $.post("#{@server}/settings", post_args).done (data, textStatus, jqXHR) => cb data.set deleteSetting: (setting, cb=$.noop) -> $.post("#{@server}/settings/#{setting}", {"_method": "DELETE"}).done (data, textStatus, jqXHR) => cb data.deleted getHeaders: (cb=$.noop) -> $.get("#{@server}/headers").done (data, textStatus, jqXHR) => cb data.headers getLanguagePreference: (settings, cb=$.noop) => # check if user provided a language preference. If yes, this will override the browser preference queried in translate.coffee if settings?.language? # we found a language, provide it with priority 10 cb settings.language, 10 # otherwise we may parse a language out of the headers else await @getHeaders defer(headers) if headers?.HTTP_ACCEPT_LANGUAGE? # Need to parse out language preferences console.log "#{headers.HTTP_ACCEPT_LANGUAGE}" for language_range in headers.HTTP_ACCEPT_LANGUAGE.split(',') [ language_tag, quality ] = language_range.split ';' console.log "#{language_tag}, #{quality}" if language_tag == '*' # let's give that half priority cb 'English', -0.5 else language_code = language_tag.split('-')[0] # check if the language code is available if langc of exportObj.codeToLanguage # yep - use as language with reasonable priority cb(exportObj.codeToLanguage[language_code], 8) else # bullshit priority - we can't support what the user wants # (maybe he gave another option though in his browser settings) cb 'English', -1 break else # no headers, callback with bullshit priority cb 'English', -1 getCollectionCheck: (settings, cb=$.noop) => if settings?.collectioncheck? cb settings.collectioncheck else @collectioncheck = true cb true saveCollection: (collection, cb=$.noop) -> post_args = expansions: collection.expansions singletons: collection.singletons checks: collection.checks $.post("#{@server}/collection", post_args).done (data, textStatus, jqXHR) -> cb data.success loadCollection: -> # Backend provides an empty collection if none exists yet for the user. $.get("#{@server}/collection").done (data, textStatus, jqXHR) -> collection = data.collection new exportObj.Collection expansions: collection.expansions singletons: collection.singletons checks: collection.checks
[ { "context": "ent handler for the\n MD Snackbar.\n @author Derek Gransaull <derek@dgtlife.com>\n @copyright DGTLife, LLC 201", "end": 128, "score": 0.9998872876167297, "start": 113, "tag": "NAME", "value": "Derek Gransaull" }, { "context": "e\n MD Snackbar.\n @author Derek Gransaull <derek@dgtlife.com>\n @copyright DGTLife, LLC 2015\n###\n\n{ Template }", "end": 147, "score": 0.9999328851699829, "start": 130, "tag": "EMAIL", "value": "derek@dgtlife.com" } ]
client/imports/ui/md-snackbar/md-snackbar.coffee
dgtlife/material-for-meteor
12
### @file Defines the helper, the on-render callback, and event handler for the MD Snackbar. @author Derek Gransaull <derek@dgtlife.com> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' getCurrentSnackbarElement = require('../../api/md-snackbar-api.js').getCurrentSnackbarElement displayCurrentSnackbar = require('../../api/md-snackbar-api.js').displayCurrentSnackbar handleTouchmove = require('../../api/md-snackbar-api.js').handleTouchmove require './md-snackbar.jade' # Helper for MD Snackbar. Template.md_snackbar.helpers currentSnackbar: -> getCurrentSnackbarElement() # On-render callback for MD Snackbar. Template._snackbar.onRendered -> # Display the current snackbar (i.e. the one just rendered). displayCurrentSnackbar @data._id # Event Handler for MD Snackbar. Template._snackbar.events # A touchmove on the snackbar (as the user swipes). 'touchmove [data-current-snackbar]': (event) -> event.preventDefault() handleTouchmove @_id, event
9168
### @file Defines the helper, the on-render callback, and event handler for the MD Snackbar. @author <NAME> <<EMAIL>> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' getCurrentSnackbarElement = require('../../api/md-snackbar-api.js').getCurrentSnackbarElement displayCurrentSnackbar = require('../../api/md-snackbar-api.js').displayCurrentSnackbar handleTouchmove = require('../../api/md-snackbar-api.js').handleTouchmove require './md-snackbar.jade' # Helper for MD Snackbar. Template.md_snackbar.helpers currentSnackbar: -> getCurrentSnackbarElement() # On-render callback for MD Snackbar. Template._snackbar.onRendered -> # Display the current snackbar (i.e. the one just rendered). displayCurrentSnackbar @data._id # Event Handler for MD Snackbar. Template._snackbar.events # A touchmove on the snackbar (as the user swipes). 'touchmove [data-current-snackbar]': (event) -> event.preventDefault() handleTouchmove @_id, event
true
### @file Defines the helper, the on-render callback, and event handler for the MD Snackbar. @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @copyright DGTLife, LLC 2015 ### { Template } = require 'meteor/templating' getCurrentSnackbarElement = require('../../api/md-snackbar-api.js').getCurrentSnackbarElement displayCurrentSnackbar = require('../../api/md-snackbar-api.js').displayCurrentSnackbar handleTouchmove = require('../../api/md-snackbar-api.js').handleTouchmove require './md-snackbar.jade' # Helper for MD Snackbar. Template.md_snackbar.helpers currentSnackbar: -> getCurrentSnackbarElement() # On-render callback for MD Snackbar. Template._snackbar.onRendered -> # Display the current snackbar (i.e. the one just rendered). displayCurrentSnackbar @data._id # Event Handler for MD Snackbar. Template._snackbar.events # A touchmove on the snackbar (as the user swipes). 'touchmove [data-current-snackbar]': (event) -> event.preventDefault() handleTouchmove @_id, event
[ { "context": ".equals result,\n _id: 0xff\n _name: 'test'\n done()\n ,\n _id: 0xff\n foo: 'f", "end": 1389, "score": 0.9623197317123413, "start": 1385, "tag": "NAME", "value": "test" }, { "context": "f\n foo: 'foo'\n bar: 'bar'\n _name: 'test'\n\n 'when nothing match predicate, receive empty ", "end": 1478, "score": 0.9430189728736877, "start": 1474, "tag": "NAME", "value": "test" }, { "context": "}\n done()\n ,\n bool: yes\n name: 'test hash'\n id: 0xf91\n age: undefined\n child", "end": 1756, "score": 0.9988962411880493, "start": 1747, "tag": "NAME", "value": "test hash" } ]
test/filter-test.coffee
chrhsmt/pp.js
1
if typeof require is 'function' buster = require 'buster' pp = require '../lib/pp' buster.testCase 'pp.filter', 'when receiver isnt function, throw error': (done) -> try pp.filter (next, v) -> next null, yes , 'not function', [1..9] catch error assert error instanceof TypeError done() 'when iterator isnt function, receive error': (done) -> pp.filter 'not function', (error, result) -> assert error instanceof TypeError done() , [1..9] 'filtering array by predicate': (done) -> pp.filter (next, v) -> next null, v % 2 < 1 , (error, result) -> assert.isNull error assert.equals result, [2, 4] done() , [1..5] 'when nothing is match filter, receive []': (done) -> pp.filter (next, v) -> next null, v > 10 , (error, result) -> assert.isNull error assert.equals result, [] done() , [1..5] 'when all matches, receive all elements': (done) -> pp.filter (next, v) -> next null, typeof v is 'number' , (error, result) -> assert.isNull error assert.equals result, [1..5] done() , [1..5] 'enable filter for hash table': (done) -> pp.filter (next, v, k) -> next null, k.match /^_/i , (error, result) -> assert.isNull error assert.equals result, _id: 0xff _name: 'test' done() , _id: 0xff foo: 'foo' bar: 'bar' _name: 'test' 'when nothing match predicate, receive empty object': (done) -> pp.filter (next, v, k) -> next null, typeof v is 'function' , (error, result) -> assert.isNull error assert.equals result, {} done() , bool: yes name: 'test hash' id: 0xf91 age: undefined child: null cleateAt: new Date()
12626
if typeof require is 'function' buster = require 'buster' pp = require '../lib/pp' buster.testCase 'pp.filter', 'when receiver isnt function, throw error': (done) -> try pp.filter (next, v) -> next null, yes , 'not function', [1..9] catch error assert error instanceof TypeError done() 'when iterator isnt function, receive error': (done) -> pp.filter 'not function', (error, result) -> assert error instanceof TypeError done() , [1..9] 'filtering array by predicate': (done) -> pp.filter (next, v) -> next null, v % 2 < 1 , (error, result) -> assert.isNull error assert.equals result, [2, 4] done() , [1..5] 'when nothing is match filter, receive []': (done) -> pp.filter (next, v) -> next null, v > 10 , (error, result) -> assert.isNull error assert.equals result, [] done() , [1..5] 'when all matches, receive all elements': (done) -> pp.filter (next, v) -> next null, typeof v is 'number' , (error, result) -> assert.isNull error assert.equals result, [1..5] done() , [1..5] 'enable filter for hash table': (done) -> pp.filter (next, v, k) -> next null, k.match /^_/i , (error, result) -> assert.isNull error assert.equals result, _id: 0xff _name: '<NAME>' done() , _id: 0xff foo: 'foo' bar: 'bar' _name: '<NAME>' 'when nothing match predicate, receive empty object': (done) -> pp.filter (next, v, k) -> next null, typeof v is 'function' , (error, result) -> assert.isNull error assert.equals result, {} done() , bool: yes name: '<NAME>' id: 0xf91 age: undefined child: null cleateAt: new Date()
true
if typeof require is 'function' buster = require 'buster' pp = require '../lib/pp' buster.testCase 'pp.filter', 'when receiver isnt function, throw error': (done) -> try pp.filter (next, v) -> next null, yes , 'not function', [1..9] catch error assert error instanceof TypeError done() 'when iterator isnt function, receive error': (done) -> pp.filter 'not function', (error, result) -> assert error instanceof TypeError done() , [1..9] 'filtering array by predicate': (done) -> pp.filter (next, v) -> next null, v % 2 < 1 , (error, result) -> assert.isNull error assert.equals result, [2, 4] done() , [1..5] 'when nothing is match filter, receive []': (done) -> pp.filter (next, v) -> next null, v > 10 , (error, result) -> assert.isNull error assert.equals result, [] done() , [1..5] 'when all matches, receive all elements': (done) -> pp.filter (next, v) -> next null, typeof v is 'number' , (error, result) -> assert.isNull error assert.equals result, [1..5] done() , [1..5] 'enable filter for hash table': (done) -> pp.filter (next, v, k) -> next null, k.match /^_/i , (error, result) -> assert.isNull error assert.equals result, _id: 0xff _name: 'PI:NAME:<NAME>END_PI' done() , _id: 0xff foo: 'foo' bar: 'bar' _name: 'PI:NAME:<NAME>END_PI' 'when nothing match predicate, receive empty object': (done) -> pp.filter (next, v, k) -> next null, typeof v is 'function' , (error, result) -> assert.isNull error assert.equals result, {} done() , bool: yes name: 'PI:NAME:<NAME>END_PI' id: 0xf91 age: undefined child: null cleateAt: new Date()
[ { "context": "name: 'Freemarker',\nscopeName: 'source.freemarker',\ntype: 'tree-sit", "end": 17, "score": 0.8624306917190552, "start": 7, "tag": "NAME", "value": "Freemarker" } ]
grammars/tree-sitter-fmkr.cson
Jake-Nolder/tsl-freemarker
0
name: 'Freemarker', scopeName: 'source.freemarker', type: 'tree-sitter', parser: 'tree-sitter-freemarker', limitLineLength: false, fileTypes: [ 'ftl' ], injectionSelector: 'text.html.basic', scopes: { 'source_file': 'entity.name.source', 'directive': 'entity.name.directive', 'expression': 'entity.type.expression', 'operator': 'entity.type.operator', 'string': 'entity.type.string', 'bracket': 'entity.type.bracket', 'built_in': 'entity.type.built_in', 'built_in>top_level': 'entity.type.built_in', 'top_level': 'entity.type.top_level', 'sub_level': 'entity.type.sub_level', 'spec_var': 'entity.type.spec_var', 'user_defined': 'entity.name.user_defined', 'interpolation': 'entity.name.interpolation', 'ERROR': 'entity.type.error' }, folds: [{ type: 'directive' }]
83255
name: '<NAME>', scopeName: 'source.freemarker', type: 'tree-sitter', parser: 'tree-sitter-freemarker', limitLineLength: false, fileTypes: [ 'ftl' ], injectionSelector: 'text.html.basic', scopes: { 'source_file': 'entity.name.source', 'directive': 'entity.name.directive', 'expression': 'entity.type.expression', 'operator': 'entity.type.operator', 'string': 'entity.type.string', 'bracket': 'entity.type.bracket', 'built_in': 'entity.type.built_in', 'built_in>top_level': 'entity.type.built_in', 'top_level': 'entity.type.top_level', 'sub_level': 'entity.type.sub_level', 'spec_var': 'entity.type.spec_var', 'user_defined': 'entity.name.user_defined', 'interpolation': 'entity.name.interpolation', 'ERROR': 'entity.type.error' }, folds: [{ type: 'directive' }]
true
name: 'PI:NAME:<NAME>END_PI', scopeName: 'source.freemarker', type: 'tree-sitter', parser: 'tree-sitter-freemarker', limitLineLength: false, fileTypes: [ 'ftl' ], injectionSelector: 'text.html.basic', scopes: { 'source_file': 'entity.name.source', 'directive': 'entity.name.directive', 'expression': 'entity.type.expression', 'operator': 'entity.type.operator', 'string': 'entity.type.string', 'bracket': 'entity.type.bracket', 'built_in': 'entity.type.built_in', 'built_in>top_level': 'entity.type.built_in', 'top_level': 'entity.type.top_level', 'sub_level': 'entity.type.sub_level', 'spec_var': 'entity.type.spec_var', 'user_defined': 'entity.name.user_defined', 'interpolation': 'entity.name.interpolation', 'ERROR': 'entity.type.error' }, folds: [{ type: 'directive' }]
[ { "context": "oGLib\n# Module | Stat methods\n# Author | Sherif Emabrak\n# Description | Standard Error\n# ----------------", "end": 163, "score": 0.9998802542686462, "start": 149, "tag": "NAME", "value": "Sherif Emabrak" } ]
src/lib/statistics/summary/se.coffee
Sherif-Embarak/gp-test
0
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | Sherif Emabrak # Description | Standard Error # ------------------------------------------------------------------------------ se = () ->
219277
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | <NAME> # Description | Standard Error # ------------------------------------------------------------------------------ se = () ->
true
# ------------------------------------------------------------------------------ # Project | GoGLib # Module | Stat methods # Author | PI:NAME:<NAME>END_PI # Description | Standard Error # ------------------------------------------------------------------------------ se = () ->
[ { "context": " # for debugging only\n# employee.email = \"jk@websector.de\"\n# employee.firstName = \"j\"\n# emplo", "end": 566, "score": 0.9999297261238098, "start": 551, "tag": "EMAIL", "value": "jk@websector.de" }, { "context": " \"jk@websector.de\"\n# employee.firstName = \"j\"\n# employee.lastName = \"k\"\n# employ", "end": 600, "score": 0.9993884563446045, "start": 599, "tag": "NAME", "value": "j" }, { "context": "yee.firstName = \"j\"\n# employee.lastName = \"k\"\n# employee.startDate = \"2013-10-06\"\n\n ", "end": 633, "score": 0.9987725019454956, "start": 632, "tag": "NAME", "value": "k" } ]
app/assets/javascripts/controllers/createEmployeeController.coffee
sectore/CafeTownsend-Angular-Rails
70
angular.module('cafeTownsend.employee') .controller 'CreateEmployeeController', [ '$log' '$location' 'SessionService' 'EmployeesService' 'SelectedEmployee' 'ViewState' ($log, $location, SessionService, EmployeesService, SelectedEmployee, ViewState) -> self = this # init # ------------------------------------------------------------ init = -> ViewState.current = 'create' if !!SessionService.authorized() employee = new EmployeesService() # for debugging only # employee.email = "jk@websector.de" # employee.firstName = "j" # employee.lastName = "k" # employee.startDate = "2013-10-06" # store new created instance # set reference to selectedEmployee SelectedEmployee.instance = self.selectedEmployee = employee else $location.path '/login' @submit = (validData)-> if !!validData SelectedEmployee.instance.create() .then -> self.browseToOverview() , (error) -> message = "Error trying to create a new employee: #{JSON.stringify(error.data)})" alert message @browseToOverview = -> # clear selected employee SelectedEmployee.instance = undefined $location.path '/employees' # call init() # ------------------------------------------------------------ init() # return a reference to controller itself # to avoid returning init(), which causes issues self ]
10394
angular.module('cafeTownsend.employee') .controller 'CreateEmployeeController', [ '$log' '$location' 'SessionService' 'EmployeesService' 'SelectedEmployee' 'ViewState' ($log, $location, SessionService, EmployeesService, SelectedEmployee, ViewState) -> self = this # init # ------------------------------------------------------------ init = -> ViewState.current = 'create' if !!SessionService.authorized() employee = new EmployeesService() # for debugging only # employee.email = "<EMAIL>" # employee.firstName = "<NAME>" # employee.lastName = "<NAME>" # employee.startDate = "2013-10-06" # store new created instance # set reference to selectedEmployee SelectedEmployee.instance = self.selectedEmployee = employee else $location.path '/login' @submit = (validData)-> if !!validData SelectedEmployee.instance.create() .then -> self.browseToOverview() , (error) -> message = "Error trying to create a new employee: #{JSON.stringify(error.data)})" alert message @browseToOverview = -> # clear selected employee SelectedEmployee.instance = undefined $location.path '/employees' # call init() # ------------------------------------------------------------ init() # return a reference to controller itself # to avoid returning init(), which causes issues self ]
true
angular.module('cafeTownsend.employee') .controller 'CreateEmployeeController', [ '$log' '$location' 'SessionService' 'EmployeesService' 'SelectedEmployee' 'ViewState' ($log, $location, SessionService, EmployeesService, SelectedEmployee, ViewState) -> self = this # init # ------------------------------------------------------------ init = -> ViewState.current = 'create' if !!SessionService.authorized() employee = new EmployeesService() # for debugging only # employee.email = "PI:EMAIL:<EMAIL>END_PI" # employee.firstName = "PI:NAME:<NAME>END_PI" # employee.lastName = "PI:NAME:<NAME>END_PI" # employee.startDate = "2013-10-06" # store new created instance # set reference to selectedEmployee SelectedEmployee.instance = self.selectedEmployee = employee else $location.path '/login' @submit = (validData)-> if !!validData SelectedEmployee.instance.create() .then -> self.browseToOverview() , (error) -> message = "Error trying to create a new employee: #{JSON.stringify(error.data)})" alert message @browseToOverview = -> # clear selected employee SelectedEmployee.instance = undefined $location.path '/employees' # call init() # ------------------------------------------------------------ init() # return a reference to controller itself # to avoid returning init(), which causes issues self ]
[ { "context": ".eql(\n\t\t\t\t'allow[]': ['on', 'on']\n\t\t\t\tfirstName: 'John'\n\t\t\t\tlastName: 'Doe'\n\t\t\t)\n\t\t\tdone()\n\n\t\t$('#tests ", "end": 563, "score": 0.9998215436935425, "start": 559, "tag": "NAME", "value": "John" }, { "context": "['on', 'on']\n\t\t\t\tfirstName: 'John'\n\t\t\t\tlastName: 'Doe'\n\t\t\t)\n\t\t\tdone()\n\n\t\t$('#tests form.base').submit()", "end": 583, "score": 0.9996074438095093, "start": 580, "tag": "NAME", "value": "Doe" }, { "context": "kbox'\n\t\t\t\t'allow[]': ['on', 'on']\n\t\t\t\tfirstName: 'John'\n\t\t\t\tlastName: 'Doe'\n\t\t\t)\n\t\t\tdone()\n\n\t\t$('#tests ", "end": 910, "score": 0.9998214840888977, "start": 906, "tag": "NAME", "value": "John" }, { "context": "['on', 'on']\n\t\t\t\tfirstName: 'John'\n\t\t\t\tlastName: 'Doe'\n\t\t\t)\n\t\t\tdone()\n\n\t\t$('#tests form.base input[name", "end": 930, "score": 0.999542236328125, "start": 927, "tag": "NAME", "value": "Doe" } ]
test/tests/Extensions.Forms.coffee
sakren/node-browser-http
3
Http = null Forms = null describe 'Extensions.Forms', -> beforeEach( -> Http = new http.Mocks.Http Forms = new http.Extensions.Forms($) Http.addExtension('forms', Forms) ) afterEach( -> Forms.detach() ) it 'should send form', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('GET') expect(request.url).to.be.equal(window.location.href) expect(response.data).to.be.eql( 'allow[]': ['on', 'on'] firstName: 'John' lastName: 'Doe' ) done() $('#tests form.base').submit() it 'should send form with button click', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add checkbox' 'allow[]': ['on', 'on'] firstName: 'John' lastName: 'Doe' ) done() $('#tests form.base input[name="add"]').click() it 'should send form with different action and method', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('POST') expect(request.url).to.be.equal('google.com') expect(response.data).to.be.eql( name: 'some name' ) done() $('#tests form.custom').submit() it 'should send non-ajax form with ajax button', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add name' name: 'another name' ) done() $('#tests form.button input[name="add"]').click()
56702
Http = null Forms = null describe 'Extensions.Forms', -> beforeEach( -> Http = new http.Mocks.Http Forms = new http.Extensions.Forms($) Http.addExtension('forms', Forms) ) afterEach( -> Forms.detach() ) it 'should send form', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('GET') expect(request.url).to.be.equal(window.location.href) expect(response.data).to.be.eql( 'allow[]': ['on', 'on'] firstName: '<NAME>' lastName: '<NAME>' ) done() $('#tests form.base').submit() it 'should send form with button click', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add checkbox' 'allow[]': ['on', 'on'] firstName: '<NAME>' lastName: '<NAME>' ) done() $('#tests form.base input[name="add"]').click() it 'should send form with different action and method', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('POST') expect(request.url).to.be.equal('google.com') expect(response.data).to.be.eql( name: 'some name' ) done() $('#tests form.custom').submit() it 'should send non-ajax form with ajax button', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add name' name: 'another name' ) done() $('#tests form.button input[name="add"]').click()
true
Http = null Forms = null describe 'Extensions.Forms', -> beforeEach( -> Http = new http.Mocks.Http Forms = new http.Extensions.Forms($) Http.addExtension('forms', Forms) ) afterEach( -> Forms.detach() ) it 'should send form', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('GET') expect(request.url).to.be.equal(window.location.href) expect(response.data).to.be.eql( 'allow[]': ['on', 'on'] firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' ) done() $('#tests form.base').submit() it 'should send form with button click', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add checkbox' 'allow[]': ['on', 'on'] firstName: 'PI:NAME:<NAME>END_PI' lastName: 'PI:NAME:<NAME>END_PI' ) done() $('#tests form.base input[name="add"]').click() it 'should send form with different action and method', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response, request) -> expect(request.type).to.be.equal('POST') expect(request.url).to.be.equal('google.com') expect(response.data).to.be.eql( name: 'some name' ) done() $('#tests form.custom').submit() it 'should send non-ajax form with ajax button', (done) -> Http.receiveDataFromRequestAndSendBack({'content-type': 'application/json'}) Http.on 'success', (response) -> expect(response.data).to.be.eql( add: 'Add name' name: 'another name' ) done() $('#tests form.button input[name="add"]').click()
[ { "context": "default = OrgC\n \n emailAddress = email@domain.com\n emailAddress_default = email@domain.com\n", "end": 1552, "score": 0.9995423555374146, "start": 1536, "tag": "EMAIL", "value": "email@domain.com" }, { "context": "= email@domain.com\n emailAddress_default = email@domain.com\n \n [ v3_req ]\n subjectAltName = @alt_names\n [", "end": 1601, "score": 0.9996899366378784, "start": 1585, "tag": "EMAIL", "value": "email@domain.com" }, { "context": "ltName = @alt_names\n [alt_names]\n DNS.1 = 10.110.25.57.xip.io\n DNS.2 = *.10.110.25.57.xip.io\n DN", "end": 1690, "score": 0.9992079138755798, "start": 1678, "tag": "IP_ADDRESS", "value": "10.110.25.57" }, { "context": "S.1 = 10.110.25.57.xip.io\n DNS.2 = *.10.110.25.57.xip.io\n DNS.3 = devops.domain.com\n DNS.4 ", "end": 1728, "score": 0.980479896068573, "start": 1716, "tag": "IP_ADDRESS", "value": "10.110.25.57" }, { "context": " = *.devops.domain.com\n DNS.5 = *.ioc-test.10.110.25.57.xip.io\n ```\n ### 生成命令\n -nodes 私钥不加密\n ```\n op", "end": 1845, "score": 0.9936864972114563, "start": 1833, "tag": "IP_ADDRESS", "value": "10.110.25.57" } ]
notes/956e2275-4208-4980-bd7c-0c2390d4f19b.cson
cwocwo/boostnote
0
createdAt: "2018-07-10T01:40:37.448Z" updatedAt: "2018-09-22T03:34:45.784Z" type: "MARKDOWN_NOTE" folder: "66dff0cfbfde06f3d2e8" title: "openssl 生成 p10请求" content: ''' # openssl 生成 p10请求 ## 生成私钥 openssl genrsa -des3 -out private_key.pem 1024\\2048 ## 生成p10 openssl req -new -out cert.csr -key private_key.pem openssl req -new -nodes -key prvtkey.pem -out cert.csr ## 签发证书 openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert\\tls.key -out app-cert\\tls.crt -subj “\\CN=app.ioc.com” openssl x509 -req -in cert.csr -out rsa_public_key.der -outform der -signkey rsa_private_key.pem -days 3650 openssl x509 -req -in cert.csr -out rsa_public_key.pem -signkey private_key.pem -days 3650 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ### 通过配置生成证书示例 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ## 生成devops.domain.com的p10 ### 配置文件 openssl-req.conf ``` [req] req_extensions = v3_req distinguished_name = subject [ subject ] countryName = CN countryName_default = CN stateOrProvinceName = stateA stateOrProvinceName_default = stateA localityName = CityB localityName_default = CityB organizationName = domain organizationName_default = domain commonName = OrgC commonName_default = OrgC emailAddress = email@domain.com emailAddress_default = email@domain.com [ v3_req ] subjectAltName = @alt_names [alt_names] DNS.1 = 10.110.25.57.xip.io DNS.2 = *.10.110.25.57.xip.io DNS.3 = devops.domain.com DNS.4 = *.devops.domain.com DNS.5 = *.ioc-test.10.110.25.57.xip.io ``` ### 生成命令 -nodes 私钥不加密 ``` openssl req -newkey rsa:2048 -nodes -keyout devops.domain.com.key.pem -keyform PEM -out devops.domain.com.req.pem -outform PEM -config openssl-req.conf -days 3650 ``` ### 查看请求 openssl req -in devops.domain.com.req.pem -text -noout ---- 参考 [使用OpenSSL生成证书 - 孤剑 - 博客园](https:\\\\www.cnblogs.com\\AloneSword\\p\\3809002.html) [openssl: generate certificate request with non-DNS subject alternative names - Server Fault](https:\\\\serverfault.com\\questions\\596909\\openssl-generate-certificate-request-with-non-dns-subject-alternative-names) [openssl req -- PKCS#10 certificate and certificate generating utility.](https:\\\\www.mkssoftware.com\\docs\\man1\\openssl_req.1.asp) ''' tags: [] isStarred: false isTrashed: false
123585
createdAt: "2018-07-10T01:40:37.448Z" updatedAt: "2018-09-22T03:34:45.784Z" type: "MARKDOWN_NOTE" folder: "66dff0cfbfde06f3d2e8" title: "openssl 生成 p10请求" content: ''' # openssl 生成 p10请求 ## 生成私钥 openssl genrsa -des3 -out private_key.pem 1024\\2048 ## 生成p10 openssl req -new -out cert.csr -key private_key.pem openssl req -new -nodes -key prvtkey.pem -out cert.csr ## 签发证书 openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert\\tls.key -out app-cert\\tls.crt -subj “\\CN=app.ioc.com” openssl x509 -req -in cert.csr -out rsa_public_key.der -outform der -signkey rsa_private_key.pem -days 3650 openssl x509 -req -in cert.csr -out rsa_public_key.pem -signkey private_key.pem -days 3650 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ### 通过配置生成证书示例 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ## 生成devops.domain.com的p10 ### 配置文件 openssl-req.conf ``` [req] req_extensions = v3_req distinguished_name = subject [ subject ] countryName = CN countryName_default = CN stateOrProvinceName = stateA stateOrProvinceName_default = stateA localityName = CityB localityName_default = CityB organizationName = domain organizationName_default = domain commonName = OrgC commonName_default = OrgC emailAddress = <EMAIL> emailAddress_default = <EMAIL> [ v3_req ] subjectAltName = @alt_names [alt_names] DNS.1 = 10.110.25.57.xip.io DNS.2 = *.10.110.25.57.xip.io DNS.3 = devops.domain.com DNS.4 = *.devops.domain.com DNS.5 = *.ioc-test.10.110.25.57.xip.io ``` ### 生成命令 -nodes 私钥不加密 ``` openssl req -newkey rsa:2048 -nodes -keyout devops.domain.com.key.pem -keyform PEM -out devops.domain.com.req.pem -outform PEM -config openssl-req.conf -days 3650 ``` ### 查看请求 openssl req -in devops.domain.com.req.pem -text -noout ---- 参考 [使用OpenSSL生成证书 - 孤剑 - 博客园](https:\\\\www.cnblogs.com\\AloneSword\\p\\3809002.html) [openssl: generate certificate request with non-DNS subject alternative names - Server Fault](https:\\\\serverfault.com\\questions\\596909\\openssl-generate-certificate-request-with-non-dns-subject-alternative-names) [openssl req -- PKCS#10 certificate and certificate generating utility.](https:\\\\www.mkssoftware.com\\docs\\man1\\openssl_req.1.asp) ''' tags: [] isStarred: false isTrashed: false
true
createdAt: "2018-07-10T01:40:37.448Z" updatedAt: "2018-09-22T03:34:45.784Z" type: "MARKDOWN_NOTE" folder: "66dff0cfbfde06f3d2e8" title: "openssl 生成 p10请求" content: ''' # openssl 生成 p10请求 ## 生成私钥 openssl genrsa -des3 -out private_key.pem 1024\\2048 ## 生成p10 openssl req -new -out cert.csr -key private_key.pem openssl req -new -nodes -key prvtkey.pem -out cert.csr ## 签发证书 openssl req -x509 -nodes -days 3650 -newkey rsa:2048 -keyout app-cert\\tls.key -out app-cert\\tls.crt -subj “\\CN=app.ioc.com” openssl x509 -req -in cert.csr -out rsa_public_key.der -outform der -signkey rsa_private_key.pem -days 3650 openssl x509 -req -in cert.csr -out rsa_public_key.pem -signkey private_key.pem -days 3650 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ### 通过配置生成证书示例 openssl req -config openssl.conf -new -x509 -newkey rsa:2048 -nodes -keyout ioc.key.pem -days 3650 -out ioc.cert.pem ## 生成devops.domain.com的p10 ### 配置文件 openssl-req.conf ``` [req] req_extensions = v3_req distinguished_name = subject [ subject ] countryName = CN countryName_default = CN stateOrProvinceName = stateA stateOrProvinceName_default = stateA localityName = CityB localityName_default = CityB organizationName = domain organizationName_default = domain commonName = OrgC commonName_default = OrgC emailAddress = PI:EMAIL:<EMAIL>END_PI emailAddress_default = PI:EMAIL:<EMAIL>END_PI [ v3_req ] subjectAltName = @alt_names [alt_names] DNS.1 = 10.110.25.57.xip.io DNS.2 = *.10.110.25.57.xip.io DNS.3 = devops.domain.com DNS.4 = *.devops.domain.com DNS.5 = *.ioc-test.10.110.25.57.xip.io ``` ### 生成命令 -nodes 私钥不加密 ``` openssl req -newkey rsa:2048 -nodes -keyout devops.domain.com.key.pem -keyform PEM -out devops.domain.com.req.pem -outform PEM -config openssl-req.conf -days 3650 ``` ### 查看请求 openssl req -in devops.domain.com.req.pem -text -noout ---- 参考 [使用OpenSSL生成证书 - 孤剑 - 博客园](https:\\\\www.cnblogs.com\\AloneSword\\p\\3809002.html) [openssl: generate certificate request with non-DNS subject alternative names - Server Fault](https:\\\\serverfault.com\\questions\\596909\\openssl-generate-certificate-request-with-non-dns-subject-alternative-names) [openssl req -- PKCS#10 certificate and certificate generating utility.](https:\\\\www.mkssoftware.com\\docs\\man1\\openssl_req.1.asp) ''' tags: [] isStarred: false isTrashed: false
[ { "context": "er\", (done) ->\n user = new User(\n email: \"test@gmail.com\"\n password: \"password\"\n )\n user.save (", "end": 736, "score": 0.9999265670776367, "start": 722, "tag": "EMAIL", "value": "test@gmail.com" }, { "context": "r(\n email: \"test@gmail.com\"\n password: \"password\"\n )\n user.save (err) ->\n return done(e", "end": 763, "score": 0.9995248317718506, "start": 755, "tag": "PASSWORD", "value": "password" }, { "context": "il\", (done) ->\n user = new User(\n email: \"test@gmail.com\"\n password: \"password\"\n )\n user.save (", "end": 978, "score": 0.9999292492866516, "start": 964, "tag": "EMAIL", "value": "test@gmail.com" }, { "context": "r(\n email: \"test@gmail.com\"\n password: \"password\"\n )\n user.save (err) ->\n err.code.shou", "end": 1005, "score": 0.9995051622390747, "start": 997, "tag": "PASSWORD", "value": "password" }, { "context": " email\", (done) ->\n User.findOne\n email: \"test@gmail.com\"\n , (err, user) ->\n return done(err) if ", "end": 1197, "score": 0.99992835521698, "start": 1183, "tag": "EMAIL", "value": "test@gmail.com" }, { "context": " done(err) if err\n user.email.should.equal \"test@gmail.com\"\n done()\n return\n\n return\n\n it \"sho", "end": 1296, "score": 0.9999262094497681, "start": 1282, "tag": "EMAIL", "value": "test@gmail.com" }, { "context": " a user\", (done) ->\n User.remove\n email: \"test@gmail.com\"\n , (err) ->\n return done(err) if err\n ", "end": 1420, "score": 0.9999290704727173, "start": 1406, "tag": "EMAIL", "value": "test@gmail.com" } ]
development/server/test/models.coffee
SwingDev/MEAN-starter
0
chai = require("chai") should = chai.should() User = require("../models/User") process.env.NODE_ENV = "test" config = require("../config/config") mongoose = require("mongoose") before (done) -> clearDB = -> for i of mongoose.connection.collections mongoose.connection.collections[i].remove((err, numberOfRemovedDocs) -> ) if mongoose.connection.readyState == 0 console.log('Trying to connect to mongoDB... ') mongoose.connect config.db, (err) -> throw err if err clearDB() done() else clearDB() done() return after (done) -> mongoose.disconnect() done() describe "User Model", -> it "should create a new user", (done) -> user = new User( email: "test@gmail.com" password: "password" ) user.save (err) -> return done(err) if err done() return return it "should not create a user with the unique email", (done) -> user = new User( email: "test@gmail.com" password: "password" ) user.save (err) -> err.code.should.equal 11000 done() return return it "should find user by email", (done) -> User.findOne email: "test@gmail.com" , (err, user) -> return done(err) if err user.email.should.equal "test@gmail.com" done() return return it "should delete a user", (done) -> User.remove email: "test@gmail.com" , (err) -> return done(err) if err done() return return return before (done) -> done() after (done) -> done()
109925
chai = require("chai") should = chai.should() User = require("../models/User") process.env.NODE_ENV = "test" config = require("../config/config") mongoose = require("mongoose") before (done) -> clearDB = -> for i of mongoose.connection.collections mongoose.connection.collections[i].remove((err, numberOfRemovedDocs) -> ) if mongoose.connection.readyState == 0 console.log('Trying to connect to mongoDB... ') mongoose.connect config.db, (err) -> throw err if err clearDB() done() else clearDB() done() return after (done) -> mongoose.disconnect() done() describe "User Model", -> it "should create a new user", (done) -> user = new User( email: "<EMAIL>" password: "<PASSWORD>" ) user.save (err) -> return done(err) if err done() return return it "should not create a user with the unique email", (done) -> user = new User( email: "<EMAIL>" password: "<PASSWORD>" ) user.save (err) -> err.code.should.equal 11000 done() return return it "should find user by email", (done) -> User.findOne email: "<EMAIL>" , (err, user) -> return done(err) if err user.email.should.equal "<EMAIL>" done() return return it "should delete a user", (done) -> User.remove email: "<EMAIL>" , (err) -> return done(err) if err done() return return return before (done) -> done() after (done) -> done()
true
chai = require("chai") should = chai.should() User = require("../models/User") process.env.NODE_ENV = "test" config = require("../config/config") mongoose = require("mongoose") before (done) -> clearDB = -> for i of mongoose.connection.collections mongoose.connection.collections[i].remove((err, numberOfRemovedDocs) -> ) if mongoose.connection.readyState == 0 console.log('Trying to connect to mongoDB... ') mongoose.connect config.db, (err) -> throw err if err clearDB() done() else clearDB() done() return after (done) -> mongoose.disconnect() done() describe "User Model", -> it "should create a new user", (done) -> user = new User( email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" ) user.save (err) -> return done(err) if err done() return return it "should not create a user with the unique email", (done) -> user = new User( email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" ) user.save (err) -> err.code.should.equal 11000 done() return return it "should find user by email", (done) -> User.findOne email: "PI:EMAIL:<EMAIL>END_PI" , (err, user) -> return done(err) if err user.email.should.equal "PI:EMAIL:<EMAIL>END_PI" done() return return it "should delete a user", (done) -> User.remove email: "PI:EMAIL:<EMAIL>END_PI" , (err) -> return done(err) if err done() return return return before (done) -> done() after (done) -> done()
[ { "context": "p.Data.maps.create {dateCreated: new Date(), name: newMapName}\n\n @hide()\n\n # Chang", "end": 2936, "score": 0.8723249435424805, "start": 2933, "tag": "NAME", "value": "new" } ]
assets/js/view/createMapView.coffee
dmahlow/system
0
# CREATE MAP VIEW # -------------------------------------------------------------------------- # Represents the "Create new map" overlay what shows up when user # clicks a "Create new..." option on the top menu. class SystemApp.CreateMapView extends SystemApp.OverlayView $txtName: null # the text field to enter the new map name $menuItem: null # the top menu DOM element # INIT AND DISPOSE # ---------------------------------------------------------------------- # Init the "Create Map" overlay view. initialize: => @overlayInit "#map-create-overlay" @setDom() @setEvents() # Clear contents and dispose the view. dispose: => @baseDispose() # Set the DOM elements cache. setDom: => @$txtName = $ "#map-create-overlay-name" @$menuItem = $ "#menu-createmap" # Bind events to DOM and other controls. setEvents: => @$txtName.keyup @keyUp # SHOW AND HIDE # ---------------------------------------------------------------------- # Hide the view using a fade out effect. onHide: => $(document).unbind "keyup", @keyUp SystemApp.footerView.setText null @$el.fadeOut SystemApp.Settings.general.fadeDelay # Show the view using a fade in effect and pass the entity type. # If user has no "mapcreate" role, hide the view immediately. onShow: => if not SystemApp.Data.loggedUser.hasRole "mapcreate" errorMsg = SystemApp.Messages.errNoPermissionTo.replace "#", SystemApp.Messages.createMaps SystemApp.alertEvents.trigger "tooltip", {isError: true, title: SystemApp.Messages.accessDenied, message: errorMsg} # Cancel the view and go to previous screen. cancelShow = => @hide() window.history.back() setTimeout cancelShow, 10 return $(document).keyup @keyUp SystemApp.footerView.setText SystemApp.Messages.createMapText @$el.fadeIn SystemApp.Settings.general.fadeDelay, @focus # Clear and set focus on the textbox. @$txtName.val "" @$txtName.focus() SystemApp.menuEvents.trigger "active:menu", @$menuItem # When user presses a key on the `txtName` field. keyUp: (e) => if e.which is 27 @hide e if e.which is 13 newMapName = $.trim @$txtName.val() existing = SystemApp.Data.maps.where {name: newMapName} if existing.length > 0 errTitle = SystemApp.Messages.errCreatingMap errMessage = SystemApp.Messages.errMapNameExists.replace "#", newMapName SystemApp.alertEvents.trigger "footer", {title: errTitle, message: errMessage, isError: true} @warnField @$txtName return map = SystemApp.Data.maps.create {dateCreated: new Date(), name: newMapName} @hide() # Change the URL using the new map key. SystemApp.routes.navigate "map/" + map.urlKey(), {trigger: true}
215288
# CREATE MAP VIEW # -------------------------------------------------------------------------- # Represents the "Create new map" overlay what shows up when user # clicks a "Create new..." option on the top menu. class SystemApp.CreateMapView extends SystemApp.OverlayView $txtName: null # the text field to enter the new map name $menuItem: null # the top menu DOM element # INIT AND DISPOSE # ---------------------------------------------------------------------- # Init the "Create Map" overlay view. initialize: => @overlayInit "#map-create-overlay" @setDom() @setEvents() # Clear contents and dispose the view. dispose: => @baseDispose() # Set the DOM elements cache. setDom: => @$txtName = $ "#map-create-overlay-name" @$menuItem = $ "#menu-createmap" # Bind events to DOM and other controls. setEvents: => @$txtName.keyup @keyUp # SHOW AND HIDE # ---------------------------------------------------------------------- # Hide the view using a fade out effect. onHide: => $(document).unbind "keyup", @keyUp SystemApp.footerView.setText null @$el.fadeOut SystemApp.Settings.general.fadeDelay # Show the view using a fade in effect and pass the entity type. # If user has no "mapcreate" role, hide the view immediately. onShow: => if not SystemApp.Data.loggedUser.hasRole "mapcreate" errorMsg = SystemApp.Messages.errNoPermissionTo.replace "#", SystemApp.Messages.createMaps SystemApp.alertEvents.trigger "tooltip", {isError: true, title: SystemApp.Messages.accessDenied, message: errorMsg} # Cancel the view and go to previous screen. cancelShow = => @hide() window.history.back() setTimeout cancelShow, 10 return $(document).keyup @keyUp SystemApp.footerView.setText SystemApp.Messages.createMapText @$el.fadeIn SystemApp.Settings.general.fadeDelay, @focus # Clear and set focus on the textbox. @$txtName.val "" @$txtName.focus() SystemApp.menuEvents.trigger "active:menu", @$menuItem # When user presses a key on the `txtName` field. keyUp: (e) => if e.which is 27 @hide e if e.which is 13 newMapName = $.trim @$txtName.val() existing = SystemApp.Data.maps.where {name: newMapName} if existing.length > 0 errTitle = SystemApp.Messages.errCreatingMap errMessage = SystemApp.Messages.errMapNameExists.replace "#", newMapName SystemApp.alertEvents.trigger "footer", {title: errTitle, message: errMessage, isError: true} @warnField @$txtName return map = SystemApp.Data.maps.create {dateCreated: new Date(), name: <NAME>MapName} @hide() # Change the URL using the new map key. SystemApp.routes.navigate "map/" + map.urlKey(), {trigger: true}
true
# CREATE MAP VIEW # -------------------------------------------------------------------------- # Represents the "Create new map" overlay what shows up when user # clicks a "Create new..." option on the top menu. class SystemApp.CreateMapView extends SystemApp.OverlayView $txtName: null # the text field to enter the new map name $menuItem: null # the top menu DOM element # INIT AND DISPOSE # ---------------------------------------------------------------------- # Init the "Create Map" overlay view. initialize: => @overlayInit "#map-create-overlay" @setDom() @setEvents() # Clear contents and dispose the view. dispose: => @baseDispose() # Set the DOM elements cache. setDom: => @$txtName = $ "#map-create-overlay-name" @$menuItem = $ "#menu-createmap" # Bind events to DOM and other controls. setEvents: => @$txtName.keyup @keyUp # SHOW AND HIDE # ---------------------------------------------------------------------- # Hide the view using a fade out effect. onHide: => $(document).unbind "keyup", @keyUp SystemApp.footerView.setText null @$el.fadeOut SystemApp.Settings.general.fadeDelay # Show the view using a fade in effect and pass the entity type. # If user has no "mapcreate" role, hide the view immediately. onShow: => if not SystemApp.Data.loggedUser.hasRole "mapcreate" errorMsg = SystemApp.Messages.errNoPermissionTo.replace "#", SystemApp.Messages.createMaps SystemApp.alertEvents.trigger "tooltip", {isError: true, title: SystemApp.Messages.accessDenied, message: errorMsg} # Cancel the view and go to previous screen. cancelShow = => @hide() window.history.back() setTimeout cancelShow, 10 return $(document).keyup @keyUp SystemApp.footerView.setText SystemApp.Messages.createMapText @$el.fadeIn SystemApp.Settings.general.fadeDelay, @focus # Clear and set focus on the textbox. @$txtName.val "" @$txtName.focus() SystemApp.menuEvents.trigger "active:menu", @$menuItem # When user presses a key on the `txtName` field. keyUp: (e) => if e.which is 27 @hide e if e.which is 13 newMapName = $.trim @$txtName.val() existing = SystemApp.Data.maps.where {name: newMapName} if existing.length > 0 errTitle = SystemApp.Messages.errCreatingMap errMessage = SystemApp.Messages.errMapNameExists.replace "#", newMapName SystemApp.alertEvents.trigger "footer", {title: errTitle, message: errMessage, isError: true} @warnField @$txtName return map = SystemApp.Data.maps.create {dateCreated: new Date(), name: PI:NAME:<NAME>END_PIMapName} @hide() # Change the URL using the new map key. SystemApp.routes.navigate "map/" + map.urlKey(), {trigger: true}
[ { "context": "and play with the commandline utility parameters\n# Dominique Da Silva / Nov 2014\n\n# 2018 Dec - Added support for Youtub", "end": 188, "score": 0.9998670220375061, "start": 170, "tag": "NAME", "value": "Dominique Da Silva" }, { "context": "\n\n{\n\ncommand: \"\"\"/path/to/ubersicht-youtube -key=\"XXXXXX\" -username=\"channelname\" -position=\"BL|20|120\" -l", "end": 403, "score": 0.9993500709533691, "start": 397, "tag": "KEY", "value": "XXXXXX" }, { "context": "ath/to/ubersicht-youtube -key=\"XXXXXX\" -username=\"channelname\" -position=\"BL|20|120\" -lang=\"FR\" -showname -logo", "end": 427, "score": 0.991053581237793, "start": 416, "tag": "USERNAME", "value": "channelname" }, { "context": "ws\"\n\t\tvideos: \"videos\"\n\t},\n\tFR: {\n\t\tsubscribers: \"abonnés\"\n\t\tviews: \"vues\"\n\t\tvideos: \"vidéos\"\n\t},\n\tPT: {\n\t\t", "end": 2055, "score": 0.9798102378845215, "start": 2048, "tag": "NAME", "value": "abonnés" } ]
Youtube.widget/index.coffee
atika/Ubersicht-Youtube
3
# Ubersicht Youtube widget # Display public statistics of a Youtube User Channel # Change the path to the script below and play with the commandline utility parameters # Dominique Da Silva / Nov 2014 # 2018 Dec - Added support for Youtube API v3 (cli app written in Go lang) # 2014 Nov - A NodeJS app get the stats from a public Youtube feed page { command: """/path/to/ubersicht-youtube -key="XXXXXX" -username="channelname" -position="BL|20|120" -lang="FR" -showname -logored """ refreshFrequency: 3600000 #every hours render: -> """ <div class="icon"></div> <a href="https://www.youtube.com" class="name">Youtube</a> <div class="subscribers"></div> <div class="stats"> <span class="views"> </span><br> <span class="uploads"> </span> </div> """ style: """ width: 290px height: 55px font-family: Helvetica Neue font-size: 13px color: #FFF padding:15px 0px border-radius: 6px .subscribers width: 100px height: 100% font-size:30px line-height:24px text-align:right padding-right: 10px padding-top: 5px border-right: solid 1px rgba(255,255,255,0.2) .label display: block //position: absolute color:rgba(255,255,255,0.3) font-size:12px .stats position: absolute width: 150px left: 120px color:rgba(255,255,255,0.3) top: 35px .views width: 100% height: 25px display: inline-block white-space: nowrap font-size: 1.2em opacity: 0.3 color: #FFF line-height:1.3em span margin: auto b margin: auto font-size: 0.8em .icon width: 50px height: 35px background: url(Youtube.widget/icon.png) no-repeat background-size: 50%; position: absolute left: 120px opacity:0.1 .icon.red background: url(Youtube.widget/icon-red.png) no-repeat background-size: 50%; .error color: red a.name text-decoration: none color: #FFF opacity: 0.1 position: absolute top: 16px left: 151px a.name:hover color:red """ lang: { US: { subscribers: "subscribers" views: "views" videos: "videos" }, FR: { subscribers: "abonnés" views: "vues" videos: "vidéos" }, PT: { subscribers: "subscritores" views: "visualizações" videos: "vídeos" } } toggleView: (m, domEl) -> language = m.lang[m.youtube.theme.lang] || m.lang['US'] if m.timer clearTimeout m.timer m.timer = undefined if m.t ct = '<span>' + m.youtube.statsf.subscribers2 + '</span> <b>' + language.subscribers + '</b>' delay = 10000 else ct = '<span>' + m.youtube.statsf.views + '</span> <b>' + language.views + '</b>' delay = 40000 m.t = !m.t # Animate st = $(domEl).find('.stats .views') st.stop(true, true).animate { 'opacity': 0.0 }, 350, () -> st.html(ct) .delay(100).animate({ 'opacity': 1.0 }, 1000) m.timer = setTimeout m.toggleView, delay, m, domEl update: (output, domEl) -> m = @ try @youtube = JSON.parse(output) catch e return $(domEl).html("<b class=\"error\">YouTube Widget</b>: " + e) language = @lang[@youtube.theme.lang] || @lang['US'] position = @youtube.theme.position.split("|") if @timer clearTimeout @timer @timer = undefined @t = false # Theme switch position[0] when "TL" $(domEl).css({ 'left': parseInt(position[1]), 'top': parseInt(position[2]) }) when "TR" $(domEl).css({ 'right': parseInt(position[1]), 'top': parseInt(position[2]) }) when "BR" $(domEl).css({ 'right': parseInt(position[1]), 'bottom': parseInt(position[2]) }) when "C" ww = $(window).width() wdw = $(domEl).width() wdh = $(window).height() $(domEl).css({ 'left': (ww / 2) - (wdw / 2), 'top': (wdh / 2 - 50) }) else $(domEl).css({ 'left': parseInt(position[1]), 'bottom': parseInt(position[2]) }) $(domEl).css('background-color', @youtube.theme.back_color) if @youtube.theme.back_color != '' if @youtube.error return $(domEl).html("<b class=\"error\">YouTube Widget Error</b><br>" + @youtube.error) # Populate and animate $(domEl).find('.subscribers') .animate { 'opacity': 0.4 }, 400 .html @youtube.statsf.subscribers + ' <span class="label">' + language.subscribers + '</span>' .animate { 'opacity': 1 }, 300 @toggleView(@, domEl) $(domEl).find('.icon').addClass('red') if @youtube.theme.logo_red $(domEl).find('.uploads').html @youtube.statsf.uploads + ' ' + language.videos $(domEl).find('.name').attr 'href', 'https://www.youtube.com/user/' + @youtube.user $(domEl).find('.name').html(@youtube.displayname) if @youtube.theme.show_name $(domEl).find('.icon, .name') .animate { 'opacity': 1.0 }, 500 .delay(500).animate { 'opacity': @youtube.theme.logo_alpha }, 250 $(domEl).find('.stats').on 'click', () -> m.toggleView m, domEl }
124557
# Ubersicht Youtube widget # Display public statistics of a Youtube User Channel # Change the path to the script below and play with the commandline utility parameters # <NAME> / Nov 2014 # 2018 Dec - Added support for Youtube API v3 (cli app written in Go lang) # 2014 Nov - A NodeJS app get the stats from a public Youtube feed page { command: """/path/to/ubersicht-youtube -key="<KEY>" -username="channelname" -position="BL|20|120" -lang="FR" -showname -logored """ refreshFrequency: 3600000 #every hours render: -> """ <div class="icon"></div> <a href="https://www.youtube.com" class="name">Youtube</a> <div class="subscribers"></div> <div class="stats"> <span class="views"> </span><br> <span class="uploads"> </span> </div> """ style: """ width: 290px height: 55px font-family: Helvetica Neue font-size: 13px color: #FFF padding:15px 0px border-radius: 6px .subscribers width: 100px height: 100% font-size:30px line-height:24px text-align:right padding-right: 10px padding-top: 5px border-right: solid 1px rgba(255,255,255,0.2) .label display: block //position: absolute color:rgba(255,255,255,0.3) font-size:12px .stats position: absolute width: 150px left: 120px color:rgba(255,255,255,0.3) top: 35px .views width: 100% height: 25px display: inline-block white-space: nowrap font-size: 1.2em opacity: 0.3 color: #FFF line-height:1.3em span margin: auto b margin: auto font-size: 0.8em .icon width: 50px height: 35px background: url(Youtube.widget/icon.png) no-repeat background-size: 50%; position: absolute left: 120px opacity:0.1 .icon.red background: url(Youtube.widget/icon-red.png) no-repeat background-size: 50%; .error color: red a.name text-decoration: none color: #FFF opacity: 0.1 position: absolute top: 16px left: 151px a.name:hover color:red """ lang: { US: { subscribers: "subscribers" views: "views" videos: "videos" }, FR: { subscribers: "<NAME>" views: "vues" videos: "vidéos" }, PT: { subscribers: "subscritores" views: "visualizações" videos: "vídeos" } } toggleView: (m, domEl) -> language = m.lang[m.youtube.theme.lang] || m.lang['US'] if m.timer clearTimeout m.timer m.timer = undefined if m.t ct = '<span>' + m.youtube.statsf.subscribers2 + '</span> <b>' + language.subscribers + '</b>' delay = 10000 else ct = '<span>' + m.youtube.statsf.views + '</span> <b>' + language.views + '</b>' delay = 40000 m.t = !m.t # Animate st = $(domEl).find('.stats .views') st.stop(true, true).animate { 'opacity': 0.0 }, 350, () -> st.html(ct) .delay(100).animate({ 'opacity': 1.0 }, 1000) m.timer = setTimeout m.toggleView, delay, m, domEl update: (output, domEl) -> m = @ try @youtube = JSON.parse(output) catch e return $(domEl).html("<b class=\"error\">YouTube Widget</b>: " + e) language = @lang[@youtube.theme.lang] || @lang['US'] position = @youtube.theme.position.split("|") if @timer clearTimeout @timer @timer = undefined @t = false # Theme switch position[0] when "TL" $(domEl).css({ 'left': parseInt(position[1]), 'top': parseInt(position[2]) }) when "TR" $(domEl).css({ 'right': parseInt(position[1]), 'top': parseInt(position[2]) }) when "BR" $(domEl).css({ 'right': parseInt(position[1]), 'bottom': parseInt(position[2]) }) when "C" ww = $(window).width() wdw = $(domEl).width() wdh = $(window).height() $(domEl).css({ 'left': (ww / 2) - (wdw / 2), 'top': (wdh / 2 - 50) }) else $(domEl).css({ 'left': parseInt(position[1]), 'bottom': parseInt(position[2]) }) $(domEl).css('background-color', @youtube.theme.back_color) if @youtube.theme.back_color != '' if @youtube.error return $(domEl).html("<b class=\"error\">YouTube Widget Error</b><br>" + @youtube.error) # Populate and animate $(domEl).find('.subscribers') .animate { 'opacity': 0.4 }, 400 .html @youtube.statsf.subscribers + ' <span class="label">' + language.subscribers + '</span>' .animate { 'opacity': 1 }, 300 @toggleView(@, domEl) $(domEl).find('.icon').addClass('red') if @youtube.theme.logo_red $(domEl).find('.uploads').html @youtube.statsf.uploads + ' ' + language.videos $(domEl).find('.name').attr 'href', 'https://www.youtube.com/user/' + @youtube.user $(domEl).find('.name').html(@youtube.displayname) if @youtube.theme.show_name $(domEl).find('.icon, .name') .animate { 'opacity': 1.0 }, 500 .delay(500).animate { 'opacity': @youtube.theme.logo_alpha }, 250 $(domEl).find('.stats').on 'click', () -> m.toggleView m, domEl }
true
# Ubersicht Youtube widget # Display public statistics of a Youtube User Channel # Change the path to the script below and play with the commandline utility parameters # PI:NAME:<NAME>END_PI / Nov 2014 # 2018 Dec - Added support for Youtube API v3 (cli app written in Go lang) # 2014 Nov - A NodeJS app get the stats from a public Youtube feed page { command: """/path/to/ubersicht-youtube -key="PI:KEY:<KEY>END_PI" -username="channelname" -position="BL|20|120" -lang="FR" -showname -logored """ refreshFrequency: 3600000 #every hours render: -> """ <div class="icon"></div> <a href="https://www.youtube.com" class="name">Youtube</a> <div class="subscribers"></div> <div class="stats"> <span class="views"> </span><br> <span class="uploads"> </span> </div> """ style: """ width: 290px height: 55px font-family: Helvetica Neue font-size: 13px color: #FFF padding:15px 0px border-radius: 6px .subscribers width: 100px height: 100% font-size:30px line-height:24px text-align:right padding-right: 10px padding-top: 5px border-right: solid 1px rgba(255,255,255,0.2) .label display: block //position: absolute color:rgba(255,255,255,0.3) font-size:12px .stats position: absolute width: 150px left: 120px color:rgba(255,255,255,0.3) top: 35px .views width: 100% height: 25px display: inline-block white-space: nowrap font-size: 1.2em opacity: 0.3 color: #FFF line-height:1.3em span margin: auto b margin: auto font-size: 0.8em .icon width: 50px height: 35px background: url(Youtube.widget/icon.png) no-repeat background-size: 50%; position: absolute left: 120px opacity:0.1 .icon.red background: url(Youtube.widget/icon-red.png) no-repeat background-size: 50%; .error color: red a.name text-decoration: none color: #FFF opacity: 0.1 position: absolute top: 16px left: 151px a.name:hover color:red """ lang: { US: { subscribers: "subscribers" views: "views" videos: "videos" }, FR: { subscribers: "PI:NAME:<NAME>END_PI" views: "vues" videos: "vidéos" }, PT: { subscribers: "subscritores" views: "visualizações" videos: "vídeos" } } toggleView: (m, domEl) -> language = m.lang[m.youtube.theme.lang] || m.lang['US'] if m.timer clearTimeout m.timer m.timer = undefined if m.t ct = '<span>' + m.youtube.statsf.subscribers2 + '</span> <b>' + language.subscribers + '</b>' delay = 10000 else ct = '<span>' + m.youtube.statsf.views + '</span> <b>' + language.views + '</b>' delay = 40000 m.t = !m.t # Animate st = $(domEl).find('.stats .views') st.stop(true, true).animate { 'opacity': 0.0 }, 350, () -> st.html(ct) .delay(100).animate({ 'opacity': 1.0 }, 1000) m.timer = setTimeout m.toggleView, delay, m, domEl update: (output, domEl) -> m = @ try @youtube = JSON.parse(output) catch e return $(domEl).html("<b class=\"error\">YouTube Widget</b>: " + e) language = @lang[@youtube.theme.lang] || @lang['US'] position = @youtube.theme.position.split("|") if @timer clearTimeout @timer @timer = undefined @t = false # Theme switch position[0] when "TL" $(domEl).css({ 'left': parseInt(position[1]), 'top': parseInt(position[2]) }) when "TR" $(domEl).css({ 'right': parseInt(position[1]), 'top': parseInt(position[2]) }) when "BR" $(domEl).css({ 'right': parseInt(position[1]), 'bottom': parseInt(position[2]) }) when "C" ww = $(window).width() wdw = $(domEl).width() wdh = $(window).height() $(domEl).css({ 'left': (ww / 2) - (wdw / 2), 'top': (wdh / 2 - 50) }) else $(domEl).css({ 'left': parseInt(position[1]), 'bottom': parseInt(position[2]) }) $(domEl).css('background-color', @youtube.theme.back_color) if @youtube.theme.back_color != '' if @youtube.error return $(domEl).html("<b class=\"error\">YouTube Widget Error</b><br>" + @youtube.error) # Populate and animate $(domEl).find('.subscribers') .animate { 'opacity': 0.4 }, 400 .html @youtube.statsf.subscribers + ' <span class="label">' + language.subscribers + '</span>' .animate { 'opacity': 1 }, 300 @toggleView(@, domEl) $(domEl).find('.icon').addClass('red') if @youtube.theme.logo_red $(domEl).find('.uploads').html @youtube.statsf.uploads + ' ' + language.videos $(domEl).find('.name').attr 'href', 'https://www.youtube.com/user/' + @youtube.user $(domEl).find('.name').html(@youtube.displayname) if @youtube.theme.show_name $(domEl).find('.icon, .name') .animate { 'opacity': 1.0 }, 500 .delay(500).animate { 'opacity': @youtube.theme.logo_alpha }, 250 $(domEl).find('.stats').on 'click', () -> m.toggleView m, domEl }
[ { "context": "/utils/lookup'`\n\n\napplication = null\n\nTESTPASS = 'Pa$$w0rd'\n\nmodule('Integration: enroll',\n\n setup: (assert", "end": 288, "score": 0.9994516372680664, "start": 280, "tag": "PASSWORD", "value": "Pa$$w0rd" } ]
tests/acceptance/wallet/enroll-test.coffee
melis-wallet/melis-cm-client
1
`import { module, test, skip, moduleFor } from 'qunit'` `import Ember from 'ember'` `import config from '../../../config/environment'` `import startApp from '../../helpers/start-app'` `import { lookupService } from '../../helpers/utils/lookup'` application = null TESTPASS = 'Pa$$w0rd' module('Integration: enroll', setup: (assert)-> application = startApp() session = lookupService(application, 'cm-session') session.waitForConnect() teardown: -> Ember.run(application, 'destroy') ) test 'ready for tests', (assert) -> visit '/wallet/enroll' andThen( -> Ember.run.later (-> assert.ok find('#start_enroll') find('#start_enroll').click() ), 500 ) andThen( -> expectElement('#generated_mnemonic') find('#qr_switcher').click() ) andThen( -> expectElement('#generated_mnemonic_qr') find('#done_mnemonics').click() ) andThen( -> expectElement('#pass_input') expectNoElement('#submit-passphrase') find('#pass_input > input').val('foo').trigger('focusout') ) andThen( -> expectElement('#pass_input.has-error') find('#pass_input > input').val(TESTPASS).trigger('focusout') ) andThen( -> expectElement('#pass_input.has-success') find('#pass_check > input').val(TESTPASS).trigger('focusout') ) andThen(-> expectElement('#submit-passphrase') find('#submit-passphrase').click() ) andThen(-> expectElement('#enroll-progress') )
154065
`import { module, test, skip, moduleFor } from 'qunit'` `import Ember from 'ember'` `import config from '../../../config/environment'` `import startApp from '../../helpers/start-app'` `import { lookupService } from '../../helpers/utils/lookup'` application = null TESTPASS = '<PASSWORD>' module('Integration: enroll', setup: (assert)-> application = startApp() session = lookupService(application, 'cm-session') session.waitForConnect() teardown: -> Ember.run(application, 'destroy') ) test 'ready for tests', (assert) -> visit '/wallet/enroll' andThen( -> Ember.run.later (-> assert.ok find('#start_enroll') find('#start_enroll').click() ), 500 ) andThen( -> expectElement('#generated_mnemonic') find('#qr_switcher').click() ) andThen( -> expectElement('#generated_mnemonic_qr') find('#done_mnemonics').click() ) andThen( -> expectElement('#pass_input') expectNoElement('#submit-passphrase') find('#pass_input > input').val('foo').trigger('focusout') ) andThen( -> expectElement('#pass_input.has-error') find('#pass_input > input').val(TESTPASS).trigger('focusout') ) andThen( -> expectElement('#pass_input.has-success') find('#pass_check > input').val(TESTPASS).trigger('focusout') ) andThen(-> expectElement('#submit-passphrase') find('#submit-passphrase').click() ) andThen(-> expectElement('#enroll-progress') )
true
`import { module, test, skip, moduleFor } from 'qunit'` `import Ember from 'ember'` `import config from '../../../config/environment'` `import startApp from '../../helpers/start-app'` `import { lookupService } from '../../helpers/utils/lookup'` application = null TESTPASS = 'PI:PASSWORD:<PASSWORD>END_PI' module('Integration: enroll', setup: (assert)-> application = startApp() session = lookupService(application, 'cm-session') session.waitForConnect() teardown: -> Ember.run(application, 'destroy') ) test 'ready for tests', (assert) -> visit '/wallet/enroll' andThen( -> Ember.run.later (-> assert.ok find('#start_enroll') find('#start_enroll').click() ), 500 ) andThen( -> expectElement('#generated_mnemonic') find('#qr_switcher').click() ) andThen( -> expectElement('#generated_mnemonic_qr') find('#done_mnemonics').click() ) andThen( -> expectElement('#pass_input') expectNoElement('#submit-passphrase') find('#pass_input > input').val('foo').trigger('focusout') ) andThen( -> expectElement('#pass_input.has-error') find('#pass_input > input').val(TESTPASS).trigger('focusout') ) andThen( -> expectElement('#pass_input.has-success') find('#pass_check > input').val(TESTPASS).trigger('focusout') ) andThen(-> expectElement('#submit-passphrase') find('#submit-passphrase').click() ) andThen(-> expectElement('#enroll-progress') )
[ { "context": "isplay: 'Artist page', model: 'artist', display: 'zoe leonard' }\n { display: 'Partner Show Page', model:", "end": 366, "score": 0.9976785778999329, "start": 355, "tag": "NAME", "value": "zoe leonard" } ]
src/desktop/apps/search/test/collections/global_search_results.coffee
streamich/force
1
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' GlobalSearchResults = require '../../collections/global_search_results.coffee' describe 'GlobalSearchResults', -> describe '#parse', -> beforeEach -> @response = [ { display: 'Artist page', model: 'artist', display: 'zoe leonard' } { display: 'Partner Show Page', model: 'partnershow', venue: 'Foo Gallery' } ] it 'filters out sensitive results', -> results = new GlobalSearchResults @response, parse: true results.length.should.equal 1 describe '#moveMatchResultsToTop', -> it 'moves matching results to the top', -> results = new GlobalSearchResults [ { display: 'bar bar', model: 'fair' } { display: 'foo bar', model: 'fair' } ] results.first().get('display').should.equal 'bar bar' results.moveMatchResultsToTop 'foo bar' results.first().get('display').should.equal 'foo bar'
214804
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' GlobalSearchResults = require '../../collections/global_search_results.coffee' describe 'GlobalSearchResults', -> describe '#parse', -> beforeEach -> @response = [ { display: 'Artist page', model: 'artist', display: '<NAME>' } { display: 'Partner Show Page', model: 'partnershow', venue: 'Foo Gallery' } ] it 'filters out sensitive results', -> results = new GlobalSearchResults @response, parse: true results.length.should.equal 1 describe '#moveMatchResultsToTop', -> it 'moves matching results to the top', -> results = new GlobalSearchResults [ { display: 'bar bar', model: 'fair' } { display: 'foo bar', model: 'fair' } ] results.first().get('display').should.equal 'bar bar' results.moveMatchResultsToTop 'foo bar' results.first().get('display').should.equal 'foo bar'
true
_ = require 'underscore' sinon = require 'sinon' Backbone = require 'backbone' { fabricate } = require 'antigravity' GlobalSearchResults = require '../../collections/global_search_results.coffee' describe 'GlobalSearchResults', -> describe '#parse', -> beforeEach -> @response = [ { display: 'Artist page', model: 'artist', display: 'PI:NAME:<NAME>END_PI' } { display: 'Partner Show Page', model: 'partnershow', venue: 'Foo Gallery' } ] it 'filters out sensitive results', -> results = new GlobalSearchResults @response, parse: true results.length.should.equal 1 describe '#moveMatchResultsToTop', -> it 'moves matching results to the top', -> results = new GlobalSearchResults [ { display: 'bar bar', model: 'fair' } { display: 'foo bar', model: 'fair' } ] results.first().get('display').should.equal 'bar bar' results.moveMatchResultsToTop 'foo bar' results.first().get('display').should.equal 'foo bar'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.999192476272583, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-readdouble.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. # # * Tests to verify we're reading in doubles correctly # # # * Test (64 bit) double # test = (clazz) -> buffer = new clazz(8) buffer[0] = 0x55 buffer[1] = 0x55 buffer[2] = 0x55 buffer[3] = 0x55 buffer[4] = 0x55 buffer[5] = 0x55 buffer[6] = 0xd5 buffer[7] = 0x3f ASSERT.equal 1.1945305291680097e+103, buffer.readDoubleBE(0) ASSERT.equal 0.3333333333333333, buffer.readDoubleLE(0) buffer[0] = 1 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 7.291122019655968e-304, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000002, buffer.readDoubleLE(0) buffer[0] = 2 ASSERT.equal 4.778309726801735e-299, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000004, buffer.readDoubleLE(0) buffer[0] = 1 buffer[6] = 0 buffer[7] = 0 ASSERT.equal 7.291122019556398e-304, buffer.readDoubleBE(0) ASSERT.equal 5e-324, buffer.readDoubleLE(0) buffer[0] = 0xff buffer[1] = 0xff buffer[2] = 0xff buffer[3] = 0xff buffer[4] = 0xff buffer[5] = 0xff buffer[6] = 0x0f buffer[7] = 0x00 ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 2.225073858507201e-308, buffer.readDoubleLE(0) buffer[6] = 0xef buffer[7] = 0x7f ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 1.7976931348623157e+308, buffer.readDoubleLE(0) buffer[0] = 0 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 3.03865e-319, buffer.readDoubleBE(0) ASSERT.equal 1, buffer.readDoubleLE(0) buffer[6] = 0 buffer[7] = 0x40 ASSERT.equal 3.16e-322, buffer.readDoubleBE(0) ASSERT.equal 2, buffer.readDoubleLE(0) buffer[7] = 0xc0 ASSERT.equal 9.5e-322, buffer.readDoubleBE(0) ASSERT.equal -2, buffer.readDoubleLE(0) buffer[6] = 0x10 buffer[7] = 0 ASSERT.equal 2.0237e-320, buffer.readDoubleBE(0) ASSERT.equal 2.2250738585072014e-308, buffer.readDoubleLE(0) buffer[6] = 0 ASSERT.equal 0, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal false, 1 / buffer.readDoubleLE(0) < 0 buffer[7] = 0x80 ASSERT.equal 6.3e-322, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal true, 1 / buffer.readDoubleLE(0) < 0 buffer[6] = 0xf0 buffer[7] = 0x7f ASSERT.equal 3.0418e-319, buffer.readDoubleBE(0) ASSERT.equal Infinity, buffer.readDoubleLE(0) buffer[6] = 0xf0 buffer[7] = 0xff ASSERT.equal 3.04814e-319, buffer.readDoubleBE(0) ASSERT.equal -Infinity, buffer.readDoubleLE(0) return common = require("../common") ASSERT = require("assert") test Buffer
142704
# 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. # # * Tests to verify we're reading in doubles correctly # # # * Test (64 bit) double # test = (clazz) -> buffer = new clazz(8) buffer[0] = 0x55 buffer[1] = 0x55 buffer[2] = 0x55 buffer[3] = 0x55 buffer[4] = 0x55 buffer[5] = 0x55 buffer[6] = 0xd5 buffer[7] = 0x3f ASSERT.equal 1.1945305291680097e+103, buffer.readDoubleBE(0) ASSERT.equal 0.3333333333333333, buffer.readDoubleLE(0) buffer[0] = 1 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 7.291122019655968e-304, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000002, buffer.readDoubleLE(0) buffer[0] = 2 ASSERT.equal 4.778309726801735e-299, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000004, buffer.readDoubleLE(0) buffer[0] = 1 buffer[6] = 0 buffer[7] = 0 ASSERT.equal 7.291122019556398e-304, buffer.readDoubleBE(0) ASSERT.equal 5e-324, buffer.readDoubleLE(0) buffer[0] = 0xff buffer[1] = 0xff buffer[2] = 0xff buffer[3] = 0xff buffer[4] = 0xff buffer[5] = 0xff buffer[6] = 0x0f buffer[7] = 0x00 ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 2.225073858507201e-308, buffer.readDoubleLE(0) buffer[6] = 0xef buffer[7] = 0x7f ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 1.7976931348623157e+308, buffer.readDoubleLE(0) buffer[0] = 0 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 3.03865e-319, buffer.readDoubleBE(0) ASSERT.equal 1, buffer.readDoubleLE(0) buffer[6] = 0 buffer[7] = 0x40 ASSERT.equal 3.16e-322, buffer.readDoubleBE(0) ASSERT.equal 2, buffer.readDoubleLE(0) buffer[7] = 0xc0 ASSERT.equal 9.5e-322, buffer.readDoubleBE(0) ASSERT.equal -2, buffer.readDoubleLE(0) buffer[6] = 0x10 buffer[7] = 0 ASSERT.equal 2.0237e-320, buffer.readDoubleBE(0) ASSERT.equal 2.2250738585072014e-308, buffer.readDoubleLE(0) buffer[6] = 0 ASSERT.equal 0, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal false, 1 / buffer.readDoubleLE(0) < 0 buffer[7] = 0x80 ASSERT.equal 6.3e-322, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal true, 1 / buffer.readDoubleLE(0) < 0 buffer[6] = 0xf0 buffer[7] = 0x7f ASSERT.equal 3.0418e-319, buffer.readDoubleBE(0) ASSERT.equal Infinity, buffer.readDoubleLE(0) buffer[6] = 0xf0 buffer[7] = 0xff ASSERT.equal 3.04814e-319, buffer.readDoubleBE(0) ASSERT.equal -Infinity, buffer.readDoubleLE(0) return common = require("../common") ASSERT = require("assert") test Buffer
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. # # * Tests to verify we're reading in doubles correctly # # # * Test (64 bit) double # test = (clazz) -> buffer = new clazz(8) buffer[0] = 0x55 buffer[1] = 0x55 buffer[2] = 0x55 buffer[3] = 0x55 buffer[4] = 0x55 buffer[5] = 0x55 buffer[6] = 0xd5 buffer[7] = 0x3f ASSERT.equal 1.1945305291680097e+103, buffer.readDoubleBE(0) ASSERT.equal 0.3333333333333333, buffer.readDoubleLE(0) buffer[0] = 1 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 7.291122019655968e-304, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000002, buffer.readDoubleLE(0) buffer[0] = 2 ASSERT.equal 4.778309726801735e-299, buffer.readDoubleBE(0) ASSERT.equal 1.0000000000000004, buffer.readDoubleLE(0) buffer[0] = 1 buffer[6] = 0 buffer[7] = 0 ASSERT.equal 7.291122019556398e-304, buffer.readDoubleBE(0) ASSERT.equal 5e-324, buffer.readDoubleLE(0) buffer[0] = 0xff buffer[1] = 0xff buffer[2] = 0xff buffer[3] = 0xff buffer[4] = 0xff buffer[5] = 0xff buffer[6] = 0x0f buffer[7] = 0x00 ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 2.225073858507201e-308, buffer.readDoubleLE(0) buffer[6] = 0xef buffer[7] = 0x7f ASSERT.ok isNaN(buffer.readDoubleBE(0)) ASSERT.equal 1.7976931348623157e+308, buffer.readDoubleLE(0) buffer[0] = 0 buffer[1] = 0 buffer[2] = 0 buffer[3] = 0 buffer[4] = 0 buffer[5] = 0 buffer[6] = 0xf0 buffer[7] = 0x3f ASSERT.equal 3.03865e-319, buffer.readDoubleBE(0) ASSERT.equal 1, buffer.readDoubleLE(0) buffer[6] = 0 buffer[7] = 0x40 ASSERT.equal 3.16e-322, buffer.readDoubleBE(0) ASSERT.equal 2, buffer.readDoubleLE(0) buffer[7] = 0xc0 ASSERT.equal 9.5e-322, buffer.readDoubleBE(0) ASSERT.equal -2, buffer.readDoubleLE(0) buffer[6] = 0x10 buffer[7] = 0 ASSERT.equal 2.0237e-320, buffer.readDoubleBE(0) ASSERT.equal 2.2250738585072014e-308, buffer.readDoubleLE(0) buffer[6] = 0 ASSERT.equal 0, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal false, 1 / buffer.readDoubleLE(0) < 0 buffer[7] = 0x80 ASSERT.equal 6.3e-322, buffer.readDoubleBE(0) ASSERT.equal 0, buffer.readDoubleLE(0) ASSERT.equal true, 1 / buffer.readDoubleLE(0) < 0 buffer[6] = 0xf0 buffer[7] = 0x7f ASSERT.equal 3.0418e-319, buffer.readDoubleBE(0) ASSERT.equal Infinity, buffer.readDoubleLE(0) buffer[6] = 0xf0 buffer[7] = 0xff ASSERT.equal 3.04814e-319, buffer.readDoubleBE(0) ASSERT.equal -Infinity, buffer.readDoubleLE(0) return common = require("../common") ASSERT = require("assert") test Buffer
[ { "context": "ge in backend\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Original page design :\n# IonizeCMS ", "end": 86, "score": 0.9994423389434814, "start": 80, "tag": "USERNAME", "value": "nodize" }, { "context": " IonizeCMS (http://www.ionizecms.com), \n# (c) Partikule (http://www.partikule.net)\n#\n# CoffeeKup conve", "end": 177, "score": 0.6003641486167908, "start": 175, "tag": "NAME", "value": "ik" }, { "context": "e: \"usersFilter\", method: \"post\", action: \"http://192.168.1.162/admin/users/users_list\", ->\n # \"", "end": 1932, "score": 0.9993541240692139, "start": 1919, "tag": "IP_ADDRESS", "value": "192.168.1.162" }, { "context": "er_username.inputtext.w140\", type: \"text\", name: \"username\", value: \"\"\n # \"Screen name\"\n ", "end": 3059, "score": 0.9992127418518066, "start": 3051, "tag": "USERNAME", "value": "username" }, { "context": "e: \"newUserForm\", method: \"post\", action: \"http://192.168.1.162/admin/users/save\", ->\n # \"Userna", "end": 4423, "score": 0.9685019850730896, "start": 4410, "tag": "IP_ADDRESS", "value": "192.168.1.162" }, { "context": " dt ->\n label for: \"username\", -> @ion_lang.ionize_label_username\n ", "end": 4579, "score": 0.9979631900787354, "start": 4571, "tag": "USERNAME", "value": "username" }, { "context": " input \"#username.inputtext.w140\", name: \"username\", type: \"text\", value: \"\"\n # \"Sc", "end": 4714, "score": 0.9992019534111023, "start": 4706, "tag": "USERNAME", "value": "username" } ]
modules/backend/inline_views/view_users.coffee
nodize/nodizecms
32
# Users / groups management page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) Partikule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Displaying users management page # @view backend_users: -> html -> div "#maincolumn", -> h2 "#main-title.main.groups", @ion_lang.ionize_title_users # ------------------------------ # Tabs definition # ------------------------------ div "#usersTab.mainTabs.mt20", -> ul ".tab-menu", -> li "#usersListTab", -> a @ion_lang.ionize_title_existing_users li -> a @ion_lang.ionize_title_existing_groups div class:"clear" # ------------------------------ # List of existing users # ------------------------------ div "#usersTabContent", -> div ".tabcontent", -> div ".tabsidecolumn", -> # "Infos about all users" div ".info.mb10", -> # # Displaying user count & last registered user # Not implemented yet # # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_users_count # dd "1" # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_last_registered # dd() h3 ".toggler1", @ion_lang.ionize_title_filter_userslist div ".element1", -> # "User list filter" form "#usersFilter", name: "usersFilter", method: "post", action: "http://192.168.1.162/admin/users/users_list", -> # "Users / page" dl ".small", -> dt -> label for: "filter_nb", -> @ion_lang.ionize_label_users_per_page dd -> input "#filter_nb.inputtext.w60", type: "text", name: "nb", value: 50 # "Group" dl ".small", -> dt -> label for: "filter_id_group", -> @ion_lang.ionize_label_group dd -> select "#filter_slug.select", name: "slug", -> option value: "", -> @ion_lang.ionize_label_all_groups for user_group in @user_groups option value: user_group.slug, -> user_group.group_name # "ID" dl ".small", -> dt -> label for: "filter_username", -> @ion_lang.ionize_label_username dd -> input "#filter_username.inputtext.w140", type: "text", name: "username", value: "" # "Screen name" dl ".small", -> dt -> label for: "filter_screenname", -> @ion_lang.ionize_label_screen_name dd -> input "#filter_screenname.inputtext.w140", type: "text", name: "screenname", value: "" # "Email" dl ".small", -> dt -> label for: "filter_email", -> @ion_lang.ionize_label_email dd -> input "#filter_email.inputtext.w140", type: "text", name: "email", value: "" # "Last registered" dl ".small", -> dt -> label for: "filter_registered", -> @ion_lang.ionize_label_last_registered dd -> input "#filter_registered.inputcheckbox", type: "checkbox", name: "registered", value: 1 # "Submit" dl ".small", -> dt "&#160;" dd -> input "#submit_filter.submit", type: "submit", value: "Filter" h3 ".toggler1", @ion_lang.ionize_title_add_user div ".element1", -> form "#newUserForm", name: "newUserForm", method: "post", action: "http://192.168.1.162/admin/users/save", -> # "Username" dl ".small", -> dt -> label for: "username", -> @ion_lang.ionize_label_username dd -> input "#username.inputtext.w140", name: "username", type: "text", value: "" # "Screen name" dl ".small", -> dt -> label for: "screen_name", -> @ion_lang.ionize_label_screen_name dd -> input "#screen_name.inputtext.w140", name: "screen_name", type: "text", value: "" # "Group" dl ".small", -> dt -> label for: "group_FK", -> @ion_lang.ionize_label_group dd -> select ".select", name: "id_group", -> for user_group in @user_groups option value: user_group.id_group, -> user_group.group_name # "Email" dl ".small", -> dt -> label for: "email", -> @ion_lang.ionize_label_email dd -> input "#email.inputtext.w140", name: "email", type: "text", value: "" # "Password" dl ".small", -> dt -> label for: "password", -> @ion_lang.ionize_label_password dd -> input "#password.inputtext.w120", name: "password", type: "password", value: "" # "Password confirm" dl ".small", -> dt -> label for: "password2", -> @ion_lang.ionize_label_password2 dd -> input "#password2.inputtext.w120", name: "password2", type: "password", value: "" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_user.submit", type: "submit", value: @ion_lang.ionize_button_save # "Users list" div ".tabcolumn", -> div id:"usersList" # ------------------------------ # Groups # ------------------------------ div ".tabcontent", -> # # "New group" box # div ".tabsidecolumn", -> h3 @ion_lang.ionize_title_add_group form "#newGroupForm", name: "newGroupForm", method: "post", action: "/admin/groups/save", -> # "Group name" dl ".small", -> dt -> label for: "group_name", -> @ion_lang.ionize_label_group_name dd -> input "#slug.inputtext.w140", name: "group_name", type: "text", value: "" # "Level" dl ".small", -> dt -> label for: "level", -> @ion_lang.ionize_label_group_level dd -> input "#slug.inputtext.w140", name: "level", type: "text", value: "100" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_group.submit", type: "submit", value: "Save" # # "Groups list" # div ".tabcolumn", -> table "#groupsTable.list", -> thead -> tr -> th axis: "string", -> @ion_lang.ionize_label_id th axis: "string", -> @ion_lang.ionize_label_group_name #th axis: "string", -> @ion_lang.ionize_label_group_title th axis: "string", -> @ion_lang.ionize_label_group_level #th axis: "string", -> @ion_lang.ionize_label_group_description th() tbody -> for user_group in @user_groups tr ".groups#{user_group.id}", -> td user_group.id td -> a "#group#{user_group.id}.group", rel: user_group.id, href: @lang+"/admin/groups/edit/"+user_group.id, -> user_group.group_name #td user_group.group_name td user_group.level # td() td -> a ".icon.delete", rel:user_group.id_group # /maincolumn coffeescript -> # # Panel toolbox # ION.initToolbox "empty_toolbox" # # Options Accordion # ION.initAccordion ".toggler1", "div.element1", false, "usersAccordion" # # Tabs init # usersTabSwapper = new TabSwapper( tabsContainer: "usersTab" sectionsContainer: "usersTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "usersTab" ) # # Users list tab # $("usersListTab").addEvent "click", -> unless @retrieve("loaded") ION.updateElement url: "users\/\/users_list" element: "usersList" # # Init help tips on label # $("usersListTab").fireEvent "click" ION.initLabelHelpLinks "#newUserForm" ION.initLabelHelpLinks "#newGroupForm" # # New user form action # see init.js for more information about this method # ION.setFormSubmit "newUserForm", "submit_new_user", "users\/\/save" ION.setFormSubmit "newGroupForm", "submit_new_group", "groups\/\/save" # # Filter users list # $("submit_filter").addEvent "click", (e) -> e.stop() new Request.HTML( url: admin_url + "users\/\/users_list" method: "post" loadMethod: "xhr" data: $("usersFilter") update: $("usersList") onRequest: -> MUI.showSpinner() onFailure: (xhr) -> MUI.hideSpinner() onComplete: -> MUI.hideSpinner() ).send() # # Events to each group # Opens an edition window # $$(".group").each (item) -> item.addEvent "click", (e) -> e.stop() id = item.getProperty("rel") ION.formWindow id, "groupForm", "ionize_title_group_edit", "groups\/\/edit\/" + id, width: 340 height: 230 # # Groups itemManager # groupsManager = new ION.ItemManager( container: "groupsTable" element: "groups" ) # # Adds Sortable function to the user list table # new SortableTable("groupsTable", sortOn: 3 sortBy: "ASC" )
10460
# Users / groups management page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) Part<NAME>ule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Displaying users management page # @view backend_users: -> html -> div "#maincolumn", -> h2 "#main-title.main.groups", @ion_lang.ionize_title_users # ------------------------------ # Tabs definition # ------------------------------ div "#usersTab.mainTabs.mt20", -> ul ".tab-menu", -> li "#usersListTab", -> a @ion_lang.ionize_title_existing_users li -> a @ion_lang.ionize_title_existing_groups div class:"clear" # ------------------------------ # List of existing users # ------------------------------ div "#usersTabContent", -> div ".tabcontent", -> div ".tabsidecolumn", -> # "Infos about all users" div ".info.mb10", -> # # Displaying user count & last registered user # Not implemented yet # # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_users_count # dd "1" # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_last_registered # dd() h3 ".toggler1", @ion_lang.ionize_title_filter_userslist div ".element1", -> # "User list filter" form "#usersFilter", name: "usersFilter", method: "post", action: "http://192.168.1.162/admin/users/users_list", -> # "Users / page" dl ".small", -> dt -> label for: "filter_nb", -> @ion_lang.ionize_label_users_per_page dd -> input "#filter_nb.inputtext.w60", type: "text", name: "nb", value: 50 # "Group" dl ".small", -> dt -> label for: "filter_id_group", -> @ion_lang.ionize_label_group dd -> select "#filter_slug.select", name: "slug", -> option value: "", -> @ion_lang.ionize_label_all_groups for user_group in @user_groups option value: user_group.slug, -> user_group.group_name # "ID" dl ".small", -> dt -> label for: "filter_username", -> @ion_lang.ionize_label_username dd -> input "#filter_username.inputtext.w140", type: "text", name: "username", value: "" # "Screen name" dl ".small", -> dt -> label for: "filter_screenname", -> @ion_lang.ionize_label_screen_name dd -> input "#filter_screenname.inputtext.w140", type: "text", name: "screenname", value: "" # "Email" dl ".small", -> dt -> label for: "filter_email", -> @ion_lang.ionize_label_email dd -> input "#filter_email.inputtext.w140", type: "text", name: "email", value: "" # "Last registered" dl ".small", -> dt -> label for: "filter_registered", -> @ion_lang.ionize_label_last_registered dd -> input "#filter_registered.inputcheckbox", type: "checkbox", name: "registered", value: 1 # "Submit" dl ".small", -> dt "&#160;" dd -> input "#submit_filter.submit", type: "submit", value: "Filter" h3 ".toggler1", @ion_lang.ionize_title_add_user div ".element1", -> form "#newUserForm", name: "newUserForm", method: "post", action: "http://192.168.1.162/admin/users/save", -> # "Username" dl ".small", -> dt -> label for: "username", -> @ion_lang.ionize_label_username dd -> input "#username.inputtext.w140", name: "username", type: "text", value: "" # "Screen name" dl ".small", -> dt -> label for: "screen_name", -> @ion_lang.ionize_label_screen_name dd -> input "#screen_name.inputtext.w140", name: "screen_name", type: "text", value: "" # "Group" dl ".small", -> dt -> label for: "group_FK", -> @ion_lang.ionize_label_group dd -> select ".select", name: "id_group", -> for user_group in @user_groups option value: user_group.id_group, -> user_group.group_name # "Email" dl ".small", -> dt -> label for: "email", -> @ion_lang.ionize_label_email dd -> input "#email.inputtext.w140", name: "email", type: "text", value: "" # "Password" dl ".small", -> dt -> label for: "password", -> @ion_lang.ionize_label_password dd -> input "#password.inputtext.w120", name: "password", type: "password", value: "" # "Password confirm" dl ".small", -> dt -> label for: "password2", -> @ion_lang.ionize_label_password2 dd -> input "#password2.inputtext.w120", name: "password2", type: "password", value: "" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_user.submit", type: "submit", value: @ion_lang.ionize_button_save # "Users list" div ".tabcolumn", -> div id:"usersList" # ------------------------------ # Groups # ------------------------------ div ".tabcontent", -> # # "New group" box # div ".tabsidecolumn", -> h3 @ion_lang.ionize_title_add_group form "#newGroupForm", name: "newGroupForm", method: "post", action: "/admin/groups/save", -> # "Group name" dl ".small", -> dt -> label for: "group_name", -> @ion_lang.ionize_label_group_name dd -> input "#slug.inputtext.w140", name: "group_name", type: "text", value: "" # "Level" dl ".small", -> dt -> label for: "level", -> @ion_lang.ionize_label_group_level dd -> input "#slug.inputtext.w140", name: "level", type: "text", value: "100" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_group.submit", type: "submit", value: "Save" # # "Groups list" # div ".tabcolumn", -> table "#groupsTable.list", -> thead -> tr -> th axis: "string", -> @ion_lang.ionize_label_id th axis: "string", -> @ion_lang.ionize_label_group_name #th axis: "string", -> @ion_lang.ionize_label_group_title th axis: "string", -> @ion_lang.ionize_label_group_level #th axis: "string", -> @ion_lang.ionize_label_group_description th() tbody -> for user_group in @user_groups tr ".groups#{user_group.id}", -> td user_group.id td -> a "#group#{user_group.id}.group", rel: user_group.id, href: @lang+"/admin/groups/edit/"+user_group.id, -> user_group.group_name #td user_group.group_name td user_group.level # td() td -> a ".icon.delete", rel:user_group.id_group # /maincolumn coffeescript -> # # Panel toolbox # ION.initToolbox "empty_toolbox" # # Options Accordion # ION.initAccordion ".toggler1", "div.element1", false, "usersAccordion" # # Tabs init # usersTabSwapper = new TabSwapper( tabsContainer: "usersTab" sectionsContainer: "usersTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "usersTab" ) # # Users list tab # $("usersListTab").addEvent "click", -> unless @retrieve("loaded") ION.updateElement url: "users\/\/users_list" element: "usersList" # # Init help tips on label # $("usersListTab").fireEvent "click" ION.initLabelHelpLinks "#newUserForm" ION.initLabelHelpLinks "#newGroupForm" # # New user form action # see init.js for more information about this method # ION.setFormSubmit "newUserForm", "submit_new_user", "users\/\/save" ION.setFormSubmit "newGroupForm", "submit_new_group", "groups\/\/save" # # Filter users list # $("submit_filter").addEvent "click", (e) -> e.stop() new Request.HTML( url: admin_url + "users\/\/users_list" method: "post" loadMethod: "xhr" data: $("usersFilter") update: $("usersList") onRequest: -> MUI.showSpinner() onFailure: (xhr) -> MUI.hideSpinner() onComplete: -> MUI.hideSpinner() ).send() # # Events to each group # Opens an edition window # $$(".group").each (item) -> item.addEvent "click", (e) -> e.stop() id = item.getProperty("rel") ION.formWindow id, "groupForm", "ionize_title_group_edit", "groups\/\/edit\/" + id, width: 340 height: 230 # # Groups itemManager # groupsManager = new ION.ItemManager( container: "groupsTable" element: "groups" ) # # Adds Sortable function to the user list table # new SortableTable("groupsTable", sortOn: 3 sortBy: "ASC" )
true
# Users / groups management page in backend # # Nodize CMS # https://github.com/nodize/nodizecms # # Original page design : # IonizeCMS (http://www.ionizecms.com), # (c) PartPI:NAME:<NAME>END_PIule (http://www.partikule.net) # # CoffeeKup conversion & adaptation : # Hypee (http://hypee.com) # # Licensed under the MIT license: # http://www.opensource.org/licenses/MIT # @include = -> # # Displaying users management page # @view backend_users: -> html -> div "#maincolumn", -> h2 "#main-title.main.groups", @ion_lang.ionize_title_users # ------------------------------ # Tabs definition # ------------------------------ div "#usersTab.mainTabs.mt20", -> ul ".tab-menu", -> li "#usersListTab", -> a @ion_lang.ionize_title_existing_users li -> a @ion_lang.ionize_title_existing_groups div class:"clear" # ------------------------------ # List of existing users # ------------------------------ div "#usersTabContent", -> div ".tabcontent", -> div ".tabsidecolumn", -> # "Infos about all users" div ".info.mb10", -> # # Displaying user count & last registered user # Not implemented yet # # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_users_count # dd "1" # dl ".small.compact", -> # dt -> # label @ion_lang.ionize_label_last_registered # dd() h3 ".toggler1", @ion_lang.ionize_title_filter_userslist div ".element1", -> # "User list filter" form "#usersFilter", name: "usersFilter", method: "post", action: "http://192.168.1.162/admin/users/users_list", -> # "Users / page" dl ".small", -> dt -> label for: "filter_nb", -> @ion_lang.ionize_label_users_per_page dd -> input "#filter_nb.inputtext.w60", type: "text", name: "nb", value: 50 # "Group" dl ".small", -> dt -> label for: "filter_id_group", -> @ion_lang.ionize_label_group dd -> select "#filter_slug.select", name: "slug", -> option value: "", -> @ion_lang.ionize_label_all_groups for user_group in @user_groups option value: user_group.slug, -> user_group.group_name # "ID" dl ".small", -> dt -> label for: "filter_username", -> @ion_lang.ionize_label_username dd -> input "#filter_username.inputtext.w140", type: "text", name: "username", value: "" # "Screen name" dl ".small", -> dt -> label for: "filter_screenname", -> @ion_lang.ionize_label_screen_name dd -> input "#filter_screenname.inputtext.w140", type: "text", name: "screenname", value: "" # "Email" dl ".small", -> dt -> label for: "filter_email", -> @ion_lang.ionize_label_email dd -> input "#filter_email.inputtext.w140", type: "text", name: "email", value: "" # "Last registered" dl ".small", -> dt -> label for: "filter_registered", -> @ion_lang.ionize_label_last_registered dd -> input "#filter_registered.inputcheckbox", type: "checkbox", name: "registered", value: 1 # "Submit" dl ".small", -> dt "&#160;" dd -> input "#submit_filter.submit", type: "submit", value: "Filter" h3 ".toggler1", @ion_lang.ionize_title_add_user div ".element1", -> form "#newUserForm", name: "newUserForm", method: "post", action: "http://192.168.1.162/admin/users/save", -> # "Username" dl ".small", -> dt -> label for: "username", -> @ion_lang.ionize_label_username dd -> input "#username.inputtext.w140", name: "username", type: "text", value: "" # "Screen name" dl ".small", -> dt -> label for: "screen_name", -> @ion_lang.ionize_label_screen_name dd -> input "#screen_name.inputtext.w140", name: "screen_name", type: "text", value: "" # "Group" dl ".small", -> dt -> label for: "group_FK", -> @ion_lang.ionize_label_group dd -> select ".select", name: "id_group", -> for user_group in @user_groups option value: user_group.id_group, -> user_group.group_name # "Email" dl ".small", -> dt -> label for: "email", -> @ion_lang.ionize_label_email dd -> input "#email.inputtext.w140", name: "email", type: "text", value: "" # "Password" dl ".small", -> dt -> label for: "password", -> @ion_lang.ionize_label_password dd -> input "#password.inputtext.w120", name: "password", type: "password", value: "" # "Password confirm" dl ".small", -> dt -> label for: "password2", -> @ion_lang.ionize_label_password2 dd -> input "#password2.inputtext.w120", name: "password2", type: "password", value: "" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_user.submit", type: "submit", value: @ion_lang.ionize_button_save # "Users list" div ".tabcolumn", -> div id:"usersList" # ------------------------------ # Groups # ------------------------------ div ".tabcontent", -> # # "New group" box # div ".tabsidecolumn", -> h3 @ion_lang.ionize_title_add_group form "#newGroupForm", name: "newGroupForm", method: "post", action: "/admin/groups/save", -> # "Group name" dl ".small", -> dt -> label for: "group_name", -> @ion_lang.ionize_label_group_name dd -> input "#slug.inputtext.w140", name: "group_name", type: "text", value: "" # "Level" dl ".small", -> dt -> label for: "level", -> @ion_lang.ionize_label_group_level dd -> input "#slug.inputtext.w140", name: "level", type: "text", value: "100" # "Submit button" dl ".small", -> dt "&#160;" dd -> input "#submit_new_group.submit", type: "submit", value: "Save" # # "Groups list" # div ".tabcolumn", -> table "#groupsTable.list", -> thead -> tr -> th axis: "string", -> @ion_lang.ionize_label_id th axis: "string", -> @ion_lang.ionize_label_group_name #th axis: "string", -> @ion_lang.ionize_label_group_title th axis: "string", -> @ion_lang.ionize_label_group_level #th axis: "string", -> @ion_lang.ionize_label_group_description th() tbody -> for user_group in @user_groups tr ".groups#{user_group.id}", -> td user_group.id td -> a "#group#{user_group.id}.group", rel: user_group.id, href: @lang+"/admin/groups/edit/"+user_group.id, -> user_group.group_name #td user_group.group_name td user_group.level # td() td -> a ".icon.delete", rel:user_group.id_group # /maincolumn coffeescript -> # # Panel toolbox # ION.initToolbox "empty_toolbox" # # Options Accordion # ION.initAccordion ".toggler1", "div.element1", false, "usersAccordion" # # Tabs init # usersTabSwapper = new TabSwapper( tabsContainer: "usersTab" sectionsContainer: "usersTabContent" selectedClass: "selected" deselectedClass: "" tabs: "li" clickers: "li a" sections: "div.tabcontent" cookieName: "usersTab" ) # # Users list tab # $("usersListTab").addEvent "click", -> unless @retrieve("loaded") ION.updateElement url: "users\/\/users_list" element: "usersList" # # Init help tips on label # $("usersListTab").fireEvent "click" ION.initLabelHelpLinks "#newUserForm" ION.initLabelHelpLinks "#newGroupForm" # # New user form action # see init.js for more information about this method # ION.setFormSubmit "newUserForm", "submit_new_user", "users\/\/save" ION.setFormSubmit "newGroupForm", "submit_new_group", "groups\/\/save" # # Filter users list # $("submit_filter").addEvent "click", (e) -> e.stop() new Request.HTML( url: admin_url + "users\/\/users_list" method: "post" loadMethod: "xhr" data: $("usersFilter") update: $("usersList") onRequest: -> MUI.showSpinner() onFailure: (xhr) -> MUI.hideSpinner() onComplete: -> MUI.hideSpinner() ).send() # # Events to each group # Opens an edition window # $$(".group").each (item) -> item.addEvent "click", (e) -> e.stop() id = item.getProperty("rel") ION.formWindow id, "groupForm", "ionize_title_group_edit", "groups\/\/edit\/" + id, width: 340 height: 230 # # Groups itemManager # groupsManager = new ION.ItemManager( container: "groupsTable" element: "groups" ) # # Adds Sortable function to the user list table # new SortableTable("groupsTable", sortOn: 3 sortBy: "ASC" )
[ { "context": "'''\nwatchOS : Device\n\n@auther Jungho song (threeword.com)\n@since 2016.11.23\n'''\nclass expor", "end": 41, "score": 0.9998555183410645, "start": 30, "tag": "NAME", "value": "Jungho song" } ]
modules/watchos-kit-device.coffee
framer-modules/watchos
2
''' watchOS : Device @auther Jungho song (threeword.com) @since 2016.11.23 ''' class exports.Device extends Framer.BaseClass # Events defined Events.DigitalCrown = 'digitalCrown' Events.Side = 'side' # Haptic type HapticType = Notification: "haptics-notification" DirectionUp: "haptics-directionUp" DirectionDown: "haptics-directionDown" Success: "haptics-success" Failure: "haptics-failure" Retry: "haptics-retry" Start: "haptics-start" Stop: "haptics-stop" Click: "haptics-click" @define "HapticType", @simpleProperty("HapticType", HapticType) # this.HapticType = HapticType # Device : Apple Watch 42mm @define "width", @simpleProperty("width", 312) @define "height", @simpleProperty("height", 390) @define "ratio", @simpleProperty("ratio", undefined) # Constructor constructor: (options = {}) -> super options # @ratio = Screen.width / @width Framer.Device.contentScale = @ratio # Phychical if Framer.Device.deviceType.indexOf("watch") isnt -1 x; y if Framer.Device.deviceType.indexOf("38mm") isnt -1 x = -5; y = 88 else if Framer.Device.deviceType.indexOf("42mm") isnt -1 x = 5; y = 100 # Digital Crown @digitalCrown = new Layer name: "DigitalCrown" x: Align.right(x), y: Align.center(-y) width: 50, height: 100 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone # Side button @side = new Layer name: "Side" x: Align.right(x-13), y: Align.center(y-20) width: 32, height: 150 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone if Utils.isDesktop() and not Utils.isLocalUrl(document.URL) @digitalCrown.guide = createGuide html: "Digital Crown", parent: @digitalCrown @side.guide = createGuide html: "Side Button", parent: @side # 이벤트 @digitalCrown.onClick -> @emit Events.DigitalCrown, @ @side.onClick -> @emit Events.Side, @ createGuide = (options = {})-> guide = new Layer _.extend options, name: ".guide" style: fontWeight: "400" fontSize: "25px" textTransform: "uppercase" letterSpacing: "-1.5px" paddingLeft: "30px" color: "gray" backgroundColor: "" Util.text.autoSize guide guide.props = x: guide.parent.width + 10, y: Align.center arrow = new Layer name: ".arrow" y: Align.center size: 16 rotation: 45 style: borderStyle: "hidden hidden solid solid" borderColor: "gray", borderWidth: 3 backgroundColor: "" parent: guide arrow.line = new Layer point: Align.center(1.5) width: 21, height: 3 rotation: -45 backgroundColor: "gray" parent: arrow return guide # Play haptic feedback playHaptic: (type = HapticType.Success) -> # Count repeat = 0 switch type when HapticType.Success then repeat = 2 # Tap Framer.Device.phone.rotation = .5 Framer.Device.phone.animate rotation: 0, options: time: .1 repeat: repeat curve: "spring(1000,20,0)" # Audio @playAudio type # Play audio feedback playAudio: (type) -> unless @audioLayer @audioLayer = new Layer size: 0, visible: false @player = document.createElement("audio") @player.setAttribute("webkit-playsinline", "true") @player.setAttribute("preload", "auto") @player.volume ?= 0.75 @audioLayer._element.appendChild(@player) @player.src = "audio/#{type}.mp3" @player.play() # 이벤트 헬퍼 onDigitalCrown: (cb) => @digitalCrown.on Events.DigitalCrown, cb onSide: (cb) => @side.on Events.Side, cb
207024
''' watchOS : Device @auther <NAME> (threeword.com) @since 2016.11.23 ''' class exports.Device extends Framer.BaseClass # Events defined Events.DigitalCrown = 'digitalCrown' Events.Side = 'side' # Haptic type HapticType = Notification: "haptics-notification" DirectionUp: "haptics-directionUp" DirectionDown: "haptics-directionDown" Success: "haptics-success" Failure: "haptics-failure" Retry: "haptics-retry" Start: "haptics-start" Stop: "haptics-stop" Click: "haptics-click" @define "HapticType", @simpleProperty("HapticType", HapticType) # this.HapticType = HapticType # Device : Apple Watch 42mm @define "width", @simpleProperty("width", 312) @define "height", @simpleProperty("height", 390) @define "ratio", @simpleProperty("ratio", undefined) # Constructor constructor: (options = {}) -> super options # @ratio = Screen.width / @width Framer.Device.contentScale = @ratio # Phychical if Framer.Device.deviceType.indexOf("watch") isnt -1 x; y if Framer.Device.deviceType.indexOf("38mm") isnt -1 x = -5; y = 88 else if Framer.Device.deviceType.indexOf("42mm") isnt -1 x = 5; y = 100 # Digital Crown @digitalCrown = new Layer name: "DigitalCrown" x: Align.right(x), y: Align.center(-y) width: 50, height: 100 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone # Side button @side = new Layer name: "Side" x: Align.right(x-13), y: Align.center(y-20) width: 32, height: 150 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone if Utils.isDesktop() and not Utils.isLocalUrl(document.URL) @digitalCrown.guide = createGuide html: "Digital Crown", parent: @digitalCrown @side.guide = createGuide html: "Side Button", parent: @side # 이벤트 @digitalCrown.onClick -> @emit Events.DigitalCrown, @ @side.onClick -> @emit Events.Side, @ createGuide = (options = {})-> guide = new Layer _.extend options, name: ".guide" style: fontWeight: "400" fontSize: "25px" textTransform: "uppercase" letterSpacing: "-1.5px" paddingLeft: "30px" color: "gray" backgroundColor: "" Util.text.autoSize guide guide.props = x: guide.parent.width + 10, y: Align.center arrow = new Layer name: ".arrow" y: Align.center size: 16 rotation: 45 style: borderStyle: "hidden hidden solid solid" borderColor: "gray", borderWidth: 3 backgroundColor: "" parent: guide arrow.line = new Layer point: Align.center(1.5) width: 21, height: 3 rotation: -45 backgroundColor: "gray" parent: arrow return guide # Play haptic feedback playHaptic: (type = HapticType.Success) -> # Count repeat = 0 switch type when HapticType.Success then repeat = 2 # Tap Framer.Device.phone.rotation = .5 Framer.Device.phone.animate rotation: 0, options: time: .1 repeat: repeat curve: "spring(1000,20,0)" # Audio @playAudio type # Play audio feedback playAudio: (type) -> unless @audioLayer @audioLayer = new Layer size: 0, visible: false @player = document.createElement("audio") @player.setAttribute("webkit-playsinline", "true") @player.setAttribute("preload", "auto") @player.volume ?= 0.75 @audioLayer._element.appendChild(@player) @player.src = "audio/#{type}.mp3" @player.play() # 이벤트 헬퍼 onDigitalCrown: (cb) => @digitalCrown.on Events.DigitalCrown, cb onSide: (cb) => @side.on Events.Side, cb
true
''' watchOS : Device @auther PI:NAME:<NAME>END_PI (threeword.com) @since 2016.11.23 ''' class exports.Device extends Framer.BaseClass # Events defined Events.DigitalCrown = 'digitalCrown' Events.Side = 'side' # Haptic type HapticType = Notification: "haptics-notification" DirectionUp: "haptics-directionUp" DirectionDown: "haptics-directionDown" Success: "haptics-success" Failure: "haptics-failure" Retry: "haptics-retry" Start: "haptics-start" Stop: "haptics-stop" Click: "haptics-click" @define "HapticType", @simpleProperty("HapticType", HapticType) # this.HapticType = HapticType # Device : Apple Watch 42mm @define "width", @simpleProperty("width", 312) @define "height", @simpleProperty("height", 390) @define "ratio", @simpleProperty("ratio", undefined) # Constructor constructor: (options = {}) -> super options # @ratio = Screen.width / @width Framer.Device.contentScale = @ratio # Phychical if Framer.Device.deviceType.indexOf("watch") isnt -1 x; y if Framer.Device.deviceType.indexOf("38mm") isnt -1 x = -5; y = 88 else if Framer.Device.deviceType.indexOf("42mm") isnt -1 x = 5; y = 100 # Digital Crown @digitalCrown = new Layer name: "DigitalCrown" x: Align.right(x), y: Align.center(-y) width: 50, height: 100 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone # Side button @side = new Layer name: "Side" x: Align.right(x-13), y: Align.center(y-20) width: 32, height: 150 backgroundColor: "rgba(255,0,0,0)" parent: Framer.Device.phone if Utils.isDesktop() and not Utils.isLocalUrl(document.URL) @digitalCrown.guide = createGuide html: "Digital Crown", parent: @digitalCrown @side.guide = createGuide html: "Side Button", parent: @side # 이벤트 @digitalCrown.onClick -> @emit Events.DigitalCrown, @ @side.onClick -> @emit Events.Side, @ createGuide = (options = {})-> guide = new Layer _.extend options, name: ".guide" style: fontWeight: "400" fontSize: "25px" textTransform: "uppercase" letterSpacing: "-1.5px" paddingLeft: "30px" color: "gray" backgroundColor: "" Util.text.autoSize guide guide.props = x: guide.parent.width + 10, y: Align.center arrow = new Layer name: ".arrow" y: Align.center size: 16 rotation: 45 style: borderStyle: "hidden hidden solid solid" borderColor: "gray", borderWidth: 3 backgroundColor: "" parent: guide arrow.line = new Layer point: Align.center(1.5) width: 21, height: 3 rotation: -45 backgroundColor: "gray" parent: arrow return guide # Play haptic feedback playHaptic: (type = HapticType.Success) -> # Count repeat = 0 switch type when HapticType.Success then repeat = 2 # Tap Framer.Device.phone.rotation = .5 Framer.Device.phone.animate rotation: 0, options: time: .1 repeat: repeat curve: "spring(1000,20,0)" # Audio @playAudio type # Play audio feedback playAudio: (type) -> unless @audioLayer @audioLayer = new Layer size: 0, visible: false @player = document.createElement("audio") @player.setAttribute("webkit-playsinline", "true") @player.setAttribute("preload", "auto") @player.volume ?= 0.75 @audioLayer._element.appendChild(@player) @player.src = "audio/#{type}.mp3" @player.play() # 이벤트 헬퍼 onDigitalCrown: (cb) => @digitalCrown.on Events.DigitalCrown, cb onSide: (cb) => @side.on Events.Side, cb
[ { "context": "ets.js\n# =========\n\n# > version: 0.5.2\n# > author: Michael Richards\n# > license: MIT\n# >\n# > http://rivetsjs.com/\n\n# ", "end": 72, "score": 0.9997547268867493, "start": 56, "tag": "NAME", "value": "Michael Richards" } ]
src/rivets.coffee
dobtco/rivets
0
# Rivets.js # ========= # > version: 0.5.2 # > author: Michael Richards # > license: MIT # > # > http://rivetsjs.com/ # --- # The Rivets namespace. Rivets = {} # Polyfill For `String::trim`. unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, '' # Rivets.Binding # -------------- # A single binding between a model attribute and a DOM element. class Rivets.Binding # All information about the binding is passed into the constructor; the # containing view, the DOM node, the type of binding, the model object and the # keypath at which to listen for changes. constructor: (@view, @el, @type, @key, @keypath, @options = {}) -> unless @binder = @view.binders[@type] for identifier, value of @view.binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test @type @binder = value @args = new RegExp("^#{identifier.replace('*', '(.+)')}$").exec @type @args.shift() @binder or= @view.binders['*'] @binder = {routine: @binder} if @binder instanceof Function @formatters = @options.formatters || [] @model = @view.models[@key] # Applies all the current formatters to the supplied value and returns the # formatted value. formattedValue: (value) => for formatter in @formatters args = formatter.split /\s+/ id = args.shift() formatter = if @model[id] instanceof Function @model[id] else @view.formatters[id] if formatter?.read instanceof Function value = formatter.read value, args... else if formatter instanceof Function value = formatter value, args... value # Sets the value for the binding. This Basically just runs the binding routine # with the suplied value formatted. set: (value) => value = if value instanceof Function and !@binder.function @formattedValue value.call @model else @formattedValue value @binder.routine?.call @, @el, value # Syncs up the view binding with the model. sync: => @set if @options.bypass @model[@keypath] else @view.config.adapter.read @model, @keypath # Publishes the value currently set on the input element back to the model. publish: => value = Rivets.Util.getInputValue @el for formatter in @formatters.slice(0).reverse() args = formatter.split /\s+/ id = args.shift() if @view.formatters[id]?.publish value = @view.formatters[id].publish value, args... @view.config.adapter.publish @model, @keypath, value # Subscribes to the model for changes at the specified keypath. Bi-directional # routines will also listen for changes on the element to propagate them back # to the model. bind: => @binder.bind?.call @, @el if @options.bypass @sync() else @view.config.adapter.subscribe @model, @keypath, @sync @sync() if @view.config.preloadData if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.subscribe model, keypath, @sync # Unsubscribes from the model and the element. unbind: => @binder.unbind?.call @, @el unless @options.bypass @view.config.adapter.unsubscribe @model, @keypath, @sync if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.unsubscribe model, keypath, @sync # Updates the binding's model from what is currently set on the view. Unbinds # the old model first and then re-binds with the new model. update: => @unbind() @model = @view.models[@key] @bind() # Rivets.View # ----------- # A collection of bindings built from a set of parent nodes. class Rivets.View # The DOM elements and the model objects for binding are passed into the # constructor along with any local options that should be used throughout the # context of the view and it's bindings. constructor: (@els, @models, @options = {}) -> @els = [@els] unless (@els.jquery || @els instanceof Array) for option in ['config', 'binders', 'formatters'] @[option] = {} @[option][k] = v for k, v of @options[option] if @options[option] @[option][k] ?= v for k, v of Rivets[option] @build() # Regular expression used to match binding attributes. bindingRegExp: => prefix = @config.prefix if prefix then new RegExp("^data-#{prefix}-") else /^data-/ # Parses the DOM tree and builds `Rivets.Binding` instances for every matched # binding declaration. Subsequent calls to build will replace the previous # `Rivets.Binding` instances with new ones, so be sure to unbind them first. build: => @bindings = [] skipNodes = [] bindingRegExp = @bindingRegExp() parse = (node) => unless node in skipNodes for attribute in node.attributes if bindingRegExp.test attribute.name type = attribute.name.replace bindingRegExp, '' unless binder = @binders[type] for identifier, value of @binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test type binder = value binder or= @binders['*'] if binder.block skipNodes.push n for n in node.getElementsByTagName '*' attributes = [attribute] for attribute in attributes or node.attributes if bindingRegExp.test attribute.name options = {} type = attribute.name.replace bindingRegExp, '' pipes = (pipe.trim() for pipe in attribute.value.split '|') context = (ctx.trim() for ctx in pipes.shift().split '<') path = context.shift() splitPath = path.split /\.|:/ options.formatters = pipes options.bypass = path.indexOf(':') != -1 if splitPath[0] key = splitPath.shift() else key = null splitPath.shift() keypath = splitPath.join '.' if @models[key]? if dependencies = context.shift() options.dependencies = dependencies.split /\s+/ @bindings.push new Rivets.Binding @, node, type, key, keypath, options attributes = null if attributes return for el in @els parse el parse node for node in el.getElementsByTagName '*' when node.attributes? return # Returns an array of bindings where the supplied function evaluates to true. select: (fn) => binding for binding in @bindings when fn binding # Binds all of the current bindings for this view. bind: => binding.bind() for binding in @bindings # Unbinds all of the current bindings for this view. unbind: => binding.unbind() for binding in @bindings # Syncs up the view with the model by running the routines on all bindings. sync: => binding.sync() for binding in @bindings # Publishes the input values from the view back to the model (reverse sync). publish: => binding.publish() for binding in @select (b) -> b.binder.publishes # Updates the view's models along with any affected bindings. update: (models = {}) => for key, model of models @models[key] = model binding.update() for binding in @select (b) -> b.key is key # Rivets.Util # ----------- # Houses common utility functions used internally by Rivets.js. Rivets.Util = # Create a single DOM event binding. bindEvent: (el, event, handler, view) -> fn = (ev) -> handler.call @, ev, view if window.jQuery? el = jQuery el if el.on? then el.on event, fn else el.bind event, fn else if window.addEventListener? el.addEventListener event, fn, false else event = 'on' + event el.attachEvent event, fn fn # Remove a single DOM event binding. unbindEvent: (el, event, fn) -> if window.jQuery? el = jQuery el if el.off? then el.off event, fn else el.unbind event, fn else if window.removeEventListener el.removeEventListener event, fn, false else event = 'on' + event el.detachEvent event, fn # Get the current value of an input node. getInputValue: (el) -> if window.jQuery? el = jQuery el switch el[0].type when 'checkbox' then el.is ':checked' else el.val() else switch el.type when 'checkbox' then el.checked when 'select-multiple' then o.value for o in el when o.selected else el.value # Rivets.binders # -------------- # Core binders that are included with Rivets.js, publicly available on # `module.binders`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.binders = enabled: (el, value) -> el.disabled = !value disabled: (el, value) -> el.disabled = !!value checked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() is value?.toString() else el.checked = !!value unchecked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() isnt value?.toString() else el.checked = !value show: (el, value) -> el.style.display = if value then '' else 'none' hide: (el, value) -> el.style.display = if value then 'none' else '' html: (el, value) -> el.innerHTML = if value? then value else '' value: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if window.jQuery? el = jQuery el if value?.toString() isnt el.val()?.toString() el.val if value? then value else '' else if el.type is 'select-multiple' o.selected = o.value in value for o in el if value? else if value?.toString() isnt el.value?.toString() el.value = if value? then value else '' text: (el, value) -> if el.innerText? el.innerText = if value? then value else '' else el.textContent = if value? then value else '' "on-*": function: true routine: (el, value) -> Rivets.Util.unbindEvent el, @args[0], @currentListener if @currentListener @currentListener = Rivets.Util.bindEvent el, @args[0], value, @view "each-*": block: true bind: (el, collection) -> el.removeAttribute ['data', @view.config.prefix, @type].join('-').replace '--', '-' unbind: (el, collection) -> view.unbind() for view in @iterated if @iterated? routine: (el, collection) -> if @iterated? for view in @iterated view.unbind() e.parentNode.removeChild e for e in view.els else @marker = document.createComment " rivets: #{@type} " el.parentNode.insertBefore @marker, el el.parentNode.removeChild el @iterated = [] if collection for item in collection data = {} data[n] = m for n, m of @view.models data[@args[0]] = item itemEl = el.cloneNode true previous = if @iterated.length @iterated[@iterated.length - 1].els[0] else @marker @marker.parentNode.insertBefore itemEl, previous.nextSibling ? null options = binders: @view.options.binders formatters: @view.options.binders config: {} options.config[k] = v for k, v of @view.options.config if @view.options.config # Ensure preloadData is set to true since child elements won't get initiated otherwise until the next change (which might not be the first) options.config.preloadData = true view = new Rivets.View(itemEl, data, options) view.bind() @iterated.push view "class-*": (el, value) -> elClass = " #{el.className} " if !value is (elClass.indexOf(" #{@args[0]} ") isnt -1) el.className = if value "#{el.className} #{@args[0]}" else elClass.replace(" #{@args[0]} ", ' ').trim() "*": (el, value) -> if value el.setAttribute @type, value else el.removeAttribute @type # Rivets.config # ------------- # Default configuration, publicly accessible on `module.config`. Can be # overridden globally or local to a `Rivets.View` instance. Rivets.config = preloadData: true # Rivets.formatters # ----------------- # Default formatters (there aren't any), publicly accessible on # `module.formatters`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.formatters = {} # Rivets.factory # -------------- # The Rivets.js module factory. Rivets.factory = (exports) -> # Exposes the core binding routines that can be extended or stripped down. exports.binders = Rivets.binders # Exposes the formatters object to be extended. exports.formatters = Rivets.formatters # Exposes the rivets configuration options. These can be set manually or from # rivets.configure with an object literal. exports.config = Rivets.config # Sets configuration options by merging an object literal. exports.configure = (options={}) -> for property, value of options Rivets.config[property] = value return # Binds a set of model objects to a parent DOM element and returns a # `Rivets.View` instance. exports.bind = (el, models = {}, options = {}) -> view = new Rivets.View(el, models, options) view.bind() view # Export # ------ # Exports Rivets.js for CommonJS, AMD and the browser. if typeof exports == 'object' Rivets.factory(exports) else if typeof define == 'function' && define.amd define ['exports'], (exports) -> Rivets.factory(@rivets = exports) return exports else Rivets.factory(@rivets = {})
125452
# Rivets.js # ========= # > version: 0.5.2 # > author: <NAME> # > license: MIT # > # > http://rivetsjs.com/ # --- # The Rivets namespace. Rivets = {} # Polyfill For `String::trim`. unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, '' # Rivets.Binding # -------------- # A single binding between a model attribute and a DOM element. class Rivets.Binding # All information about the binding is passed into the constructor; the # containing view, the DOM node, the type of binding, the model object and the # keypath at which to listen for changes. constructor: (@view, @el, @type, @key, @keypath, @options = {}) -> unless @binder = @view.binders[@type] for identifier, value of @view.binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test @type @binder = value @args = new RegExp("^#{identifier.replace('*', '(.+)')}$").exec @type @args.shift() @binder or= @view.binders['*'] @binder = {routine: @binder} if @binder instanceof Function @formatters = @options.formatters || [] @model = @view.models[@key] # Applies all the current formatters to the supplied value and returns the # formatted value. formattedValue: (value) => for formatter in @formatters args = formatter.split /\s+/ id = args.shift() formatter = if @model[id] instanceof Function @model[id] else @view.formatters[id] if formatter?.read instanceof Function value = formatter.read value, args... else if formatter instanceof Function value = formatter value, args... value # Sets the value for the binding. This Basically just runs the binding routine # with the suplied value formatted. set: (value) => value = if value instanceof Function and !@binder.function @formattedValue value.call @model else @formattedValue value @binder.routine?.call @, @el, value # Syncs up the view binding with the model. sync: => @set if @options.bypass @model[@keypath] else @view.config.adapter.read @model, @keypath # Publishes the value currently set on the input element back to the model. publish: => value = Rivets.Util.getInputValue @el for formatter in @formatters.slice(0).reverse() args = formatter.split /\s+/ id = args.shift() if @view.formatters[id]?.publish value = @view.formatters[id].publish value, args... @view.config.adapter.publish @model, @keypath, value # Subscribes to the model for changes at the specified keypath. Bi-directional # routines will also listen for changes on the element to propagate them back # to the model. bind: => @binder.bind?.call @, @el if @options.bypass @sync() else @view.config.adapter.subscribe @model, @keypath, @sync @sync() if @view.config.preloadData if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.subscribe model, keypath, @sync # Unsubscribes from the model and the element. unbind: => @binder.unbind?.call @, @el unless @options.bypass @view.config.adapter.unsubscribe @model, @keypath, @sync if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.unsubscribe model, keypath, @sync # Updates the binding's model from what is currently set on the view. Unbinds # the old model first and then re-binds with the new model. update: => @unbind() @model = @view.models[@key] @bind() # Rivets.View # ----------- # A collection of bindings built from a set of parent nodes. class Rivets.View # The DOM elements and the model objects for binding are passed into the # constructor along with any local options that should be used throughout the # context of the view and it's bindings. constructor: (@els, @models, @options = {}) -> @els = [@els] unless (@els.jquery || @els instanceof Array) for option in ['config', 'binders', 'formatters'] @[option] = {} @[option][k] = v for k, v of @options[option] if @options[option] @[option][k] ?= v for k, v of Rivets[option] @build() # Regular expression used to match binding attributes. bindingRegExp: => prefix = @config.prefix if prefix then new RegExp("^data-#{prefix}-") else /^data-/ # Parses the DOM tree and builds `Rivets.Binding` instances for every matched # binding declaration. Subsequent calls to build will replace the previous # `Rivets.Binding` instances with new ones, so be sure to unbind them first. build: => @bindings = [] skipNodes = [] bindingRegExp = @bindingRegExp() parse = (node) => unless node in skipNodes for attribute in node.attributes if bindingRegExp.test attribute.name type = attribute.name.replace bindingRegExp, '' unless binder = @binders[type] for identifier, value of @binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test type binder = value binder or= @binders['*'] if binder.block skipNodes.push n for n in node.getElementsByTagName '*' attributes = [attribute] for attribute in attributes or node.attributes if bindingRegExp.test attribute.name options = {} type = attribute.name.replace bindingRegExp, '' pipes = (pipe.trim() for pipe in attribute.value.split '|') context = (ctx.trim() for ctx in pipes.shift().split '<') path = context.shift() splitPath = path.split /\.|:/ options.formatters = pipes options.bypass = path.indexOf(':') != -1 if splitPath[0] key = splitPath.shift() else key = null splitPath.shift() keypath = splitPath.join '.' if @models[key]? if dependencies = context.shift() options.dependencies = dependencies.split /\s+/ @bindings.push new Rivets.Binding @, node, type, key, keypath, options attributes = null if attributes return for el in @els parse el parse node for node in el.getElementsByTagName '*' when node.attributes? return # Returns an array of bindings where the supplied function evaluates to true. select: (fn) => binding for binding in @bindings when fn binding # Binds all of the current bindings for this view. bind: => binding.bind() for binding in @bindings # Unbinds all of the current bindings for this view. unbind: => binding.unbind() for binding in @bindings # Syncs up the view with the model by running the routines on all bindings. sync: => binding.sync() for binding in @bindings # Publishes the input values from the view back to the model (reverse sync). publish: => binding.publish() for binding in @select (b) -> b.binder.publishes # Updates the view's models along with any affected bindings. update: (models = {}) => for key, model of models @models[key] = model binding.update() for binding in @select (b) -> b.key is key # Rivets.Util # ----------- # Houses common utility functions used internally by Rivets.js. Rivets.Util = # Create a single DOM event binding. bindEvent: (el, event, handler, view) -> fn = (ev) -> handler.call @, ev, view if window.jQuery? el = jQuery el if el.on? then el.on event, fn else el.bind event, fn else if window.addEventListener? el.addEventListener event, fn, false else event = 'on' + event el.attachEvent event, fn fn # Remove a single DOM event binding. unbindEvent: (el, event, fn) -> if window.jQuery? el = jQuery el if el.off? then el.off event, fn else el.unbind event, fn else if window.removeEventListener el.removeEventListener event, fn, false else event = 'on' + event el.detachEvent event, fn # Get the current value of an input node. getInputValue: (el) -> if window.jQuery? el = jQuery el switch el[0].type when 'checkbox' then el.is ':checked' else el.val() else switch el.type when 'checkbox' then el.checked when 'select-multiple' then o.value for o in el when o.selected else el.value # Rivets.binders # -------------- # Core binders that are included with Rivets.js, publicly available on # `module.binders`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.binders = enabled: (el, value) -> el.disabled = !value disabled: (el, value) -> el.disabled = !!value checked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() is value?.toString() else el.checked = !!value unchecked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() isnt value?.toString() else el.checked = !value show: (el, value) -> el.style.display = if value then '' else 'none' hide: (el, value) -> el.style.display = if value then 'none' else '' html: (el, value) -> el.innerHTML = if value? then value else '' value: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if window.jQuery? el = jQuery el if value?.toString() isnt el.val()?.toString() el.val if value? then value else '' else if el.type is 'select-multiple' o.selected = o.value in value for o in el if value? else if value?.toString() isnt el.value?.toString() el.value = if value? then value else '' text: (el, value) -> if el.innerText? el.innerText = if value? then value else '' else el.textContent = if value? then value else '' "on-*": function: true routine: (el, value) -> Rivets.Util.unbindEvent el, @args[0], @currentListener if @currentListener @currentListener = Rivets.Util.bindEvent el, @args[0], value, @view "each-*": block: true bind: (el, collection) -> el.removeAttribute ['data', @view.config.prefix, @type].join('-').replace '--', '-' unbind: (el, collection) -> view.unbind() for view in @iterated if @iterated? routine: (el, collection) -> if @iterated? for view in @iterated view.unbind() e.parentNode.removeChild e for e in view.els else @marker = document.createComment " rivets: #{@type} " el.parentNode.insertBefore @marker, el el.parentNode.removeChild el @iterated = [] if collection for item in collection data = {} data[n] = m for n, m of @view.models data[@args[0]] = item itemEl = el.cloneNode true previous = if @iterated.length @iterated[@iterated.length - 1].els[0] else @marker @marker.parentNode.insertBefore itemEl, previous.nextSibling ? null options = binders: @view.options.binders formatters: @view.options.binders config: {} options.config[k] = v for k, v of @view.options.config if @view.options.config # Ensure preloadData is set to true since child elements won't get initiated otherwise until the next change (which might not be the first) options.config.preloadData = true view = new Rivets.View(itemEl, data, options) view.bind() @iterated.push view "class-*": (el, value) -> elClass = " #{el.className} " if !value is (elClass.indexOf(" #{@args[0]} ") isnt -1) el.className = if value "#{el.className} #{@args[0]}" else elClass.replace(" #{@args[0]} ", ' ').trim() "*": (el, value) -> if value el.setAttribute @type, value else el.removeAttribute @type # Rivets.config # ------------- # Default configuration, publicly accessible on `module.config`. Can be # overridden globally or local to a `Rivets.View` instance. Rivets.config = preloadData: true # Rivets.formatters # ----------------- # Default formatters (there aren't any), publicly accessible on # `module.formatters`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.formatters = {} # Rivets.factory # -------------- # The Rivets.js module factory. Rivets.factory = (exports) -> # Exposes the core binding routines that can be extended or stripped down. exports.binders = Rivets.binders # Exposes the formatters object to be extended. exports.formatters = Rivets.formatters # Exposes the rivets configuration options. These can be set manually or from # rivets.configure with an object literal. exports.config = Rivets.config # Sets configuration options by merging an object literal. exports.configure = (options={}) -> for property, value of options Rivets.config[property] = value return # Binds a set of model objects to a parent DOM element and returns a # `Rivets.View` instance. exports.bind = (el, models = {}, options = {}) -> view = new Rivets.View(el, models, options) view.bind() view # Export # ------ # Exports Rivets.js for CommonJS, AMD and the browser. if typeof exports == 'object' Rivets.factory(exports) else if typeof define == 'function' && define.amd define ['exports'], (exports) -> Rivets.factory(@rivets = exports) return exports else Rivets.factory(@rivets = {})
true
# Rivets.js # ========= # > version: 0.5.2 # > author: PI:NAME:<NAME>END_PI # > license: MIT # > # > http://rivetsjs.com/ # --- # The Rivets namespace. Rivets = {} # Polyfill For `String::trim`. unless String::trim then String::trim = -> @replace /^\s+|\s+$/g, '' # Rivets.Binding # -------------- # A single binding between a model attribute and a DOM element. class Rivets.Binding # All information about the binding is passed into the constructor; the # containing view, the DOM node, the type of binding, the model object and the # keypath at which to listen for changes. constructor: (@view, @el, @type, @key, @keypath, @options = {}) -> unless @binder = @view.binders[@type] for identifier, value of @view.binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test @type @binder = value @args = new RegExp("^#{identifier.replace('*', '(.+)')}$").exec @type @args.shift() @binder or= @view.binders['*'] @binder = {routine: @binder} if @binder instanceof Function @formatters = @options.formatters || [] @model = @view.models[@key] # Applies all the current formatters to the supplied value and returns the # formatted value. formattedValue: (value) => for formatter in @formatters args = formatter.split /\s+/ id = args.shift() formatter = if @model[id] instanceof Function @model[id] else @view.formatters[id] if formatter?.read instanceof Function value = formatter.read value, args... else if formatter instanceof Function value = formatter value, args... value # Sets the value for the binding. This Basically just runs the binding routine # with the suplied value formatted. set: (value) => value = if value instanceof Function and !@binder.function @formattedValue value.call @model else @formattedValue value @binder.routine?.call @, @el, value # Syncs up the view binding with the model. sync: => @set if @options.bypass @model[@keypath] else @view.config.adapter.read @model, @keypath # Publishes the value currently set on the input element back to the model. publish: => value = Rivets.Util.getInputValue @el for formatter in @formatters.slice(0).reverse() args = formatter.split /\s+/ id = args.shift() if @view.formatters[id]?.publish value = @view.formatters[id].publish value, args... @view.config.adapter.publish @model, @keypath, value # Subscribes to the model for changes at the specified keypath. Bi-directional # routines will also listen for changes on the element to propagate them back # to the model. bind: => @binder.bind?.call @, @el if @options.bypass @sync() else @view.config.adapter.subscribe @model, @keypath, @sync @sync() if @view.config.preloadData if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.subscribe model, keypath, @sync # Unsubscribes from the model and the element. unbind: => @binder.unbind?.call @, @el unless @options.bypass @view.config.adapter.unsubscribe @model, @keypath, @sync if @options.dependencies?.length for dependency in @options.dependencies if /^\./.test dependency model = @model keypath = dependency.substr 1 else dependency = dependency.split '.' model = @view.models[dependency.shift()] keypath = dependency.join '.' @view.config.adapter.unsubscribe model, keypath, @sync # Updates the binding's model from what is currently set on the view. Unbinds # the old model first and then re-binds with the new model. update: => @unbind() @model = @view.models[@key] @bind() # Rivets.View # ----------- # A collection of bindings built from a set of parent nodes. class Rivets.View # The DOM elements and the model objects for binding are passed into the # constructor along with any local options that should be used throughout the # context of the view and it's bindings. constructor: (@els, @models, @options = {}) -> @els = [@els] unless (@els.jquery || @els instanceof Array) for option in ['config', 'binders', 'formatters'] @[option] = {} @[option][k] = v for k, v of @options[option] if @options[option] @[option][k] ?= v for k, v of Rivets[option] @build() # Regular expression used to match binding attributes. bindingRegExp: => prefix = @config.prefix if prefix then new RegExp("^data-#{prefix}-") else /^data-/ # Parses the DOM tree and builds `Rivets.Binding` instances for every matched # binding declaration. Subsequent calls to build will replace the previous # `Rivets.Binding` instances with new ones, so be sure to unbind them first. build: => @bindings = [] skipNodes = [] bindingRegExp = @bindingRegExp() parse = (node) => unless node in skipNodes for attribute in node.attributes if bindingRegExp.test attribute.name type = attribute.name.replace bindingRegExp, '' unless binder = @binders[type] for identifier, value of @binders if identifier isnt '*' and identifier.indexOf('*') isnt -1 regexp = new RegExp "^#{identifier.replace('*', '.+')}$" if regexp.test type binder = value binder or= @binders['*'] if binder.block skipNodes.push n for n in node.getElementsByTagName '*' attributes = [attribute] for attribute in attributes or node.attributes if bindingRegExp.test attribute.name options = {} type = attribute.name.replace bindingRegExp, '' pipes = (pipe.trim() for pipe in attribute.value.split '|') context = (ctx.trim() for ctx in pipes.shift().split '<') path = context.shift() splitPath = path.split /\.|:/ options.formatters = pipes options.bypass = path.indexOf(':') != -1 if splitPath[0] key = splitPath.shift() else key = null splitPath.shift() keypath = splitPath.join '.' if @models[key]? if dependencies = context.shift() options.dependencies = dependencies.split /\s+/ @bindings.push new Rivets.Binding @, node, type, key, keypath, options attributes = null if attributes return for el in @els parse el parse node for node in el.getElementsByTagName '*' when node.attributes? return # Returns an array of bindings where the supplied function evaluates to true. select: (fn) => binding for binding in @bindings when fn binding # Binds all of the current bindings for this view. bind: => binding.bind() for binding in @bindings # Unbinds all of the current bindings for this view. unbind: => binding.unbind() for binding in @bindings # Syncs up the view with the model by running the routines on all bindings. sync: => binding.sync() for binding in @bindings # Publishes the input values from the view back to the model (reverse sync). publish: => binding.publish() for binding in @select (b) -> b.binder.publishes # Updates the view's models along with any affected bindings. update: (models = {}) => for key, model of models @models[key] = model binding.update() for binding in @select (b) -> b.key is key # Rivets.Util # ----------- # Houses common utility functions used internally by Rivets.js. Rivets.Util = # Create a single DOM event binding. bindEvent: (el, event, handler, view) -> fn = (ev) -> handler.call @, ev, view if window.jQuery? el = jQuery el if el.on? then el.on event, fn else el.bind event, fn else if window.addEventListener? el.addEventListener event, fn, false else event = 'on' + event el.attachEvent event, fn fn # Remove a single DOM event binding. unbindEvent: (el, event, fn) -> if window.jQuery? el = jQuery el if el.off? then el.off event, fn else el.unbind event, fn else if window.removeEventListener el.removeEventListener event, fn, false else event = 'on' + event el.detachEvent event, fn # Get the current value of an input node. getInputValue: (el) -> if window.jQuery? el = jQuery el switch el[0].type when 'checkbox' then el.is ':checked' else el.val() else switch el.type when 'checkbox' then el.checked when 'select-multiple' then o.value for o in el when o.selected else el.value # Rivets.binders # -------------- # Core binders that are included with Rivets.js, publicly available on # `module.binders`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.binders = enabled: (el, value) -> el.disabled = !value disabled: (el, value) -> el.disabled = !!value checked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() is value?.toString() else el.checked = !!value unchecked: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if el.type is 'radio' el.checked = el.value?.toString() isnt value?.toString() else el.checked = !value show: (el, value) -> el.style.display = if value then '' else 'none' hide: (el, value) -> el.style.display = if value then 'none' else '' html: (el, value) -> el.innerHTML = if value? then value else '' value: publishes: true bind: (el) -> @currentListener = Rivets.Util.bindEvent el, 'change', @publish unbind: (el) -> Rivets.Util.unbindEvent el, 'change', @currentListener routine: (el, value) -> if window.jQuery? el = jQuery el if value?.toString() isnt el.val()?.toString() el.val if value? then value else '' else if el.type is 'select-multiple' o.selected = o.value in value for o in el if value? else if value?.toString() isnt el.value?.toString() el.value = if value? then value else '' text: (el, value) -> if el.innerText? el.innerText = if value? then value else '' else el.textContent = if value? then value else '' "on-*": function: true routine: (el, value) -> Rivets.Util.unbindEvent el, @args[0], @currentListener if @currentListener @currentListener = Rivets.Util.bindEvent el, @args[0], value, @view "each-*": block: true bind: (el, collection) -> el.removeAttribute ['data', @view.config.prefix, @type].join('-').replace '--', '-' unbind: (el, collection) -> view.unbind() for view in @iterated if @iterated? routine: (el, collection) -> if @iterated? for view in @iterated view.unbind() e.parentNode.removeChild e for e in view.els else @marker = document.createComment " rivets: #{@type} " el.parentNode.insertBefore @marker, el el.parentNode.removeChild el @iterated = [] if collection for item in collection data = {} data[n] = m for n, m of @view.models data[@args[0]] = item itemEl = el.cloneNode true previous = if @iterated.length @iterated[@iterated.length - 1].els[0] else @marker @marker.parentNode.insertBefore itemEl, previous.nextSibling ? null options = binders: @view.options.binders formatters: @view.options.binders config: {} options.config[k] = v for k, v of @view.options.config if @view.options.config # Ensure preloadData is set to true since child elements won't get initiated otherwise until the next change (which might not be the first) options.config.preloadData = true view = new Rivets.View(itemEl, data, options) view.bind() @iterated.push view "class-*": (el, value) -> elClass = " #{el.className} " if !value is (elClass.indexOf(" #{@args[0]} ") isnt -1) el.className = if value "#{el.className} #{@args[0]}" else elClass.replace(" #{@args[0]} ", ' ').trim() "*": (el, value) -> if value el.setAttribute @type, value else el.removeAttribute @type # Rivets.config # ------------- # Default configuration, publicly accessible on `module.config`. Can be # overridden globally or local to a `Rivets.View` instance. Rivets.config = preloadData: true # Rivets.formatters # ----------------- # Default formatters (there aren't any), publicly accessible on # `module.formatters`. Can be overridden globally or local to a `Rivets.View` # instance. Rivets.formatters = {} # Rivets.factory # -------------- # The Rivets.js module factory. Rivets.factory = (exports) -> # Exposes the core binding routines that can be extended or stripped down. exports.binders = Rivets.binders # Exposes the formatters object to be extended. exports.formatters = Rivets.formatters # Exposes the rivets configuration options. These can be set manually or from # rivets.configure with an object literal. exports.config = Rivets.config # Sets configuration options by merging an object literal. exports.configure = (options={}) -> for property, value of options Rivets.config[property] = value return # Binds a set of model objects to a parent DOM element and returns a # `Rivets.View` instance. exports.bind = (el, models = {}, options = {}) -> view = new Rivets.View(el, models, options) view.bind() view # Export # ------ # Exports Rivets.js for CommonJS, AMD and the browser. if typeof exports == 'object' Rivets.factory(exports) else if typeof define == 'function' && define.amd define ['exports'], (exports) -> Rivets.factory(@rivets = exports) return exports else Rivets.factory(@rivets = {})
[ { "context": "mail: $info.data('email')\n buyer_name: name\n buyer_tel: $info.data('phone')\n ", "end": 1531, "score": 0.978598952293396, "start": 1527, "tag": "NAME", "value": "name" } ]
public/assets/coffee/order-id-payment.coffee
ejang/OpenCloset-Share-Web
2
$ -> IMP = window.IMP IMP.init(CONFIG.iamport.id) STATUS = choose_address: 49 # 주소선택 payment_done: 50 # 결제완료 waiting_deposit: 56 # 입금대기 $('#btn-payment').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') # card: 신용카드 # trans: 실시간계좌이체 # vbank: 가상계좌 # phone: 휴대폰소액결제 pay_method = $('#payment-method').val() unless pay_method in [ "card", "trans", "vbank", "phone" ] $.growl.error({ title: "결제 실패", message: "결제 수단을 선택하세요." }) $this.removeClass('disabled') return $info = $('#payment-info') name = $info.data("name") order_id = $info.data("order-id") unless order_id? && /^\d+$/.test(order_id) && order_id > 0 $.growl.error({ title: "결제 실패", message: "주문서가 없습니다." }) $this.removeClass('disabled') return unless name? && name.length > 0 $.growl.error({ title: "결제 실패", message: "사용자 이름이 없습니다." }) $this.removeClass('disabled') return $.ajax "/orders/#{order_id}/payments", type: 'POST' data: pay_method: pay_method dataType: 'json' success: (data, textStatus, jqXHR) -> vbank_due = $('#shipping-date').data('vbank-due') imp_params = pg: 'html5_inicis' pay_method: pay_method merchant_uid: data.cid name: "#{name}##{order_id}" amount: $('#order-price').data('price') buyer_email: $info.data('email') buyer_name: name buyer_tel: $info.data('phone') buyer_addr: $info.data('address1') vbank_due: "#{vbank_due}" m_redirect_url: "#{location.protocol}//#{location.host}/payments/#{data.id}/callback" imp_params.notice_url = CONFIG.iamport.notice_url if CONFIG.iamport.notice_url? IMP.request_pay imp_params, (res) -> payment_status = res.status unless res.success payment_status = "cancelled" $.growl.error({ title: '결제실패', message: res.error_msg }) $.ajax "/payments/#{data.id}", type: 'PUT' dataType: 'json' data: order_id: order_id imp_uid: res.imp_uid merchant_uid: res.merchant_uid amount: res.paid_amount status: payment_status pg_provider: res.pg_provider pay_method: res.pay_method success: (data, textStatus, jqXHR) -> ## ready 라면 입금대기로 상태변경 ## paid 라면 결제완료로 상태변경 if res.success and res.status in ['paid', 'ready'] status = if res.status is 'paid' then 'payment_done' else 'waiting_deposit' $.ajax location.href, type: 'PUT' data: { status_id: STATUS[status] } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#btn-choose-address:not(.disabled)').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') $.ajax location.href, type: 'PUT' data: { status_id: STATUS.choose_address } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') $('input[name=code]').mask('AAAA') $('#coupon-modal').on 'shown.bs.modal', (e) -> $('input[name=code]:first').focus() $('#coupon-modal form').submit (e) -> e.preventDefault() $this = $(@) $submit = $this.find('.btn-submit') return if $submit.hasClass('disabled') action = $this.prop('action') $.ajax action, type: 'POST' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $submit.addClass('disabled') # 쿠폰의 정보를 나타내고 사용여부를 다시 묻는다 data.isRate = data.type is 'rate' data.isSuit = data.type is 'suit' data.isDefault = data.type is 'default' ## You can use the if helper to conditionally render a block. ## If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block. ## int 로 변환해주지 않으면 "0" 으로 인식되어서 항상 true 이다 data.price = parseInt(data.price) data.free_shipping = parseInt(data.free_shipping) template = JST['coupon/info'] html = template(data) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) error: (jqXHR, textStatus, errorThrown) -> template = JST['coupon/error'] html = template({ error: jqXHR.responseJSON.error }) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) complete: (jqXHR, textStatus) -> $('#coupon-modal').on 'click', '#btn-coupon-use', (e) -> e.preventDefault() coupon_id = $(@).data('coupon-id') extra = $(@).closest('.modal-footer').find('input[name=extra]').val() $.ajax "#{location.href}/coupon", type: 'POST' data: { coupon_id: coupon_id, extra: extra } dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('.js-add-category').click (e) -> e.preventDefault() name = $(@).data('name') price = $(@).data('price') url = $(@).prop('href') $.ajax url, type: 'POST' dataType: 'json' data: { name: name, price: price } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title: "품목추가 실패", message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $('#btn-force-deposit').click (e) -> val = $(@).data('value') $.ajax location.href, type: 'PUT' dataType: 'json' data: { force_deposit: val } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) ->
87064
$ -> IMP = window.IMP IMP.init(CONFIG.iamport.id) STATUS = choose_address: 49 # 주소선택 payment_done: 50 # 결제완료 waiting_deposit: 56 # 입금대기 $('#btn-payment').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') # card: 신용카드 # trans: 실시간계좌이체 # vbank: 가상계좌 # phone: 휴대폰소액결제 pay_method = $('#payment-method').val() unless pay_method in [ "card", "trans", "vbank", "phone" ] $.growl.error({ title: "결제 실패", message: "결제 수단을 선택하세요." }) $this.removeClass('disabled') return $info = $('#payment-info') name = $info.data("name") order_id = $info.data("order-id") unless order_id? && /^\d+$/.test(order_id) && order_id > 0 $.growl.error({ title: "결제 실패", message: "주문서가 없습니다." }) $this.removeClass('disabled') return unless name? && name.length > 0 $.growl.error({ title: "결제 실패", message: "사용자 이름이 없습니다." }) $this.removeClass('disabled') return $.ajax "/orders/#{order_id}/payments", type: 'POST' data: pay_method: pay_method dataType: 'json' success: (data, textStatus, jqXHR) -> vbank_due = $('#shipping-date').data('vbank-due') imp_params = pg: 'html5_inicis' pay_method: pay_method merchant_uid: data.cid name: "#{name}##{order_id}" amount: $('#order-price').data('price') buyer_email: $info.data('email') buyer_name: <NAME> buyer_tel: $info.data('phone') buyer_addr: $info.data('address1') vbank_due: "#{vbank_due}" m_redirect_url: "#{location.protocol}//#{location.host}/payments/#{data.id}/callback" imp_params.notice_url = CONFIG.iamport.notice_url if CONFIG.iamport.notice_url? IMP.request_pay imp_params, (res) -> payment_status = res.status unless res.success payment_status = "cancelled" $.growl.error({ title: '결제실패', message: res.error_msg }) $.ajax "/payments/#{data.id}", type: 'PUT' dataType: 'json' data: order_id: order_id imp_uid: res.imp_uid merchant_uid: res.merchant_uid amount: res.paid_amount status: payment_status pg_provider: res.pg_provider pay_method: res.pay_method success: (data, textStatus, jqXHR) -> ## ready 라면 입금대기로 상태변경 ## paid 라면 결제완료로 상태변경 if res.success and res.status in ['paid', 'ready'] status = if res.status is 'paid' then 'payment_done' else 'waiting_deposit' $.ajax location.href, type: 'PUT' data: { status_id: STATUS[status] } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#btn-choose-address:not(.disabled)').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') $.ajax location.href, type: 'PUT' data: { status_id: STATUS.choose_address } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') $('input[name=code]').mask('AAAA') $('#coupon-modal').on 'shown.bs.modal', (e) -> $('input[name=code]:first').focus() $('#coupon-modal form').submit (e) -> e.preventDefault() $this = $(@) $submit = $this.find('.btn-submit') return if $submit.hasClass('disabled') action = $this.prop('action') $.ajax action, type: 'POST' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $submit.addClass('disabled') # 쿠폰의 정보를 나타내고 사용여부를 다시 묻는다 data.isRate = data.type is 'rate' data.isSuit = data.type is 'suit' data.isDefault = data.type is 'default' ## You can use the if helper to conditionally render a block. ## If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block. ## int 로 변환해주지 않으면 "0" 으로 인식되어서 항상 true 이다 data.price = parseInt(data.price) data.free_shipping = parseInt(data.free_shipping) template = JST['coupon/info'] html = template(data) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) error: (jqXHR, textStatus, errorThrown) -> template = JST['coupon/error'] html = template({ error: jqXHR.responseJSON.error }) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) complete: (jqXHR, textStatus) -> $('#coupon-modal').on 'click', '#btn-coupon-use', (e) -> e.preventDefault() coupon_id = $(@).data('coupon-id') extra = $(@).closest('.modal-footer').find('input[name=extra]').val() $.ajax "#{location.href}/coupon", type: 'POST' data: { coupon_id: coupon_id, extra: extra } dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('.js-add-category').click (e) -> e.preventDefault() name = $(@).data('name') price = $(@).data('price') url = $(@).prop('href') $.ajax url, type: 'POST' dataType: 'json' data: { name: name, price: price } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title: "품목추가 실패", message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $('#btn-force-deposit').click (e) -> val = $(@).data('value') $.ajax location.href, type: 'PUT' dataType: 'json' data: { force_deposit: val } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) ->
true
$ -> IMP = window.IMP IMP.init(CONFIG.iamport.id) STATUS = choose_address: 49 # 주소선택 payment_done: 50 # 결제완료 waiting_deposit: 56 # 입금대기 $('#btn-payment').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') # card: 신용카드 # trans: 실시간계좌이체 # vbank: 가상계좌 # phone: 휴대폰소액결제 pay_method = $('#payment-method').val() unless pay_method in [ "card", "trans", "vbank", "phone" ] $.growl.error({ title: "결제 실패", message: "결제 수단을 선택하세요." }) $this.removeClass('disabled') return $info = $('#payment-info') name = $info.data("name") order_id = $info.data("order-id") unless order_id? && /^\d+$/.test(order_id) && order_id > 0 $.growl.error({ title: "결제 실패", message: "주문서가 없습니다." }) $this.removeClass('disabled') return unless name? && name.length > 0 $.growl.error({ title: "결제 실패", message: "사용자 이름이 없습니다." }) $this.removeClass('disabled') return $.ajax "/orders/#{order_id}/payments", type: 'POST' data: pay_method: pay_method dataType: 'json' success: (data, textStatus, jqXHR) -> vbank_due = $('#shipping-date').data('vbank-due') imp_params = pg: 'html5_inicis' pay_method: pay_method merchant_uid: data.cid name: "#{name}##{order_id}" amount: $('#order-price').data('price') buyer_email: $info.data('email') buyer_name: PI:NAME:<NAME>END_PI buyer_tel: $info.data('phone') buyer_addr: $info.data('address1') vbank_due: "#{vbank_due}" m_redirect_url: "#{location.protocol}//#{location.host}/payments/#{data.id}/callback" imp_params.notice_url = CONFIG.iamport.notice_url if CONFIG.iamport.notice_url? IMP.request_pay imp_params, (res) -> payment_status = res.status unless res.success payment_status = "cancelled" $.growl.error({ title: '결제실패', message: res.error_msg }) $.ajax "/payments/#{data.id}", type: 'PUT' dataType: 'json' data: order_id: order_id imp_uid: res.imp_uid merchant_uid: res.merchant_uid amount: res.paid_amount status: payment_status pg_provider: res.pg_provider pay_method: res.pay_method success: (data, textStatus, jqXHR) -> ## ready 라면 입금대기로 상태변경 ## paid 라면 결제완료로 상태변경 if res.success and res.status in ['paid', 'ready'] status = if res.status is 'paid' then 'payment_done' else 'waiting_deposit' $.ajax location.href, type: 'PUT' data: { status_id: STATUS[status] } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('#btn-choose-address:not(.disabled)').click (e) -> e.preventDefault() $this = $(@) $this.addClass('disabled') $.ajax location.href, type: 'PUT' data: { status_id: STATUS.choose_address } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $this.removeClass('disabled') $('input[name=code]').mask('AAAA') $('#coupon-modal').on 'shown.bs.modal', (e) -> $('input[name=code]:first').focus() $('#coupon-modal form').submit (e) -> e.preventDefault() $this = $(@) $submit = $this.find('.btn-submit') return if $submit.hasClass('disabled') action = $this.prop('action') $.ajax action, type: 'POST' data: $this.serialize() dataType: 'json' success: (data, textStatus, jqXHR) -> $submit.addClass('disabled') # 쿠폰의 정보를 나타내고 사용여부를 다시 묻는다 data.isRate = data.type is 'rate' data.isSuit = data.type is 'suit' data.isDefault = data.type is 'default' ## You can use the if helper to conditionally render a block. ## If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block. ## int 로 변환해주지 않으면 "0" 으로 인식되어서 항상 true 이다 data.price = parseInt(data.price) data.free_shipping = parseInt(data.free_shipping) template = JST['coupon/info'] html = template(data) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) error: (jqXHR, textStatus, errorThrown) -> template = JST['coupon/error'] html = template({ error: jqXHR.responseJSON.error }) $('#coupon-modal .modal-footer').remove() $('#coupon-modal .modal-content').append(html) complete: (jqXHR, textStatus) -> $('#coupon-modal').on 'click', '#btn-coupon-use', (e) -> e.preventDefault() coupon_id = $(@).data('coupon-id') extra = $(@).closest('.modal-footer').find('input[name=extra]').val() $.ajax "#{location.href}/coupon", type: 'POST' data: { coupon_id: coupon_id, extra: extra } dataType: 'json' success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) -> $('.js-add-category').click (e) -> e.preventDefault() name = $(@).data('name') price = $(@).data('price') url = $(@).prop('href') $.ajax url, type: 'POST' dataType: 'json' data: { name: name, price: price } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> $.growl.error({ title: "품목추가 실패", message: jqXHR.responseJSON.error }) complete: (jqXHR, textStatus) -> $('#btn-force-deposit').click (e) -> val = $(@).data('value') $.ajax location.href, type: 'PUT' dataType: 'json' data: { force_deposit: val } success: (data, textStatus, jqXHR) -> location.reload() error: (jqXHR, textStatus, errorThrown) -> complete: (jqXHR, textStatus) ->
[ { "context": "er streams\n#\n# Author:\n# Based on tweetstream by Christophe Hamerling\n# Rewritten in coffeescript and transformed int", "end": 92, "score": 0.9998788833618164, "start": 72, "tag": "NAME", "value": "Christophe Hamerling" }, { "context": "rmed into a class with authorization # guards by Matthew Weier O'Phinney\n\n_ = require('lodash')\nStream = require './twitte", "end": 208, "score": 0.9998729228973389, "start": 185, "tag": "NAME", "value": "Matthew Weier O'Phinney" }, { "context": "status/#{tweet.id_str}\"\n author_name: \"#{tweet.user.screen_name} @#{tweet.user.name}\"\n autho", "end": 2460, "score": 0.89618319272995, "start": 2450, "tag": "USERNAME", "value": "tweet.user" }, { "context": " author_name: \"#{tweet.user.screen_name} @#{tweet.user.name}\"\n author_link: \"https://twitter.com/#{t", "end": 2492, "score": 0.9164034724235535, "start": 2477, "tag": "USERNAME", "value": "tweet.user.name" }, { "context": "e}\"\n author_link: \"https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}\"\n ", "end": 2546, "score": 0.6175005435943604, "start": 2541, "tag": "USERNAME", "value": "tweet" } ]
lib/twitter-tweetstream.coffee
inovadeveloper/zfbot
11
# Interact with twitter streams # # Author: # Based on tweetstream by Christophe Hamerling # Rewritten in coffeescript and transformed into a class with authorization # guards by Matthew Weier O'Phinney _ = require('lodash') Stream = require './twitter-stream' TYPES = require './twitter-types' class TweetStream constructor: (@robot, @twit, @clear_subs) -> BRAIN_TWITTER_STREAMS: "twitter" loaded: false streams: [] saveTweetStream: (stream) -> @streams.push(stream) found = _.find @robot.brain.get(@BRAIN_TWITTER_STREAMS), (subscription) -> switch stream.type when TYPES.FOLLOW return subscription.follow == stream.follow && subscription.room == stream.room && subscription.type == stream.type when TYPES.TRACK return subscription.track == stream.track && subscription.room == stream.room && subscription.type == stream.type return if found toSave = null switch stream.type when TYPES.FOLLOW toSave = type: TYPES.FOLLOW room: stream.room follow: stream.follow screen_name: stream.screen_name when TYPES.TRACK toSave = type: TYPES.TRACK room: stream.room track: stream.track else return savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS savedStreams.push toSave @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams formatTimeString: (date) -> ampm = "am" hours = date.getHours() ampm = "pm" if hours > 11 hours = hours - 12 if hours > 12 hours = 12 if hours == 0 minutes = date.getMinutes() minutes = "0" + minutes if minutes < 10 "#{hours}:#{minutes} #{ampm}" initializeStream: (stream) -> filter = {} switch stream.type when TYPES.FOLLOW filter.follow = stream.follow when TYPES.TRACK filter.track = stream.track else return tweetStream = @twit.stream 'statuses/filter', filter tweetStream.on 'tweet', (tweet) => return if stream.type == TYPES.FOLLOW && tweet.user.id_str != stream.follow ts = new Date tweet.created_at ts = new Date ts.getTime() created = @formatTimeString ts attachment = attachments: [ color: "#00ACED" fallback: "@#{tweet.user.screen_name} at #{created}: https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_name: "#{tweet.user.screen_name} @#{tweet.user.name}" author_link: "https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_icon: "#{tweet.user.profile_image_url_https}" text: tweet.text footer: "Twitter" footer_icon: "https://a.slack-edge.com/66f9/img/services/twitter_128.png" ts: Math.floor(ts.getTime() / 1000) ] if tweet.entities?.media? && tweet.entities.media.length > 0 tweet.entities.media.forEach (media) -> attachment.attachments.push { color: "#00ACED" fallback: media.media_url_https pretext: media.media_url_https image_url: media.media_url_https } @robot.send room: stream.room, attachment @robot.logger.info "Started a new twitter stream", filter stream.tweet_stream = tweetStream @saveTweetStream stream restoreSubscription: (subscription) -> return @robot.logger.error('Can not restore subscription; missing room or type', subscription) if !subscription || !subscription.room || !subscription.type switch subscription.type when TYPES.FOLLOW return @robot.logger.error('Can not restore follow subscription; missing follow identifier or screen name', subscription) if !subscription.screen_name || !subscription.follow stream = new Stream() stream.toFollow subscription.room, subscription.screen_name, subscription.follow @initializeStream stream when TYPES.TRACK return @robot.logger.error('Can not restore track subscription; missing tracking string', subscription) if !subscription.track stream = new Stream() stream.toTrack subscription.room, subscription.track @initializeStream stream restoreSubscriptions: -> subscriptions = @robot.brain.get @BRAIN_TWITTER_STREAMS return @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) if !subscriptions?.length? @restoreSubscription(subscription) for subscription in subscriptions getIdFromScreenName: (screen_name, callback) -> @twit.get 'users/lookup', {screen_name}, (err, response) -> return callback(err) if err return callback(new Error("User not found")) if !response?.length? callback null, response[0].id_str load: (data) -> # this loaded event is sent on each robot.brain.set, skip it after initial load return if @loaded @loaded = true if @clear_subs then @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) else @restoreSubscriptions() clear: (msg) -> match = (subscription) -> subscription.room == msg.message.room toRemove = _.remove @streams, match return msg.send "No subscription in this room" if !toRemove.length subscription.stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS @robot.brain.set(@BRAIN_TWITTER_STREAMS, _.remove(savedStreams, match)) msg.send "Unsubscribed from all" follow: (msg) -> screen_name = msg.match[1] @getIdFromScreenName screen_name, (err, id) => return @robot.logger.error("Can not get twitter user id from #{screen_name}", err) if err stream = new Stream() stream.toFollow msg.message.room, screen_name, id @initializeStream stream msg.send "I have started following tweets from @#{screen_name}" list: (msg) -> currentRoomTags = @streams .filter((subscription) -> subscription.room == msg.message.room) .map((subscription) -> if subscription.room == msg.message.room switch subscription.type when TYPES.FOLLOW then return "- From user @#{subscription.screen_name}" when TYPES.TRACK then return "- Matching #{subscription.track}" ) return msg.send("No subscriptions. Hint: Type 'twitter track/follow XXX' to listen to XXX related tweets in current room") if not currentRoomTags.length currentRoomTags.unshift "I am listening to tweets with the following criteria:" msg.send currentRoomTags.join "\n" unsubscribe: (match) -> toRemove = _.remove @streams, match return false if !toRemove.length subscription.tweet_stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS _.remove savedStreams, match @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams true unfollow: (msg) -> screen_name = msg.match[1] msg.send("I stopped following tweets from '#{screen_name}'") if @unsubscribe((subscription) => subscription.type == TYPES.FOLLOW && subscription.screen_name == screen_name && subscription.room == msg.message.room) untrack: (msg) -> word = msg.match[1] msg.send("I have stopped tracking tweets matching '#{word}'") if @unsubscribe((subscription) => subscription.type == TYPES.TRACK && subscription.track == word && subscription.room == msg.message.room) track: (msg) -> stream = new Stream() stream.toTrack msg.message.room, msg.match[1] @initializeStream stream msg.send "I have started tracking tweets matching '#{msg.match[1]}'" module.exports = TweetStream
52734
# Interact with twitter streams # # Author: # Based on tweetstream by <NAME> # Rewritten in coffeescript and transformed into a class with authorization # guards by <NAME> _ = require('lodash') Stream = require './twitter-stream' TYPES = require './twitter-types' class TweetStream constructor: (@robot, @twit, @clear_subs) -> BRAIN_TWITTER_STREAMS: "twitter" loaded: false streams: [] saveTweetStream: (stream) -> @streams.push(stream) found = _.find @robot.brain.get(@BRAIN_TWITTER_STREAMS), (subscription) -> switch stream.type when TYPES.FOLLOW return subscription.follow == stream.follow && subscription.room == stream.room && subscription.type == stream.type when TYPES.TRACK return subscription.track == stream.track && subscription.room == stream.room && subscription.type == stream.type return if found toSave = null switch stream.type when TYPES.FOLLOW toSave = type: TYPES.FOLLOW room: stream.room follow: stream.follow screen_name: stream.screen_name when TYPES.TRACK toSave = type: TYPES.TRACK room: stream.room track: stream.track else return savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS savedStreams.push toSave @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams formatTimeString: (date) -> ampm = "am" hours = date.getHours() ampm = "pm" if hours > 11 hours = hours - 12 if hours > 12 hours = 12 if hours == 0 minutes = date.getMinutes() minutes = "0" + minutes if minutes < 10 "#{hours}:#{minutes} #{ampm}" initializeStream: (stream) -> filter = {} switch stream.type when TYPES.FOLLOW filter.follow = stream.follow when TYPES.TRACK filter.track = stream.track else return tweetStream = @twit.stream 'statuses/filter', filter tweetStream.on 'tweet', (tweet) => return if stream.type == TYPES.FOLLOW && tweet.user.id_str != stream.follow ts = new Date tweet.created_at ts = new Date ts.getTime() created = @formatTimeString ts attachment = attachments: [ color: "#00ACED" fallback: "@#{tweet.user.screen_name} at #{created}: https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_name: "#{tweet.user.screen_name} @#{tweet.user.name}" author_link: "https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_icon: "#{tweet.user.profile_image_url_https}" text: tweet.text footer: "Twitter" footer_icon: "https://a.slack-edge.com/66f9/img/services/twitter_128.png" ts: Math.floor(ts.getTime() / 1000) ] if tweet.entities?.media? && tweet.entities.media.length > 0 tweet.entities.media.forEach (media) -> attachment.attachments.push { color: "#00ACED" fallback: media.media_url_https pretext: media.media_url_https image_url: media.media_url_https } @robot.send room: stream.room, attachment @robot.logger.info "Started a new twitter stream", filter stream.tweet_stream = tweetStream @saveTweetStream stream restoreSubscription: (subscription) -> return @robot.logger.error('Can not restore subscription; missing room or type', subscription) if !subscription || !subscription.room || !subscription.type switch subscription.type when TYPES.FOLLOW return @robot.logger.error('Can not restore follow subscription; missing follow identifier or screen name', subscription) if !subscription.screen_name || !subscription.follow stream = new Stream() stream.toFollow subscription.room, subscription.screen_name, subscription.follow @initializeStream stream when TYPES.TRACK return @robot.logger.error('Can not restore track subscription; missing tracking string', subscription) if !subscription.track stream = new Stream() stream.toTrack subscription.room, subscription.track @initializeStream stream restoreSubscriptions: -> subscriptions = @robot.brain.get @BRAIN_TWITTER_STREAMS return @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) if !subscriptions?.length? @restoreSubscription(subscription) for subscription in subscriptions getIdFromScreenName: (screen_name, callback) -> @twit.get 'users/lookup', {screen_name}, (err, response) -> return callback(err) if err return callback(new Error("User not found")) if !response?.length? callback null, response[0].id_str load: (data) -> # this loaded event is sent on each robot.brain.set, skip it after initial load return if @loaded @loaded = true if @clear_subs then @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) else @restoreSubscriptions() clear: (msg) -> match = (subscription) -> subscription.room == msg.message.room toRemove = _.remove @streams, match return msg.send "No subscription in this room" if !toRemove.length subscription.stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS @robot.brain.set(@BRAIN_TWITTER_STREAMS, _.remove(savedStreams, match)) msg.send "Unsubscribed from all" follow: (msg) -> screen_name = msg.match[1] @getIdFromScreenName screen_name, (err, id) => return @robot.logger.error("Can not get twitter user id from #{screen_name}", err) if err stream = new Stream() stream.toFollow msg.message.room, screen_name, id @initializeStream stream msg.send "I have started following tweets from @#{screen_name}" list: (msg) -> currentRoomTags = @streams .filter((subscription) -> subscription.room == msg.message.room) .map((subscription) -> if subscription.room == msg.message.room switch subscription.type when TYPES.FOLLOW then return "- From user @#{subscription.screen_name}" when TYPES.TRACK then return "- Matching #{subscription.track}" ) return msg.send("No subscriptions. Hint: Type 'twitter track/follow XXX' to listen to XXX related tweets in current room") if not currentRoomTags.length currentRoomTags.unshift "I am listening to tweets with the following criteria:" msg.send currentRoomTags.join "\n" unsubscribe: (match) -> toRemove = _.remove @streams, match return false if !toRemove.length subscription.tweet_stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS _.remove savedStreams, match @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams true unfollow: (msg) -> screen_name = msg.match[1] msg.send("I stopped following tweets from '#{screen_name}'") if @unsubscribe((subscription) => subscription.type == TYPES.FOLLOW && subscription.screen_name == screen_name && subscription.room == msg.message.room) untrack: (msg) -> word = msg.match[1] msg.send("I have stopped tracking tweets matching '#{word}'") if @unsubscribe((subscription) => subscription.type == TYPES.TRACK && subscription.track == word && subscription.room == msg.message.room) track: (msg) -> stream = new Stream() stream.toTrack msg.message.room, msg.match[1] @initializeStream stream msg.send "I have started tracking tweets matching '#{msg.match[1]}'" module.exports = TweetStream
true
# Interact with twitter streams # # Author: # Based on tweetstream by PI:NAME:<NAME>END_PI # Rewritten in coffeescript and transformed into a class with authorization # guards by PI:NAME:<NAME>END_PI _ = require('lodash') Stream = require './twitter-stream' TYPES = require './twitter-types' class TweetStream constructor: (@robot, @twit, @clear_subs) -> BRAIN_TWITTER_STREAMS: "twitter" loaded: false streams: [] saveTweetStream: (stream) -> @streams.push(stream) found = _.find @robot.brain.get(@BRAIN_TWITTER_STREAMS), (subscription) -> switch stream.type when TYPES.FOLLOW return subscription.follow == stream.follow && subscription.room == stream.room && subscription.type == stream.type when TYPES.TRACK return subscription.track == stream.track && subscription.room == stream.room && subscription.type == stream.type return if found toSave = null switch stream.type when TYPES.FOLLOW toSave = type: TYPES.FOLLOW room: stream.room follow: stream.follow screen_name: stream.screen_name when TYPES.TRACK toSave = type: TYPES.TRACK room: stream.room track: stream.track else return savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS savedStreams.push toSave @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams formatTimeString: (date) -> ampm = "am" hours = date.getHours() ampm = "pm" if hours > 11 hours = hours - 12 if hours > 12 hours = 12 if hours == 0 minutes = date.getMinutes() minutes = "0" + minutes if minutes < 10 "#{hours}:#{minutes} #{ampm}" initializeStream: (stream) -> filter = {} switch stream.type when TYPES.FOLLOW filter.follow = stream.follow when TYPES.TRACK filter.track = stream.track else return tweetStream = @twit.stream 'statuses/filter', filter tweetStream.on 'tweet', (tweet) => return if stream.type == TYPES.FOLLOW && tweet.user.id_str != stream.follow ts = new Date tweet.created_at ts = new Date ts.getTime() created = @formatTimeString ts attachment = attachments: [ color: "#00ACED" fallback: "@#{tweet.user.screen_name} at #{created}: https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_name: "#{tweet.user.screen_name} @#{tweet.user.name}" author_link: "https://twitter.com/#{tweet.user.screen_name}/status/#{tweet.id_str}" author_icon: "#{tweet.user.profile_image_url_https}" text: tweet.text footer: "Twitter" footer_icon: "https://a.slack-edge.com/66f9/img/services/twitter_128.png" ts: Math.floor(ts.getTime() / 1000) ] if tweet.entities?.media? && tweet.entities.media.length > 0 tweet.entities.media.forEach (media) -> attachment.attachments.push { color: "#00ACED" fallback: media.media_url_https pretext: media.media_url_https image_url: media.media_url_https } @robot.send room: stream.room, attachment @robot.logger.info "Started a new twitter stream", filter stream.tweet_stream = tweetStream @saveTweetStream stream restoreSubscription: (subscription) -> return @robot.logger.error('Can not restore subscription; missing room or type', subscription) if !subscription || !subscription.room || !subscription.type switch subscription.type when TYPES.FOLLOW return @robot.logger.error('Can not restore follow subscription; missing follow identifier or screen name', subscription) if !subscription.screen_name || !subscription.follow stream = new Stream() stream.toFollow subscription.room, subscription.screen_name, subscription.follow @initializeStream stream when TYPES.TRACK return @robot.logger.error('Can not restore track subscription; missing tracking string', subscription) if !subscription.track stream = new Stream() stream.toTrack subscription.room, subscription.track @initializeStream stream restoreSubscriptions: -> subscriptions = @robot.brain.get @BRAIN_TWITTER_STREAMS return @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) if !subscriptions?.length? @restoreSubscription(subscription) for subscription in subscriptions getIdFromScreenName: (screen_name, callback) -> @twit.get 'users/lookup', {screen_name}, (err, response) -> return callback(err) if err return callback(new Error("User not found")) if !response?.length? callback null, response[0].id_str load: (data) -> # this loaded event is sent on each robot.brain.set, skip it after initial load return if @loaded @loaded = true if @clear_subs then @robot.brain.set(@BRAIN_TWITTER_STREAMS, []) else @restoreSubscriptions() clear: (msg) -> match = (subscription) -> subscription.room == msg.message.room toRemove = _.remove @streams, match return msg.send "No subscription in this room" if !toRemove.length subscription.stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS @robot.brain.set(@BRAIN_TWITTER_STREAMS, _.remove(savedStreams, match)) msg.send "Unsubscribed from all" follow: (msg) -> screen_name = msg.match[1] @getIdFromScreenName screen_name, (err, id) => return @robot.logger.error("Can not get twitter user id from #{screen_name}", err) if err stream = new Stream() stream.toFollow msg.message.room, screen_name, id @initializeStream stream msg.send "I have started following tweets from @#{screen_name}" list: (msg) -> currentRoomTags = @streams .filter((subscription) -> subscription.room == msg.message.room) .map((subscription) -> if subscription.room == msg.message.room switch subscription.type when TYPES.FOLLOW then return "- From user @#{subscription.screen_name}" when TYPES.TRACK then return "- Matching #{subscription.track}" ) return msg.send("No subscriptions. Hint: Type 'twitter track/follow XXX' to listen to XXX related tweets in current room") if not currentRoomTags.length currentRoomTags.unshift "I am listening to tweets with the following criteria:" msg.send currentRoomTags.join "\n" unsubscribe: (match) -> toRemove = _.remove @streams, match return false if !toRemove.length subscription.tweet_stream.stop() for subscription in toRemove savedStreams = @robot.brain.get @BRAIN_TWITTER_STREAMS _.remove savedStreams, match @robot.brain.set @BRAIN_TWITTER_STREAMS, savedStreams true unfollow: (msg) -> screen_name = msg.match[1] msg.send("I stopped following tweets from '#{screen_name}'") if @unsubscribe((subscription) => subscription.type == TYPES.FOLLOW && subscription.screen_name == screen_name && subscription.room == msg.message.room) untrack: (msg) -> word = msg.match[1] msg.send("I have stopped tracking tweets matching '#{word}'") if @unsubscribe((subscription) => subscription.type == TYPES.TRACK && subscription.track == word && subscription.room == msg.message.room) track: (msg) -> stream = new Stream() stream.toTrack msg.message.room, msg.match[1] @initializeStream stream msg.send "I have started tracking tweets matching '#{msg.match[1]}'" module.exports = TweetStream
[ { "context": "# Copyright 2012 Joshua Carver \n# \n# Licensed under the Apache License, Versio", "end": 30, "score": 0.9998712539672852, "start": 17, "tag": "NAME", "value": "Joshua Carver" } ]
src/coffeescript/charts/bullet_chart_options.coffee
jcarver989/raphy-charts
5
# Copyright 2012 Joshua Carver # # 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. class BulletChartOptions @DEFAULTS: { line_width: 4 line_color: "#000" area_color: "#00aadd" area_width: 20 area_opacity: 0.2 bar_margin: 8 show_average: true average_width: 4 average_height: 8 average_color: "#000" font_family: "Helvetica, Arial, sans-serif" x_label_size: 14 y_label_size: 14 x_padding: 45 y_padding: 40 } @merge: (from = {}, to = {}) -> opts = {} for option, value of from opts[option] = value for option, value of to when to.hasOwnProperty(option) opts[option] = value return opts constructor: (options) -> opts = {} for option, value of BulletChartOptions.DEFAULTS opts[option] = value for option, value of options when options.hasOwnProperty(option) opts[option] = value return opts
48083
# Copyright 2012 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BulletChartOptions @DEFAULTS: { line_width: 4 line_color: "#000" area_color: "#00aadd" area_width: 20 area_opacity: 0.2 bar_margin: 8 show_average: true average_width: 4 average_height: 8 average_color: "#000" font_family: "Helvetica, Arial, sans-serif" x_label_size: 14 y_label_size: 14 x_padding: 45 y_padding: 40 } @merge: (from = {}, to = {}) -> opts = {} for option, value of from opts[option] = value for option, value of to when to.hasOwnProperty(option) opts[option] = value return opts constructor: (options) -> opts = {} for option, value of BulletChartOptions.DEFAULTS opts[option] = value for option, value of options when options.hasOwnProperty(option) opts[option] = value return opts
true
# Copyright 2012 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class BulletChartOptions @DEFAULTS: { line_width: 4 line_color: "#000" area_color: "#00aadd" area_width: 20 area_opacity: 0.2 bar_margin: 8 show_average: true average_width: 4 average_height: 8 average_color: "#000" font_family: "Helvetica, Arial, sans-serif" x_label_size: 14 y_label_size: 14 x_padding: 45 y_padding: 40 } @merge: (from = {}, to = {}) -> opts = {} for option, value of from opts[option] = value for option, value of to when to.hasOwnProperty(option) opts[option] = value return opts constructor: (options) -> opts = {} for option, value of BulletChartOptions.DEFAULTS opts[option] = value for option, value of options when options.hasOwnProperty(option) opts[option] = value return opts
[ { "context": " has_policy: 'yes'\n meta:\n creator: 'joe+doaj@oa.works'\n contributors: ['joe+doaj@oa.works']\n ", "end": 10230, "score": 0.9999215602874756, "start": 10213, "tag": "EMAIL", "value": "joe+doaj@oa.works" }, { "context": "reator: 'joe+doaj@oa.works'\n contributors: ['joe+doaj@oa.works']\n monitoring: 'Automatic'\n\n if issns and i", "end": 10271, "score": 0.9999226331710815, "start": 10254, "tag": "EMAIL", "value": "joe+doaj@oa.works" }, { "context": "er.id = meta.publisher\n altoa.meta.creator = ['joe+oapublisher@oa.works']\n altoa.meta.contributors = ['joe+oapublisher", "end": 12045, "score": 0.9998989105224609, "start": 12021, "tag": "EMAIL", "value": "joe+oapublisher@oa.works" }, { "context": "lisher@oa.works']\n altoa.meta.contributors = ['joe+oapublisher@oa.works']\n altoa.provenance = {oa_evidence: '", "end": 12095, "score": 0.8854275941848755, "start": 12080, "tag": "USERNAME", "value": "joe+oapublisher" }, { "context": "']\n altoa.meta.contributors = ['joe+oapublisher@oa.works']\n altoa.provenance = {oa_evidence: 'OA publis", "end": 12104, "score": 0.9998799562454224, "start": 12095, "tag": "EMAIL", "value": "@oa.works" }, { "context": " id: meta.doi\n meta:\n creator: 'support@unpaywall.org'\n contributors: ['support@unpaywall.org'", "end": 12827, "score": 0.9999256730079651, "start": 12806, "tag": "EMAIL", "value": "support@unpaywall.org" }, { "context": "'support@unpaywall.org'\n contributors: ['support@unpaywall.org']\n monitoring: 'Automatic'\n upd", "end": 12876, "score": 0.9999265670776367, "start": 12855, "tag": "EMAIL", "value": "support@unpaywall.org" }, { "context": "s\n\n\n\nP.permissions.journals = _sheet: '1ZTcYJUzhNJYIuxsjKzdVFCbOhJsviVik-8K1DpU7-eE/Main', _prefix: false, _format: (recs=[]) ->\n ready =", "end": 17793, "score": 0.8952497839927673, "start": 17755, "tag": "KEY", "value": "YIuxsjKzdVFCbOhJsviVik-8K1DpU7-eE/Main" } ]
worker/src/permissions.coffee
oaworks/api
0
P.permissions = (meta, ror, getmeta, oadoi, crossref) -> # oadoi and crossref are just ways for other functions to pass in oadoi or crossref record objects to save looking them up again overall_policy_restriction = false haddoi = false _format = (rec) -> if haddoi and rec.embargo_months and (meta.published or meta.year) em = new Date Date.parse meta.published ? meta.year + '-01-01' em = new Date em.setMonth em.getMonth() + rec.embargo_months rec.embargo_end = em.toISOString().split('T')[0] delete rec.embargo_end if rec.embargo_end is '' rec.copyright_name = if rec.copyright_owner and rec.copyright_owner.toLowerCase() is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner and rec.copyright_owner.toLowerCase() in ['journal','affiliation'] then (meta.journal ? '') else if (haddoi and rec.copyright_owner and rec.copyright_owner.toLowerCase().includes('author')) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else '' if rec.copyright_name.toLowerCase() in ['publisher','journal'] and (crossref or meta.doi or rec.provenance?.example) crossref ?= await @src.crossref.works meta.doi ? rec.provenance.example for a in (crossref?.assertion ? []) if a.name.toLowerCase() is 'copyright' try rec.copyright_name = a.value try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim() rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year delete rec.copyright_year if rec.copyright_year is '' if haddoi and rec.deposit_statement? and rec.deposit_statement.includes '<<' fst = '' for pt in rec.deposit_statement.split '<<' if fst is '' and not pt.includes '>>' fst += pt else eph = pt.split '>>' ph = eph[0].toLowerCase() swaps = 'journal title': 'journal' 'vol': 'volume' 'date of publication': 'published' '(c)': 'year' 'article title': 'title' 'copyright name': 'copyright_name' ph = swaps[ph] if swaps[ph]? if ph is 'author' try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else fst += meta[ph] ? rec[ph] ? '' try fst += eph[1] rec.deposit_statement = fst if rec._id? rec.meta ?= {} rec.meta.source = 'https://' + (if S.dev then 'beta.oa.works/permissions/' else 'api.oa.works/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id overall_policy_restriction = rec.issuer.has_policy if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown'] delete rec[d] for d in ['_id', 'hide'] return rec _score = (rec) => score = if rec.can_archive then 1000 else 0 score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ' if rec.requirements? score -= 10 else score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0 score -= 5 if rec.licence score += if rec.issuer?.type.toLowerCase() is 'journal' then 5 else if rec.issuer?.type.toLowerCase() is 'publisher' then 4 else if rec.issuer?.type.toLowerCase() is 'university' then 3 else if rec.issuer?.type.toLowerCase() in ['article'] then 2 else 0 score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or Date.parse(rec.embargo_end) < Date.now()) return score if typeof meta is 'string' meta = if meta.startsWith('10.') then {doi: meta} else {issn: meta} meta ?= @copy @params delete meta.metadata if meta?.metadata is true # just a pass-through for us to show metadata for debug if meta?.permissions? and typeof meta.permissions is 'string' if meta.permissions.startsWith 'journal/' meta.issn = meta.permissions.replace 'journal/', '' else if meta.permissions.startsWith 'affiliation/' meta.ror = meta.permissions.replace 'affiliation/', '' else if meta.permissions.startsWith 'publisher/' meta.publisher = meta.permissions.replace 'publisher/', '' else if meta.permissions.startsWith('10.') and meta.permissions.includes '/' meta.doi = meta.permissions else if meta.permissions.includes('-') and meta.permissions.length < 10 and meta.permissions.length > 6 meta.issn = meta.permissions else if not meta.permissions.includes(' ') and not meta.permissions.includes(',') and meta.permissions.replace(/[0-9]/g, '').length isnt meta.permissions.length meta.ror = meta.permissions else meta.publisher = meta.permissions # but could be a ROR? delete meta.permissions if meta.affiliation meta.ror = meta.affiliation delete meta.affiliation meta.ror ?= ror meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.includes ',' if meta.journal and not meta.journal.includes(' ') and meta.journal.includes '-' meta.issn = meta.journal delete meta.journal issns = if Array.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.includes ',' if JSON.stringify(meta) is '{}' or (meta.issn and not JSON.stringify(meta.issn).includes('-')) or (meta.doi and (typeof meta.doi isnt 'string' or not meta.doi.startsWith('10.') or not meta.doi.includes '/')) return body: 'No valid DOI, ISSN, or ROR provided', status: 404 # NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror # we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article _getmeta = () => psm = @copy meta if JSON.stringify(psm) isnt '{}' for mk of rsm = (crossref ? (await @metadata(meta.doi)) ? {}) meta[mk] ?= rsm[mk] await _getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn) meta.published = meta.year + '-01-01' if not meta.published and meta.year haddoi = meta.doi? if meta.issn meta.issn = [meta.issn] if typeof meta.issn is 'string' if not issns.length # they're already meta.issn in this case anyway for inisn in meta.issn issns.push(inisn) if inisn not in issns # check just in case try meta.doi ?= await @permissions.journals.example issns if not haddoi and meta.doi await _getmeta() if haddoi and meta.type not in ['journal-article'] return body: 'DOI is not a journal article' status: 501 if meta.publisher and meta.publisher.includes('(') and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7) # could be a publisher name with the acronym at the end, like Public Library of Science (PLoS) # so get rid of the acronym because that is not included in the publisher name in crossref and other sources meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim() try meta.citation = '[' meta.citation += meta.title + '. ' if meta.title meta.citation += meta.journal + ' ' if meta.journal meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume meta.citation += meta.issue + ' ' if meta.issue meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages? if meta.year or meta.published meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')' meta.citation = meta.citation.trim() meta.citation += ']' perms = best_permission: undefined, all_permissions: [] rors = [] if meta.ror? meta.ror = [meta.ror] if typeof meta.ror is 'string' rs = await @permissions.affiliations 'issuer.id:"' + meta.ror.join('" OR issuer.id:"') + '"' if not rs?.hits?.total try # look up the ROR, get the ISO 3166-1 alpha-2 code, search affiliations for that rw = await @src.ror(if meta.ror.length is 1 then meta.ror[0] else 'id:"' + meta.ror.join(" OR id:") + '"') rw = rw.hits.hits[0]._source if rw.hits?.total if rw.country.country_code rs = await @permissions.affiliations 'issuer.id:"' + rw.country.country_code + '"' for rr in rs?.hits?.hits ? [] tr = await _format rr._source tr.score = await _score tr rors.push tr indoaj = undefined if issns for await rec from @index._for 'src_doaj_journals', 'bibjson.pissn:"' + issns.join('" OR bibjson.pissn:"') + '" OR bibjson.eissn:"' + issns.join('" OR bibjson.eissn:"') + '"' indoaj = rec if not indoaj issns.push(rec.bibjson.pissn) if rec.bibjson.pissn not in issns issns.push(rec.bibjson.eissn) if rec.bibjson.eissn not in issns if not indoaj? nisns = [] for await rec from @index._for 'src_openalex_venues', 'issn:"' + issns.join('" OR issn:"') + '"' for en in rec.issn nisns.push(en) if en not in nisns issns = nisns if issns.length ps = await @permissions.journals 'issuer.id:"' + issns.join('" OR issuer.id:"') + '"' for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp if meta.publisher qr = 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be ps = await @permissions.publishers qr for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp altoa = can_archive: true version: 'publishedVersion' versions: ['publishedVersion'] licence: undefined locations: ['institutional repository'] embargo_months: undefined issuer: type: 'Journal' has_policy: 'yes' meta: creator: 'joe+doaj@oa.works' contributors: ['joe+doaj@oa.works'] monitoring: 'Automatic' if issns and indoaj ?= await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 for dl in (indoaj.bibjson?.license ? []) altoa.licence = dl.type if not altoa.licence or altoa.licence.length > dl.type altoa.licences ?= [] altoa.licences.push type: dl.type if not altoa.licence? and crj = await @src.crossref.journals 'ISSN.keyword:"' + issns.join('" OR ISSN.keyword:"') + '"', 1 for ll in (crj.license ? []) altoa.licence = ll.type if not altoa.licence or altoa.licence.length > ll.type if typeof altoa.licence is 'string' altoa.licence = altoa.licence.toLowerCase().trim() if altoa.licence.startsWith 'cc' altoa.licence = altoa.licence.replace(/ /g, '-') else if altoa.licence.includes 'creative' altoa.licence = if altoa.licence.includes('0') or altoa.licence.includes('zero') then 'cc0' else if altoa.licence.includes('share') then 'ccbysa' else if altoa.licence.includes('derivative') then 'ccbynd' else 'ccby' else delete altoa.licence else delete altoa.licence altoa.issuer.id = if indoaj.bibjson.eissn and indoaj.bibjson.pissn then [indoaj.bibjson.pissn, indoaj.bibjson.eissn] else if indoaj.bibjson.pissn then [indoaj.bibjson.pissn] else [indoaj.bibjson.eissn] altoa.embargo_months = 0 altoa.provenance = {oa_evidence: 'In DOAJ'} altoa.score = await _score altoa perms.all_permissions.push altoa else if not issns and meta.publisher and (await @permissions.publishers.oa meta.publisher).oa altoa.issuer.id = meta.publisher altoa.meta.creator = ['joe+oapublisher@oa.works'] altoa.meta.contributors = ['joe+oapublisher@oa.works'] altoa.provenance = {oa_evidence: 'OA publisher'} # does this mean embargo_months should be zero too? altoa.score = await _score altoa perms.all_permissions.push altoa if meta.doi oadoi ?= await @src.oadoi meta.doi if haddoi and oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # (haddoi or oadoi?.journal_is_oa) doa = can_archive: true version: oadoi.best_oa_location.version versions: [] licence: oadoi.best_oa_location.license locations: ['institutional repository'] issuer: type: 'article' has_policy: 'yes' id: meta.doi meta: creator: 'support@unpaywall.org' contributors: ['support@unpaywall.org'] monitoring: 'Automatic' updated: oadoi.best_oa_location.updated provenance: oa_evidence: oadoi.best_oa_location.evidence if doa.version doa.versions = if doa.version in ['submittedVersion'] then ['submittedVersion'] else if doa.version in ['acceptedVersion'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion'] doa.score = await _score doa perms.all_permissions.push doa # sort rors by score, and sort alts by score, then combine if perms.all_permissions.length perms.all_permissions.sort (a, b) => return if (a.score < b.score) then 1 else -1 # note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything for wp in perms.all_permissions if not wp.licences? wp.licences = [] wp.licences.push(type: wp.licence) if wp.licence delete wp.issuer.journal_oa_type if haddoi and wp.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(wp.issuer.journal_oa_type_from) delete wp.issuer.journal_oa_type_from if (issns or wp.issuer?.type is 'journal') and not wp.issuer.journal_oa_type wp.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? wp.issuer.id), indoaj, oadoi, crossref if not wp.provenance?.enforcement_from perms.best_permission ?= @copy wp else if not meta.published or Date.parse(meta.published) > Date.parse wp.provenance.enforcement_from.split('/').reverse().join '-' # NOTE Date.parse would try to work on format 31/01/2020 but reads it in American, so would think 31 is a month and is too big # but 2020-01-31 is treated in ISO so the 31 will be the day. So, given that we use DD/MM/YYYY, split on / then reverse then join on - to get a better parse perms.best_permission ?= @copy wp if rors.length # this only happens as an augment to some other permission, so far rors.sort (a, b) => return if (a.score < b.score) then 1 else -1 for ro in rors # check this gives the order in the direction we want, else reverse it delete ro.issuer.journal_oa_type if haddoi and ro.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(ro.issuer.journal_oa_type_from) delete ro.issuer.journal_oa_type_from if (issns or ro.issuer?.type is 'journal') and not ro.issuer.journal_oa_type ro.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? ro.issuer.id), indoaj, oadoi, crossref perms.all_permissions.push ro if not perms.best_permission?.author_affiliation_requirement? if perms.best_permission? if not ro.provenance?.enforcement_from or not meta.published or Date.parse(meta.published) > Date.parse ro.provenance.enforcement_from.split('/').reverse().join '-' pb = @copy perms.best_permission for key in ['versions', 'locations'] for vl in ro[key] pb[key] ?= [] pb[key].push(vl) if vl not in pb[key] pb.version = if 'publishedVersion' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions then 'acceptedVersion' else 'submittedVersion' if pb.embargo_end if ro.embargo_end if Date.parse(ro.embargo_end) < Date.parse pb.embargo_end pb.embargo_end = ro.embargo_end if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months pb.embargo_months = ro.embargo_months pb.can_archive = true if ro.can_archive is true pb.requirements ?= {} pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0] pb.issuer.affiliation = ro.issuer pb.meta ?= {} pb.meta.affiliation = ro.meta pb.provenance ?= {} pb.provenance.affiliation = ro.provenance pb.score = parseInt(pb.score) + parseInt(ro.score) perms.best_permission = pb perms.all_permissions.push pb if overall_policy_restriction msgs = 'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it' return body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction status: 501 else perms.metadata = meta if @params.metadata is true or getmeta is true return perms P.permissions.journals = _sheet: '1ZTcYJUzhNJYIuxsjKzdVFCbOhJsviVik-8K1DpU7-eE/Main', _prefix: false, _format: (recs=[]) -> ready = [] for rec in (if typeof recs is 'object' and not Array.isArray(recs) then [recs] else recs) nr = # a controlled structure for JSON output, can't be guaranteed as not JSON spec, but Joe likes it for visual review can_archive: undefined version: undefined versions: [] licence: undefined locations: undefined embargo_months: undefined embargo_end: undefined deposit_statement: undefined copyright_owner: '' copyright_name: '' copyright_year: '' issuer: {} meta: {} provenance: {} requirements: {} for k of rec rec[k] = rec[k].trim() if typeof rec[k] is 'string' if k is 'id' nr.issuer.id = if typeof rec.id is 'string' and rec.id.includes(',') then rec.id.split(',') else rec.id if typeof nr.issuer.id is 'string' and nr.issuer.id.startsWith('10.') and nr.issuer.id.includes('/') and not nr.issuer.id.includes ' ' nr.DOI = nr.issuer.id else cids = [] for nid in (if typeof nr.issuer.id is 'string' then [nr.issuer.id] else nr.issuer.id) nid = nid.trim() if nr.issuer.type is 'journal' and nid.includes('-') and not nid.includes ' ' nid = nid.toUpperCase() if af = await @journal 'ISSN:"' + nid + '"', 1 #if af = await @src.openalex.venues 'issn:"' + nid + '"', 1 for an in af.issn cids.push(an) if an not in cids cids.push(nid) if nid not in cids nr.issuer.id = cids else if k is 'embargo_months' kn = if typeof rec[k] is 'number' then rec[k] else if typeof rec[k] is 'string' then parseInt(rec[k].trim()) else undefined if kn and typeof kn is 'number' nr.embargo_months = kn nr.embargo_end = '' # just to allow neat output later - can't be calculated until compared to a particular article else if k and rec[k]? and rec[k] not in ['', 'none', 'unclear'] if k is 'versions' and rec.versions.length nr.can_archive = true nr.version = if rec.versions.includes('ublish') then 'publishedVersion' else if rec.versions.includes('ccept') then 'acceptedVersion' else 'submittedVersion' if k in ['versions', 'locations', 'meta.contributors', 'meta.creator', 'meta.reviewer', 'provenance.archiving_policy', 'requirements.funder', 'journal'] rec[k] = rec[k].trim().replace(/\, /, ',').replace(/ \,/, ',').split ',' await @dot nr, (if k is 'license' then 'licence' else k), rec[k] nr.copyright_owner = nr.issuer.type if (not nr.copyright_owner or nr.copyright_owner.toLowerCase() is 'journal') and nr.issuer.type delete nr.requirements if JSON.stringify(nr.requirements) is '{}' ready.push nr return if ready.length is 1 then ready[0] else ready P.permissions.publishers = _sheet: '11rsHmef1j9Q9Xb0WtQ_BklQceaSkkFEIm7tJ4qz0fJk/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.affiliations = _sheet: '15fa1DADj6y_3aZQcP9-zBalhaThxzZw9dyEbxMBBb5Y/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.journals.example = (issn) -> issn ?= @params.doi ? @params.issn issn = issn.split(',') if typeof issn is 'string' try res = await @src.crossref.works 'ISSN:"' + issn.join('" OR ISSN:"') + '"', 1 return res.DOI return P.permissions.journals.transformative = _index: true, _prefix: false P.permissions.journals.transformative.load = () -> batch = [] tfs = await @fetch 'https://api.journalcheckertool.org/tj?q=*&include=title,issn&size=10000' batch.push(rec._source) for rec in tfs.hits.hits if batch.length await @permissions.journals.transformative '' await @permissions.journals.transformative batch return batch.length P.permissions.journals.transformative.load._bg = true P.permissions.journals.transformative.load._async = true P.permissions.journals.transformative.load._auth = 'root' P.permissions.journals.oa = (issn, oadoi) -> # NOTE it is still to be decided what licence is acceptable to be counted as OA on the crossref index. For now it's anything CC, including NC try issn ?= @params.journals ? @params.journal ? @params.issn ? @params.oa ret = {} if issn ret.articles = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '"' ret.open = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '" AND is_oa:true' # could add AND NOT licence:nc if ret.articles is ret.open ret.oa = true if jr = await @src.doaj.journals 'bibjson.pissn:"' + issn + '" OR bibjson.eissn:"' + issn + '"', 1 ret.open = ret.articles ret.doaj = true ret.oa = true if ex = await @permissions.journals.example issn oadoi ?= await @src.oadoi ex, 1 if oadoi? delete ret.oa ret.open = ret.articles ret.oadoi = true ret.oa = oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # oadoi.journal_is_oa else ret.oa = false return ret P.permissions.journals.oa.type = (issns, doajrnl, oadoi, crossref) -> if typeof issns is 'string' and issns.startsWith '10.' oadoi ?= await @src.oadoi issns crossref ?= await @src.crossref.works issns issns = undefined issns ?= oadoi?.journal_issns ? crossref?.ISSN ? @params.journals ? @params.journal ? @params.type ? @params.issn ? @params.issns issns = issns.split(',') if typeof issns is 'string' js = 'unknown' if crossref?.type? and crossref.type isnt 'journal-article' js = 'not applicable' else if not crossref?.type or crossref.type is 'journal-article' js = if oadoi?.oa_status is 'gold' or oadoi?.journal_is_oa or oadoi?.journal_is_in_doaj then 'gold' else if oadoi?.oa_status is 'bronze' then 'closed' else if oadoi?.oa_status is 'hybrid' then 'hybrid' else 'closed' if not doajrnl? and issns doajrnl = await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 if doajrnl? js = if doajrnl.bibjson?.apc?.has_apc is false then 'diamond' else 'gold' else if issns if issns and await @permissions.journals.transformative.count 'issn:"' + issns.join('" OR issn:"') + '"' js = 'transformative' else if js is 'closed' and await @src.oadoi.hybrid issns # check if it really is closed because sometimes OADOI says it is for one particular DOI but really it isn't (or was at time of publication of that article, but isn't now) js = 'hybrid' return js P.permissions.publishers.oa = (publisher) -> ret = publisher: (publisher ? @params.publisher ? @params.oa).replace /&/g, '' if not await @src.crossref.journals 'publisher:"' + ret.publisher + '"', 1 if fz = await @src.crossref.journals 'publisher:"' + ret.publisher.split(' ').join('" AND publisher:"') + '"', 1 if fz.publisher.toLowerCase() isnt ret.publisher.toLowerCase() lvs = await @levenshtein fz.publisher, ret.publisher ret.publisher = fz.publisher if lvs.distance < 5 or (if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b)/lvs.distance > 10 else ret.journals = 0 ret.journals ?= await @src.crossref.journals.count 'publisher:"' + ret.publisher + '" AND NOT discontinued:true' ret.open = await @src.doaj.journals.count 'publisher:"' + ret.publisher + '" AND NOT bibjson.discontinued_date:* AND NOT .bibjson.is_replaced_by:*' ret.percent = if ret.journals then Math.ceil((ret.open / ret.journals) * 100) else if ret.open then 100 else 0 ret.oa = (not ret.journals and ret.open) or (ret.journals and ret.journals is ret.open) return ret
85085
P.permissions = (meta, ror, getmeta, oadoi, crossref) -> # oadoi and crossref are just ways for other functions to pass in oadoi or crossref record objects to save looking them up again overall_policy_restriction = false haddoi = false _format = (rec) -> if haddoi and rec.embargo_months and (meta.published or meta.year) em = new Date Date.parse meta.published ? meta.year + '-01-01' em = new Date em.setMonth em.getMonth() + rec.embargo_months rec.embargo_end = em.toISOString().split('T')[0] delete rec.embargo_end if rec.embargo_end is '' rec.copyright_name = if rec.copyright_owner and rec.copyright_owner.toLowerCase() is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner and rec.copyright_owner.toLowerCase() in ['journal','affiliation'] then (meta.journal ? '') else if (haddoi and rec.copyright_owner and rec.copyright_owner.toLowerCase().includes('author')) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else '' if rec.copyright_name.toLowerCase() in ['publisher','journal'] and (crossref or meta.doi or rec.provenance?.example) crossref ?= await @src.crossref.works meta.doi ? rec.provenance.example for a in (crossref?.assertion ? []) if a.name.toLowerCase() is 'copyright' try rec.copyright_name = a.value try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim() rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year delete rec.copyright_year if rec.copyright_year is '' if haddoi and rec.deposit_statement? and rec.deposit_statement.includes '<<' fst = '' for pt in rec.deposit_statement.split '<<' if fst is '' and not pt.includes '>>' fst += pt else eph = pt.split '>>' ph = eph[0].toLowerCase() swaps = 'journal title': 'journal' 'vol': 'volume' 'date of publication': 'published' '(c)': 'year' 'article title': 'title' 'copyright name': 'copyright_name' ph = swaps[ph] if swaps[ph]? if ph is 'author' try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else fst += meta[ph] ? rec[ph] ? '' try fst += eph[1] rec.deposit_statement = fst if rec._id? rec.meta ?= {} rec.meta.source = 'https://' + (if S.dev then 'beta.oa.works/permissions/' else 'api.oa.works/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id overall_policy_restriction = rec.issuer.has_policy if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown'] delete rec[d] for d in ['_id', 'hide'] return rec _score = (rec) => score = if rec.can_archive then 1000 else 0 score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ' if rec.requirements? score -= 10 else score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0 score -= 5 if rec.licence score += if rec.issuer?.type.toLowerCase() is 'journal' then 5 else if rec.issuer?.type.toLowerCase() is 'publisher' then 4 else if rec.issuer?.type.toLowerCase() is 'university' then 3 else if rec.issuer?.type.toLowerCase() in ['article'] then 2 else 0 score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or Date.parse(rec.embargo_end) < Date.now()) return score if typeof meta is 'string' meta = if meta.startsWith('10.') then {doi: meta} else {issn: meta} meta ?= @copy @params delete meta.metadata if meta?.metadata is true # just a pass-through for us to show metadata for debug if meta?.permissions? and typeof meta.permissions is 'string' if meta.permissions.startsWith 'journal/' meta.issn = meta.permissions.replace 'journal/', '' else if meta.permissions.startsWith 'affiliation/' meta.ror = meta.permissions.replace 'affiliation/', '' else if meta.permissions.startsWith 'publisher/' meta.publisher = meta.permissions.replace 'publisher/', '' else if meta.permissions.startsWith('10.') and meta.permissions.includes '/' meta.doi = meta.permissions else if meta.permissions.includes('-') and meta.permissions.length < 10 and meta.permissions.length > 6 meta.issn = meta.permissions else if not meta.permissions.includes(' ') and not meta.permissions.includes(',') and meta.permissions.replace(/[0-9]/g, '').length isnt meta.permissions.length meta.ror = meta.permissions else meta.publisher = meta.permissions # but could be a ROR? delete meta.permissions if meta.affiliation meta.ror = meta.affiliation delete meta.affiliation meta.ror ?= ror meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.includes ',' if meta.journal and not meta.journal.includes(' ') and meta.journal.includes '-' meta.issn = meta.journal delete meta.journal issns = if Array.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.includes ',' if JSON.stringify(meta) is '{}' or (meta.issn and not JSON.stringify(meta.issn).includes('-')) or (meta.doi and (typeof meta.doi isnt 'string' or not meta.doi.startsWith('10.') or not meta.doi.includes '/')) return body: 'No valid DOI, ISSN, or ROR provided', status: 404 # NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror # we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article _getmeta = () => psm = @copy meta if JSON.stringify(psm) isnt '{}' for mk of rsm = (crossref ? (await @metadata(meta.doi)) ? {}) meta[mk] ?= rsm[mk] await _getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn) meta.published = meta.year + '-01-01' if not meta.published and meta.year haddoi = meta.doi? if meta.issn meta.issn = [meta.issn] if typeof meta.issn is 'string' if not issns.length # they're already meta.issn in this case anyway for inisn in meta.issn issns.push(inisn) if inisn not in issns # check just in case try meta.doi ?= await @permissions.journals.example issns if not haddoi and meta.doi await _getmeta() if haddoi and meta.type not in ['journal-article'] return body: 'DOI is not a journal article' status: 501 if meta.publisher and meta.publisher.includes('(') and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7) # could be a publisher name with the acronym at the end, like Public Library of Science (PLoS) # so get rid of the acronym because that is not included in the publisher name in crossref and other sources meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim() try meta.citation = '[' meta.citation += meta.title + '. ' if meta.title meta.citation += meta.journal + ' ' if meta.journal meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume meta.citation += meta.issue + ' ' if meta.issue meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages? if meta.year or meta.published meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')' meta.citation = meta.citation.trim() meta.citation += ']' perms = best_permission: undefined, all_permissions: [] rors = [] if meta.ror? meta.ror = [meta.ror] if typeof meta.ror is 'string' rs = await @permissions.affiliations 'issuer.id:"' + meta.ror.join('" OR issuer.id:"') + '"' if not rs?.hits?.total try # look up the ROR, get the ISO 3166-1 alpha-2 code, search affiliations for that rw = await @src.ror(if meta.ror.length is 1 then meta.ror[0] else 'id:"' + meta.ror.join(" OR id:") + '"') rw = rw.hits.hits[0]._source if rw.hits?.total if rw.country.country_code rs = await @permissions.affiliations 'issuer.id:"' + rw.country.country_code + '"' for rr in rs?.hits?.hits ? [] tr = await _format rr._source tr.score = await _score tr rors.push tr indoaj = undefined if issns for await rec from @index._for 'src_doaj_journals', 'bibjson.pissn:"' + issns.join('" OR bibjson.pissn:"') + '" OR bibjson.eissn:"' + issns.join('" OR bibjson.eissn:"') + '"' indoaj = rec if not indoaj issns.push(rec.bibjson.pissn) if rec.bibjson.pissn not in issns issns.push(rec.bibjson.eissn) if rec.bibjson.eissn not in issns if not indoaj? nisns = [] for await rec from @index._for 'src_openalex_venues', 'issn:"' + issns.join('" OR issn:"') + '"' for en in rec.issn nisns.push(en) if en not in nisns issns = nisns if issns.length ps = await @permissions.journals 'issuer.id:"' + issns.join('" OR issuer.id:"') + '"' for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp if meta.publisher qr = 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be ps = await @permissions.publishers qr for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp altoa = can_archive: true version: 'publishedVersion' versions: ['publishedVersion'] licence: undefined locations: ['institutional repository'] embargo_months: undefined issuer: type: 'Journal' has_policy: 'yes' meta: creator: '<EMAIL>' contributors: ['<EMAIL>'] monitoring: 'Automatic' if issns and indoaj ?= await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 for dl in (indoaj.bibjson?.license ? []) altoa.licence = dl.type if not altoa.licence or altoa.licence.length > dl.type altoa.licences ?= [] altoa.licences.push type: dl.type if not altoa.licence? and crj = await @src.crossref.journals 'ISSN.keyword:"' + issns.join('" OR ISSN.keyword:"') + '"', 1 for ll in (crj.license ? []) altoa.licence = ll.type if not altoa.licence or altoa.licence.length > ll.type if typeof altoa.licence is 'string' altoa.licence = altoa.licence.toLowerCase().trim() if altoa.licence.startsWith 'cc' altoa.licence = altoa.licence.replace(/ /g, '-') else if altoa.licence.includes 'creative' altoa.licence = if altoa.licence.includes('0') or altoa.licence.includes('zero') then 'cc0' else if altoa.licence.includes('share') then 'ccbysa' else if altoa.licence.includes('derivative') then 'ccbynd' else 'ccby' else delete altoa.licence else delete altoa.licence altoa.issuer.id = if indoaj.bibjson.eissn and indoaj.bibjson.pissn then [indoaj.bibjson.pissn, indoaj.bibjson.eissn] else if indoaj.bibjson.pissn then [indoaj.bibjson.pissn] else [indoaj.bibjson.eissn] altoa.embargo_months = 0 altoa.provenance = {oa_evidence: 'In DOAJ'} altoa.score = await _score altoa perms.all_permissions.push altoa else if not issns and meta.publisher and (await @permissions.publishers.oa meta.publisher).oa altoa.issuer.id = meta.publisher altoa.meta.creator = ['<EMAIL>'] altoa.meta.contributors = ['joe+oapublisher<EMAIL>'] altoa.provenance = {oa_evidence: 'OA publisher'} # does this mean embargo_months should be zero too? altoa.score = await _score altoa perms.all_permissions.push altoa if meta.doi oadoi ?= await @src.oadoi meta.doi if haddoi and oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # (haddoi or oadoi?.journal_is_oa) doa = can_archive: true version: oadoi.best_oa_location.version versions: [] licence: oadoi.best_oa_location.license locations: ['institutional repository'] issuer: type: 'article' has_policy: 'yes' id: meta.doi meta: creator: '<EMAIL>' contributors: ['<EMAIL>'] monitoring: 'Automatic' updated: oadoi.best_oa_location.updated provenance: oa_evidence: oadoi.best_oa_location.evidence if doa.version doa.versions = if doa.version in ['submittedVersion'] then ['submittedVersion'] else if doa.version in ['acceptedVersion'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion'] doa.score = await _score doa perms.all_permissions.push doa # sort rors by score, and sort alts by score, then combine if perms.all_permissions.length perms.all_permissions.sort (a, b) => return if (a.score < b.score) then 1 else -1 # note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything for wp in perms.all_permissions if not wp.licences? wp.licences = [] wp.licences.push(type: wp.licence) if wp.licence delete wp.issuer.journal_oa_type if haddoi and wp.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(wp.issuer.journal_oa_type_from) delete wp.issuer.journal_oa_type_from if (issns or wp.issuer?.type is 'journal') and not wp.issuer.journal_oa_type wp.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? wp.issuer.id), indoaj, oadoi, crossref if not wp.provenance?.enforcement_from perms.best_permission ?= @copy wp else if not meta.published or Date.parse(meta.published) > Date.parse wp.provenance.enforcement_from.split('/').reverse().join '-' # NOTE Date.parse would try to work on format 31/01/2020 but reads it in American, so would think 31 is a month and is too big # but 2020-01-31 is treated in ISO so the 31 will be the day. So, given that we use DD/MM/YYYY, split on / then reverse then join on - to get a better parse perms.best_permission ?= @copy wp if rors.length # this only happens as an augment to some other permission, so far rors.sort (a, b) => return if (a.score < b.score) then 1 else -1 for ro in rors # check this gives the order in the direction we want, else reverse it delete ro.issuer.journal_oa_type if haddoi and ro.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(ro.issuer.journal_oa_type_from) delete ro.issuer.journal_oa_type_from if (issns or ro.issuer?.type is 'journal') and not ro.issuer.journal_oa_type ro.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? ro.issuer.id), indoaj, oadoi, crossref perms.all_permissions.push ro if not perms.best_permission?.author_affiliation_requirement? if perms.best_permission? if not ro.provenance?.enforcement_from or not meta.published or Date.parse(meta.published) > Date.parse ro.provenance.enforcement_from.split('/').reverse().join '-' pb = @copy perms.best_permission for key in ['versions', 'locations'] for vl in ro[key] pb[key] ?= [] pb[key].push(vl) if vl not in pb[key] pb.version = if 'publishedVersion' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions then 'acceptedVersion' else 'submittedVersion' if pb.embargo_end if ro.embargo_end if Date.parse(ro.embargo_end) < Date.parse pb.embargo_end pb.embargo_end = ro.embargo_end if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months pb.embargo_months = ro.embargo_months pb.can_archive = true if ro.can_archive is true pb.requirements ?= {} pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0] pb.issuer.affiliation = ro.issuer pb.meta ?= {} pb.meta.affiliation = ro.meta pb.provenance ?= {} pb.provenance.affiliation = ro.provenance pb.score = parseInt(pb.score) + parseInt(ro.score) perms.best_permission = pb perms.all_permissions.push pb if overall_policy_restriction msgs = 'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it' return body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction status: 501 else perms.metadata = meta if @params.metadata is true or getmeta is true return perms P.permissions.journals = _sheet: '1ZTcYJUzhNJ<KEY>', _prefix: false, _format: (recs=[]) -> ready = [] for rec in (if typeof recs is 'object' and not Array.isArray(recs) then [recs] else recs) nr = # a controlled structure for JSON output, can't be guaranteed as not JSON spec, but Joe likes it for visual review can_archive: undefined version: undefined versions: [] licence: undefined locations: undefined embargo_months: undefined embargo_end: undefined deposit_statement: undefined copyright_owner: '' copyright_name: '' copyright_year: '' issuer: {} meta: {} provenance: {} requirements: {} for k of rec rec[k] = rec[k].trim() if typeof rec[k] is 'string' if k is 'id' nr.issuer.id = if typeof rec.id is 'string' and rec.id.includes(',') then rec.id.split(',') else rec.id if typeof nr.issuer.id is 'string' and nr.issuer.id.startsWith('10.') and nr.issuer.id.includes('/') and not nr.issuer.id.includes ' ' nr.DOI = nr.issuer.id else cids = [] for nid in (if typeof nr.issuer.id is 'string' then [nr.issuer.id] else nr.issuer.id) nid = nid.trim() if nr.issuer.type is 'journal' and nid.includes('-') and not nid.includes ' ' nid = nid.toUpperCase() if af = await @journal 'ISSN:"' + nid + '"', 1 #if af = await @src.openalex.venues 'issn:"' + nid + '"', 1 for an in af.issn cids.push(an) if an not in cids cids.push(nid) if nid not in cids nr.issuer.id = cids else if k is 'embargo_months' kn = if typeof rec[k] is 'number' then rec[k] else if typeof rec[k] is 'string' then parseInt(rec[k].trim()) else undefined if kn and typeof kn is 'number' nr.embargo_months = kn nr.embargo_end = '' # just to allow neat output later - can't be calculated until compared to a particular article else if k and rec[k]? and rec[k] not in ['', 'none', 'unclear'] if k is 'versions' and rec.versions.length nr.can_archive = true nr.version = if rec.versions.includes('ublish') then 'publishedVersion' else if rec.versions.includes('ccept') then 'acceptedVersion' else 'submittedVersion' if k in ['versions', 'locations', 'meta.contributors', 'meta.creator', 'meta.reviewer', 'provenance.archiving_policy', 'requirements.funder', 'journal'] rec[k] = rec[k].trim().replace(/\, /, ',').replace(/ \,/, ',').split ',' await @dot nr, (if k is 'license' then 'licence' else k), rec[k] nr.copyright_owner = nr.issuer.type if (not nr.copyright_owner or nr.copyright_owner.toLowerCase() is 'journal') and nr.issuer.type delete nr.requirements if JSON.stringify(nr.requirements) is '{}' ready.push nr return if ready.length is 1 then ready[0] else ready P.permissions.publishers = _sheet: '11rsHmef1j9Q9Xb0WtQ_BklQceaSkkFEIm7tJ4qz0fJk/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.affiliations = _sheet: '15fa1DADj6y_3aZQcP9-zBalhaThxzZw9dyEbxMBBb5Y/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.journals.example = (issn) -> issn ?= @params.doi ? @params.issn issn = issn.split(',') if typeof issn is 'string' try res = await @src.crossref.works 'ISSN:"' + issn.join('" OR ISSN:"') + '"', 1 return res.DOI return P.permissions.journals.transformative = _index: true, _prefix: false P.permissions.journals.transformative.load = () -> batch = [] tfs = await @fetch 'https://api.journalcheckertool.org/tj?q=*&include=title,issn&size=10000' batch.push(rec._source) for rec in tfs.hits.hits if batch.length await @permissions.journals.transformative '' await @permissions.journals.transformative batch return batch.length P.permissions.journals.transformative.load._bg = true P.permissions.journals.transformative.load._async = true P.permissions.journals.transformative.load._auth = 'root' P.permissions.journals.oa = (issn, oadoi) -> # NOTE it is still to be decided what licence is acceptable to be counted as OA on the crossref index. For now it's anything CC, including NC try issn ?= @params.journals ? @params.journal ? @params.issn ? @params.oa ret = {} if issn ret.articles = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '"' ret.open = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '" AND is_oa:true' # could add AND NOT licence:nc if ret.articles is ret.open ret.oa = true if jr = await @src.doaj.journals 'bibjson.pissn:"' + issn + '" OR bibjson.eissn:"' + issn + '"', 1 ret.open = ret.articles ret.doaj = true ret.oa = true if ex = await @permissions.journals.example issn oadoi ?= await @src.oadoi ex, 1 if oadoi? delete ret.oa ret.open = ret.articles ret.oadoi = true ret.oa = oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # oadoi.journal_is_oa else ret.oa = false return ret P.permissions.journals.oa.type = (issns, doajrnl, oadoi, crossref) -> if typeof issns is 'string' and issns.startsWith '10.' oadoi ?= await @src.oadoi issns crossref ?= await @src.crossref.works issns issns = undefined issns ?= oadoi?.journal_issns ? crossref?.ISSN ? @params.journals ? @params.journal ? @params.type ? @params.issn ? @params.issns issns = issns.split(',') if typeof issns is 'string' js = 'unknown' if crossref?.type? and crossref.type isnt 'journal-article' js = 'not applicable' else if not crossref?.type or crossref.type is 'journal-article' js = if oadoi?.oa_status is 'gold' or oadoi?.journal_is_oa or oadoi?.journal_is_in_doaj then 'gold' else if oadoi?.oa_status is 'bronze' then 'closed' else if oadoi?.oa_status is 'hybrid' then 'hybrid' else 'closed' if not doajrnl? and issns doajrnl = await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 if doajrnl? js = if doajrnl.bibjson?.apc?.has_apc is false then 'diamond' else 'gold' else if issns if issns and await @permissions.journals.transformative.count 'issn:"' + issns.join('" OR issn:"') + '"' js = 'transformative' else if js is 'closed' and await @src.oadoi.hybrid issns # check if it really is closed because sometimes OADOI says it is for one particular DOI but really it isn't (or was at time of publication of that article, but isn't now) js = 'hybrid' return js P.permissions.publishers.oa = (publisher) -> ret = publisher: (publisher ? @params.publisher ? @params.oa).replace /&/g, '' if not await @src.crossref.journals 'publisher:"' + ret.publisher + '"', 1 if fz = await @src.crossref.journals 'publisher:"' + ret.publisher.split(' ').join('" AND publisher:"') + '"', 1 if fz.publisher.toLowerCase() isnt ret.publisher.toLowerCase() lvs = await @levenshtein fz.publisher, ret.publisher ret.publisher = fz.publisher if lvs.distance < 5 or (if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b)/lvs.distance > 10 else ret.journals = 0 ret.journals ?= await @src.crossref.journals.count 'publisher:"' + ret.publisher + '" AND NOT discontinued:true' ret.open = await @src.doaj.journals.count 'publisher:"' + ret.publisher + '" AND NOT bibjson.discontinued_date:* AND NOT .bibjson.is_replaced_by:*' ret.percent = if ret.journals then Math.ceil((ret.open / ret.journals) * 100) else if ret.open then 100 else 0 ret.oa = (not ret.journals and ret.open) or (ret.journals and ret.journals is ret.open) return ret
true
P.permissions = (meta, ror, getmeta, oadoi, crossref) -> # oadoi and crossref are just ways for other functions to pass in oadoi or crossref record objects to save looking them up again overall_policy_restriction = false haddoi = false _format = (rec) -> if haddoi and rec.embargo_months and (meta.published or meta.year) em = new Date Date.parse meta.published ? meta.year + '-01-01' em = new Date em.setMonth em.getMonth() + rec.embargo_months rec.embargo_end = em.toISOString().split('T')[0] delete rec.embargo_end if rec.embargo_end is '' rec.copyright_name = if rec.copyright_owner and rec.copyright_owner.toLowerCase() is 'publisher' then (if typeof rec.issuer.parent_policy is 'string' then rec.issuer.parent_policy else if typeof rec.issuer.id is 'string' then rec.issuer.id else rec.issuer.id[0]) else if rec.copyright_owner and rec.copyright_owner.toLowerCase() in ['journal','affiliation'] then (meta.journal ? '') else if (haddoi and rec.copyright_owner and rec.copyright_owner.toLowerCase().includes('author')) and meta.author? and meta.author.length and (meta.author[0].name or meta.author[0].family) then (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else '' if rec.copyright_name.toLowerCase() in ['publisher','journal'] and (crossref or meta.doi or rec.provenance?.example) crossref ?= await @src.crossref.works meta.doi ? rec.provenance.example for a in (crossref?.assertion ? []) if a.name.toLowerCase() is 'copyright' try rec.copyright_name = a.value try rec.copyright_name = a.value.replace('\u00a9 ','').replace(/[0-9]/g,'').trim() rec.copyright_year = meta.year if haddoi and rec.copyright_year is '' and meta.year delete rec.copyright_year if rec.copyright_year is '' if haddoi and rec.deposit_statement? and rec.deposit_statement.includes '<<' fst = '' for pt in rec.deposit_statement.split '<<' if fst is '' and not pt.includes '>>' fst += pt else eph = pt.split '>>' ph = eph[0].toLowerCase() swaps = 'journal title': 'journal' 'vol': 'volume' 'date of publication': 'published' '(c)': 'year' 'article title': 'title' 'copyright name': 'copyright_name' ph = swaps[ph] if swaps[ph]? if ph is 'author' try fst += (meta.author[0].name ? meta.author[0].family) + (if meta.author.length > 1 then ' et al' else '') else fst += meta[ph] ? rec[ph] ? '' try fst += eph[1] rec.deposit_statement = fst if rec._id? rec.meta ?= {} rec.meta.source = 'https://' + (if S.dev then 'beta.oa.works/permissions/' else 'api.oa.works/permissions/') + (if rec.issuer.type then rec.issuer.type + '/' else '') + rec._id overall_policy_restriction = rec.issuer.has_policy if typeof rec.issuer?.has_policy is 'string' and rec.issuer.has_policy.toLowerCase().trim() in ['not publisher','takedown'] delete rec[d] for d in ['_id', 'hide'] return rec _score = (rec) => score = if rec.can_archive then 1000 else 0 score += 1000 if rec.provenance?.oa_evidence is 'In DOAJ' if rec.requirements? score -= 10 else score += if rec.version is 'publishedVersion' then 200 else if rec.version is 'acceptedVersion' then 100 else 0 score -= 5 if rec.licence score += if rec.issuer?.type.toLowerCase() is 'journal' then 5 else if rec.issuer?.type.toLowerCase() is 'publisher' then 4 else if rec.issuer?.type.toLowerCase() is 'university' then 3 else if rec.issuer?.type.toLowerCase() in ['article'] then 2 else 0 score -= 25 if rec.embargo_months and rec.embargo_months >= 36 and (not rec.embargo_end or Date.parse(rec.embargo_end) < Date.now()) return score if typeof meta is 'string' meta = if meta.startsWith('10.') then {doi: meta} else {issn: meta} meta ?= @copy @params delete meta.metadata if meta?.metadata is true # just a pass-through for us to show metadata for debug if meta?.permissions? and typeof meta.permissions is 'string' if meta.permissions.startsWith 'journal/' meta.issn = meta.permissions.replace 'journal/', '' else if meta.permissions.startsWith 'affiliation/' meta.ror = meta.permissions.replace 'affiliation/', '' else if meta.permissions.startsWith 'publisher/' meta.publisher = meta.permissions.replace 'publisher/', '' else if meta.permissions.startsWith('10.') and meta.permissions.includes '/' meta.doi = meta.permissions else if meta.permissions.includes('-') and meta.permissions.length < 10 and meta.permissions.length > 6 meta.issn = meta.permissions else if not meta.permissions.includes(' ') and not meta.permissions.includes(',') and meta.permissions.replace(/[0-9]/g, '').length isnt meta.permissions.length meta.ror = meta.permissions else meta.publisher = meta.permissions # but could be a ROR? delete meta.permissions if meta.affiliation meta.ror = meta.affiliation delete meta.affiliation meta.ror ?= ror meta.ror = meta.ror.split(',') if typeof meta.ror is 'string' and meta.ror.includes ',' if meta.journal and not meta.journal.includes(' ') and meta.journal.includes '-' meta.issn = meta.journal delete meta.journal issns = if Array.isArray(meta.issn) then meta.issn else [] # only if directly passed a list of ISSNs for the same article, accept them as the ISSNs list to use meta.issn = meta.issn.split(',') if typeof meta.issn is 'string' and meta.issn.includes ',' if JSON.stringify(meta) is '{}' or (meta.issn and not JSON.stringify(meta.issn).includes('-')) or (meta.doi and (typeof meta.doi isnt 'string' or not meta.doi.startsWith('10.') or not meta.doi.includes '/')) return body: 'No valid DOI, ISSN, or ROR provided', status: 404 # NOTE later will want to find affiliations related to the authors of the paper, but for now only act on affiliation provided as a ror # we now always try to get the metadata because joe wants to serve a 501 if the doi is not a journal article _getmeta = () => psm = @copy meta if JSON.stringify(psm) isnt '{}' for mk of rsm = (crossref ? (await @metadata(meta.doi)) ? {}) meta[mk] ?= rsm[mk] await _getmeta() if getmeta isnt false and meta.doi and (not meta.publisher or not meta.issn) meta.published = meta.year + '-01-01' if not meta.published and meta.year haddoi = meta.doi? if meta.issn meta.issn = [meta.issn] if typeof meta.issn is 'string' if not issns.length # they're already meta.issn in this case anyway for inisn in meta.issn issns.push(inisn) if inisn not in issns # check just in case try meta.doi ?= await @permissions.journals.example issns if not haddoi and meta.doi await _getmeta() if haddoi and meta.type not in ['journal-article'] return body: 'DOI is not a journal article' status: 501 if meta.publisher and meta.publisher.includes('(') and meta.publisher.lastIndexOf(')') > (meta.publisher.length*.7) # could be a publisher name with the acronym at the end, like Public Library of Science (PLoS) # so get rid of the acronym because that is not included in the publisher name in crossref and other sources meta.publisher = meta.publisher.substring(0, meta.publisher.lastIndexOf('(')).trim() try meta.citation = '[' meta.citation += meta.title + '. ' if meta.title meta.citation += meta.journal + ' ' if meta.journal meta.citation += meta.volume + (if meta.issue then ', ' else ' ') if meta.volume meta.citation += meta.issue + ' ' if meta.issue meta.citation += 'p' + (meta.page ? meta.pages) if meta.page? or meta.pages? if meta.year or meta.published meta.citation += ' (' + (meta.year ? meta.published).split('-')[0] + ')' meta.citation = meta.citation.trim() meta.citation += ']' perms = best_permission: undefined, all_permissions: [] rors = [] if meta.ror? meta.ror = [meta.ror] if typeof meta.ror is 'string' rs = await @permissions.affiliations 'issuer.id:"' + meta.ror.join('" OR issuer.id:"') + '"' if not rs?.hits?.total try # look up the ROR, get the ISO 3166-1 alpha-2 code, search affiliations for that rw = await @src.ror(if meta.ror.length is 1 then meta.ror[0] else 'id:"' + meta.ror.join(" OR id:") + '"') rw = rw.hits.hits[0]._source if rw.hits?.total if rw.country.country_code rs = await @permissions.affiliations 'issuer.id:"' + rw.country.country_code + '"' for rr in rs?.hits?.hits ? [] tr = await _format rr._source tr.score = await _score tr rors.push tr indoaj = undefined if issns for await rec from @index._for 'src_doaj_journals', 'bibjson.pissn:"' + issns.join('" OR bibjson.pissn:"') + '" OR bibjson.eissn:"' + issns.join('" OR bibjson.eissn:"') + '"' indoaj = rec if not indoaj issns.push(rec.bibjson.pissn) if rec.bibjson.pissn not in issns issns.push(rec.bibjson.eissn) if rec.bibjson.eissn not in issns if not indoaj? nisns = [] for await rec from @index._for 'src_openalex_venues', 'issn:"' + issns.join('" OR issn:"') + '"' for en in rec.issn nisns.push(en) if en not in nisns issns = nisns if issns.length ps = await @permissions.journals 'issuer.id:"' + issns.join('" OR issuer.id:"') + '"' for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp if meta.publisher qr = 'issuer.id:"' + meta.publisher + '"' # how exact/fuzzy can this be ps = await @permissions.publishers qr for p in ps?.hits?.hits ? [] rp = await _format p._source rp.score = await _score rp perms.all_permissions.push rp altoa = can_archive: true version: 'publishedVersion' versions: ['publishedVersion'] licence: undefined locations: ['institutional repository'] embargo_months: undefined issuer: type: 'Journal' has_policy: 'yes' meta: creator: 'PI:EMAIL:<EMAIL>END_PI' contributors: ['PI:EMAIL:<EMAIL>END_PI'] monitoring: 'Automatic' if issns and indoaj ?= await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 for dl in (indoaj.bibjson?.license ? []) altoa.licence = dl.type if not altoa.licence or altoa.licence.length > dl.type altoa.licences ?= [] altoa.licences.push type: dl.type if not altoa.licence? and crj = await @src.crossref.journals 'ISSN.keyword:"' + issns.join('" OR ISSN.keyword:"') + '"', 1 for ll in (crj.license ? []) altoa.licence = ll.type if not altoa.licence or altoa.licence.length > ll.type if typeof altoa.licence is 'string' altoa.licence = altoa.licence.toLowerCase().trim() if altoa.licence.startsWith 'cc' altoa.licence = altoa.licence.replace(/ /g, '-') else if altoa.licence.includes 'creative' altoa.licence = if altoa.licence.includes('0') or altoa.licence.includes('zero') then 'cc0' else if altoa.licence.includes('share') then 'ccbysa' else if altoa.licence.includes('derivative') then 'ccbynd' else 'ccby' else delete altoa.licence else delete altoa.licence altoa.issuer.id = if indoaj.bibjson.eissn and indoaj.bibjson.pissn then [indoaj.bibjson.pissn, indoaj.bibjson.eissn] else if indoaj.bibjson.pissn then [indoaj.bibjson.pissn] else [indoaj.bibjson.eissn] altoa.embargo_months = 0 altoa.provenance = {oa_evidence: 'In DOAJ'} altoa.score = await _score altoa perms.all_permissions.push altoa else if not issns and meta.publisher and (await @permissions.publishers.oa meta.publisher).oa altoa.issuer.id = meta.publisher altoa.meta.creator = ['PI:EMAIL:<EMAIL>END_PI'] altoa.meta.contributors = ['joe+oapublisherPI:EMAIL:<EMAIL>END_PI'] altoa.provenance = {oa_evidence: 'OA publisher'} # does this mean embargo_months should be zero too? altoa.score = await _score altoa perms.all_permissions.push altoa if meta.doi oadoi ?= await @src.oadoi meta.doi if haddoi and oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # (haddoi or oadoi?.journal_is_oa) doa = can_archive: true version: oadoi.best_oa_location.version versions: [] licence: oadoi.best_oa_location.license locations: ['institutional repository'] issuer: type: 'article' has_policy: 'yes' id: meta.doi meta: creator: 'PI:EMAIL:<EMAIL>END_PI' contributors: ['PI:EMAIL:<EMAIL>END_PI'] monitoring: 'Automatic' updated: oadoi.best_oa_location.updated provenance: oa_evidence: oadoi.best_oa_location.evidence if doa.version doa.versions = if doa.version in ['submittedVersion'] then ['submittedVersion'] else if doa.version in ['acceptedVersion'] then ['submittedVersion', 'acceptedVersion'] else ['submittedVersion', 'acceptedVersion', 'publishedVersion'] doa.score = await _score doa perms.all_permissions.push doa # sort rors by score, and sort alts by score, then combine if perms.all_permissions.length perms.all_permissions.sort (a, b) => return if (a.score < b.score) then 1 else -1 # note if enforcement_from is after published date, don't apply the permission. If no date, the permission applies to everything for wp in perms.all_permissions if not wp.licences? wp.licences = [] wp.licences.push(type: wp.licence) if wp.licence delete wp.issuer.journal_oa_type if haddoi and wp.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(wp.issuer.journal_oa_type_from) delete wp.issuer.journal_oa_type_from if (issns or wp.issuer?.type is 'journal') and not wp.issuer.journal_oa_type wp.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? wp.issuer.id), indoaj, oadoi, crossref if not wp.provenance?.enforcement_from perms.best_permission ?= @copy wp else if not meta.published or Date.parse(meta.published) > Date.parse wp.provenance.enforcement_from.split('/').reverse().join '-' # NOTE Date.parse would try to work on format 31/01/2020 but reads it in American, so would think 31 is a month and is too big # but 2020-01-31 is treated in ISO so the 31 will be the day. So, given that we use DD/MM/YYYY, split on / then reverse then join on - to get a better parse perms.best_permission ?= @copy wp if rors.length # this only happens as an augment to some other permission, so far rors.sort (a, b) => return if (a.score < b.score) then 1 else -1 for ro in rors # check this gives the order in the direction we want, else reverse it delete ro.issuer.journal_oa_type if haddoi and ro.issuer?.journal_oa_type_from and meta.published and Date.parse(meta.published) < Date.parse(ro.issuer.journal_oa_type_from) delete ro.issuer.journal_oa_type_from if (issns or ro.issuer?.type is 'journal') and not ro.issuer.journal_oa_type ro.issuer.journal_oa_type = await @permissions.journals.oa.type (issns ? ro.issuer.id), indoaj, oadoi, crossref perms.all_permissions.push ro if not perms.best_permission?.author_affiliation_requirement? if perms.best_permission? if not ro.provenance?.enforcement_from or not meta.published or Date.parse(meta.published) > Date.parse ro.provenance.enforcement_from.split('/').reverse().join '-' pb = @copy perms.best_permission for key in ['versions', 'locations'] for vl in ro[key] pb[key] ?= [] pb[key].push(vl) if vl not in pb[key] pb.version = if 'publishedVersion' in pb.versions then 'publishedVersion' else if 'acceptedVersion' in pb.versions then 'acceptedVersion' else 'submittedVersion' if pb.embargo_end if ro.embargo_end if Date.parse(ro.embargo_end) < Date.parse pb.embargo_end pb.embargo_end = ro.embargo_end if pb.embargo_months and ro.embargo_months? and ro.embargo_months < pb.embargo_months pb.embargo_months = ro.embargo_months pb.can_archive = true if ro.can_archive is true pb.requirements ?= {} pb.requirements.author_affiliation_requirement = if not meta.ror? then ro.issuer.id else if typeof meta.ror is 'string' then meta.ror else meta.ror[0] pb.issuer.affiliation = ro.issuer pb.meta ?= {} pb.meta.affiliation = ro.meta pb.provenance ?= {} pb.provenance.affiliation = ro.provenance pb.score = parseInt(pb.score) + parseInt(ro.score) perms.best_permission = pb perms.all_permissions.push pb if overall_policy_restriction msgs = 'not publisher': 'Please find another DOI for this article as this is provided as this doesn’t allow us to find required information like who published it' return body: if typeof overall_policy_restriction isnt 'string' then overall_policy_restriction else msgs[overall_policy_restriction.toLowerCase()] ? overall_policy_restriction status: 501 else perms.metadata = meta if @params.metadata is true or getmeta is true return perms P.permissions.journals = _sheet: '1ZTcYJUzhNJPI:KEY:<KEY>END_PI', _prefix: false, _format: (recs=[]) -> ready = [] for rec in (if typeof recs is 'object' and not Array.isArray(recs) then [recs] else recs) nr = # a controlled structure for JSON output, can't be guaranteed as not JSON spec, but Joe likes it for visual review can_archive: undefined version: undefined versions: [] licence: undefined locations: undefined embargo_months: undefined embargo_end: undefined deposit_statement: undefined copyright_owner: '' copyright_name: '' copyright_year: '' issuer: {} meta: {} provenance: {} requirements: {} for k of rec rec[k] = rec[k].trim() if typeof rec[k] is 'string' if k is 'id' nr.issuer.id = if typeof rec.id is 'string' and rec.id.includes(',') then rec.id.split(',') else rec.id if typeof nr.issuer.id is 'string' and nr.issuer.id.startsWith('10.') and nr.issuer.id.includes('/') and not nr.issuer.id.includes ' ' nr.DOI = nr.issuer.id else cids = [] for nid in (if typeof nr.issuer.id is 'string' then [nr.issuer.id] else nr.issuer.id) nid = nid.trim() if nr.issuer.type is 'journal' and nid.includes('-') and not nid.includes ' ' nid = nid.toUpperCase() if af = await @journal 'ISSN:"' + nid + '"', 1 #if af = await @src.openalex.venues 'issn:"' + nid + '"', 1 for an in af.issn cids.push(an) if an not in cids cids.push(nid) if nid not in cids nr.issuer.id = cids else if k is 'embargo_months' kn = if typeof rec[k] is 'number' then rec[k] else if typeof rec[k] is 'string' then parseInt(rec[k].trim()) else undefined if kn and typeof kn is 'number' nr.embargo_months = kn nr.embargo_end = '' # just to allow neat output later - can't be calculated until compared to a particular article else if k and rec[k]? and rec[k] not in ['', 'none', 'unclear'] if k is 'versions' and rec.versions.length nr.can_archive = true nr.version = if rec.versions.includes('ublish') then 'publishedVersion' else if rec.versions.includes('ccept') then 'acceptedVersion' else 'submittedVersion' if k in ['versions', 'locations', 'meta.contributors', 'meta.creator', 'meta.reviewer', 'provenance.archiving_policy', 'requirements.funder', 'journal'] rec[k] = rec[k].trim().replace(/\, /, ',').replace(/ \,/, ',').split ',' await @dot nr, (if k is 'license' then 'licence' else k), rec[k] nr.copyright_owner = nr.issuer.type if (not nr.copyright_owner or nr.copyright_owner.toLowerCase() is 'journal') and nr.issuer.type delete nr.requirements if JSON.stringify(nr.requirements) is '{}' ready.push nr return if ready.length is 1 then ready[0] else ready P.permissions.publishers = _sheet: '11rsHmef1j9Q9Xb0WtQ_BklQceaSkkFEIm7tJ4qz0fJk/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.affiliations = _sheet: '15fa1DADj6y_3aZQcP9-zBalhaThxzZw9dyEbxMBBb5Y/Main', _prefix: false, _format: P.permissions.journals._format P.permissions.journals.example = (issn) -> issn ?= @params.doi ? @params.issn issn = issn.split(',') if typeof issn is 'string' try res = await @src.crossref.works 'ISSN:"' + issn.join('" OR ISSN:"') + '"', 1 return res.DOI return P.permissions.journals.transformative = _index: true, _prefix: false P.permissions.journals.transformative.load = () -> batch = [] tfs = await @fetch 'https://api.journalcheckertool.org/tj?q=*&include=title,issn&size=10000' batch.push(rec._source) for rec in tfs.hits.hits if batch.length await @permissions.journals.transformative '' await @permissions.journals.transformative batch return batch.length P.permissions.journals.transformative.load._bg = true P.permissions.journals.transformative.load._async = true P.permissions.journals.transformative.load._auth = 'root' P.permissions.journals.oa = (issn, oadoi) -> # NOTE it is still to be decided what licence is acceptable to be counted as OA on the crossref index. For now it's anything CC, including NC try issn ?= @params.journals ? @params.journal ? @params.issn ? @params.oa ret = {} if issn ret.articles = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '"' ret.open = await @src.crossref.works.count 'type:"journal-article" AND ISSN:"' + issn + '" AND is_oa:true' # could add AND NOT licence:nc if ret.articles is ret.open ret.oa = true if jr = await @src.doaj.journals 'bibjson.pissn:"' + issn + '" OR bibjson.eissn:"' + issn + '"', 1 ret.open = ret.articles ret.doaj = true ret.oa = true if ex = await @permissions.journals.example issn oadoi ?= await @src.oadoi ex, 1 if oadoi? delete ret.oa ret.open = ret.articles ret.oadoi = true ret.oa = oadoi?.best_oa_location?.license and oadoi.best_oa_location.license.includes 'cc' # oadoi.journal_is_oa else ret.oa = false return ret P.permissions.journals.oa.type = (issns, doajrnl, oadoi, crossref) -> if typeof issns is 'string' and issns.startsWith '10.' oadoi ?= await @src.oadoi issns crossref ?= await @src.crossref.works issns issns = undefined issns ?= oadoi?.journal_issns ? crossref?.ISSN ? @params.journals ? @params.journal ? @params.type ? @params.issn ? @params.issns issns = issns.split(',') if typeof issns is 'string' js = 'unknown' if crossref?.type? and crossref.type isnt 'journal-article' js = 'not applicable' else if not crossref?.type or crossref.type is 'journal-article' js = if oadoi?.oa_status is 'gold' or oadoi?.journal_is_oa or oadoi?.journal_is_in_doaj then 'gold' else if oadoi?.oa_status is 'bronze' then 'closed' else if oadoi?.oa_status is 'hybrid' then 'hybrid' else 'closed' if not doajrnl? and issns doajrnl = await @src.doaj.journals 'bibjson.eissn.keyword:"' + issns.join('" OR bibjson.eissn.keyword:"') + '" OR bibjson.pissn.keyword:"' + issns.join('" OR bibjson.pissn.keyword:"') + '"', 1 if doajrnl? js = if doajrnl.bibjson?.apc?.has_apc is false then 'diamond' else 'gold' else if issns if issns and await @permissions.journals.transformative.count 'issn:"' + issns.join('" OR issn:"') + '"' js = 'transformative' else if js is 'closed' and await @src.oadoi.hybrid issns # check if it really is closed because sometimes OADOI says it is for one particular DOI but really it isn't (or was at time of publication of that article, but isn't now) js = 'hybrid' return js P.permissions.publishers.oa = (publisher) -> ret = publisher: (publisher ? @params.publisher ? @params.oa).replace /&/g, '' if not await @src.crossref.journals 'publisher:"' + ret.publisher + '"', 1 if fz = await @src.crossref.journals 'publisher:"' + ret.publisher.split(' ').join('" AND publisher:"') + '"', 1 if fz.publisher.toLowerCase() isnt ret.publisher.toLowerCase() lvs = await @levenshtein fz.publisher, ret.publisher ret.publisher = fz.publisher if lvs.distance < 5 or (if lvs.length.a > lvs.length.b then lvs.length.a else lvs.length.b)/lvs.distance > 10 else ret.journals = 0 ret.journals ?= await @src.crossref.journals.count 'publisher:"' + ret.publisher + '" AND NOT discontinued:true' ret.open = await @src.doaj.journals.count 'publisher:"' + ret.publisher + '" AND NOT bibjson.discontinued_date:* AND NOT .bibjson.is_replaced_by:*' ret.percent = if ret.journals then Math.ceil((ret.open / ret.journals) * 100) else if ret.open then 100 else 0 ret.oa = (not ret.journals and ret.open) or (ret.journals and ret.journals is ret.open) return ret
[ { "context": "iew Tests for no-use-before-define rule.\n# @author Ilya Volodin\n###\n\n'use strict'\n\n#-----------------------------", "end": 80, "score": 0.999819815158844, "start": 68, "tag": "NAME", "value": "Ilya Volodin" } ]
src/tests/rules/no-use-before-define.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-use-before-define rule. # @author Ilya Volodin ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-use-before-define' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-use-before-define', rule, valid: [ ''' a = 10 alert a ''' 'b = (a) -> alert(a)' 'Object.hasOwnProperty.call(a)' 'a = -> alert(arguments)' 'foo = (a = 1) ->' , code: ''' b = -> a() a = -> alert(arguments) ''' options: ['nofunc'] , ''' do -> a = 42 alert a ''' ''' class A new A() ''' ''' a = 0 b = a ''' '{a = 0, b = a} = {}' '[a = 0, b = a] = {}' 'foo = -> foo()' ''' a = null for a of a ; ''' ''' a = null for a from a ; ''' ''' a = null for a in a ; ''' ''' b for b in [0...1] ''' ''' b++ while b ''' ''' not b unless b ''' , # object style options code: ''' b = -> a() a = -> alert(arguments) ''' options: [functions: no] , code: ''' foo = -> new A class A ''' options: [classes: no] , # "variables" option code: ''' foo = -> bar bar = null ''' options: [variables: no] , ''' nums = (y for n in [1, 2, 3] when n & 1) ''' ''' odds = (prop + '!' for prop, value of obj when value & 1) ''' ''' ob = a: for v, i in test then i b: for v, i in test then i ''' ] invalid: [ code: ''' a++ a = 19 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' alert a[1] a = [1, 3] ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert b b = 10 a() ''' errors: [ message: "'a' was used before it was defined.", type: 'Identifier' , message: "'b' was used before it was defined.", type: 'Identifier' ] , code: ''' a() a = -> ''' options: ['nofunc'] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert(arguments) ''' options: [functions: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do -> alert a a = 42 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do => a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' (-> a())() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() try throw new Error() catch foo a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' f = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' switch foo when 1 a() else a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' if true foo = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # object style options code: ''' a() a = -> ''' options: [functions: no, classes: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' options: [functions: no, classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' options: [classes: no] parserOptions: ecmaVersion: 6 errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' options: [classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , # invalid initializers code: 'a = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = a + b' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = foo a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'foo = (a = a) ->' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = a} = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = a] = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{b = a, a} = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[b = a, a] = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = 0} = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = 0] = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # "variables" option code: ''' foo = -> bar bar = 1 bar ''' options: [variables: no] errors: [ message: "'bar' was used before it was defined.", type: 'Identifier' ] , code: ''' foo foo = null ''' options: [variables: no] errors: [ message: "'foo' was used before it was defined.", type: 'Identifier' ] , code: ''' for x of xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' for x from xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' try catch {message = x} ; x = '' ''' errors: ["'x' was used before it was defined."] , code: ''' a() try throw new Error() catch a ''' errors: ["'a' was used before it was defined."] ]
126953
###* # @fileoverview Tests for no-use-before-define rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-use-before-define' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-use-before-define', rule, valid: [ ''' a = 10 alert a ''' 'b = (a) -> alert(a)' 'Object.hasOwnProperty.call(a)' 'a = -> alert(arguments)' 'foo = (a = 1) ->' , code: ''' b = -> a() a = -> alert(arguments) ''' options: ['nofunc'] , ''' do -> a = 42 alert a ''' ''' class A new A() ''' ''' a = 0 b = a ''' '{a = 0, b = a} = {}' '[a = 0, b = a] = {}' 'foo = -> foo()' ''' a = null for a of a ; ''' ''' a = null for a from a ; ''' ''' a = null for a in a ; ''' ''' b for b in [0...1] ''' ''' b++ while b ''' ''' not b unless b ''' , # object style options code: ''' b = -> a() a = -> alert(arguments) ''' options: [functions: no] , code: ''' foo = -> new A class A ''' options: [classes: no] , # "variables" option code: ''' foo = -> bar bar = null ''' options: [variables: no] , ''' nums = (y for n in [1, 2, 3] when n & 1) ''' ''' odds = (prop + '!' for prop, value of obj when value & 1) ''' ''' ob = a: for v, i in test then i b: for v, i in test then i ''' ] invalid: [ code: ''' a++ a = 19 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' alert a[1] a = [1, 3] ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert b b = 10 a() ''' errors: [ message: "'a' was used before it was defined.", type: 'Identifier' , message: "'b' was used before it was defined.", type: 'Identifier' ] , code: ''' a() a = -> ''' options: ['nofunc'] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert(arguments) ''' options: [functions: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do -> alert a a = 42 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do => a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' (-> a())() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() try throw new Error() catch foo a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' f = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' switch foo when 1 a() else a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' if true foo = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # object style options code: ''' a() a = -> ''' options: [functions: no, classes: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' options: [functions: no, classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' options: [classes: no] parserOptions: ecmaVersion: 6 errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' options: [classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , # invalid initializers code: 'a = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = a + b' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = foo a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'foo = (a = a) ->' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = a} = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = a] = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{b = a, a} = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[b = a, a] = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = 0} = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = 0] = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # "variables" option code: ''' foo = -> bar bar = 1 bar ''' options: [variables: no] errors: [ message: "'bar' was used before it was defined.", type: 'Identifier' ] , code: ''' foo foo = null ''' options: [variables: no] errors: [ message: "'foo' was used before it was defined.", type: 'Identifier' ] , code: ''' for x of xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' for x from xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' try catch {message = x} ; x = '' ''' errors: ["'x' was used before it was defined."] , code: ''' a() try throw new Error() catch a ''' errors: ["'a' was used before it was defined."] ]
true
###* # @fileoverview Tests for no-use-before-define rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-use-before-define' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-use-before-define', rule, valid: [ ''' a = 10 alert a ''' 'b = (a) -> alert(a)' 'Object.hasOwnProperty.call(a)' 'a = -> alert(arguments)' 'foo = (a = 1) ->' , code: ''' b = -> a() a = -> alert(arguments) ''' options: ['nofunc'] , ''' do -> a = 42 alert a ''' ''' class A new A() ''' ''' a = 0 b = a ''' '{a = 0, b = a} = {}' '[a = 0, b = a] = {}' 'foo = -> foo()' ''' a = null for a of a ; ''' ''' a = null for a from a ; ''' ''' a = null for a in a ; ''' ''' b for b in [0...1] ''' ''' b++ while b ''' ''' not b unless b ''' , # object style options code: ''' b = -> a() a = -> alert(arguments) ''' options: [functions: no] , code: ''' foo = -> new A class A ''' options: [classes: no] , # "variables" option code: ''' foo = -> bar bar = null ''' options: [variables: no] , ''' nums = (y for n in [1, 2, 3] when n & 1) ''' ''' odds = (prop + '!' for prop, value of obj when value & 1) ''' ''' ob = a: for v, i in test then i b: for v, i in test then i ''' ] invalid: [ code: ''' a++ a = 19 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' alert a[1] a = [1, 3] ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert b b = 10 a() ''' errors: [ message: "'a' was used before it was defined.", type: 'Identifier' , message: "'b' was used before it was defined.", type: 'Identifier' ] , code: ''' a() a = -> ''' options: ['nofunc'] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() a = -> alert(arguments) ''' options: [functions: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do -> alert a a = 42 ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' do => a() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' (-> a())() a = -> ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' a() try throw new Error() catch foo a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' f = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A class A ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' switch foo when 1 a() else a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' if true foo = -> a a = null ''' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # object style options code: ''' a() a = -> ''' options: [functions: no, classes: no] errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: ''' new A() class A ''' options: [functions: no, classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' new A() A = class ''' options: [classes: no] parserOptions: ecmaVersion: 6 errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , code: ''' foo = -> new A() A = class ''' options: [classes: no] errors: [message: "'A' was used before it was defined.", type: 'Identifier'] , # invalid initializers code: 'a = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = a + b' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'a = foo a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: 'foo = (a = a) ->' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = a} = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = a] = []' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{b = a, a} = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[b = a, a] = {}' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '{a = 0} = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , code: '[a = 0] = a' errors: [message: "'a' was used before it was defined.", type: 'Identifier'] , # "variables" option code: ''' foo = -> bar bar = 1 bar ''' options: [variables: no] errors: [ message: "'bar' was used before it was defined.", type: 'Identifier' ] , code: ''' foo foo = null ''' options: [variables: no] errors: [ message: "'foo' was used before it was defined.", type: 'Identifier' ] , code: ''' for x of xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' for x from xs ; xs = [] ''' errors: ["'xs' was used before it was defined."] , code: ''' try catch {message = x} ; x = '' ''' errors: ["'x' was used before it was defined."] , code: ''' a() try throw new Error() catch a ''' errors: ["'a' was used before it was defined."] ]
[ { "context": "om/articulate/grunt-release\n#\n# Copyright (c) 2013 Andrew Nordman\n# Licensed under the MIT license.\n#\n\nmodule.expor", "end": 101, "score": 0.9998000264167786, "start": 87, "tag": "NAME", "value": "Andrew Nordman" } ]
Gruntfile.coffee
articulate/grunt-release
0
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 Andrew Nordman # Licensed under the MIT license. # module.exports = (grunt) -> grunt.initConfig jshint: all: [ 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' clean: tests: [ 'tmp' ] nodeunit: tests: ['test/*_test.js'] coffee: src: expand: true flatten: false cwd: 'src' src: '**/*.coffee' dest: '.' ext: '.js' release: github: options: repo: 'articulate/grunt-release' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.registerTask 'test', ['clean', 'release', 'nodeunit'] grunt.registerTask 'default', ['jshint', 'test']
40622
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 <NAME> # Licensed under the MIT license. # module.exports = (grunt) -> grunt.initConfig jshint: all: [ 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' clean: tests: [ 'tmp' ] nodeunit: tests: ['test/*_test.js'] coffee: src: expand: true flatten: false cwd: 'src' src: '**/*.coffee' dest: '.' ext: '.js' release: github: options: repo: 'articulate/grunt-release' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.registerTask 'test', ['clean', 'release', 'nodeunit'] grunt.registerTask 'default', ['jshint', 'test']
true
# # grunt-release # https://github.com/articulate/grunt-release # # Copyright (c) 2013 PI:NAME:<NAME>END_PI # Licensed under the MIT license. # module.exports = (grunt) -> grunt.initConfig jshint: all: [ 'tasks/*.js' '<%= nodeunit.tests %>' ] options: jshintrc: '.jshintrc' clean: tests: [ 'tmp' ] nodeunit: tests: ['test/*_test.js'] coffee: src: expand: true flatten: false cwd: 'src' src: '**/*.coffee' dest: '.' ext: '.js' release: github: options: repo: 'articulate/grunt-release' grunt.loadTasks 'tasks' grunt.loadNpmTasks 'grunt-contrib-jshint' grunt.loadNpmTasks 'grunt-contrib-clean' grunt.loadNpmTasks 'grunt-contrib-nodeunit' grunt.loadNpmTasks 'grunt-contrib-coffee' grunt.registerTask 'test', ['clean', 'release', 'nodeunit'] grunt.registerTask 'default', ['jshint', 'test']
[ { "context": "# Copyright © 2014–6 Brad Ackerman.\n#\n# Licensed under the Apache License, Version 2", "end": 34, "score": 0.9998487234115601, "start": 21, "tag": "NAME", "value": "Brad Ackerman" } ]
assets/coffee/directives/char-picker.coffee
backerman/eveindy
2
# Copyright © 2014–6 Brad Ackerman. # # 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. # Constants angular.module 'eveindy' .directive 'charPicker', ['$timeout', ($timeout) -> templateUrl: 'view/directives/char-picker.html' restrict: 'E' transclude: true scope: characters: '=' name: '@' selectedCharacter: '=charSelected' selected: '&changed' link: ($scope, $element, $attrs) -> # Set a default input field name. $scope.name ?= "selectedToon" # Ensure that the selected function is only executed after the model # has been updated. $scope.selectionChanged = (params) -> $timeout(() -> $scope.selected(params)) ]
198035
# Copyright © 2014–6 <NAME>. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Constants angular.module 'eveindy' .directive 'charPicker', ['$timeout', ($timeout) -> templateUrl: 'view/directives/char-picker.html' restrict: 'E' transclude: true scope: characters: '=' name: '@' selectedCharacter: '=charSelected' selected: '&changed' link: ($scope, $element, $attrs) -> # Set a default input field name. $scope.name ?= "selectedToon" # Ensure that the selected function is only executed after the model # has been updated. $scope.selectionChanged = (params) -> $timeout(() -> $scope.selected(params)) ]
true
# Copyright © 2014–6 PI:NAME:<NAME>END_PI. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Constants angular.module 'eveindy' .directive 'charPicker', ['$timeout', ($timeout) -> templateUrl: 'view/directives/char-picker.html' restrict: 'E' transclude: true scope: characters: '=' name: '@' selectedCharacter: '=charSelected' selected: '&changed' link: ($scope, $element, $attrs) -> # Set a default input field name. $scope.name ?= "selectedToon" # Ensure that the selected function is only executed after the model # has been updated. $scope.selectionChanged = (params) -> $timeout(() -> $scope.selected(params)) ]
[ { "context": "nal notes required for the script>\n#\n# Author:\n# Yoanm <yoanm@users.noreply.github.com>\n\nforwardToRobotF", "end": 481, "score": 0.9408101439476013, "start": 476, "tag": "USERNAME", "value": "Yoanm" }, { "context": "s required for the script>\n#\n# Author:\n# Yoanm <yoanm@users.noreply.github.com>\n\nforwardToRobotFactory = require './utils/forwar", "end": 513, "score": 0.9999259114265442, "start": 483, "tag": "EMAIL", "value": "yoanm@users.noreply.github.com" } ]
src/hubot-slack-command-forwarder.coffee
yoanm/node-hubot-slack-command-forwarder
0
# Description # Hubot script to manage slack command forwarding to hubot # # Configuration: # SLACK_APP_TOKEN in case you want to use another token than the one used for hubot-slack adapter # # Commands: # /hubot => hubot # /hubot test2 => hubot test2 # /hubot test3 arg1 arg2 => hubot test3 arg1 arg2 # /subCommand => hubot subCommand # /subCommand arg1 arg2 => hubot subCommand arg1 arg2 # # Notes: # <optional notes required for the script> # # Author: # Yoanm <yoanm@users.noreply.github.com> forwardToRobotFactory = require './utils/forward-to-robot'; module.exports = (robot) -> webApiToken = process.env.SLACK_APP_TOKEN || robot.adapter.options.token; forwardToRobot = forwardToRobotFactory robot, webApiToken; robot.router.post '/slack-command-forwarder', (req, res) -> try # Confirm reception before anything res.send(); robot.logger.debug("Command received : translating ...", {body: req.body}); return forwardToRobot(req); catch error robot.emit 'error', error;
43085
# Description # Hubot script to manage slack command forwarding to hubot # # Configuration: # SLACK_APP_TOKEN in case you want to use another token than the one used for hubot-slack adapter # # Commands: # /hubot => hubot # /hubot test2 => hubot test2 # /hubot test3 arg1 arg2 => hubot test3 arg1 arg2 # /subCommand => hubot subCommand # /subCommand arg1 arg2 => hubot subCommand arg1 arg2 # # Notes: # <optional notes required for the script> # # Author: # Yoanm <<EMAIL>> forwardToRobotFactory = require './utils/forward-to-robot'; module.exports = (robot) -> webApiToken = process.env.SLACK_APP_TOKEN || robot.adapter.options.token; forwardToRobot = forwardToRobotFactory robot, webApiToken; robot.router.post '/slack-command-forwarder', (req, res) -> try # Confirm reception before anything res.send(); robot.logger.debug("Command received : translating ...", {body: req.body}); return forwardToRobot(req); catch error robot.emit 'error', error;
true
# Description # Hubot script to manage slack command forwarding to hubot # # Configuration: # SLACK_APP_TOKEN in case you want to use another token than the one used for hubot-slack adapter # # Commands: # /hubot => hubot # /hubot test2 => hubot test2 # /hubot test3 arg1 arg2 => hubot test3 arg1 arg2 # /subCommand => hubot subCommand # /subCommand arg1 arg2 => hubot subCommand arg1 arg2 # # Notes: # <optional notes required for the script> # # Author: # Yoanm <PI:EMAIL:<EMAIL>END_PI> forwardToRobotFactory = require './utils/forward-to-robot'; module.exports = (robot) -> webApiToken = process.env.SLACK_APP_TOKEN || robot.adapter.options.token; forwardToRobot = forwardToRobotFactory robot, webApiToken; robot.router.post '/slack-command-forwarder', (req, res) -> try # Confirm reception before anything res.send(); robot.logger.debug("Command received : translating ...", {body: req.body}); return forwardToRobot(req); catch error robot.emit 'error', error;
[ { "context": "xtends LayerInfo\n @shouldParse: (key) -> key is 'iOpa'\n\n parse: ->\n @value = @file.readByte()", "end": 134, "score": 0.9742894172668457, "start": 130, "tag": "KEY", "value": "iOpa" } ]
lib/psd/layer_info/fill_opacity.coffee
LoginovIlya/psd.js
2,218
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is 'iOpa' parse: -> @value = @file.readByte()
120594
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is '<KEY>' parse: -> @value = @file.readByte()
true
LayerInfo = require '../layer_info.coffee' module.exports = class FillOpacity extends LayerInfo @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' parse: -> @value = @file.readByte()
[ { "context": "ente mais tarde ou envie um email diretamente para guilherme.defreitas@gmail.com.</p><p>Obrigado!</p></div>\")\n\t\t\t\t\t$('#contact-mes", "end": 1409, "score": 0.9999241232872009, "start": 1380, "tag": "EMAIL", "value": "guilherme.defreitas@gmail.com" } ]
themes/default/assets/js/app.coffee
nextorigin/flat-white
0
class CanvasImage constructor: (element, image) -> this.image = image this.element = element this.element.width = this.image.width this.element.height = this.image.height this.context = this.element.getContext("2d") this.context.drawImage(this.image, 0, 0) blur: (passes) -> this.context.globalAlpha = 0.5 for i in [0..(passes)] for y in [-1..2] for x in [-1..2] this.context.drawImage(this.element, x, y) this.context.globalAlpha = 1.0 $(document).ready(() -> id = 'bgcanvas' url = '/img/bg2.jpg' image = new Image() image.onload = -> canvasImage = new CanvasImage(document.getElementById(id), this) canvasImage.blur(4) image.src = url $('#search-button').click(() -> $('#search-form').slideDown('fast', () -> $('#search-field').focus(); ) ) $('#search-field').blur(() -> if($(this).val() == "") $('#search-form').slideUp('fast', () -> ) ) $('.contact-form').submit(() -> $.ajax({ type: "POST", url: "/about/message", data: $('.contact-form').serialize(), dataType: "json", beforeSend: () -> #alert('before') , error: (jqXHR, textStatus, errorThrown) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Ocorreu um problema ao enviar a mensagem, por favor tente novamente mais tarde ou envie um email diretamente para guilherme.defreitas@gmail.com.</p><p>Obrigado!</p></div>") $('#contact-message').fadeIn() ) , success: (data) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Mensagem enviada com sucesso. Obrigado!</p></div>") $('#contact-message').fadeIn() ) }) event.preventDefault() ) )
181989
class CanvasImage constructor: (element, image) -> this.image = image this.element = element this.element.width = this.image.width this.element.height = this.image.height this.context = this.element.getContext("2d") this.context.drawImage(this.image, 0, 0) blur: (passes) -> this.context.globalAlpha = 0.5 for i in [0..(passes)] for y in [-1..2] for x in [-1..2] this.context.drawImage(this.element, x, y) this.context.globalAlpha = 1.0 $(document).ready(() -> id = 'bgcanvas' url = '/img/bg2.jpg' image = new Image() image.onload = -> canvasImage = new CanvasImage(document.getElementById(id), this) canvasImage.blur(4) image.src = url $('#search-button').click(() -> $('#search-form').slideDown('fast', () -> $('#search-field').focus(); ) ) $('#search-field').blur(() -> if($(this).val() == "") $('#search-form').slideUp('fast', () -> ) ) $('.contact-form').submit(() -> $.ajax({ type: "POST", url: "/about/message", data: $('.contact-form').serialize(), dataType: "json", beforeSend: () -> #alert('before') , error: (jqXHR, textStatus, errorThrown) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Ocorreu um problema ao enviar a mensagem, por favor tente novamente mais tarde ou envie um email diretamente para <EMAIL>.</p><p>Obrigado!</p></div>") $('#contact-message').fadeIn() ) , success: (data) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Mensagem enviada com sucesso. Obrigado!</p></div>") $('#contact-message').fadeIn() ) }) event.preventDefault() ) )
true
class CanvasImage constructor: (element, image) -> this.image = image this.element = element this.element.width = this.image.width this.element.height = this.image.height this.context = this.element.getContext("2d") this.context.drawImage(this.image, 0, 0) blur: (passes) -> this.context.globalAlpha = 0.5 for i in [0..(passes)] for y in [-1..2] for x in [-1..2] this.context.drawImage(this.element, x, y) this.context.globalAlpha = 1.0 $(document).ready(() -> id = 'bgcanvas' url = '/img/bg2.jpg' image = new Image() image.onload = -> canvasImage = new CanvasImage(document.getElementById(id), this) canvasImage.blur(4) image.src = url $('#search-button').click(() -> $('#search-form').slideDown('fast', () -> $('#search-field').focus(); ) ) $('#search-field').blur(() -> if($(this).val() == "") $('#search-form').slideUp('fast', () -> ) ) $('.contact-form').submit(() -> $.ajax({ type: "POST", url: "/about/message", data: $('.contact-form').serialize(), dataType: "json", beforeSend: () -> #alert('before') , error: (jqXHR, textStatus, errorThrown) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Ocorreu um problema ao enviar a mensagem, por favor tente novamente mais tarde ou envie um email diretamente para PI:EMAIL:<EMAIL>END_PI.</p><p>Obrigado!</p></div>") $('#contact-message').fadeIn() ) , success: (data) -> $('.contact-form').fadeOut(() -> $('#contact-form-area').html("<div id='contact-message'><p>Mensagem enviada com sucesso. Obrigado!</p></div>") $('#contact-message').fadeIn() ) }) event.preventDefault() ) )
[ { "context": "name: \"SyON\"\nscopeName: \"source.sy\"\nfileTypes: [\"sy\"]\npattern", "end": 11, "score": 0.8766459822654724, "start": 7, "tag": "USERNAME", "value": "SyON" }, { "context": "ion\n\t\t\t\t(?<![-.,?:\\\\#;])\n\t\t\t\"\"\"\n\t\t},{\n\t\t\t# mailto:this@guy\n\t\t\tname: \"markup.underline.link.mailto.sy\"\n\t\t", "end": 18148, "score": 0.5066872835159302, "start": 18144, "tag": "EMAIL", "value": "this" }, { "context": "\t\t\t\t(?<![-.,?:\\\\#;])\n\t\t\t\"\"\"\n\t\t},{\n\t\t\t# mailto:this@guy\n\t\t\tname: \"markup.underline.link.mailto.sy\"\n\t\t\tmat", "end": 18152, "score": 0.5064842104911804, "start": 18148, "tag": "PASSWORD", "value": "@guy" } ]
grammars/syon.cson
Alhadis/language-regexp
5
name: "SyON" scopeName: "source.sy" fileTypes: ["sy"] patterns: [include: "#blockInnards"] repository: main: patterns: [ {include: "#signature"} {include: "#comment"} {include: "#regexp"} {include: "#fieldQuotedEarly"} {include: "#heredoc"} {include: "#string"} {include: "#stringJunk"} {include: "#block"} {include: "#field"} {include: "#array"} {include: "#byteArray"} {include: "#brackets"} {include: "#boolean"} {include: "#null"} {include: "#date"} {include: "#number"} {include: "#comma"} {include: "#operator"} ] # [Array] array: name: "meta.array.sy" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.bracket.square.sy" endCaptures: 0: name: "punctuation.definition.array.end.bracket.square.sy" patterns: [ {include: "#main"} match: "(?:[^,\\[\\]{}<>\"'`\\s:]|:(?=\\S))+" name: "string.unquoted.sy" ] # { Block } block: patterns: [{ # Tagged block { name: "meta.block.tagged.sy" begin: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)({)" end: "}" beginCaptures: 1: name: "entity.name.block.tag.label.sy" 2: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] },{ name: "meta.block.sy" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] }] # Stuff matched directly inside of a block blockInnards: patterns: [ {include: "#fieldQuotedEarly"} {include: "#main"} # Assumed to be a multiline field name match: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)" captures: 1: name: "entity.name.tag.property.sy" ] # Brackets (expressions) brackets: name: "meta.expression.sy" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.round.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.round.sy" patterns: [ {include: "#operator"} {include: "#main"} ] # Boolean keywords boolean: patterns: [{ # True name: "constant.language.boolean.true.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:true|yes|on|TRUE|YES|ON) (?=$|[\\s\\]},]) """ },{ # False name: "constant.language.boolean.false.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:false|no|off|TRUE|YES|ON) (?=$|[\\s\\]},]) """ }] # Arbitrary binary data byteArray: patterns: [{ # Base64-encoded: <base64: YWJjCg> name: "meta.byte-array.base64.sy" begin: "(<)(base64)(:)" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 1: name: "punctuation.section.byte-array.begin.bracket.angle.sy" 2: name: "storage.modifier.encoding.base64.sy" 3: name: "punctuation.separator.key-value.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Data name: "constant.character.encoded.base64.sy" match: "[A-Za-z0-9+/=]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] },{ # Base85 (Ascii85): <~ … ~> name: "meta.byte-array.base85.sy" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 0: name: "punctuation.section.byte-array.end.bracket.angle.sy" patterns: [ {match: "[!-uz]+", name: "constant.character.encoded.base85.sy"} {match: "[^!-uz\\s~]", name: "invalid.illegal.character.sy"} ] },{ # Hexadecimal: <37 A2 E7 7E> name: "meta.byte-array.sy" begin: "<" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Byte name: "constant.numeric.integer.int.hexadecimal.hex.sy" match: "[A-Fa-f0-9]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] }] # Comma comma: name: "punctuation.separator.delimiter.comma.sy" match: "," # Comments comment: patterns: [{ # ### Block comment ### name: "comment.block.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))(\#{3,})(?=\\s|$)" end: "\\1" beginCaptures: 1: name: "punctuation.definition.comment.begin.sy" endCaptures: 0: name: "punctuation.definition.comment.end.sy" },{ # Single-line comment name: "comment.line.number-sign.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))#(?=\\s|$)" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.sy" }] # Date or datetime date: name: "constant.other.date.sy" match: """(?x) # Date [0-9]{4} - # Year [0-9]{2} - # Month [0-9]{2} # Day # Time (?: (?:T|\\s+) [0-9]{1,2} : # Hours [0-9]{1,2} : # Minutes [0-9]{1,2} # Seconds (?:\\.[0-9]+)? # Milliseconds (\\+[0-9]{4}|Z)? # Timezone )? # Followed by delimiter, EOL, or comment (?= \\s* (?:$|[,\\]}]) | \\s+ \\#(?:$|\\s) ) """ # Escaped character escape: patterns: [{ # Newline hack name: "constant.character.escape.newline.sy" begin: "\\\\$\\s*" end: "^" beginCaptures: 0: name: "punctuation.backslash.definition.escape.sy" },{ # Hexadecimal escape: \x1B name: "constant.character.escape.unicode.sy" match: "(\\\\)x[A-Fa-f0-9]{2}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u0032 name: "constant.character.escape.unicode.sy" match: "(\\\\)u[A-Fa-f0-9]{4}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u{1B240} name: "constant.character.escape.unicode.sy" match: "(\\\\)u({)[A-Fa-f0-9]+(})" captures: 1: name: "punctuation.backslash.definition.escape.sy" 2: name: "punctuation.definition.unicode-escape.begin.bracket.curly.sy" 3: name: "punctuation.definition.unicode-escape.end.bracket.curly.sy" },{ # Invalid unicode escape: \u{nope}, \u{} name: "invalid.illegal.unicode-escape.sy" match: "\\\\u{[^}\"]*}" },{ # Invalid unicode escape: \uNOPE name: "invalid.illegal.unicode-escape.sy" match: "\\\\u(?![A-Fa-f0-9]{4})[^\"]*" },{ # Anything else name: "constant.character.escape.sy" match: "(\\\\)." captures: 0: name: "punctuation.backslash.definition.escape.sy" }] # Only one escape possible in a verbatim string: `` escapeVerbatim: name: "constant.character.escape.backtick.sy" match: "``" # Bunch of numbers, possibly with operators expression: name: "meta.expression.sy" match: """(?x) \\G ( (?:\\s*\\()* \\s* ~? [-+]? ~? \\d [-+*/%~^&|\\(\\)eE\\s.oOxXbB\\d]* ) (?= \\s* (?: $ | , | \\] | \\} | (?<=\\s)\\#(?=\\s|$) ) ) """ captures: 1: patterns: [ {include: "#brackets"} {include: "#number"} {include: "#operator"} ] # Named property field: name: "meta.field.sy" begin: """(?x) (?: # Quoted property name (?<=[:{\\[]) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) | # Unquoted property name ([^{}\\[\\]<>\\s][^,]*?) (?<!\\\\) (:) | # Presumably one following a multiline string (?<=["'`]) \\s* (:) ) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" 5: name: "entity.name.tag.property.sy", patterns: [include: "#escape"] 6: name: "punctuation.separator.key-value.sy" 7: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] # Quoted field, hack for preceding #string rule fieldQuotedEarly: name: "meta.field.sy" begin: """(?x) (?:\\G|^) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] fieldInnards: patterns: [ {include: "#date"} {include: "#expression"} {include: "#main"} # Unquoted string name: "string.unquoted.sy" match: """(?x) \\G (?! ~?[-+]?[0-9] | (?<=\\s)\\#(?=\\s|$) ) [^\\s{}\\[\\]<:"'`] (?: [^\\#,}\\]:] | (?<=\\S) [\\#:] | [:\\#] (?=\\S) )* (?! \\s* (?:[\\{:]) ) """ captures: 0: patterns: [include: "#url"] ] # Multi-line string literals heredoc: patterns: [ {include: "#heredocDouble"} {include: "#heredocSingle"} {include: "#heredocVerbatim"} ] # """ Double-quoted heredoc """ heredocDouble: patterns: [{ # Hinted name: "string.quoted.double.heredoc.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+("{3,})' end: '\\2' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.heredoc.sy" begin: '("{3,})' end: '\\1' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ''' Single-quoted heredoc ''' heredocSingle: patterns: [{ # Hinted name: "string.quoted.single.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+('{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.heredoc.sy" begin: "('{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ``` Verbatim heredoc ``` heredocVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.heredoc.sy" begin: "(`{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" }] injection: begin: "\\A(?:\\xC2\\xAD|\\xAD){2}" end: "(?=A)B" beginCaptures: 0: patterns: [include: "#signature"] patterns: [include: "#blockInnards"] # Null keyword null: name: "constant.language.null.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:null|NULL) (?=$|[\\s\\]},]) """ # Numeric literals number: match: """(?x) (?:^|(?<=[\\s\\[\\({,~])|\\G) (?: ([-+]?0[xX][A-Fa-f0-9_]+) # Hexadecimal | ([-+]?0[oO][0-7_]+) # Octal | ([-+]?0[bB][0-1_]+) # Binary | ([-+]?[0-9_]+\\.(?:[0-9_]*[eE][+-]?[0-9_]+|[0-9_]+)) # Float | ([-+]?[0-9_]+(?:[eE][+-]?[0-9_]+)?) # Integer ) \\s* (?= $ | [-+*/%^&|\\)<>\\s\\]},] | (?<=\\s)\\#(?=\\s|$) ) """ captures: 1: name: "constant.numeric.integer.int.hexadecimal.hex.sy" 2: name: "constant.numeric.integer.int.octal.oct.sy" 3: name: "constant.numeric.integer.int.binary.bin.sy" 4: name: "constant.numeric.float.decimal.dec.sy" 5: name: "constant.numeric.integer.int.decimal.dec.sy" # Expression operators operator: patterns: [{ # Arithmetic name: "keyword.operator.arithmetic.sy" match: "\\*\\*|[-+*/%]" },{ # Bitwise name: "keyword.operator.bitwise.sy" match: "(<<|>>|>>>|[~&|^])" }] # Regular expressions regexp: patterns: [{ # Multiline regexp name: "string.regexp.multiline.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/{3,})" end: "(\\2)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.begin.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.begin.sy"} ] endCaptures: 1: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.end.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.end.sy"} ] 2: patterns: [include: "source.regexp#scopedModifiers"] },{ # Single-line regexp name: "string.regexp.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/)" end: "(/)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 1: name: "punctuation.definition.string.end.sy" 2: patterns: [include: "source.regexp#scopedModifiers"] }] # Start-of-file marker (magic number/signature). Used to identify SyON in the absence of # a known file extension, which is otherwise required to distinguish SyON from a similar # but incompatible format (like YAML). Synapse inserts this signature automatically when # saving a SyON file; the number of soft-hyphens identifies the version of the format if # future changes make backwards compatibility an issue (though it's unlikely to happen). # # Signatures are allowed at the beginning of any line (not just the start-of-file); this # allows xopts(1) to handle cat(1) output when passed multiple `.sy` files. Soft hyphens # found anywhere else are treated normally (as a syntactically-insignificant character). signature: name: "punctuation.whitespace.shy-hyphens.signature.sy" match: "^(?:\\xC2\\xAD|\\xAD){2,}" # Quoted string literals string: patterns: [ {include: "#stringDouble"} {include: "#stringSingle"} {include: "#stringVerbatim"} ] # "Double-quoted string" stringDouble: patterns: [{ # Hinted name: "string.quoted.double.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+(")' end: '"' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.sy" begin: '"' end: '"' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # 'Single-quoted string' stringSingle: patterns: [{ # Hinted name: "string.quoted.single.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(')" end: "'" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.sy" begin: "'" end: "'" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # `Verbatim string` stringVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`)" end: "`" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.sy" begin: "`" end: "`(?!`)" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#escapeVerbatim"] }] # Unexpected crap found after a closed quote stringJunk: name: "invalid.illegal.syntax.sy" begin: "(?<=[\"'`])(?!\\s*$)(?=\\s*[^:,}\\]])" end: "(?=[:,}\\]])" stringInnards: patterns: [ {include: "#url"} {include: "#escape"} ] # Underlined URLs. Not a datatype. url: patterns: [{ # https://etc, git://github.com/ name: "constant.other.reference.link.underline.sy" match: """(?x) \\b # Protocol ( https? | s?ftp | ftps | file | wss? | smb | git (?:\\+https?) | ssh | rsync | afp | nfs | (?:x-)?man(?:-page)? | gopher | txmt | issue | atom ) :// # Path specifier (?: (?! \\#\\w*\\#) (?: [-:\\@\\w.,~%+_/?=&\\#;|!]) )+ # Don't include trailing punctuation (?<![-.,?:\\#;]) """ },{ # mailto:this@guy name: "markup.underline.link.mailto.sy" match: """(?x) \\b mailto: (?: (?! \\#\\w*\\#) (?: [-:@\\w.,~%+_/?=&\\#;|!]) )+ (?<![-.,?:\\#;]) """ }]
52499
name: "SyON" scopeName: "source.sy" fileTypes: ["sy"] patterns: [include: "#blockInnards"] repository: main: patterns: [ {include: "#signature"} {include: "#comment"} {include: "#regexp"} {include: "#fieldQuotedEarly"} {include: "#heredoc"} {include: "#string"} {include: "#stringJunk"} {include: "#block"} {include: "#field"} {include: "#array"} {include: "#byteArray"} {include: "#brackets"} {include: "#boolean"} {include: "#null"} {include: "#date"} {include: "#number"} {include: "#comma"} {include: "#operator"} ] # [Array] array: name: "meta.array.sy" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.bracket.square.sy" endCaptures: 0: name: "punctuation.definition.array.end.bracket.square.sy" patterns: [ {include: "#main"} match: "(?:[^,\\[\\]{}<>\"'`\\s:]|:(?=\\S))+" name: "string.unquoted.sy" ] # { Block } block: patterns: [{ # Tagged block { name: "meta.block.tagged.sy" begin: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)({)" end: "}" beginCaptures: 1: name: "entity.name.block.tag.label.sy" 2: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] },{ name: "meta.block.sy" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] }] # Stuff matched directly inside of a block blockInnards: patterns: [ {include: "#fieldQuotedEarly"} {include: "#main"} # Assumed to be a multiline field name match: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)" captures: 1: name: "entity.name.tag.property.sy" ] # Brackets (expressions) brackets: name: "meta.expression.sy" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.round.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.round.sy" patterns: [ {include: "#operator"} {include: "#main"} ] # Boolean keywords boolean: patterns: [{ # True name: "constant.language.boolean.true.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:true|yes|on|TRUE|YES|ON) (?=$|[\\s\\]},]) """ },{ # False name: "constant.language.boolean.false.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:false|no|off|TRUE|YES|ON) (?=$|[\\s\\]},]) """ }] # Arbitrary binary data byteArray: patterns: [{ # Base64-encoded: <base64: YWJjCg> name: "meta.byte-array.base64.sy" begin: "(<)(base64)(:)" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 1: name: "punctuation.section.byte-array.begin.bracket.angle.sy" 2: name: "storage.modifier.encoding.base64.sy" 3: name: "punctuation.separator.key-value.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Data name: "constant.character.encoded.base64.sy" match: "[A-Za-z0-9+/=]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] },{ # Base85 (Ascii85): <~ … ~> name: "meta.byte-array.base85.sy" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 0: name: "punctuation.section.byte-array.end.bracket.angle.sy" patterns: [ {match: "[!-uz]+", name: "constant.character.encoded.base85.sy"} {match: "[^!-uz\\s~]", name: "invalid.illegal.character.sy"} ] },{ # Hexadecimal: <37 A2 E7 7E> name: "meta.byte-array.sy" begin: "<" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Byte name: "constant.numeric.integer.int.hexadecimal.hex.sy" match: "[A-Fa-f0-9]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] }] # Comma comma: name: "punctuation.separator.delimiter.comma.sy" match: "," # Comments comment: patterns: [{ # ### Block comment ### name: "comment.block.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))(\#{3,})(?=\\s|$)" end: "\\1" beginCaptures: 1: name: "punctuation.definition.comment.begin.sy" endCaptures: 0: name: "punctuation.definition.comment.end.sy" },{ # Single-line comment name: "comment.line.number-sign.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))#(?=\\s|$)" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.sy" }] # Date or datetime date: name: "constant.other.date.sy" match: """(?x) # Date [0-9]{4} - # Year [0-9]{2} - # Month [0-9]{2} # Day # Time (?: (?:T|\\s+) [0-9]{1,2} : # Hours [0-9]{1,2} : # Minutes [0-9]{1,2} # Seconds (?:\\.[0-9]+)? # Milliseconds (\\+[0-9]{4}|Z)? # Timezone )? # Followed by delimiter, EOL, or comment (?= \\s* (?:$|[,\\]}]) | \\s+ \\#(?:$|\\s) ) """ # Escaped character escape: patterns: [{ # Newline hack name: "constant.character.escape.newline.sy" begin: "\\\\$\\s*" end: "^" beginCaptures: 0: name: "punctuation.backslash.definition.escape.sy" },{ # Hexadecimal escape: \x1B name: "constant.character.escape.unicode.sy" match: "(\\\\)x[A-Fa-f0-9]{2}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u0032 name: "constant.character.escape.unicode.sy" match: "(\\\\)u[A-Fa-f0-9]{4}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u{1B240} name: "constant.character.escape.unicode.sy" match: "(\\\\)u({)[A-Fa-f0-9]+(})" captures: 1: name: "punctuation.backslash.definition.escape.sy" 2: name: "punctuation.definition.unicode-escape.begin.bracket.curly.sy" 3: name: "punctuation.definition.unicode-escape.end.bracket.curly.sy" },{ # Invalid unicode escape: \u{nope}, \u{} name: "invalid.illegal.unicode-escape.sy" match: "\\\\u{[^}\"]*}" },{ # Invalid unicode escape: \uNOPE name: "invalid.illegal.unicode-escape.sy" match: "\\\\u(?![A-Fa-f0-9]{4})[^\"]*" },{ # Anything else name: "constant.character.escape.sy" match: "(\\\\)." captures: 0: name: "punctuation.backslash.definition.escape.sy" }] # Only one escape possible in a verbatim string: `` escapeVerbatim: name: "constant.character.escape.backtick.sy" match: "``" # Bunch of numbers, possibly with operators expression: name: "meta.expression.sy" match: """(?x) \\G ( (?:\\s*\\()* \\s* ~? [-+]? ~? \\d [-+*/%~^&|\\(\\)eE\\s.oOxXbB\\d]* ) (?= \\s* (?: $ | , | \\] | \\} | (?<=\\s)\\#(?=\\s|$) ) ) """ captures: 1: patterns: [ {include: "#brackets"} {include: "#number"} {include: "#operator"} ] # Named property field: name: "meta.field.sy" begin: """(?x) (?: # Quoted property name (?<=[:{\\[]) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) | # Unquoted property name ([^{}\\[\\]<>\\s][^,]*?) (?<!\\\\) (:) | # Presumably one following a multiline string (?<=["'`]) \\s* (:) ) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" 5: name: "entity.name.tag.property.sy", patterns: [include: "#escape"] 6: name: "punctuation.separator.key-value.sy" 7: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] # Quoted field, hack for preceding #string rule fieldQuotedEarly: name: "meta.field.sy" begin: """(?x) (?:\\G|^) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] fieldInnards: patterns: [ {include: "#date"} {include: "#expression"} {include: "#main"} # Unquoted string name: "string.unquoted.sy" match: """(?x) \\G (?! ~?[-+]?[0-9] | (?<=\\s)\\#(?=\\s|$) ) [^\\s{}\\[\\]<:"'`] (?: [^\\#,}\\]:] | (?<=\\S) [\\#:] | [:\\#] (?=\\S) )* (?! \\s* (?:[\\{:]) ) """ captures: 0: patterns: [include: "#url"] ] # Multi-line string literals heredoc: patterns: [ {include: "#heredocDouble"} {include: "#heredocSingle"} {include: "#heredocVerbatim"} ] # """ Double-quoted heredoc """ heredocDouble: patterns: [{ # Hinted name: "string.quoted.double.heredoc.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+("{3,})' end: '\\2' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.heredoc.sy" begin: '("{3,})' end: '\\1' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ''' Single-quoted heredoc ''' heredocSingle: patterns: [{ # Hinted name: "string.quoted.single.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+('{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.heredoc.sy" begin: "('{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ``` Verbatim heredoc ``` heredocVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.heredoc.sy" begin: "(`{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" }] injection: begin: "\\A(?:\\xC2\\xAD|\\xAD){2}" end: "(?=A)B" beginCaptures: 0: patterns: [include: "#signature"] patterns: [include: "#blockInnards"] # Null keyword null: name: "constant.language.null.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:null|NULL) (?=$|[\\s\\]},]) """ # Numeric literals number: match: """(?x) (?:^|(?<=[\\s\\[\\({,~])|\\G) (?: ([-+]?0[xX][A-Fa-f0-9_]+) # Hexadecimal | ([-+]?0[oO][0-7_]+) # Octal | ([-+]?0[bB][0-1_]+) # Binary | ([-+]?[0-9_]+\\.(?:[0-9_]*[eE][+-]?[0-9_]+|[0-9_]+)) # Float | ([-+]?[0-9_]+(?:[eE][+-]?[0-9_]+)?) # Integer ) \\s* (?= $ | [-+*/%^&|\\)<>\\s\\]},] | (?<=\\s)\\#(?=\\s|$) ) """ captures: 1: name: "constant.numeric.integer.int.hexadecimal.hex.sy" 2: name: "constant.numeric.integer.int.octal.oct.sy" 3: name: "constant.numeric.integer.int.binary.bin.sy" 4: name: "constant.numeric.float.decimal.dec.sy" 5: name: "constant.numeric.integer.int.decimal.dec.sy" # Expression operators operator: patterns: [{ # Arithmetic name: "keyword.operator.arithmetic.sy" match: "\\*\\*|[-+*/%]" },{ # Bitwise name: "keyword.operator.bitwise.sy" match: "(<<|>>|>>>|[~&|^])" }] # Regular expressions regexp: patterns: [{ # Multiline regexp name: "string.regexp.multiline.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/{3,})" end: "(\\2)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.begin.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.begin.sy"} ] endCaptures: 1: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.end.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.end.sy"} ] 2: patterns: [include: "source.regexp#scopedModifiers"] },{ # Single-line regexp name: "string.regexp.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/)" end: "(/)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 1: name: "punctuation.definition.string.end.sy" 2: patterns: [include: "source.regexp#scopedModifiers"] }] # Start-of-file marker (magic number/signature). Used to identify SyON in the absence of # a known file extension, which is otherwise required to distinguish SyON from a similar # but incompatible format (like YAML). Synapse inserts this signature automatically when # saving a SyON file; the number of soft-hyphens identifies the version of the format if # future changes make backwards compatibility an issue (though it's unlikely to happen). # # Signatures are allowed at the beginning of any line (not just the start-of-file); this # allows xopts(1) to handle cat(1) output when passed multiple `.sy` files. Soft hyphens # found anywhere else are treated normally (as a syntactically-insignificant character). signature: name: "punctuation.whitespace.shy-hyphens.signature.sy" match: "^(?:\\xC2\\xAD|\\xAD){2,}" # Quoted string literals string: patterns: [ {include: "#stringDouble"} {include: "#stringSingle"} {include: "#stringVerbatim"} ] # "Double-quoted string" stringDouble: patterns: [{ # Hinted name: "string.quoted.double.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+(")' end: '"' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.sy" begin: '"' end: '"' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # 'Single-quoted string' stringSingle: patterns: [{ # Hinted name: "string.quoted.single.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(')" end: "'" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.sy" begin: "'" end: "'" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # `Verbatim string` stringVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`)" end: "`" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.sy" begin: "`" end: "`(?!`)" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#escapeVerbatim"] }] # Unexpected crap found after a closed quote stringJunk: name: "invalid.illegal.syntax.sy" begin: "(?<=[\"'`])(?!\\s*$)(?=\\s*[^:,}\\]])" end: "(?=[:,}\\]])" stringInnards: patterns: [ {include: "#url"} {include: "#escape"} ] # Underlined URLs. Not a datatype. url: patterns: [{ # https://etc, git://github.com/ name: "constant.other.reference.link.underline.sy" match: """(?x) \\b # Protocol ( https? | s?ftp | ftps | file | wss? | smb | git (?:\\+https?) | ssh | rsync | afp | nfs | (?:x-)?man(?:-page)? | gopher | txmt | issue | atom ) :// # Path specifier (?: (?! \\#\\w*\\#) (?: [-:\\@\\w.,~%+_/?=&\\#;|!]) )+ # Don't include trailing punctuation (?<![-.,?:\\#;]) """ },{ # mailto:<EMAIL> <PASSWORD> name: "markup.underline.link.mailto.sy" match: """(?x) \\b mailto: (?: (?! \\#\\w*\\#) (?: [-:@\\w.,~%+_/?=&\\#;|!]) )+ (?<![-.,?:\\#;]) """ }]
true
name: "SyON" scopeName: "source.sy" fileTypes: ["sy"] patterns: [include: "#blockInnards"] repository: main: patterns: [ {include: "#signature"} {include: "#comment"} {include: "#regexp"} {include: "#fieldQuotedEarly"} {include: "#heredoc"} {include: "#string"} {include: "#stringJunk"} {include: "#block"} {include: "#field"} {include: "#array"} {include: "#byteArray"} {include: "#brackets"} {include: "#boolean"} {include: "#null"} {include: "#date"} {include: "#number"} {include: "#comma"} {include: "#operator"} ] # [Array] array: name: "meta.array.sy" begin: "\\[" end: "\\]" beginCaptures: 0: name: "punctuation.definition.array.begin.bracket.square.sy" endCaptures: 0: name: "punctuation.definition.array.end.bracket.square.sy" patterns: [ {include: "#main"} match: "(?:[^,\\[\\]{}<>\"'`\\s:]|:(?=\\S))+" name: "string.unquoted.sy" ] # { Block } block: patterns: [{ # Tagged block { name: "meta.block.tagged.sy" begin: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)({)" end: "}" beginCaptures: 1: name: "entity.name.block.tag.label.sy" 2: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] },{ name: "meta.block.sy" begin: "{" end: "}" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.curly.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.curly.sy" patterns: [include: "#blockInnards"] }] # Stuff matched directly inside of a block blockInnards: patterns: [ {include: "#fieldQuotedEarly"} {include: "#main"} # Assumed to be a multiline field name match: "((?:[^{}\\[\\]:\\s,]|[:#](?=\\S))(?:[^:{}]|:(?=\\S)|\\\\[{:])*?)" captures: 1: name: "entity.name.tag.property.sy" ] # Brackets (expressions) brackets: name: "meta.expression.sy" begin: "\\(" end: "\\)" beginCaptures: 0: name: "punctuation.section.scope.block.begin.bracket.round.sy" endCaptures: 0: name: "punctuation.section.scope.block.end.bracket.round.sy" patterns: [ {include: "#operator"} {include: "#main"} ] # Boolean keywords boolean: patterns: [{ # True name: "constant.language.boolean.true.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:true|yes|on|TRUE|YES|ON) (?=$|[\\s\\]},]) """ },{ # False name: "constant.language.boolean.false.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:false|no|off|TRUE|YES|ON) (?=$|[\\s\\]},]) """ }] # Arbitrary binary data byteArray: patterns: [{ # Base64-encoded: <base64: YWJjCg> name: "meta.byte-array.base64.sy" begin: "(<)(base64)(:)" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 1: name: "punctuation.section.byte-array.begin.bracket.angle.sy" 2: name: "storage.modifier.encoding.base64.sy" 3: name: "punctuation.separator.key-value.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Data name: "constant.character.encoded.base64.sy" match: "[A-Za-z0-9+/=]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] },{ # Base85 (Ascii85): <~ … ~> name: "meta.byte-array.base85.sy" begin: "<~" end: "~>" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 0: name: "punctuation.section.byte-array.end.bracket.angle.sy" patterns: [ {match: "[!-uz]+", name: "constant.character.encoded.base85.sy"} {match: "[^!-uz\\s~]", name: "invalid.illegal.character.sy"} ] },{ # Hexadecimal: <37 A2 E7 7E> name: "meta.byte-array.sy" begin: "<" end: "(>)\\s*([^:,}\\]]+)" beginCaptures: 0: name: "punctuation.section.byte-array.begin.bracket.angle.sy" endCaptures: 1: name: "punctuation.section.byte-array.end.bracket.angle.sy" 2: name: "invalid.illegal.characters.sy" patterns: [{ # Byte name: "constant.numeric.integer.int.hexadecimal.hex.sy" match: "[A-Fa-f0-9]+" },{ # Embedded comments include: "#comment" },{ # Unexpected junk name: "invalid.illegal.character.sy" match: "[^\\s>]+" }] }] # Comma comma: name: "punctuation.separator.delimiter.comma.sy" match: "," # Comments comment: patterns: [{ # ### Block comment ### name: "comment.block.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))(\#{3,})(?=\\s|$)" end: "\\1" beginCaptures: 1: name: "punctuation.definition.comment.begin.sy" endCaptures: 0: name: "punctuation.definition.comment.end.sy" },{ # Single-line comment name: "comment.line.number-sign.sy" begin: "(?:\\G|^|(?<=\\s|\\xC2\\xAD|\\xAD))#(?=\\s|$)" end: "$" beginCaptures: 0: name: "punctuation.definition.comment.sy" }] # Date or datetime date: name: "constant.other.date.sy" match: """(?x) # Date [0-9]{4} - # Year [0-9]{2} - # Month [0-9]{2} # Day # Time (?: (?:T|\\s+) [0-9]{1,2} : # Hours [0-9]{1,2} : # Minutes [0-9]{1,2} # Seconds (?:\\.[0-9]+)? # Milliseconds (\\+[0-9]{4}|Z)? # Timezone )? # Followed by delimiter, EOL, or comment (?= \\s* (?:$|[,\\]}]) | \\s+ \\#(?:$|\\s) ) """ # Escaped character escape: patterns: [{ # Newline hack name: "constant.character.escape.newline.sy" begin: "\\\\$\\s*" end: "^" beginCaptures: 0: name: "punctuation.backslash.definition.escape.sy" },{ # Hexadecimal escape: \x1B name: "constant.character.escape.unicode.sy" match: "(\\\\)x[A-Fa-f0-9]{2}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u0032 name: "constant.character.escape.unicode.sy" match: "(\\\\)u[A-Fa-f0-9]{4}" captures: 1: name: "punctuation.backslash.definition.escape.sy" },{ # Unicode escape: \u{1B240} name: "constant.character.escape.unicode.sy" match: "(\\\\)u({)[A-Fa-f0-9]+(})" captures: 1: name: "punctuation.backslash.definition.escape.sy" 2: name: "punctuation.definition.unicode-escape.begin.bracket.curly.sy" 3: name: "punctuation.definition.unicode-escape.end.bracket.curly.sy" },{ # Invalid unicode escape: \u{nope}, \u{} name: "invalid.illegal.unicode-escape.sy" match: "\\\\u{[^}\"]*}" },{ # Invalid unicode escape: \uNOPE name: "invalid.illegal.unicode-escape.sy" match: "\\\\u(?![A-Fa-f0-9]{4})[^\"]*" },{ # Anything else name: "constant.character.escape.sy" match: "(\\\\)." captures: 0: name: "punctuation.backslash.definition.escape.sy" }] # Only one escape possible in a verbatim string: `` escapeVerbatim: name: "constant.character.escape.backtick.sy" match: "``" # Bunch of numbers, possibly with operators expression: name: "meta.expression.sy" match: """(?x) \\G ( (?:\\s*\\()* \\s* ~? [-+]? ~? \\d [-+*/%~^&|\\(\\)eE\\s.oOxXbB\\d]* ) (?= \\s* (?: $ | , | \\] | \\} | (?<=\\s)\\#(?=\\s|$) ) ) """ captures: 1: patterns: [ {include: "#brackets"} {include: "#number"} {include: "#operator"} ] # Named property field: name: "meta.field.sy" begin: """(?x) (?: # Quoted property name (?<=[:{\\[]) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) | # Unquoted property name ([^{}\\[\\]<>\\s][^,]*?) (?<!\\\\) (:) | # Presumably one following a multiline string (?<=["'`]) \\s* (:) ) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" 5: name: "entity.name.tag.property.sy", patterns: [include: "#escape"] 6: name: "punctuation.separator.key-value.sy" 7: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] # Quoted field, hack for preceding #string rule fieldQuotedEarly: name: "meta.field.sy" begin: """(?x) (?:\\G|^) \\s* (?: ("(?:[^"\\\\]|\\\\.)*") | ('(?:[^'\\\\]|\\\\.)*') | (`(?:[^`]|``)*+`(?!`)) ) \\s* (:) (?=\\s|$) \\s* """ end: "(?=\\s*})|^(?!\\G)" beginCaptures: 1: name: "entity.name.tag.property.quoted.double.sy", patterns: [include: "#escape"] 2: name: "entity.name.tag.property.quoted.single.sy", patterns: [include: "#escape"] 3: name: "entity.name.tag.property.quoted.backtick.sy", patterns: [include: "#escapeVerbatim"] 4: name: "punctuation.separator.key-value.sy" patterns: [include: "#fieldInnards"] fieldInnards: patterns: [ {include: "#date"} {include: "#expression"} {include: "#main"} # Unquoted string name: "string.unquoted.sy" match: """(?x) \\G (?! ~?[-+]?[0-9] | (?<=\\s)\\#(?=\\s|$) ) [^\\s{}\\[\\]<:"'`] (?: [^\\#,}\\]:] | (?<=\\S) [\\#:] | [:\\#] (?=\\S) )* (?! \\s* (?:[\\{:]) ) """ captures: 0: patterns: [include: "#url"] ] # Multi-line string literals heredoc: patterns: [ {include: "#heredocDouble"} {include: "#heredocSingle"} {include: "#heredocVerbatim"} ] # """ Double-quoted heredoc """ heredocDouble: patterns: [{ # Hinted name: "string.quoted.double.heredoc.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+("{3,})' end: '\\2' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.heredoc.sy" begin: '("{3,})' end: '\\1' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ''' Single-quoted heredoc ''' heredocSingle: patterns: [{ # Hinted name: "string.quoted.single.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+('{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.heredoc.sy" begin: "('{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # ``` Verbatim heredoc ``` heredocVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.heredoc.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`{3,})" end: "\\2" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.heredoc.sy" begin: "(`{3,})" end: "\\1" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" }] injection: begin: "\\A(?:\\xC2\\xAD|\\xAD){2}" end: "(?=A)B" beginCaptures: 0: patterns: [include: "#signature"] patterns: [include: "#blockInnards"] # Null keyword null: name: "constant.language.null.sy" match: """(?x) (?:\\G|^|(?<=[\\s\\[{,])) (?:null|NULL) (?=$|[\\s\\]},]) """ # Numeric literals number: match: """(?x) (?:^|(?<=[\\s\\[\\({,~])|\\G) (?: ([-+]?0[xX][A-Fa-f0-9_]+) # Hexadecimal | ([-+]?0[oO][0-7_]+) # Octal | ([-+]?0[bB][0-1_]+) # Binary | ([-+]?[0-9_]+\\.(?:[0-9_]*[eE][+-]?[0-9_]+|[0-9_]+)) # Float | ([-+]?[0-9_]+(?:[eE][+-]?[0-9_]+)?) # Integer ) \\s* (?= $ | [-+*/%^&|\\)<>\\s\\]},] | (?<=\\s)\\#(?=\\s|$) ) """ captures: 1: name: "constant.numeric.integer.int.hexadecimal.hex.sy" 2: name: "constant.numeric.integer.int.octal.oct.sy" 3: name: "constant.numeric.integer.int.binary.bin.sy" 4: name: "constant.numeric.float.decimal.dec.sy" 5: name: "constant.numeric.integer.int.decimal.dec.sy" # Expression operators operator: patterns: [{ # Arithmetic name: "keyword.operator.arithmetic.sy" match: "\\*\\*|[-+*/%]" },{ # Bitwise name: "keyword.operator.bitwise.sy" match: "(<<|>>|>>>|[~&|^])" }] # Regular expressions regexp: patterns: [{ # Multiline regexp name: "string.regexp.multiline.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/{3,})" end: "(\\2)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.begin.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.begin.sy"} ] endCaptures: 1: patterns: [ {match: "(?:\\G|^)/{3}$", name: "punctuation.definition.string.end.triple-slash.sy"} {match: ".+", name: "punctuation.definition.string.end.sy"} ] 2: patterns: [include: "source.regexp#scopedModifiers"] },{ # Single-line regexp name: "string.regexp.sy" begin: "(?:([-\\w]+)[ \\t]+)?(/)" end: "(/)([A-Za-z]*)" patterns: [include: "source.regexp#main"] beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 1: name: "punctuation.definition.string.end.sy" 2: patterns: [include: "source.regexp#scopedModifiers"] }] # Start-of-file marker (magic number/signature). Used to identify SyON in the absence of # a known file extension, which is otherwise required to distinguish SyON from a similar # but incompatible format (like YAML). Synapse inserts this signature automatically when # saving a SyON file; the number of soft-hyphens identifies the version of the format if # future changes make backwards compatibility an issue (though it's unlikely to happen). # # Signatures are allowed at the beginning of any line (not just the start-of-file); this # allows xopts(1) to handle cat(1) output when passed multiple `.sy` files. Soft hyphens # found anywhere else are treated normally (as a syntactically-insignificant character). signature: name: "punctuation.whitespace.shy-hyphens.signature.sy" match: "^(?:\\xC2\\xAD|\\xAD){2,}" # Quoted string literals string: patterns: [ {include: "#stringDouble"} {include: "#stringSingle"} {include: "#stringVerbatim"} ] # "Double-quoted string" stringDouble: patterns: [{ # Hinted name: "string.quoted.double.hinted.${1:/scopify}.sy" begin: '([-\\w]+)[ \\t]+(")' end: '"' beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.double.sy" begin: '"' end: '"' beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # 'Single-quoted string' stringSingle: patterns: [{ # Hinted name: "string.quoted.single.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(')" end: "'" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.single.sy" begin: "'" end: "'" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#stringInnards"] }] # `Verbatim string` stringVerbatim: patterns: [{ # Hinted name: "string.quoted.verbatim.backtick.hinted.${1:/scopify}.sy" begin: "([-\\w]+)[ \\t]+(`)" end: "`" beginCaptures: 1: name: "storage.modifier.type.parse-hint.sy" 2: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" contentName: "embedded.${1:/scopify}" },{ # Unhinted name: "string.quoted.verbatim.backtick.sy" begin: "`" end: "`(?!`)" beginCaptures: 0: name: "punctuation.definition.string.begin.sy" endCaptures: 0: name: "punctuation.definition.string.end.sy" patterns: [include: "#escapeVerbatim"] }] # Unexpected crap found after a closed quote stringJunk: name: "invalid.illegal.syntax.sy" begin: "(?<=[\"'`])(?!\\s*$)(?=\\s*[^:,}\\]])" end: "(?=[:,}\\]])" stringInnards: patterns: [ {include: "#url"} {include: "#escape"} ] # Underlined URLs. Not a datatype. url: patterns: [{ # https://etc, git://github.com/ name: "constant.other.reference.link.underline.sy" match: """(?x) \\b # Protocol ( https? | s?ftp | ftps | file | wss? | smb | git (?:\\+https?) | ssh | rsync | afp | nfs | (?:x-)?man(?:-page)? | gopher | txmt | issue | atom ) :// # Path specifier (?: (?! \\#\\w*\\#) (?: [-:\\@\\w.,~%+_/?=&\\#;|!]) )+ # Don't include trailing punctuation (?<![-.,?:\\#;]) """ },{ # mailto:PI:EMAIL:<EMAIL>END_PI PI:PASSWORD:<PASSWORD>END_PI name: "markup.underline.link.mailto.sy" match: """(?x) \\b mailto: (?: (?! \\#\\w*\\#) (?: [-:@\\w.,~%+_/?=&\\#;|!]) )+ (?<![-.,?:\\#;]) """ }]