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": "engine(enchant)\n#\n# 2014.04.04 ver2.0\n#\n# Coded by Kow Sakazaki\n#************************************************",
"end": 158,
"score": 0.9998326301574707,
"start": 146,
"tag": "NAME",
"value": "Kow Sakazaki"
}
] | lib/main.enchant.coffee | digitarhythm/enforce | 1 | #******************************************************************************
# enforce game engine(enchant)
#
# 2014.04.04 ver2.0
#
# Coded by Kow Sakazaki
#******************************************************************************
#******************************************************************************
# 初期化処理
#******************************************************************************
# 定数定義
# 色定義
WHITE = 0
BLACK = 1
# オブジェクトの種類
CONTROL = 0
SPRITE = 1
LABEL = 2
SURFACE = 3
PRIMITIVE = 4
COLLADA = 5
MAP = 6
EXMAP = 7
COLLIDER2D = 8
# 物理スプライトの種類
DYNAMIC_BOX = 0
DYNAMIC_CIRCLE = 1
STATIC_BOX = 2
STATIC_CIRCLE = 3
# Easingの種類(kind)
LINEAR = 0
SWING = 1
BACK = 2
BOUNCE = 3
CIRCLE = 4
CUBIC = 5
ELASTIC = 6
EXPO = 7
QUAD = 8
QUART = 9
QUINT = 10
SINE = 11
# Easingの動き(move)
EASEINOUT = 0
EASEIN = 1
EASEOUT = 2
NONE = 3
# Easingの配列
EASINGVALUE = []
# WebGLのプリミティブの種類
BOX = 0
CUBE = 1
SPHERE = 2
CYLINDER = 3
TORUS = 4
PLANE = 5
# Sceneの種類
BGSCENE = 0
BGSCENE_SUB1 = 1
BGSCENE_SUB2 = 2
GAMESCENE = 3
GAMESCENE_SUB1 = 4
GAMESCENE_SUB2 = 5
TOPSCENE = 6
WEBGLSCENE = 7
_SYSTEMSCENE = 8
DEBUGSCENE = 9
MAXSCENE = (if (DEBUG) then DEBUGSCENE else _SYSTEMSCENE)
# ワールドビュー
_WORLDVIEW =
centerx: SCREEN_WIDTH / 2
centery: SCREEN_HEIGHT / 2
# 数学式
RAD = (Math.PI / 180.0)
DEG = (180.0 / Math.PI)
# グローバル初期化
GLOBAL = []
# サウンドプリロード用
SOUNDARR = []
# アスペクト比
ASPECT = 0.0
# ゲームパッド情報格納変数
HORIZONTAL = 0
VERTICAL = 1
_GAMEPADSINFO = []
PADBUTTONS = []
PADBUTTONS[0] = [false, false]
PADAXES = []
PADAXES[0] = [0, 0]
PADINFO = []
ANALOGSTICK = []
ANALOGSTICK[0] = [[0, 0], [0, 0]]
_VGAMEPADCONTROL = undefined
# Frame Per Seconds
if (!FPS?)
FPS = 60
# box2dの重力値
if (!GRAVITY_X?)
GRAVITY_X = 0.0
if (!GRAVITY_Y?)
GRAVITY_Y = 0.0
# センサー系
MOTION_ACCEL = [x:0, y:0, z:0]
MOTION_GRAVITY = [x:0, y:0, z:0]
MOTION_ROTATE = [alpha:0, beta:0, gamma:0]
# 標準ブラウザ
if (_useragent.match(/^.*android.*?mobile safari.*$/i) != null && _useragent.match(/^.*\) chrome.*/i) == null)
_defaultbrowser = true
else
_defaultbrowser = false
# ブラウザ大分類
if (_useragent.match(/.* firefox\/.*/))
_browserMajorClass = "firefox"
else if (_useragent.match(/.*version\/.* safari\/.*/))
_browserMajorClass = "safari"
else if (_useragent.match(/.*chrome\/.* safari\/.*/))
_browserMajorClass = "chrome"
else
_browserMajorClass = "unknown"
# ゲーム起動時からの経過時間(秒)
LAPSEDTIME = 0.0
# ゲーム起動時のUNIXTIME
BEGINNINGTIME = undefined
# フレームレート調整用
__FRAMETIME = 0.0
# 3D系
OCULUS = undefined
RENDERER = undefined
CAMERA = undefined
LIGHT = undefined
# デバイスサイズ
_frame = getBounds()
DEVICE_WIDTH = _frame[0]
DEVICE_HEIGHT = _frame[1]
if (!SCREEN_WIDTH? && !SCREEN_HEIGHT?)
SCREEN_WIDTH = DEVICE_WIDTH
SCREEN_HEIGHT = DEVICE_HEIGHT
# 動作状況
ACTIVATE = true
# オブジェクトが入っている配列
_objects = []
# Scene格納用配列
_scenes = []
# 起動時に生成されるスタートオブジェクト
_main = null
# デバッグ用LABEL
_DEBUGLABEL = undefined
_FPSGAUGE = undefined
__fpsgaugeunit = 0
__fpscounter = 0.0
__limittimefps = 0.0
# enchantのcoreオブジェクト
core = undefined
# box2dのworldオブジェクト
box2dworld = undefined
# 3Dのscene
rootScene3d = undefined
# enchantのrootScene
rootScene = undefined
# アニメーション管理
__requestID = ( ->
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
(callback)->
window.setTimeout(callback, 1000 / 60)
)()
#******************************************************************************
# 起動時の処理
#******************************************************************************
# enchantのオマジナイ
enchant()
enchant.ENV.MOUSE_ENABLED = false
enchant.ENV.SOUND_ENABLED_ON_MOBILE_SAFARI = false
# ゲーム起動時の処理
#window.addEventListener 'load', (e)->
window.onload = ->
window.removeEventListener('load', arguments.callee, false)
# ゲーム起動時間
BEGINNINGTIME = __getTime()
# アスペクト比
ASPECT = (SCREEN_WIDTH / SCREEN_HEIGHT).toFixed(2)
# enchant初期化
core = new Core(SCREEN_WIDTH, SCREEN_HEIGHT)
# FPS設定
core.fps = FPS
# Easing定義
EASINGVALUE[LINEAR] = [enchant.Easing.LINEAR]
EASINGVALUE[SWING] = [enchant.Easing.SWING]
EASINGVALUE[BACK] = [enchant.Easing.BACK_EASEINOUT, enchant.Easing.BACK_EASEIN, enchant.Easing.BACK_EASEOUT]
EASINGVALUE[BOUNCE] = [enchant.Easing.BOUNCE_EASEINOUT, enchant.Easing.BOUNCE_EASEIN, enchant.Easing.BOUNCE_EASEOUT]
EASINGVALUE[CIRCLE] = [enchant.Easing.CIRCLE_EASEINOUT, enchant.Easing.CIRCLE_EASEIN, enchant.Easing.CIRCLE_EASEOUT]
EASINGVALUE[CUBIC] = [enchant.Easing.CUBIC_EASEINOUT, enchant.Easing.CUBIC_EASEIN, enchant.Easing.CUBIC_EASEOUT]
EASINGVALUE[ELASTIC] = [enchant.Easing.ELASTIC_EASEINOUT, enchant.Easing.ELASTIC_EASEIN, enchant.Easing.ELASTIC_EASEOUT]
EASINGVALUE[EXPO] = [enchant.Easing.EXPO_EASEINOUT, enchant.Easing.EXPO_EASEIN, enchant.Easing.EXPO_EASEOUT]
EASINGVALUE[QUAD] = [enchant.Easing.QUAD_EASEINOUT, enchant.Easing.QUAD_EASEIN, enchant.Easing.QUAD_EASEOUT]
EASINGVALUE[QUART] = [enchant.Easing.QUART_EASEINOUT, enchant.Easing.QUART_EASEIN, enchant.Easing.QUART_EASEOUT]
EASINGVALUE[QUINT] = [enchant.Easing.QUINT_EASEINOUT, enchant.Easing.QUINT_EASEIN, enchant.Easing.QUINT_EASEOUT]
EASINGVALUE[SINE] = [enchant.Easing.SINE_EASEINOUT, enchant.Easing.SINE_EASEIN, enchant.Easing.SINE_EASEOUT]
# ボタンの定義
core.keybind( 90, 'a' )
core.keybind( 88, 'b' )
core.keybind( 67, 'c' )
core.keybind( 86, 'd' )
core.keybind( 66, 'e' )
core.keybind( 78, 'f' )
core.keybind( 77, 'g' )
core.keybind( 188, 'h' )
core.keybind( 32, 'space' )
# メディアファイルのプリロード
if (MEDIALIST?)
MEDIALIST['_ascii_w'] = 'lib/ascii_w.png'
MEDIALIST['_ascii_b'] = 'lib/ascii_b.png'
MEDIALIST['_fpsgauge'] = 'lib/fpsgauge.png'
MEDIALIST['_notice'] = 'lib/notice.png'
MEDIALIST['_execbutton'] = 'lib/execbutton.png'
MEDIALIST['_pad_w'] = 'lib/pad_w.png'
MEDIALIST['_pad_b'] = 'lib/pad_b.png'
MEDIALIST['_apad_w'] = 'lib/apad_w.png'
MEDIALIST['_apad_b'] = 'lib/apad_b.png'
MEDIALIST['_apad2_w'] = 'lib/apad2_w.png'
MEDIALIST['_apad2_b'] = 'lib/apad2_b.png'
MEDIALIST['_button_w'] = 'lib/button_w.png'
MEDIALIST['_button_b'] = 'lib/button_b.png'
mediaarr = []
num = 0
for obj of MEDIALIST
mediaarr[num++] = MEDIALIST[obj]
core.preload(mediaarr)
# rootSceneをグローバルに保存
rootScene = core.rootScene
# モーションセンサーのイベント登録
window.addEventListener 'devicemotion', (e)->
MOTION_ACCEL = e.acceleration
MOTION_GRAVITY = e.accelerationIncludingGravity
window.addEventListener 'deviceorientation', (e)->
MOTION_ROTATE.alpha = e.alpha
MOTION_ROTATE.beta = e.beta
MOTION_ROTATE.gamma = e.gamma
# box2d初期化
box2dworld = new PhysicsWorld(GRAVITY_X, GRAVITY_Y)
# シーングループを生成
for i in [0..MAXSCENE]
scene = new Group()
scene.backgroundColor = "black"
_scenes[i] = scene
rootScene.addChild(scene)
if (WEBGL != undefined && WEBGL && isWebGL())
# 3Dシーンを生成
rootScene3d = new Scene3D()
_scenes[WEBGLSCENE] = rootScene3d
# スポットライト生成
#DLIGHT = new DirectionalLight()
#DLIGHT.color = [1.0, 1.0, 1.0]
#dlight.directionX = 0
#dlight.directionY = 100
#dlight.directionZ = 0
rootScene3d.setDirectionalLight(DLIGHT)
# 環境光ライト生成
#ALIGHT = new AmbientLight()
#ALIGHT.color = [1.0, 1.0, 1.0]
#alight.directionX = 0
#alight.directionY = 100
rootScene3d.setAmbientLight(ALIGHT)
# カメラ生成
CAMERA = new Camera3D()
CAMERA.x = 0
CAMERA.y = 0
CAMERA.z = 160
CAMERA.centerX = 0
CAMERA.centerY = 0
CAMERA.centerZ = 0
rootScene3d.setCamera(CAMERA)
else
rootScene.backgroundColor = BGCOLOR
WEBGL = false
#if (DEBUG == true)
# core.debug()
#else
# core.start()
core.start()
#******************************************************************************
# 起動時の処理
#******************************************************************************
core.onload = ->
# ゲーム用オブジェクトを指定された数だけ確保
for i in [0...OBJECTNUM]
_objects[i] = new _originObject()
_main = new enforceMain()
if (DEBUG)
_DEBUGLABEL = new Label()
_DEBUGLABEL.x = 0
_DEBUGLABEL.y = 0
_DEBUGLABEL.width = SCREEN_WIDTH
_DEBUGLABEL.color = "white"
_DEBUGLABEL.font = "32px 'Arial'"
_scenes[DEBUGSCENE].addChild(_DEBUGLABEL)
_FPSGAUGE = new Sprite()
_FPSGAUGE.x = SCREEN_WIDTH - 16
_FPSGAUGE.y = 0
_FPSGAUGE.width = 16
_FPSGAUGE.height = 1
_FPSGAUGE.scaleY = 1.0
_FPSGAUGE.opacity = 0.5
_FPSGAUGE.image = core.assets[MEDIALIST['_fpsgauge']]
_FPSGAUGE.frame = 0
_scenes[DEBUGSCENE].addChild(_FPSGAUGE)
__fpscounter = 0
__limittimefps = 0.0
# フレーム処理(enchant任せ)
rootScene.addEventListener 'enterframe', (e)->
# 経過時間を計算
LAPSEDTIME = parseFloat((__getTime() - parseFloat(BEGINNINGTIME.toFixed(2))) / 1000.0)
# FPS表示(デバッグモード時のみ)
if (DEBUG)
__fpscounter++
if (__limittimefps < parseFloat(LAPSEDTIME))
__limittimefps = LAPSEDTIME + 1.0
scale = parseFloat(((__fpscounter / FPS) * SCREEN_HEIGHT).toFixed(2))
_FPSGAUGE.height = scale
__fpscounter = 0
# ジョイパッド処理
if (typeof gamepadProcedure == 'function')
_GAMEPADSINFO = gamepadProcedure()
for num in [0..._GAMEPADSINFO.length]
if (!_GAMEPADSINFO[num]?)
continue
padobj = _GAMEPADSINFO[num]
PADBUTTONS[num] = padobj.padbuttons
PADAXES[num] = padobj.padaxes
ANALOGSTICK[num] = padobj.analogstick
PADINFO[num] = []
PADINFO[num].id = padobj.id
if (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.analog?)
vgpx1 = parseFloat(_VGAMEPADCONTROL.input.analog[HORIZONTAL])
vgpy1 = parseFloat(_VGAMEPADCONTROL.input.analog[VERTICAL])
else
vgpx1 = 0
vgpy1 = 0
if (_GAMEPADSINFO? && _GAMEPADSINFO[0]?)
vgpx2 = _GAMEPADSINFO[0].analogstick[0][HORIZONTAL]
vgpy2 = _GAMEPADSINFO[0].analogstick[0][VERTICAL]
else
vgpx2 = 0
vgpy2 = 0
ANALOGSTICK[0][0][HORIZONTAL] = parseFloat(vgpx1 + vgpx2)
ANALOGSTICK[0][0][VERTICAL] = parseFloat(vgpy1 + vgpy2)
if (core.input.a || core.input.space || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[0]? && _VGAMEPADCONTROL.input.buttons[0]))
PADBUTTONS[0][0] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][0] = false
if (core.input.b || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[1]? && _VGAMEPADCONTROL.input.buttons[1]))
PADBUTTONS[0][1] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][1] = false
if (core.input.c || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[2]? && _VGAMEPADCONTROL.input.buttons[2]))
PADBUTTONS[0][2] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][2] = false
if (core.input.d || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[3]? && _VGAMEPADCONTROL.input.buttons[3]))
PADBUTTONS[0][3] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][3] = false
if (core.input.e || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[4]? && _VGAMEPADCONTROL.input.buttons[4]))
PADBUTTONS[0][4] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][4] = false
if (core.input.f || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[5]? && _VGAMEPADCONTROL.input.buttons[5]))
PADBUTTONS[0][5] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][5] = false
if (core.input.g || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[6]? && _VGAMEPADCONTROL.input.buttons[6]))
PADBUTTONS[0][6] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][6] = false
if (core.input.h || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[7]? && _VGAMEPADCONTROL.input.buttons[7]))
PADBUTTONS[0][7] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][7] = false
if (core.input.left || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.left))
PADAXES[0][HORIZONTAL] = -1
else if (core.input.right || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.right))
PADAXES[0][HORIZONTAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][HORIZONTAL] = 0
if (core.input.up || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.up))
PADAXES[0][VERTICAL] = -1
else if (core.input.down || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.down))
PADAXES[0][VERTICAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][VERTICAL] = 0
if (GAMEPADMIX? && GAMEPADMIX)
mx = (ANALOGSTICK[0][0][HORIZONTAL] + PADAXES[0][HORIZONTAL])
mx = 1 if (mx > 1)
mx = -1 if (mx < -1)
my = (ANALOGSTICK[0][0][VERTICAL] + PADAXES[0][VERTICAL])
my = 1 if (my > 1)
my = -1 if (my < -1)
ANALOGSTICK[0][0][HORIZONTAL] = mx
ANALOGSTICK[0][0][VERTICAL] = my
# box2dの時間を進める
box2dworld.step(core.fps)
# 全てのオブジェクトの「behavior」を呼ぶ
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
obj.motionObj.behavior()
# 更新した座標値をスプライトに適用する
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
wx = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centerx - (SCREEN_WIDTH / 2)) else 0
wy = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centery - (SCREEN_HEIGHT / 2)) else 0
switch (obj.motionObj._type)
when CONTROL
continue
when PRIMITIVE, COLLADA
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y)
obj.motionObj.sprite.z = Math.floor(obj.motionObj.z)
when SPRITE, LABEL, SURFACE
if (obj.motionObj.rigid)
if (obj.motionObj._xback != obj.motionObj.x)
obj.motionObj.sprite.x = obj.motionObj.x - obj.motionObj._diffx - wx
if (obj.motionObj._yback != obj.motionObj.y)
obj.motionObj.sprite.y = obj.motionObj.y - obj.motionObj._diffy - wy
else
rot = parseFloat(obj.motionObj.rotation)
rot += parseFloat(obj.motionObj.rotate)
if (rot >= 360.0)
rot = rot % 360
obj.motionObj.rotation = rot
obj.motionObj.sprite.rotation = parseInt(rot)
# _reversePosFlagは、Timeline適用中はここの処理内では座標操作はせず、スプライトの座標をオブジェクトの座標に代入している
if (obj.motionObj._type == LABEL)
diffx = 0
diffy = 0
else
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
if (obj.motionObj._reversePosFlag)
obj.motionObj.x = obj.motionObj.sprite.x + diffx
obj.motionObj.y = obj.motionObj.sprite.y + diffy
else
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
if (obj.motionObj._uniqueID != obj.motionObj.collider._uniqueID)
obj.motionObj.collider.sprite.x = obj.motionObj.collider.x = obj.motionObj.sprite.x + diffx - obj.motionObj.collider._diffx + obj.motionObj.collider._offsetx
obj.motionObj.collider.sprite.y = obj.motionObj.collider.y = obj.motionObj.sprite.y + diffy - obj.motionObj.collider._diffy + obj.motionObj.collider._offsety
when MAP, EXMAP
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
#, false
#******************************************************************************
# デバッグ用関数
#******************************************************************************
debugwrite = (param)->
if (DEBUG)
if (param.clear)
labeltext = if (param.labeltext?) then param.labeltext else ""
else
labeltext = _DEBUGLABEL.text += if (param.labeltext?) then param.labeltext else ""
fontsize = if (param.fontsize?) then param.fontsize else 32
fontcolor = if (param.color?) then param.color else "white"
_DEBUGLABEL.font = fontsize+"px 'Arial'"
_DEBUGLABEL.text = labeltext
_DEBUGLABEL.color = fontcolor
debugclear =->
if (DEBUG)
_DEBUGLABEL.text = ""
#******************************************************************************
# 2D/3D共用オブジェクト生成メソッド
#******************************************************************************
addObject = (param, parent = undefined)->
# パラメーター
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
_type = if (param['type']?) then param['type'] else SPRITE
x = if (param['x']?) then param['x'] else 0
y = if (param['y']?) then param['y'] else 0
z = if (param['z']?) then param['z'] else 0
xs = if (param['xs']?) then param['xs'] else 0.0
ys = if (param['ys']?) then param['ys'] else 0.0
zs = if (param['zs']?) then param['zs'] else 0.0
gravity = if (param['gravity']?) then param['gravity'] else 0.0
image = if (param['image']?) then param['image'] else undefined
model = if (param['model']?) then param['model'] else undefined
width = if (param['width']?) then param['width'] else 1
height = if (param['height']?) then param['height'] else 1
depth = if (param['depth']?) then param['depth'] else 1.0
opacity = if (param['opacity']?) then param['opacity'] else 1.0
animlist = if (param['animlist']?) then param['animlist'] else undefined
animnum = if (param['animnum']?) then param['animnum'] else 0
visible = if (param['visible']?) then param['visible'] else true
scene = if (param['scene']?) then param['scene'] else -1
rigid = if (param['rigid']?) then param['rigid'] else false
density = if (param['density']?) then param['density'] else 1.0
friction = if (param['friction']?) then param['friction'] else 1.0
restitution = if (param['restitution']?) then param['restitution'] else 1.0
radius = if (param['radius']?) then param['radius'] else undefined
radius2 = if (param['radius2']?) then param['radius2'] else 1.0
size = if (param['size']?) then param['size'] else 1.0
scaleX = if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY = if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ = if (param['scaleZ']?) then param['scaleZ'] else 1.0
rotation = if (param['rotation']?) then param['rotation'] else 0.0
rotate = if (param['rotate']?) then param['rotate'] else 0.0
texture = if (param['texture']?) then param['texture'] else undefined
fontsize = if (param['fontsize']?) then param['fontsize'] else '16'
color = if (param['color']?) then param['color'] else 'white'
labeltext = if (param['labeltext']?) then param['labeltext'].replace(/\n/ig, "<br>") else 'text'
textalign = if (param['textalign']?) then param['textalign'] else 'left'
active = if (param['active']?) then param['active'] else true
kind = if (param['kind']?) then param['kind'] else DYNAMIC_BOX
map = if (param['map']?) then param['map'] else undefined
map2 = if (param['map2']?) then param['map2'] else undefined
mapcollision = if (param['mapcollision']?) then param['mapcollision'] else undefined
collider = if (param['collider']?) then param['collider'] else undefined
offsetx = if (param['offsetx']?) then param['offsetx'] else 0
offsety = if (param['offsety']?) then param['offsety'] else 0
bgcolor = if (param['bgcolor']?) then param['bgcolor'] else 'transparent'
worldview = if (param['worldview']?) then param['worldview'] else false
touchEnabled = if (param['touchEnabled']?) then param['touchEnabled'] else true
tmp = __getNullObject()
if (tmp == -1)
return undefined
if (motionObj == null)
motionObj = undefined
retObject = undefined
# スプライトを生成
switch (_type)
#*****************************************************************
# CONTROL、SPRITE
#*****************************************************************
when CONTROL, SPRITE, COLLIDER2D
motionsprite = undefined
if (_type == SPRITE)
if (rigid)
if (!radius?)
radius = width
switch (kind)
when DYNAMIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when DYNAMIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when STATIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
when STATIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
if (!motionsprite?)
motionsprite = new Sprite()
if (_type == COLLIDER2D)
scene = GAMESCENE_SUB2
if (scene < 0)
scene = GAMESCENE_SUB1
# アニメーション設定
if (MEDIALIST[image]?)
if (animlist?)
animtmp = animlist[animnum]
motionsprite.frame = animtmp[1][0]
else
motionsprite.frame = 0
motionsprite.backgroundColor = "transparent"
motionsprite.x = x - Math.floor(width / 2)
motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.opacity = if (_type == COLLIDER2D) then 0.8 else opacity
motionsprite.rotation = rotation
motionsprite.rotate = rotate
motionsprite.scaleX = scaleX
motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
else
motionsprite.visible = false
motionsprite.width = 0
motionsprite.height = 0
motionsprite.image = ""
# スプライトを表示
_scenes[scene].addChild(motionsprite)
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
gravity: gravity
width: width
height: height
animlist: animlist
animnum: animnum
opacity: opacity
scene: scene
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
rotation: rotation
rotate: rotate
parent: parent
radius: radius
density: density
friction: friction
restitution: restitution
active: active
rigid: rigid
kind: kind
collider: collider
offsetx: offsetx
offsety: offsety
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# LABEL
#*****************************************************************
when LABEL
if (scene < 0)
scene = GAMESCENE_SUB1
if (width == 0)
width = 120
if (height == 0)
height = 64
# ラベルを生成
motionsprite = new Label(labeltext)
# ラベルを表示
_scenes[scene].addChild(motionsprite)
# 値を代入
#motionsprite.backgroundColor = "transparent"
#motionsprite.x = x - Math.floor(width / 2)
#motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.x = x
motionsprite.y = y - Math.floor(z)
motionsprite.opacity = opacity
#motionsprite.rotation = rotation
#motionsprite.rotate = rotate
#motionsprite.scaleX = scaleX
#motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
motionsprite.color = color
motionsprite.text = ""
motionsprite.textAlign = textalign
#motionsprite.font = fontsize+"px 'Arial'"
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
width: width
height: height
opacity: opacity
scene: scene
_type: _type
active: active
motionsprite: motionsprite
motionObj: motionObj
fontsize: fontsize
color: color
labeltext: labeltext
textalign: textalign
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# プリミティブ
#*****************************************************************
when PRIMITIVE
if (!radius?)
radius = 1.0
switch (model)
when BOX
motionsprite = new Box(width, height, depth)
when CUBE
motionsprite = new Cube(size)
when SPHERE
motionsprite = new Sphere(size)
when CYLINDER
motionsprite = new Cylinder(radius, height)
when TORUS
motionsprite = new Torus(radius, radius2)
when PLANE
motionsprite = new Plane(size)
else
return undefined
if (texture?)
imagefile = MEDIALIST[texture]
tx = new Texture(imagefile)
motionsprite.mesh.texture = tx
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
active: active
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
if (visible)
rootScene3d.addChild(motionsprite)
return retObject
#*****************************************************************
# COLLADAモデル
#*****************************************************************
when COLLADA
if (!radius?)
radius = 1.0
if (MEDIALIST[model]?)
motionsprite = new Sprite3D()
motionsprite.set(core.assets[MEDIALIST[model]].clone())
else
return undefined
# 動きを定義したオブジェクトを生成する
if (visible)
rootScene3d.addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
active: active
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# Surface
#*****************************************************************
when SURFACE
if (scene < 0)
scene = GAMESCENE_SUB1
motionsprite = new Sprite(SCREEN_WIDTH, SCREEN_HEIGHT)
surface = new Surface(SCREEN_WIDTH, SCREEN_HEIGHT)
motionsprite.image = surface
context = surface.context
###
# パスの描画の初期化
context.beginPath()
# 描画開始位置の移動
context.moveTo(10, 10)
# 指定座標まで直線を描画
context.lineTo(100, 100)
# 線の色を指定 (指定しないと黒)
context.strokeStyle = "rgba(0, 255, 255, 0.5)";
# 描画を行う
context.stroke()
###
retObject = @__setMotionObj
width: SCREEN_WIDTH
height: SCREEN_HEIGHT
opacity: opacity
scene: scene
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
context: context
active: active
surface: surface
worldview: worldview
touchEnabled: touchEnabled
_scenes[scene].addChild(motionsprite)
return retObject
#*****************************************************************
# Mapオブジェクト
#*****************************************************************
when MAP, EXMAP
if (!map? || image == "")
JSLog("parameter not enough.")
else
if (scene < 0)
scene = BGSCENE_SUB1
if (_type == MAP)
motionsprite = new Map(width, height)
motionsprite.loadData(map)
else
motionsprite = new ExMap(width, height)
motionsprite.loadData(map, map2)
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
if (mapcollision?)
motionsprite.collisionData = mapcollision
_scenes[scene].addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
xs: xs
ys: ys
map: map
visible: visible
width: width
height: height
opacity: opacity
scene: scene
active: active
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
__setMotionObj = (param)->
# 動きを定義したオブジェクトを生成する
initparam =
x : if (param['x']?) then param['x'] else 0
y : if (param['y']?) then param['y'] else 0
z : if (param['z']?) then param['z'] else 0
xs : if (param['xs']?) then param['xs'] else 0
ys : if (param['ys']?) then param['ys'] else 0
zs : if (param['zs']?) then param['zs'] else 0
visible : if (param['visible']?) then param['visible'] else true
scaleX : if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY : if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ : if (param['scaleZ']?) then param['scaleZ'] else 1.0
radius : if (param['radius']?) then param['radius'] else 0.0
radius2 : if (param['radius2']?) then param['radius2'] else 0.0
size : if (param['size']?) then param['size'] else 1.0
gravity : if (param['gravity']?) then param['gravity'] else 0
intersectFlag : if (param['intersectFlag']?) then param['intersectFlag'] else true
width : if (param['width']?) then param['width'] else SCREEN_WIDTH
height : if (param['height']?) then param['height'] else SCREEN_HEIGHT
animlist : if (param['animlist']?) then param['animlist'] else undefined
animnum : if (param['animnum']?) then param['animnum'] else 0
image : if (param['image']?) then param['image'] else undefined
visible : if (param['visible']?) then param['visible'] else true
opacity : if (param['opacity']?) then param['opacity'] else 0
rotation : if (param['rotation']?) then param['rotation'] else 0.0
rotate : if (param['rotate']?) then param['rotate'] else 0.0
motionsprite : if (param['motionsprite']?) then param['motionsprite'] else 0
fontsize : if (param['fontsize']?) then param['fontsize'] else '16'
color : if (param['color']?) then param['color'] else 'white'
labeltext : if (param['labeltext']?) then param['labeltext'] else 'text'
textalign : if (param['textalign']?) then param['textalign'] else 'left'
parent : if (param['parent']?) then param['parent'] else undefined
density : if (param['density']?) then param['density'] else 1.0
friction : if (param['friction']?) then param['friction'] else 0.5
restitution : if (param['restitution']?) then param['restitution'] else 0.1
active : if (param['active']?) then param['active'] else true
kind : if (param['kind']?) then param['kind'] else undefined
rigid : if (param['rigid']?) then param['rigid'] else undefined
context : if (param['context']?) then param['context'] else undefined
surface : if (param['surface']?) then param['surface'] else undefined
collider : if (param['collider']?) then param['collider'] else undefined
offsetx : if (param['offsetx']?) then param['offsetx'] else 0
offsety : if (param['offsety']?) then param['offsety'] else 0
worldview : if (param['worldview']?) then param['worldview'] else false
touchEnabled : if (param['touchEnabled']?) then param['touchEnabled'] else true
scene = if (param['scene']?) then param['scene'] else GAMESCENE_SUB1
_type = if (param['_type']?) then param['_type'] else SPRITE
initparam._type = _type
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
map = if (param['map']?) then param['map'] else []
if (_type == MAP || _type == EXMAP)
mapwidth = map[0].length * initparam.width
mapheight = map.length * initparam.height
initparam.diffx = Math.floor(mapwidth / 2)
initparam.diffy = Math.floor(mapheight / 2)
else
initparam.diffx = Math.floor(initparam.width / 2)
initparam.diffy = Math.floor(initparam.height / 2)
objnum = __getNullObject()
if (objnum < 0)
return undefined
obj = _objects[objnum]
obj.active = true
if (motionObj?)
obj.motionObj = new motionObj(initparam)
else
obj.motionObj = new _stationary(initparam)
uid = uniqueID()
obj.motionObj._uniqueID = uid
obj.motionObj._scene = scene
obj.motionObj._type = _type
return obj.motionObj
#**********************************************************************
# オブジェクト削除(画面からも消える)
#**********************************************************************
removeObject = (motionObj)->
if (!motionObj?)
return
# 削除しようとしているmotionObjがオブジェクトリストのどこに入っているか探す
ret = false
for object in _objects
if (!object.motionObj?)
continue
if (object.motionObj._uniqueID == motionObj._uniqueID)
ret = true
break
if (ret == false)
return
if (motionObj.collider._uniqueID != motionObj._uniqueID)
removeObject(motionObj.collider)
if (typeof(motionObj.destructor) == 'function')
motionObj.destructor()
if (motionObj.rigid)
object.motionObj.sprite.destroy()
else
switch (motionObj._type)
when CONTROL, SPRITE, LABEL, MAP, EXMAP, PRIMITIVE, COLLADA, COLLIDER2D
_scenes[object.motionObj._scene].removeChild(object.motionObj.sprite)
object.motionObj.sprite = undefined
object.motionObj = undefined
object.active = false
#**********************************************************************
# オブジェクトリストの指定した番号のオブジェクトを返す
#**********************************************************************
getObject = (id)->
ret = undefined
for i in [0..._objects.length]
if (!_objects[i]?)
continue
if (!_objects[i].motionObj?)
continue
if (_objects[i].motionObj._uniqueID == id)
ret = _objects[i].motionObj
break
return ret
#**********************************************************************
# サウンド再生
#**********************************************************************
playSound = (name, vol = 1.0, flag = false)->
soundfile = MEDIALIST[name]
sound = core.assets[soundfile].clone()
if (sound.src?)
sound.play()
sound.volume = vol
sound.src.loop = flag
return sound
#**********************************************************************
# サウンド一時停止
#**********************************************************************
pauseSound = (obj)->
obj.pause()
#**********************************************************************
# サウンド再開
#**********************************************************************
resumeSound = (obj, flag = false)->
obj.play()
#obj.src.loop = flag
obj.loop = flag
#**********************************************************************
# サウンド停止
#**********************************************************************
stopSound = (obj)->
obj.stop()
#**********************************************************************
# サウンド音量設定
#**********************************************************************
setSoundLoudness = (obj, num)->
obj.volume = num
#**********************************************************************
# サウンド再生位置(時間)取得
#**********************************************************************
getSoundCurrenttime = (obj)->
return obj.currenttime
#**********************************************************************
# サウンド再生位置(時間)設定
#**********************************************************************
setSoundCurrenttime = (obj, num)->
obj.currenttime = num
#**********************************************************************
# ゲーム一時停止
#**********************************************************************
pauseGame =->
ACTIVATE = false
core.pause()
#**********************************************************************
# ゲーム再開
#**********************************************************************
resumeGame =->
ACTIVATE = true
core.resume()
#**********************************************************************
# ワールドビューの設定
#**********************************************************************
setWorldView = (cx, cy)->
if (!cx?)
cx = SCREEN_WIDTH / 2
if (!cy?)
cy = SCREEN_HEIGHT / 2
_WORLDVIEW =
centerx: cx
centery: cy
#**********************************************************************
# バーチャルゲームパッド
#**********************************************************************
createVirtualGamepad = (param)->
if (param?)
scale = if (param.scale?) then param.scale else 1
x = if (param.x?) then param.x else (100 / 2) * scale
y = if (param.y?) then param.y else SCREEN_HEIGHT - ((100 / 2) * scale)
visible = if (param.visible?) then param.visible else true
kind = if (param.kind?) then param.kind else 0
analog = if (param.analog?) then param.analog else false
button = if (param.button?) then param.button else 0
buttonscale = if (param.buttonscale?) then param.buttonscale else 1
image = if (param.image?) then param.image else undefined
coord = if (param.coord?) then param.coord else []
else
param = []
scale = param.scale = 1.0
x = param.x = (100 / 2) * scale
y = param.y = SCREEN_HEIGHT - ((100 / 2) * scale)
visible = param.visible = true
kind = param.kind = 0
analog = param.analog = false
button = param.button = 0
image = param.image = undefined
buttonscale = param.buttonscale = 1
coord = param.coord = []
if (button > 6)
button = param.button = 6
if (!_VGAMEPADCONTROL?)
_VGAMEPADCONTROL = addObject
x: x
y: y
type: CONTROL
motionObj: _vgamepadcontrol
_VGAMEPADCONTROL.createGamePad(param)
#**********************************************************************
# バーチャルゲームパッドの表示制御
#**********************************************************************
dispVirtualGamepad = (flag)->
_VGAMEPADCONTROL.setVisible(flag) if (_VGAMEPADCONTROL?)
#**********************************************************************
# 標準ブラウザは非推奨というダイアログ表示
#**********************************************************************
dispDefaultBrowserCheck = (func)->
if (_defaultbrowser)
cautionscale = SCREEN_WIDTH / 320
caution = addObject
image: '_notice'
x: SCREEN_WIDTH / 2
y: 200
width: 300
height: 140
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton = addObject
image: '_execbutton'
x: SCREEN_WIDTH / 2
y: 320
width: 80
height: 32
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton.sprite.ontouchstart = (e)->
removeObject(caution)
removeObject(okbutton)
func()
else
func()
#**********************************************************************
#**********************************************************************
#**********************************************************************
# 以下は内部使用ライブラリ関数
#**********************************************************************
#**********************************************************************
#**********************************************************************
#**********************************************************************
# オブジェクトリストの中で未使用のものの配列番号を返す。
# 無かった場合は-1を返す
#**********************************************************************
__getNullObject = ->
ret = -1
for i in [0..._objects.length]
if (_objects[i].active == false)
ret = i
break
return ret
| 41800 | #******************************************************************************
# enforce game engine(enchant)
#
# 2014.04.04 ver2.0
#
# Coded by <NAME>
#******************************************************************************
#******************************************************************************
# 初期化処理
#******************************************************************************
# 定数定義
# 色定義
WHITE = 0
BLACK = 1
# オブジェクトの種類
CONTROL = 0
SPRITE = 1
LABEL = 2
SURFACE = 3
PRIMITIVE = 4
COLLADA = 5
MAP = 6
EXMAP = 7
COLLIDER2D = 8
# 物理スプライトの種類
DYNAMIC_BOX = 0
DYNAMIC_CIRCLE = 1
STATIC_BOX = 2
STATIC_CIRCLE = 3
# Easingの種類(kind)
LINEAR = 0
SWING = 1
BACK = 2
BOUNCE = 3
CIRCLE = 4
CUBIC = 5
ELASTIC = 6
EXPO = 7
QUAD = 8
QUART = 9
QUINT = 10
SINE = 11
# Easingの動き(move)
EASEINOUT = 0
EASEIN = 1
EASEOUT = 2
NONE = 3
# Easingの配列
EASINGVALUE = []
# WebGLのプリミティブの種類
BOX = 0
CUBE = 1
SPHERE = 2
CYLINDER = 3
TORUS = 4
PLANE = 5
# Sceneの種類
BGSCENE = 0
BGSCENE_SUB1 = 1
BGSCENE_SUB2 = 2
GAMESCENE = 3
GAMESCENE_SUB1 = 4
GAMESCENE_SUB2 = 5
TOPSCENE = 6
WEBGLSCENE = 7
_SYSTEMSCENE = 8
DEBUGSCENE = 9
MAXSCENE = (if (DEBUG) then DEBUGSCENE else _SYSTEMSCENE)
# ワールドビュー
_WORLDVIEW =
centerx: SCREEN_WIDTH / 2
centery: SCREEN_HEIGHT / 2
# 数学式
RAD = (Math.PI / 180.0)
DEG = (180.0 / Math.PI)
# グローバル初期化
GLOBAL = []
# サウンドプリロード用
SOUNDARR = []
# アスペクト比
ASPECT = 0.0
# ゲームパッド情報格納変数
HORIZONTAL = 0
VERTICAL = 1
_GAMEPADSINFO = []
PADBUTTONS = []
PADBUTTONS[0] = [false, false]
PADAXES = []
PADAXES[0] = [0, 0]
PADINFO = []
ANALOGSTICK = []
ANALOGSTICK[0] = [[0, 0], [0, 0]]
_VGAMEPADCONTROL = undefined
# Frame Per Seconds
if (!FPS?)
FPS = 60
# box2dの重力値
if (!GRAVITY_X?)
GRAVITY_X = 0.0
if (!GRAVITY_Y?)
GRAVITY_Y = 0.0
# センサー系
MOTION_ACCEL = [x:0, y:0, z:0]
MOTION_GRAVITY = [x:0, y:0, z:0]
MOTION_ROTATE = [alpha:0, beta:0, gamma:0]
# 標準ブラウザ
if (_useragent.match(/^.*android.*?mobile safari.*$/i) != null && _useragent.match(/^.*\) chrome.*/i) == null)
_defaultbrowser = true
else
_defaultbrowser = false
# ブラウザ大分類
if (_useragent.match(/.* firefox\/.*/))
_browserMajorClass = "firefox"
else if (_useragent.match(/.*version\/.* safari\/.*/))
_browserMajorClass = "safari"
else if (_useragent.match(/.*chrome\/.* safari\/.*/))
_browserMajorClass = "chrome"
else
_browserMajorClass = "unknown"
# ゲーム起動時からの経過時間(秒)
LAPSEDTIME = 0.0
# ゲーム起動時のUNIXTIME
BEGINNINGTIME = undefined
# フレームレート調整用
__FRAMETIME = 0.0
# 3D系
OCULUS = undefined
RENDERER = undefined
CAMERA = undefined
LIGHT = undefined
# デバイスサイズ
_frame = getBounds()
DEVICE_WIDTH = _frame[0]
DEVICE_HEIGHT = _frame[1]
if (!SCREEN_WIDTH? && !SCREEN_HEIGHT?)
SCREEN_WIDTH = DEVICE_WIDTH
SCREEN_HEIGHT = DEVICE_HEIGHT
# 動作状況
ACTIVATE = true
# オブジェクトが入っている配列
_objects = []
# Scene格納用配列
_scenes = []
# 起動時に生成されるスタートオブジェクト
_main = null
# デバッグ用LABEL
_DEBUGLABEL = undefined
_FPSGAUGE = undefined
__fpsgaugeunit = 0
__fpscounter = 0.0
__limittimefps = 0.0
# enchantのcoreオブジェクト
core = undefined
# box2dのworldオブジェクト
box2dworld = undefined
# 3Dのscene
rootScene3d = undefined
# enchantのrootScene
rootScene = undefined
# アニメーション管理
__requestID = ( ->
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
(callback)->
window.setTimeout(callback, 1000 / 60)
)()
#******************************************************************************
# 起動時の処理
#******************************************************************************
# enchantのオマジナイ
enchant()
enchant.ENV.MOUSE_ENABLED = false
enchant.ENV.SOUND_ENABLED_ON_MOBILE_SAFARI = false
# ゲーム起動時の処理
#window.addEventListener 'load', (e)->
window.onload = ->
window.removeEventListener('load', arguments.callee, false)
# ゲーム起動時間
BEGINNINGTIME = __getTime()
# アスペクト比
ASPECT = (SCREEN_WIDTH / SCREEN_HEIGHT).toFixed(2)
# enchant初期化
core = new Core(SCREEN_WIDTH, SCREEN_HEIGHT)
# FPS設定
core.fps = FPS
# Easing定義
EASINGVALUE[LINEAR] = [enchant.Easing.LINEAR]
EASINGVALUE[SWING] = [enchant.Easing.SWING]
EASINGVALUE[BACK] = [enchant.Easing.BACK_EASEINOUT, enchant.Easing.BACK_EASEIN, enchant.Easing.BACK_EASEOUT]
EASINGVALUE[BOUNCE] = [enchant.Easing.BOUNCE_EASEINOUT, enchant.Easing.BOUNCE_EASEIN, enchant.Easing.BOUNCE_EASEOUT]
EASINGVALUE[CIRCLE] = [enchant.Easing.CIRCLE_EASEINOUT, enchant.Easing.CIRCLE_EASEIN, enchant.Easing.CIRCLE_EASEOUT]
EASINGVALUE[CUBIC] = [enchant.Easing.CUBIC_EASEINOUT, enchant.Easing.CUBIC_EASEIN, enchant.Easing.CUBIC_EASEOUT]
EASINGVALUE[ELASTIC] = [enchant.Easing.ELASTIC_EASEINOUT, enchant.Easing.ELASTIC_EASEIN, enchant.Easing.ELASTIC_EASEOUT]
EASINGVALUE[EXPO] = [enchant.Easing.EXPO_EASEINOUT, enchant.Easing.EXPO_EASEIN, enchant.Easing.EXPO_EASEOUT]
EASINGVALUE[QUAD] = [enchant.Easing.QUAD_EASEINOUT, enchant.Easing.QUAD_EASEIN, enchant.Easing.QUAD_EASEOUT]
EASINGVALUE[QUART] = [enchant.Easing.QUART_EASEINOUT, enchant.Easing.QUART_EASEIN, enchant.Easing.QUART_EASEOUT]
EASINGVALUE[QUINT] = [enchant.Easing.QUINT_EASEINOUT, enchant.Easing.QUINT_EASEIN, enchant.Easing.QUINT_EASEOUT]
EASINGVALUE[SINE] = [enchant.Easing.SINE_EASEINOUT, enchant.Easing.SINE_EASEIN, enchant.Easing.SINE_EASEOUT]
# ボタンの定義
core.keybind( 90, 'a' )
core.keybind( 88, 'b' )
core.keybind( 67, 'c' )
core.keybind( 86, 'd' )
core.keybind( 66, 'e' )
core.keybind( 78, 'f' )
core.keybind( 77, 'g' )
core.keybind( 188, 'h' )
core.keybind( 32, 'space' )
# メディアファイルのプリロード
if (MEDIALIST?)
MEDIALIST['_ascii_w'] = 'lib/ascii_w.png'
MEDIALIST['_ascii_b'] = 'lib/ascii_b.png'
MEDIALIST['_fpsgauge'] = 'lib/fpsgauge.png'
MEDIALIST['_notice'] = 'lib/notice.png'
MEDIALIST['_execbutton'] = 'lib/execbutton.png'
MEDIALIST['_pad_w'] = 'lib/pad_w.png'
MEDIALIST['_pad_b'] = 'lib/pad_b.png'
MEDIALIST['_apad_w'] = 'lib/apad_w.png'
MEDIALIST['_apad_b'] = 'lib/apad_b.png'
MEDIALIST['_apad2_w'] = 'lib/apad2_w.png'
MEDIALIST['_apad2_b'] = 'lib/apad2_b.png'
MEDIALIST['_button_w'] = 'lib/button_w.png'
MEDIALIST['_button_b'] = 'lib/button_b.png'
mediaarr = []
num = 0
for obj of MEDIALIST
mediaarr[num++] = MEDIALIST[obj]
core.preload(mediaarr)
# rootSceneをグローバルに保存
rootScene = core.rootScene
# モーションセンサーのイベント登録
window.addEventListener 'devicemotion', (e)->
MOTION_ACCEL = e.acceleration
MOTION_GRAVITY = e.accelerationIncludingGravity
window.addEventListener 'deviceorientation', (e)->
MOTION_ROTATE.alpha = e.alpha
MOTION_ROTATE.beta = e.beta
MOTION_ROTATE.gamma = e.gamma
# box2d初期化
box2dworld = new PhysicsWorld(GRAVITY_X, GRAVITY_Y)
# シーングループを生成
for i in [0..MAXSCENE]
scene = new Group()
scene.backgroundColor = "black"
_scenes[i] = scene
rootScene.addChild(scene)
if (WEBGL != undefined && WEBGL && isWebGL())
# 3Dシーンを生成
rootScene3d = new Scene3D()
_scenes[WEBGLSCENE] = rootScene3d
# スポットライト生成
#DLIGHT = new DirectionalLight()
#DLIGHT.color = [1.0, 1.0, 1.0]
#dlight.directionX = 0
#dlight.directionY = 100
#dlight.directionZ = 0
rootScene3d.setDirectionalLight(DLIGHT)
# 環境光ライト生成
#ALIGHT = new AmbientLight()
#ALIGHT.color = [1.0, 1.0, 1.0]
#alight.directionX = 0
#alight.directionY = 100
rootScene3d.setAmbientLight(ALIGHT)
# カメラ生成
CAMERA = new Camera3D()
CAMERA.x = 0
CAMERA.y = 0
CAMERA.z = 160
CAMERA.centerX = 0
CAMERA.centerY = 0
CAMERA.centerZ = 0
rootScene3d.setCamera(CAMERA)
else
rootScene.backgroundColor = BGCOLOR
WEBGL = false
#if (DEBUG == true)
# core.debug()
#else
# core.start()
core.start()
#******************************************************************************
# 起動時の処理
#******************************************************************************
core.onload = ->
# ゲーム用オブジェクトを指定された数だけ確保
for i in [0...OBJECTNUM]
_objects[i] = new _originObject()
_main = new enforceMain()
if (DEBUG)
_DEBUGLABEL = new Label()
_DEBUGLABEL.x = 0
_DEBUGLABEL.y = 0
_DEBUGLABEL.width = SCREEN_WIDTH
_DEBUGLABEL.color = "white"
_DEBUGLABEL.font = "32px 'Arial'"
_scenes[DEBUGSCENE].addChild(_DEBUGLABEL)
_FPSGAUGE = new Sprite()
_FPSGAUGE.x = SCREEN_WIDTH - 16
_FPSGAUGE.y = 0
_FPSGAUGE.width = 16
_FPSGAUGE.height = 1
_FPSGAUGE.scaleY = 1.0
_FPSGAUGE.opacity = 0.5
_FPSGAUGE.image = core.assets[MEDIALIST['_fpsgauge']]
_FPSGAUGE.frame = 0
_scenes[DEBUGSCENE].addChild(_FPSGAUGE)
__fpscounter = 0
__limittimefps = 0.0
# フレーム処理(enchant任せ)
rootScene.addEventListener 'enterframe', (e)->
# 経過時間を計算
LAPSEDTIME = parseFloat((__getTime() - parseFloat(BEGINNINGTIME.toFixed(2))) / 1000.0)
# FPS表示(デバッグモード時のみ)
if (DEBUG)
__fpscounter++
if (__limittimefps < parseFloat(LAPSEDTIME))
__limittimefps = LAPSEDTIME + 1.0
scale = parseFloat(((__fpscounter / FPS) * SCREEN_HEIGHT).toFixed(2))
_FPSGAUGE.height = scale
__fpscounter = 0
# ジョイパッド処理
if (typeof gamepadProcedure == 'function')
_GAMEPADSINFO = gamepadProcedure()
for num in [0..._GAMEPADSINFO.length]
if (!_GAMEPADSINFO[num]?)
continue
padobj = _GAMEPADSINFO[num]
PADBUTTONS[num] = padobj.padbuttons
PADAXES[num] = padobj.padaxes
ANALOGSTICK[num] = padobj.analogstick
PADINFO[num] = []
PADINFO[num].id = padobj.id
if (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.analog?)
vgpx1 = parseFloat(_VGAMEPADCONTROL.input.analog[HORIZONTAL])
vgpy1 = parseFloat(_VGAMEPADCONTROL.input.analog[VERTICAL])
else
vgpx1 = 0
vgpy1 = 0
if (_GAMEPADSINFO? && _GAMEPADSINFO[0]?)
vgpx2 = _GAMEPADSINFO[0].analogstick[0][HORIZONTAL]
vgpy2 = _GAMEPADSINFO[0].analogstick[0][VERTICAL]
else
vgpx2 = 0
vgpy2 = 0
ANALOGSTICK[0][0][HORIZONTAL] = parseFloat(vgpx1 + vgpx2)
ANALOGSTICK[0][0][VERTICAL] = parseFloat(vgpy1 + vgpy2)
if (core.input.a || core.input.space || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[0]? && _VGAMEPADCONTROL.input.buttons[0]))
PADBUTTONS[0][0] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][0] = false
if (core.input.b || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[1]? && _VGAMEPADCONTROL.input.buttons[1]))
PADBUTTONS[0][1] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][1] = false
if (core.input.c || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[2]? && _VGAMEPADCONTROL.input.buttons[2]))
PADBUTTONS[0][2] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][2] = false
if (core.input.d || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[3]? && _VGAMEPADCONTROL.input.buttons[3]))
PADBUTTONS[0][3] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][3] = false
if (core.input.e || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[4]? && _VGAMEPADCONTROL.input.buttons[4]))
PADBUTTONS[0][4] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][4] = false
if (core.input.f || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[5]? && _VGAMEPADCONTROL.input.buttons[5]))
PADBUTTONS[0][5] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][5] = false
if (core.input.g || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[6]? && _VGAMEPADCONTROL.input.buttons[6]))
PADBUTTONS[0][6] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][6] = false
if (core.input.h || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[7]? && _VGAMEPADCONTROL.input.buttons[7]))
PADBUTTONS[0][7] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][7] = false
if (core.input.left || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.left))
PADAXES[0][HORIZONTAL] = -1
else if (core.input.right || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.right))
PADAXES[0][HORIZONTAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][HORIZONTAL] = 0
if (core.input.up || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.up))
PADAXES[0][VERTICAL] = -1
else if (core.input.down || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.down))
PADAXES[0][VERTICAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][VERTICAL] = 0
if (GAMEPADMIX? && GAMEPADMIX)
mx = (ANALOGSTICK[0][0][HORIZONTAL] + PADAXES[0][HORIZONTAL])
mx = 1 if (mx > 1)
mx = -1 if (mx < -1)
my = (ANALOGSTICK[0][0][VERTICAL] + PADAXES[0][VERTICAL])
my = 1 if (my > 1)
my = -1 if (my < -1)
ANALOGSTICK[0][0][HORIZONTAL] = mx
ANALOGSTICK[0][0][VERTICAL] = my
# box2dの時間を進める
box2dworld.step(core.fps)
# 全てのオブジェクトの「behavior」を呼ぶ
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
obj.motionObj.behavior()
# 更新した座標値をスプライトに適用する
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
wx = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centerx - (SCREEN_WIDTH / 2)) else 0
wy = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centery - (SCREEN_HEIGHT / 2)) else 0
switch (obj.motionObj._type)
when CONTROL
continue
when PRIMITIVE, COLLADA
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y)
obj.motionObj.sprite.z = Math.floor(obj.motionObj.z)
when SPRITE, LABEL, SURFACE
if (obj.motionObj.rigid)
if (obj.motionObj._xback != obj.motionObj.x)
obj.motionObj.sprite.x = obj.motionObj.x - obj.motionObj._diffx - wx
if (obj.motionObj._yback != obj.motionObj.y)
obj.motionObj.sprite.y = obj.motionObj.y - obj.motionObj._diffy - wy
else
rot = parseFloat(obj.motionObj.rotation)
rot += parseFloat(obj.motionObj.rotate)
if (rot >= 360.0)
rot = rot % 360
obj.motionObj.rotation = rot
obj.motionObj.sprite.rotation = parseInt(rot)
# _reversePosFlagは、Timeline適用中はここの処理内では座標操作はせず、スプライトの座標をオブジェクトの座標に代入している
if (obj.motionObj._type == LABEL)
diffx = 0
diffy = 0
else
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
if (obj.motionObj._reversePosFlag)
obj.motionObj.x = obj.motionObj.sprite.x + diffx
obj.motionObj.y = obj.motionObj.sprite.y + diffy
else
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
if (obj.motionObj._uniqueID != obj.motionObj.collider._uniqueID)
obj.motionObj.collider.sprite.x = obj.motionObj.collider.x = obj.motionObj.sprite.x + diffx - obj.motionObj.collider._diffx + obj.motionObj.collider._offsetx
obj.motionObj.collider.sprite.y = obj.motionObj.collider.y = obj.motionObj.sprite.y + diffy - obj.motionObj.collider._diffy + obj.motionObj.collider._offsety
when MAP, EXMAP
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
#, false
#******************************************************************************
# デバッグ用関数
#******************************************************************************
debugwrite = (param)->
if (DEBUG)
if (param.clear)
labeltext = if (param.labeltext?) then param.labeltext else ""
else
labeltext = _DEBUGLABEL.text += if (param.labeltext?) then param.labeltext else ""
fontsize = if (param.fontsize?) then param.fontsize else 32
fontcolor = if (param.color?) then param.color else "white"
_DEBUGLABEL.font = fontsize+"px 'Arial'"
_DEBUGLABEL.text = labeltext
_DEBUGLABEL.color = fontcolor
debugclear =->
if (DEBUG)
_DEBUGLABEL.text = ""
#******************************************************************************
# 2D/3D共用オブジェクト生成メソッド
#******************************************************************************
addObject = (param, parent = undefined)->
# パラメーター
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
_type = if (param['type']?) then param['type'] else SPRITE
x = if (param['x']?) then param['x'] else 0
y = if (param['y']?) then param['y'] else 0
z = if (param['z']?) then param['z'] else 0
xs = if (param['xs']?) then param['xs'] else 0.0
ys = if (param['ys']?) then param['ys'] else 0.0
zs = if (param['zs']?) then param['zs'] else 0.0
gravity = if (param['gravity']?) then param['gravity'] else 0.0
image = if (param['image']?) then param['image'] else undefined
model = if (param['model']?) then param['model'] else undefined
width = if (param['width']?) then param['width'] else 1
height = if (param['height']?) then param['height'] else 1
depth = if (param['depth']?) then param['depth'] else 1.0
opacity = if (param['opacity']?) then param['opacity'] else 1.0
animlist = if (param['animlist']?) then param['animlist'] else undefined
animnum = if (param['animnum']?) then param['animnum'] else 0
visible = if (param['visible']?) then param['visible'] else true
scene = if (param['scene']?) then param['scene'] else -1
rigid = if (param['rigid']?) then param['rigid'] else false
density = if (param['density']?) then param['density'] else 1.0
friction = if (param['friction']?) then param['friction'] else 1.0
restitution = if (param['restitution']?) then param['restitution'] else 1.0
radius = if (param['radius']?) then param['radius'] else undefined
radius2 = if (param['radius2']?) then param['radius2'] else 1.0
size = if (param['size']?) then param['size'] else 1.0
scaleX = if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY = if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ = if (param['scaleZ']?) then param['scaleZ'] else 1.0
rotation = if (param['rotation']?) then param['rotation'] else 0.0
rotate = if (param['rotate']?) then param['rotate'] else 0.0
texture = if (param['texture']?) then param['texture'] else undefined
fontsize = if (param['fontsize']?) then param['fontsize'] else '16'
color = if (param['color']?) then param['color'] else 'white'
labeltext = if (param['labeltext']?) then param['labeltext'].replace(/\n/ig, "<br>") else 'text'
textalign = if (param['textalign']?) then param['textalign'] else 'left'
active = if (param['active']?) then param['active'] else true
kind = if (param['kind']?) then param['kind'] else DYNAMIC_BOX
map = if (param['map']?) then param['map'] else undefined
map2 = if (param['map2']?) then param['map2'] else undefined
mapcollision = if (param['mapcollision']?) then param['mapcollision'] else undefined
collider = if (param['collider']?) then param['collider'] else undefined
offsetx = if (param['offsetx']?) then param['offsetx'] else 0
offsety = if (param['offsety']?) then param['offsety'] else 0
bgcolor = if (param['bgcolor']?) then param['bgcolor'] else 'transparent'
worldview = if (param['worldview']?) then param['worldview'] else false
touchEnabled = if (param['touchEnabled']?) then param['touchEnabled'] else true
tmp = __getNullObject()
if (tmp == -1)
return undefined
if (motionObj == null)
motionObj = undefined
retObject = undefined
# スプライトを生成
switch (_type)
#*****************************************************************
# CONTROL、SPRITE
#*****************************************************************
when CONTROL, SPRITE, COLLIDER2D
motionsprite = undefined
if (_type == SPRITE)
if (rigid)
if (!radius?)
radius = width
switch (kind)
when DYNAMIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when DYNAMIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when STATIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
when STATIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
if (!motionsprite?)
motionsprite = new Sprite()
if (_type == COLLIDER2D)
scene = GAMESCENE_SUB2
if (scene < 0)
scene = GAMESCENE_SUB1
# アニメーション設定
if (MEDIALIST[image]?)
if (animlist?)
animtmp = animlist[animnum]
motionsprite.frame = animtmp[1][0]
else
motionsprite.frame = 0
motionsprite.backgroundColor = "transparent"
motionsprite.x = x - Math.floor(width / 2)
motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.opacity = if (_type == COLLIDER2D) then 0.8 else opacity
motionsprite.rotation = rotation
motionsprite.rotate = rotate
motionsprite.scaleX = scaleX
motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
else
motionsprite.visible = false
motionsprite.width = 0
motionsprite.height = 0
motionsprite.image = ""
# スプライトを表示
_scenes[scene].addChild(motionsprite)
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
gravity: gravity
width: width
height: height
animlist: animlist
animnum: animnum
opacity: opacity
scene: scene
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
rotation: rotation
rotate: rotate
parent: parent
radius: radius
density: density
friction: friction
restitution: restitution
active: active
rigid: rigid
kind: kind
collider: collider
offsetx: offsetx
offsety: offsety
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# LABEL
#*****************************************************************
when LABEL
if (scene < 0)
scene = GAMESCENE_SUB1
if (width == 0)
width = 120
if (height == 0)
height = 64
# ラベルを生成
motionsprite = new Label(labeltext)
# ラベルを表示
_scenes[scene].addChild(motionsprite)
# 値を代入
#motionsprite.backgroundColor = "transparent"
#motionsprite.x = x - Math.floor(width / 2)
#motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.x = x
motionsprite.y = y - Math.floor(z)
motionsprite.opacity = opacity
#motionsprite.rotation = rotation
#motionsprite.rotate = rotate
#motionsprite.scaleX = scaleX
#motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
motionsprite.color = color
motionsprite.text = ""
motionsprite.textAlign = textalign
#motionsprite.font = fontsize+"px 'Arial'"
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
width: width
height: height
opacity: opacity
scene: scene
_type: _type
active: active
motionsprite: motionsprite
motionObj: motionObj
fontsize: fontsize
color: color
labeltext: labeltext
textalign: textalign
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# プリミティブ
#*****************************************************************
when PRIMITIVE
if (!radius?)
radius = 1.0
switch (model)
when BOX
motionsprite = new Box(width, height, depth)
when CUBE
motionsprite = new Cube(size)
when SPHERE
motionsprite = new Sphere(size)
when CYLINDER
motionsprite = new Cylinder(radius, height)
when TORUS
motionsprite = new Torus(radius, radius2)
when PLANE
motionsprite = new Plane(size)
else
return undefined
if (texture?)
imagefile = MEDIALIST[texture]
tx = new Texture(imagefile)
motionsprite.mesh.texture = tx
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
active: active
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
if (visible)
rootScene3d.addChild(motionsprite)
return retObject
#*****************************************************************
# COLLADAモデル
#*****************************************************************
when COLLADA
if (!radius?)
radius = 1.0
if (MEDIALIST[model]?)
motionsprite = new Sprite3D()
motionsprite.set(core.assets[MEDIALIST[model]].clone())
else
return undefined
# 動きを定義したオブジェクトを生成する
if (visible)
rootScene3d.addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
active: active
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# Surface
#*****************************************************************
when SURFACE
if (scene < 0)
scene = GAMESCENE_SUB1
motionsprite = new Sprite(SCREEN_WIDTH, SCREEN_HEIGHT)
surface = new Surface(SCREEN_WIDTH, SCREEN_HEIGHT)
motionsprite.image = surface
context = surface.context
###
# パスの描画の初期化
context.beginPath()
# 描画開始位置の移動
context.moveTo(10, 10)
# 指定座標まで直線を描画
context.lineTo(100, 100)
# 線の色を指定 (指定しないと黒)
context.strokeStyle = "rgba(0, 255, 255, 0.5)";
# 描画を行う
context.stroke()
###
retObject = @__setMotionObj
width: SCREEN_WIDTH
height: SCREEN_HEIGHT
opacity: opacity
scene: scene
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
context: context
active: active
surface: surface
worldview: worldview
touchEnabled: touchEnabled
_scenes[scene].addChild(motionsprite)
return retObject
#*****************************************************************
# Mapオブジェクト
#*****************************************************************
when MAP, EXMAP
if (!map? || image == "")
JSLog("parameter not enough.")
else
if (scene < 0)
scene = BGSCENE_SUB1
if (_type == MAP)
motionsprite = new Map(width, height)
motionsprite.loadData(map)
else
motionsprite = new ExMap(width, height)
motionsprite.loadData(map, map2)
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
if (mapcollision?)
motionsprite.collisionData = mapcollision
_scenes[scene].addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
xs: xs
ys: ys
map: map
visible: visible
width: width
height: height
opacity: opacity
scene: scene
active: active
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
__setMotionObj = (param)->
# 動きを定義したオブジェクトを生成する
initparam =
x : if (param['x']?) then param['x'] else 0
y : if (param['y']?) then param['y'] else 0
z : if (param['z']?) then param['z'] else 0
xs : if (param['xs']?) then param['xs'] else 0
ys : if (param['ys']?) then param['ys'] else 0
zs : if (param['zs']?) then param['zs'] else 0
visible : if (param['visible']?) then param['visible'] else true
scaleX : if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY : if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ : if (param['scaleZ']?) then param['scaleZ'] else 1.0
radius : if (param['radius']?) then param['radius'] else 0.0
radius2 : if (param['radius2']?) then param['radius2'] else 0.0
size : if (param['size']?) then param['size'] else 1.0
gravity : if (param['gravity']?) then param['gravity'] else 0
intersectFlag : if (param['intersectFlag']?) then param['intersectFlag'] else true
width : if (param['width']?) then param['width'] else SCREEN_WIDTH
height : if (param['height']?) then param['height'] else SCREEN_HEIGHT
animlist : if (param['animlist']?) then param['animlist'] else undefined
animnum : if (param['animnum']?) then param['animnum'] else 0
image : if (param['image']?) then param['image'] else undefined
visible : if (param['visible']?) then param['visible'] else true
opacity : if (param['opacity']?) then param['opacity'] else 0
rotation : if (param['rotation']?) then param['rotation'] else 0.0
rotate : if (param['rotate']?) then param['rotate'] else 0.0
motionsprite : if (param['motionsprite']?) then param['motionsprite'] else 0
fontsize : if (param['fontsize']?) then param['fontsize'] else '16'
color : if (param['color']?) then param['color'] else 'white'
labeltext : if (param['labeltext']?) then param['labeltext'] else 'text'
textalign : if (param['textalign']?) then param['textalign'] else 'left'
parent : if (param['parent']?) then param['parent'] else undefined
density : if (param['density']?) then param['density'] else 1.0
friction : if (param['friction']?) then param['friction'] else 0.5
restitution : if (param['restitution']?) then param['restitution'] else 0.1
active : if (param['active']?) then param['active'] else true
kind : if (param['kind']?) then param['kind'] else undefined
rigid : if (param['rigid']?) then param['rigid'] else undefined
context : if (param['context']?) then param['context'] else undefined
surface : if (param['surface']?) then param['surface'] else undefined
collider : if (param['collider']?) then param['collider'] else undefined
offsetx : if (param['offsetx']?) then param['offsetx'] else 0
offsety : if (param['offsety']?) then param['offsety'] else 0
worldview : if (param['worldview']?) then param['worldview'] else false
touchEnabled : if (param['touchEnabled']?) then param['touchEnabled'] else true
scene = if (param['scene']?) then param['scene'] else GAMESCENE_SUB1
_type = if (param['_type']?) then param['_type'] else SPRITE
initparam._type = _type
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
map = if (param['map']?) then param['map'] else []
if (_type == MAP || _type == EXMAP)
mapwidth = map[0].length * initparam.width
mapheight = map.length * initparam.height
initparam.diffx = Math.floor(mapwidth / 2)
initparam.diffy = Math.floor(mapheight / 2)
else
initparam.diffx = Math.floor(initparam.width / 2)
initparam.diffy = Math.floor(initparam.height / 2)
objnum = __getNullObject()
if (objnum < 0)
return undefined
obj = _objects[objnum]
obj.active = true
if (motionObj?)
obj.motionObj = new motionObj(initparam)
else
obj.motionObj = new _stationary(initparam)
uid = uniqueID()
obj.motionObj._uniqueID = uid
obj.motionObj._scene = scene
obj.motionObj._type = _type
return obj.motionObj
#**********************************************************************
# オブジェクト削除(画面からも消える)
#**********************************************************************
removeObject = (motionObj)->
if (!motionObj?)
return
# 削除しようとしているmotionObjがオブジェクトリストのどこに入っているか探す
ret = false
for object in _objects
if (!object.motionObj?)
continue
if (object.motionObj._uniqueID == motionObj._uniqueID)
ret = true
break
if (ret == false)
return
if (motionObj.collider._uniqueID != motionObj._uniqueID)
removeObject(motionObj.collider)
if (typeof(motionObj.destructor) == 'function')
motionObj.destructor()
if (motionObj.rigid)
object.motionObj.sprite.destroy()
else
switch (motionObj._type)
when CONTROL, SPRITE, LABEL, MAP, EXMAP, PRIMITIVE, COLLADA, COLLIDER2D
_scenes[object.motionObj._scene].removeChild(object.motionObj.sprite)
object.motionObj.sprite = undefined
object.motionObj = undefined
object.active = false
#**********************************************************************
# オブジェクトリストの指定した番号のオブジェクトを返す
#**********************************************************************
getObject = (id)->
ret = undefined
for i in [0..._objects.length]
if (!_objects[i]?)
continue
if (!_objects[i].motionObj?)
continue
if (_objects[i].motionObj._uniqueID == id)
ret = _objects[i].motionObj
break
return ret
#**********************************************************************
# サウンド再生
#**********************************************************************
playSound = (name, vol = 1.0, flag = false)->
soundfile = MEDIALIST[name]
sound = core.assets[soundfile].clone()
if (sound.src?)
sound.play()
sound.volume = vol
sound.src.loop = flag
return sound
#**********************************************************************
# サウンド一時停止
#**********************************************************************
pauseSound = (obj)->
obj.pause()
#**********************************************************************
# サウンド再開
#**********************************************************************
resumeSound = (obj, flag = false)->
obj.play()
#obj.src.loop = flag
obj.loop = flag
#**********************************************************************
# サウンド停止
#**********************************************************************
stopSound = (obj)->
obj.stop()
#**********************************************************************
# サウンド音量設定
#**********************************************************************
setSoundLoudness = (obj, num)->
obj.volume = num
#**********************************************************************
# サウンド再生位置(時間)取得
#**********************************************************************
getSoundCurrenttime = (obj)->
return obj.currenttime
#**********************************************************************
# サウンド再生位置(時間)設定
#**********************************************************************
setSoundCurrenttime = (obj, num)->
obj.currenttime = num
#**********************************************************************
# ゲーム一時停止
#**********************************************************************
pauseGame =->
ACTIVATE = false
core.pause()
#**********************************************************************
# ゲーム再開
#**********************************************************************
resumeGame =->
ACTIVATE = true
core.resume()
#**********************************************************************
# ワールドビューの設定
#**********************************************************************
setWorldView = (cx, cy)->
if (!cx?)
cx = SCREEN_WIDTH / 2
if (!cy?)
cy = SCREEN_HEIGHT / 2
_WORLDVIEW =
centerx: cx
centery: cy
#**********************************************************************
# バーチャルゲームパッド
#**********************************************************************
createVirtualGamepad = (param)->
if (param?)
scale = if (param.scale?) then param.scale else 1
x = if (param.x?) then param.x else (100 / 2) * scale
y = if (param.y?) then param.y else SCREEN_HEIGHT - ((100 / 2) * scale)
visible = if (param.visible?) then param.visible else true
kind = if (param.kind?) then param.kind else 0
analog = if (param.analog?) then param.analog else false
button = if (param.button?) then param.button else 0
buttonscale = if (param.buttonscale?) then param.buttonscale else 1
image = if (param.image?) then param.image else undefined
coord = if (param.coord?) then param.coord else []
else
param = []
scale = param.scale = 1.0
x = param.x = (100 / 2) * scale
y = param.y = SCREEN_HEIGHT - ((100 / 2) * scale)
visible = param.visible = true
kind = param.kind = 0
analog = param.analog = false
button = param.button = 0
image = param.image = undefined
buttonscale = param.buttonscale = 1
coord = param.coord = []
if (button > 6)
button = param.button = 6
if (!_VGAMEPADCONTROL?)
_VGAMEPADCONTROL = addObject
x: x
y: y
type: CONTROL
motionObj: _vgamepadcontrol
_VGAMEPADCONTROL.createGamePad(param)
#**********************************************************************
# バーチャルゲームパッドの表示制御
#**********************************************************************
dispVirtualGamepad = (flag)->
_VGAMEPADCONTROL.setVisible(flag) if (_VGAMEPADCONTROL?)
#**********************************************************************
# 標準ブラウザは非推奨というダイアログ表示
#**********************************************************************
dispDefaultBrowserCheck = (func)->
if (_defaultbrowser)
cautionscale = SCREEN_WIDTH / 320
caution = addObject
image: '_notice'
x: SCREEN_WIDTH / 2
y: 200
width: 300
height: 140
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton = addObject
image: '_execbutton'
x: SCREEN_WIDTH / 2
y: 320
width: 80
height: 32
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton.sprite.ontouchstart = (e)->
removeObject(caution)
removeObject(okbutton)
func()
else
func()
#**********************************************************************
#**********************************************************************
#**********************************************************************
# 以下は内部使用ライブラリ関数
#**********************************************************************
#**********************************************************************
#**********************************************************************
#**********************************************************************
# オブジェクトリストの中で未使用のものの配列番号を返す。
# 無かった場合は-1を返す
#**********************************************************************
__getNullObject = ->
ret = -1
for i in [0..._objects.length]
if (_objects[i].active == false)
ret = i
break
return ret
| true | #******************************************************************************
# enforce game engine(enchant)
#
# 2014.04.04 ver2.0
#
# Coded by PI:NAME:<NAME>END_PI
#******************************************************************************
#******************************************************************************
# 初期化処理
#******************************************************************************
# 定数定義
# 色定義
WHITE = 0
BLACK = 1
# オブジェクトの種類
CONTROL = 0
SPRITE = 1
LABEL = 2
SURFACE = 3
PRIMITIVE = 4
COLLADA = 5
MAP = 6
EXMAP = 7
COLLIDER2D = 8
# 物理スプライトの種類
DYNAMIC_BOX = 0
DYNAMIC_CIRCLE = 1
STATIC_BOX = 2
STATIC_CIRCLE = 3
# Easingの種類(kind)
LINEAR = 0
SWING = 1
BACK = 2
BOUNCE = 3
CIRCLE = 4
CUBIC = 5
ELASTIC = 6
EXPO = 7
QUAD = 8
QUART = 9
QUINT = 10
SINE = 11
# Easingの動き(move)
EASEINOUT = 0
EASEIN = 1
EASEOUT = 2
NONE = 3
# Easingの配列
EASINGVALUE = []
# WebGLのプリミティブの種類
BOX = 0
CUBE = 1
SPHERE = 2
CYLINDER = 3
TORUS = 4
PLANE = 5
# Sceneの種類
BGSCENE = 0
BGSCENE_SUB1 = 1
BGSCENE_SUB2 = 2
GAMESCENE = 3
GAMESCENE_SUB1 = 4
GAMESCENE_SUB2 = 5
TOPSCENE = 6
WEBGLSCENE = 7
_SYSTEMSCENE = 8
DEBUGSCENE = 9
MAXSCENE = (if (DEBUG) then DEBUGSCENE else _SYSTEMSCENE)
# ワールドビュー
_WORLDVIEW =
centerx: SCREEN_WIDTH / 2
centery: SCREEN_HEIGHT / 2
# 数学式
RAD = (Math.PI / 180.0)
DEG = (180.0 / Math.PI)
# グローバル初期化
GLOBAL = []
# サウンドプリロード用
SOUNDARR = []
# アスペクト比
ASPECT = 0.0
# ゲームパッド情報格納変数
HORIZONTAL = 0
VERTICAL = 1
_GAMEPADSINFO = []
PADBUTTONS = []
PADBUTTONS[0] = [false, false]
PADAXES = []
PADAXES[0] = [0, 0]
PADINFO = []
ANALOGSTICK = []
ANALOGSTICK[0] = [[0, 0], [0, 0]]
_VGAMEPADCONTROL = undefined
# Frame Per Seconds
if (!FPS?)
FPS = 60
# box2dの重力値
if (!GRAVITY_X?)
GRAVITY_X = 0.0
if (!GRAVITY_Y?)
GRAVITY_Y = 0.0
# センサー系
MOTION_ACCEL = [x:0, y:0, z:0]
MOTION_GRAVITY = [x:0, y:0, z:0]
MOTION_ROTATE = [alpha:0, beta:0, gamma:0]
# 標準ブラウザ
if (_useragent.match(/^.*android.*?mobile safari.*$/i) != null && _useragent.match(/^.*\) chrome.*/i) == null)
_defaultbrowser = true
else
_defaultbrowser = false
# ブラウザ大分類
if (_useragent.match(/.* firefox\/.*/))
_browserMajorClass = "firefox"
else if (_useragent.match(/.*version\/.* safari\/.*/))
_browserMajorClass = "safari"
else if (_useragent.match(/.*chrome\/.* safari\/.*/))
_browserMajorClass = "chrome"
else
_browserMajorClass = "unknown"
# ゲーム起動時からの経過時間(秒)
LAPSEDTIME = 0.0
# ゲーム起動時のUNIXTIME
BEGINNINGTIME = undefined
# フレームレート調整用
__FRAMETIME = 0.0
# 3D系
OCULUS = undefined
RENDERER = undefined
CAMERA = undefined
LIGHT = undefined
# デバイスサイズ
_frame = getBounds()
DEVICE_WIDTH = _frame[0]
DEVICE_HEIGHT = _frame[1]
if (!SCREEN_WIDTH? && !SCREEN_HEIGHT?)
SCREEN_WIDTH = DEVICE_WIDTH
SCREEN_HEIGHT = DEVICE_HEIGHT
# 動作状況
ACTIVATE = true
# オブジェクトが入っている配列
_objects = []
# Scene格納用配列
_scenes = []
# 起動時に生成されるスタートオブジェクト
_main = null
# デバッグ用LABEL
_DEBUGLABEL = undefined
_FPSGAUGE = undefined
__fpsgaugeunit = 0
__fpscounter = 0.0
__limittimefps = 0.0
# enchantのcoreオブジェクト
core = undefined
# box2dのworldオブジェクト
box2dworld = undefined
# 3Dのscene
rootScene3d = undefined
# enchantのrootScene
rootScene = undefined
# アニメーション管理
__requestID = ( ->
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
(callback)->
window.setTimeout(callback, 1000 / 60)
)()
#******************************************************************************
# 起動時の処理
#******************************************************************************
# enchantのオマジナイ
enchant()
enchant.ENV.MOUSE_ENABLED = false
enchant.ENV.SOUND_ENABLED_ON_MOBILE_SAFARI = false
# ゲーム起動時の処理
#window.addEventListener 'load', (e)->
window.onload = ->
window.removeEventListener('load', arguments.callee, false)
# ゲーム起動時間
BEGINNINGTIME = __getTime()
# アスペクト比
ASPECT = (SCREEN_WIDTH / SCREEN_HEIGHT).toFixed(2)
# enchant初期化
core = new Core(SCREEN_WIDTH, SCREEN_HEIGHT)
# FPS設定
core.fps = FPS
# Easing定義
EASINGVALUE[LINEAR] = [enchant.Easing.LINEAR]
EASINGVALUE[SWING] = [enchant.Easing.SWING]
EASINGVALUE[BACK] = [enchant.Easing.BACK_EASEINOUT, enchant.Easing.BACK_EASEIN, enchant.Easing.BACK_EASEOUT]
EASINGVALUE[BOUNCE] = [enchant.Easing.BOUNCE_EASEINOUT, enchant.Easing.BOUNCE_EASEIN, enchant.Easing.BOUNCE_EASEOUT]
EASINGVALUE[CIRCLE] = [enchant.Easing.CIRCLE_EASEINOUT, enchant.Easing.CIRCLE_EASEIN, enchant.Easing.CIRCLE_EASEOUT]
EASINGVALUE[CUBIC] = [enchant.Easing.CUBIC_EASEINOUT, enchant.Easing.CUBIC_EASEIN, enchant.Easing.CUBIC_EASEOUT]
EASINGVALUE[ELASTIC] = [enchant.Easing.ELASTIC_EASEINOUT, enchant.Easing.ELASTIC_EASEIN, enchant.Easing.ELASTIC_EASEOUT]
EASINGVALUE[EXPO] = [enchant.Easing.EXPO_EASEINOUT, enchant.Easing.EXPO_EASEIN, enchant.Easing.EXPO_EASEOUT]
EASINGVALUE[QUAD] = [enchant.Easing.QUAD_EASEINOUT, enchant.Easing.QUAD_EASEIN, enchant.Easing.QUAD_EASEOUT]
EASINGVALUE[QUART] = [enchant.Easing.QUART_EASEINOUT, enchant.Easing.QUART_EASEIN, enchant.Easing.QUART_EASEOUT]
EASINGVALUE[QUINT] = [enchant.Easing.QUINT_EASEINOUT, enchant.Easing.QUINT_EASEIN, enchant.Easing.QUINT_EASEOUT]
EASINGVALUE[SINE] = [enchant.Easing.SINE_EASEINOUT, enchant.Easing.SINE_EASEIN, enchant.Easing.SINE_EASEOUT]
# ボタンの定義
core.keybind( 90, 'a' )
core.keybind( 88, 'b' )
core.keybind( 67, 'c' )
core.keybind( 86, 'd' )
core.keybind( 66, 'e' )
core.keybind( 78, 'f' )
core.keybind( 77, 'g' )
core.keybind( 188, 'h' )
core.keybind( 32, 'space' )
# メディアファイルのプリロード
if (MEDIALIST?)
MEDIALIST['_ascii_w'] = 'lib/ascii_w.png'
MEDIALIST['_ascii_b'] = 'lib/ascii_b.png'
MEDIALIST['_fpsgauge'] = 'lib/fpsgauge.png'
MEDIALIST['_notice'] = 'lib/notice.png'
MEDIALIST['_execbutton'] = 'lib/execbutton.png'
MEDIALIST['_pad_w'] = 'lib/pad_w.png'
MEDIALIST['_pad_b'] = 'lib/pad_b.png'
MEDIALIST['_apad_w'] = 'lib/apad_w.png'
MEDIALIST['_apad_b'] = 'lib/apad_b.png'
MEDIALIST['_apad2_w'] = 'lib/apad2_w.png'
MEDIALIST['_apad2_b'] = 'lib/apad2_b.png'
MEDIALIST['_button_w'] = 'lib/button_w.png'
MEDIALIST['_button_b'] = 'lib/button_b.png'
mediaarr = []
num = 0
for obj of MEDIALIST
mediaarr[num++] = MEDIALIST[obj]
core.preload(mediaarr)
# rootSceneをグローバルに保存
rootScene = core.rootScene
# モーションセンサーのイベント登録
window.addEventListener 'devicemotion', (e)->
MOTION_ACCEL = e.acceleration
MOTION_GRAVITY = e.accelerationIncludingGravity
window.addEventListener 'deviceorientation', (e)->
MOTION_ROTATE.alpha = e.alpha
MOTION_ROTATE.beta = e.beta
MOTION_ROTATE.gamma = e.gamma
# box2d初期化
box2dworld = new PhysicsWorld(GRAVITY_X, GRAVITY_Y)
# シーングループを生成
for i in [0..MAXSCENE]
scene = new Group()
scene.backgroundColor = "black"
_scenes[i] = scene
rootScene.addChild(scene)
if (WEBGL != undefined && WEBGL && isWebGL())
# 3Dシーンを生成
rootScene3d = new Scene3D()
_scenes[WEBGLSCENE] = rootScene3d
# スポットライト生成
#DLIGHT = new DirectionalLight()
#DLIGHT.color = [1.0, 1.0, 1.0]
#dlight.directionX = 0
#dlight.directionY = 100
#dlight.directionZ = 0
rootScene3d.setDirectionalLight(DLIGHT)
# 環境光ライト生成
#ALIGHT = new AmbientLight()
#ALIGHT.color = [1.0, 1.0, 1.0]
#alight.directionX = 0
#alight.directionY = 100
rootScene3d.setAmbientLight(ALIGHT)
# カメラ生成
CAMERA = new Camera3D()
CAMERA.x = 0
CAMERA.y = 0
CAMERA.z = 160
CAMERA.centerX = 0
CAMERA.centerY = 0
CAMERA.centerZ = 0
rootScene3d.setCamera(CAMERA)
else
rootScene.backgroundColor = BGCOLOR
WEBGL = false
#if (DEBUG == true)
# core.debug()
#else
# core.start()
core.start()
#******************************************************************************
# 起動時の処理
#******************************************************************************
core.onload = ->
# ゲーム用オブジェクトを指定された数だけ確保
for i in [0...OBJECTNUM]
_objects[i] = new _originObject()
_main = new enforceMain()
if (DEBUG)
_DEBUGLABEL = new Label()
_DEBUGLABEL.x = 0
_DEBUGLABEL.y = 0
_DEBUGLABEL.width = SCREEN_WIDTH
_DEBUGLABEL.color = "white"
_DEBUGLABEL.font = "32px 'Arial'"
_scenes[DEBUGSCENE].addChild(_DEBUGLABEL)
_FPSGAUGE = new Sprite()
_FPSGAUGE.x = SCREEN_WIDTH - 16
_FPSGAUGE.y = 0
_FPSGAUGE.width = 16
_FPSGAUGE.height = 1
_FPSGAUGE.scaleY = 1.0
_FPSGAUGE.opacity = 0.5
_FPSGAUGE.image = core.assets[MEDIALIST['_fpsgauge']]
_FPSGAUGE.frame = 0
_scenes[DEBUGSCENE].addChild(_FPSGAUGE)
__fpscounter = 0
__limittimefps = 0.0
# フレーム処理(enchant任せ)
rootScene.addEventListener 'enterframe', (e)->
# 経過時間を計算
LAPSEDTIME = parseFloat((__getTime() - parseFloat(BEGINNINGTIME.toFixed(2))) / 1000.0)
# FPS表示(デバッグモード時のみ)
if (DEBUG)
__fpscounter++
if (__limittimefps < parseFloat(LAPSEDTIME))
__limittimefps = LAPSEDTIME + 1.0
scale = parseFloat(((__fpscounter / FPS) * SCREEN_HEIGHT).toFixed(2))
_FPSGAUGE.height = scale
__fpscounter = 0
# ジョイパッド処理
if (typeof gamepadProcedure == 'function')
_GAMEPADSINFO = gamepadProcedure()
for num in [0..._GAMEPADSINFO.length]
if (!_GAMEPADSINFO[num]?)
continue
padobj = _GAMEPADSINFO[num]
PADBUTTONS[num] = padobj.padbuttons
PADAXES[num] = padobj.padaxes
ANALOGSTICK[num] = padobj.analogstick
PADINFO[num] = []
PADINFO[num].id = padobj.id
if (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.analog?)
vgpx1 = parseFloat(_VGAMEPADCONTROL.input.analog[HORIZONTAL])
vgpy1 = parseFloat(_VGAMEPADCONTROL.input.analog[VERTICAL])
else
vgpx1 = 0
vgpy1 = 0
if (_GAMEPADSINFO? && _GAMEPADSINFO[0]?)
vgpx2 = _GAMEPADSINFO[0].analogstick[0][HORIZONTAL]
vgpy2 = _GAMEPADSINFO[0].analogstick[0][VERTICAL]
else
vgpx2 = 0
vgpy2 = 0
ANALOGSTICK[0][0][HORIZONTAL] = parseFloat(vgpx1 + vgpx2)
ANALOGSTICK[0][0][VERTICAL] = parseFloat(vgpy1 + vgpy2)
if (core.input.a || core.input.space || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[0]? && _VGAMEPADCONTROL.input.buttons[0]))
PADBUTTONS[0][0] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][0] = false
if (core.input.b || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[1]? && _VGAMEPADCONTROL.input.buttons[1]))
PADBUTTONS[0][1] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][1] = false
if (core.input.c || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[2]? && _VGAMEPADCONTROL.input.buttons[2]))
PADBUTTONS[0][2] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][2] = false
if (core.input.d || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[3]? && _VGAMEPADCONTROL.input.buttons[3]))
PADBUTTONS[0][3] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][3] = false
if (core.input.e || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[4]? && _VGAMEPADCONTROL.input.buttons[4]))
PADBUTTONS[0][4] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][4] = false
if (core.input.f || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[5]? && _VGAMEPADCONTROL.input.buttons[5]))
PADBUTTONS[0][5] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][5] = false
if (core.input.g || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[6]? && _VGAMEPADCONTROL.input.buttons[6]))
PADBUTTONS[0][6] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][6] = false
if (core.input.h || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.buttons[7]? && _VGAMEPADCONTROL.input.buttons[7]))
PADBUTTONS[0][7] = true
else if (!_GAMEPADSINFO[0]?)
PADBUTTONS[0][7] = false
if (core.input.left || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.left))
PADAXES[0][HORIZONTAL] = -1
else if (core.input.right || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.right))
PADAXES[0][HORIZONTAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][HORIZONTAL] = 0
if (core.input.up || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.up))
PADAXES[0][VERTICAL] = -1
else if (core.input.down || (_VGAMEPADCONTROL? && _VGAMEPADCONTROL.input.axes.down))
PADAXES[0][VERTICAL] = 1
else if (!_GAMEPADSINFO[0]?)
PADAXES[0][VERTICAL] = 0
if (GAMEPADMIX? && GAMEPADMIX)
mx = (ANALOGSTICK[0][0][HORIZONTAL] + PADAXES[0][HORIZONTAL])
mx = 1 if (mx > 1)
mx = -1 if (mx < -1)
my = (ANALOGSTICK[0][0][VERTICAL] + PADAXES[0][VERTICAL])
my = 1 if (my > 1)
my = -1 if (my < -1)
ANALOGSTICK[0][0][HORIZONTAL] = mx
ANALOGSTICK[0][0][VERTICAL] = my
# box2dの時間を進める
box2dworld.step(core.fps)
# 全てのオブジェクトの「behavior」を呼ぶ
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
obj.motionObj.behavior()
# 更新した座標値をスプライトに適用する
for obj in _objects
if (obj.active == true && obj.motionObj != undefined && typeof(obj.motionObj.behavior) == 'function')
wx = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centerx - (SCREEN_WIDTH / 2)) else 0
wy = if (obj.motionObj.worldview? && obj.motionObj.worldview) then (_WORLDVIEW.centery - (SCREEN_HEIGHT / 2)) else 0
switch (obj.motionObj._type)
when CONTROL
continue
when PRIMITIVE, COLLADA
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y)
obj.motionObj.sprite.z = Math.floor(obj.motionObj.z)
when SPRITE, LABEL, SURFACE
if (obj.motionObj.rigid)
if (obj.motionObj._xback != obj.motionObj.x)
obj.motionObj.sprite.x = obj.motionObj.x - obj.motionObj._diffx - wx
if (obj.motionObj._yback != obj.motionObj.y)
obj.motionObj.sprite.y = obj.motionObj.y - obj.motionObj._diffy - wy
else
rot = parseFloat(obj.motionObj.rotation)
rot += parseFloat(obj.motionObj.rotate)
if (rot >= 360.0)
rot = rot % 360
obj.motionObj.rotation = rot
obj.motionObj.sprite.rotation = parseInt(rot)
# _reversePosFlagは、Timeline適用中はここの処理内では座標操作はせず、スプライトの座標をオブジェクトの座標に代入している
if (obj.motionObj._type == LABEL)
diffx = 0
diffy = 0
else
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
if (obj.motionObj._reversePosFlag)
obj.motionObj.x = obj.motionObj.sprite.x + diffx
obj.motionObj.y = obj.motionObj.sprite.y + diffy
else
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
if (obj.motionObj._uniqueID != obj.motionObj.collider._uniqueID)
obj.motionObj.collider.sprite.x = obj.motionObj.collider.x = obj.motionObj.sprite.x + diffx - obj.motionObj.collider._diffx + obj.motionObj.collider._offsetx
obj.motionObj.collider.sprite.y = obj.motionObj.collider.y = obj.motionObj.sprite.y + diffy - obj.motionObj.collider._diffy + obj.motionObj.collider._offsety
when MAP, EXMAP
diffx = obj.motionObj._diffx
diffy = obj.motionObj._diffy
obj.motionObj.sprite.x = Math.floor(obj.motionObj.x - diffx - wx)
obj.motionObj.sprite.y = Math.floor(obj.motionObj.y - diffy - wy)
#, false
#******************************************************************************
# デバッグ用関数
#******************************************************************************
debugwrite = (param)->
if (DEBUG)
if (param.clear)
labeltext = if (param.labeltext?) then param.labeltext else ""
else
labeltext = _DEBUGLABEL.text += if (param.labeltext?) then param.labeltext else ""
fontsize = if (param.fontsize?) then param.fontsize else 32
fontcolor = if (param.color?) then param.color else "white"
_DEBUGLABEL.font = fontsize+"px 'Arial'"
_DEBUGLABEL.text = labeltext
_DEBUGLABEL.color = fontcolor
debugclear =->
if (DEBUG)
_DEBUGLABEL.text = ""
#******************************************************************************
# 2D/3D共用オブジェクト生成メソッド
#******************************************************************************
addObject = (param, parent = undefined)->
# パラメーター
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
_type = if (param['type']?) then param['type'] else SPRITE
x = if (param['x']?) then param['x'] else 0
y = if (param['y']?) then param['y'] else 0
z = if (param['z']?) then param['z'] else 0
xs = if (param['xs']?) then param['xs'] else 0.0
ys = if (param['ys']?) then param['ys'] else 0.0
zs = if (param['zs']?) then param['zs'] else 0.0
gravity = if (param['gravity']?) then param['gravity'] else 0.0
image = if (param['image']?) then param['image'] else undefined
model = if (param['model']?) then param['model'] else undefined
width = if (param['width']?) then param['width'] else 1
height = if (param['height']?) then param['height'] else 1
depth = if (param['depth']?) then param['depth'] else 1.0
opacity = if (param['opacity']?) then param['opacity'] else 1.0
animlist = if (param['animlist']?) then param['animlist'] else undefined
animnum = if (param['animnum']?) then param['animnum'] else 0
visible = if (param['visible']?) then param['visible'] else true
scene = if (param['scene']?) then param['scene'] else -1
rigid = if (param['rigid']?) then param['rigid'] else false
density = if (param['density']?) then param['density'] else 1.0
friction = if (param['friction']?) then param['friction'] else 1.0
restitution = if (param['restitution']?) then param['restitution'] else 1.0
radius = if (param['radius']?) then param['radius'] else undefined
radius2 = if (param['radius2']?) then param['radius2'] else 1.0
size = if (param['size']?) then param['size'] else 1.0
scaleX = if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY = if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ = if (param['scaleZ']?) then param['scaleZ'] else 1.0
rotation = if (param['rotation']?) then param['rotation'] else 0.0
rotate = if (param['rotate']?) then param['rotate'] else 0.0
texture = if (param['texture']?) then param['texture'] else undefined
fontsize = if (param['fontsize']?) then param['fontsize'] else '16'
color = if (param['color']?) then param['color'] else 'white'
labeltext = if (param['labeltext']?) then param['labeltext'].replace(/\n/ig, "<br>") else 'text'
textalign = if (param['textalign']?) then param['textalign'] else 'left'
active = if (param['active']?) then param['active'] else true
kind = if (param['kind']?) then param['kind'] else DYNAMIC_BOX
map = if (param['map']?) then param['map'] else undefined
map2 = if (param['map2']?) then param['map2'] else undefined
mapcollision = if (param['mapcollision']?) then param['mapcollision'] else undefined
collider = if (param['collider']?) then param['collider'] else undefined
offsetx = if (param['offsetx']?) then param['offsetx'] else 0
offsety = if (param['offsety']?) then param['offsety'] else 0
bgcolor = if (param['bgcolor']?) then param['bgcolor'] else 'transparent'
worldview = if (param['worldview']?) then param['worldview'] else false
touchEnabled = if (param['touchEnabled']?) then param['touchEnabled'] else true
tmp = __getNullObject()
if (tmp == -1)
return undefined
if (motionObj == null)
motionObj = undefined
retObject = undefined
# スプライトを生成
switch (_type)
#*****************************************************************
# CONTROL、SPRITE
#*****************************************************************
when CONTROL, SPRITE, COLLIDER2D
motionsprite = undefined
if (_type == SPRITE)
if (rigid)
if (!radius?)
radius = width
switch (kind)
when DYNAMIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when DYNAMIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.DYNAMIC_SPRITE, density, friction, restitution, true)
when STATIC_BOX
motionsprite = new PhyBoxSprite(width, height, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
when STATIC_CIRCLE
motionsprite = new PhyCircleSprite(radius, enchant.box2d.STATIC_SPRITE, density, friction, restitution, true)
if (!motionsprite?)
motionsprite = new Sprite()
if (_type == COLLIDER2D)
scene = GAMESCENE_SUB2
if (scene < 0)
scene = GAMESCENE_SUB1
# アニメーション設定
if (MEDIALIST[image]?)
if (animlist?)
animtmp = animlist[animnum]
motionsprite.frame = animtmp[1][0]
else
motionsprite.frame = 0
motionsprite.backgroundColor = "transparent"
motionsprite.x = x - Math.floor(width / 2)
motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.opacity = if (_type == COLLIDER2D) then 0.8 else opacity
motionsprite.rotation = rotation
motionsprite.rotate = rotate
motionsprite.scaleX = scaleX
motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
else
motionsprite.visible = false
motionsprite.width = 0
motionsprite.height = 0
motionsprite.image = ""
# スプライトを表示
_scenes[scene].addChild(motionsprite)
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
gravity: gravity
width: width
height: height
animlist: animlist
animnum: animnum
opacity: opacity
scene: scene
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
rotation: rotation
rotate: rotate
parent: parent
radius: radius
density: density
friction: friction
restitution: restitution
active: active
rigid: rigid
kind: kind
collider: collider
offsetx: offsetx
offsety: offsety
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# LABEL
#*****************************************************************
when LABEL
if (scene < 0)
scene = GAMESCENE_SUB1
if (width == 0)
width = 120
if (height == 0)
height = 64
# ラベルを生成
motionsprite = new Label(labeltext)
# ラベルを表示
_scenes[scene].addChild(motionsprite)
# 値を代入
#motionsprite.backgroundColor = "transparent"
#motionsprite.x = x - Math.floor(width / 2)
#motionsprite.y = y - Math.floor(height / 2) - Math.floor(z)
motionsprite.x = x
motionsprite.y = y - Math.floor(z)
motionsprite.opacity = opacity
#motionsprite.rotation = rotation
#motionsprite.rotate = rotate
#motionsprite.scaleX = scaleX
#motionsprite.scaleY = scaleY
motionsprite.visible = visible
motionsprite.width = width
motionsprite.height = height
motionsprite.color = color
motionsprite.text = ""
motionsprite.textAlign = textalign
#motionsprite.font = fontsize+"px 'Arial'"
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
width: width
height: height
opacity: opacity
scene: scene
_type: _type
active: active
motionsprite: motionsprite
motionObj: motionObj
fontsize: fontsize
color: color
labeltext: labeltext
textalign: textalign
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# プリミティブ
#*****************************************************************
when PRIMITIVE
if (!radius?)
radius = 1.0
switch (model)
when BOX
motionsprite = new Box(width, height, depth)
when CUBE
motionsprite = new Cube(size)
when SPHERE
motionsprite = new Sphere(size)
when CYLINDER
motionsprite = new Cylinder(radius, height)
when TORUS
motionsprite = new Torus(radius, radius2)
when PLANE
motionsprite = new Plane(size)
else
return undefined
if (texture?)
imagefile = MEDIALIST[texture]
tx = new Texture(imagefile)
motionsprite.mesh.texture = tx
# 動きを定義したオブジェクトを生成する
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
active: active
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
if (visible)
rootScene3d.addChild(motionsprite)
return retObject
#*****************************************************************
# COLLADAモデル
#*****************************************************************
when COLLADA
if (!radius?)
radius = 1.0
if (MEDIALIST[model]?)
motionsprite = new Sprite3D()
motionsprite.set(core.assets[MEDIALIST[model]].clone())
else
return undefined
# 動きを定義したオブジェクトを生成する
if (visible)
rootScene3d.addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
z: z
xs: xs
ys: ys
zs: zs
visible: visible
scaleX: scaleX
scaleY: scaleY
scaleZ: scaleZ
radius: radius
radius2: radius2
active: active
size: size
gravity: gravity
width: width
height: height
depth: depth
animlist: animlist
animnum: animnum
opacity: opacity
scene: WEBGLSCENE
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
#*****************************************************************
# Surface
#*****************************************************************
when SURFACE
if (scene < 0)
scene = GAMESCENE_SUB1
motionsprite = new Sprite(SCREEN_WIDTH, SCREEN_HEIGHT)
surface = new Surface(SCREEN_WIDTH, SCREEN_HEIGHT)
motionsprite.image = surface
context = surface.context
###
# パスの描画の初期化
context.beginPath()
# 描画開始位置の移動
context.moveTo(10, 10)
# 指定座標まで直線を描画
context.lineTo(100, 100)
# 線の色を指定 (指定しないと黒)
context.strokeStyle = "rgba(0, 255, 255, 0.5)";
# 描画を行う
context.stroke()
###
retObject = @__setMotionObj
width: SCREEN_WIDTH
height: SCREEN_HEIGHT
opacity: opacity
scene: scene
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
context: context
active: active
surface: surface
worldview: worldview
touchEnabled: touchEnabled
_scenes[scene].addChild(motionsprite)
return retObject
#*****************************************************************
# Mapオブジェクト
#*****************************************************************
when MAP, EXMAP
if (!map? || image == "")
JSLog("parameter not enough.")
else
if (scene < 0)
scene = BGSCENE_SUB1
if (_type == MAP)
motionsprite = new Map(width, height)
motionsprite.loadData(map)
else
motionsprite = new ExMap(width, height)
motionsprite.loadData(map, map2)
img = MEDIALIST[image]
motionsprite.image = core.assets[img]
if (mapcollision?)
motionsprite.collisionData = mapcollision
_scenes[scene].addChild(motionsprite)
retObject = @__setMotionObj
x: x
y: y
xs: xs
ys: ys
map: map
visible: visible
width: width
height: height
opacity: opacity
scene: scene
active: active
image: image
_type: _type
motionsprite: motionsprite
motionObj: motionObj
parent: parent
worldview: worldview
touchEnabled: touchEnabled
return retObject
__setMotionObj = (param)->
# 動きを定義したオブジェクトを生成する
initparam =
x : if (param['x']?) then param['x'] else 0
y : if (param['y']?) then param['y'] else 0
z : if (param['z']?) then param['z'] else 0
xs : if (param['xs']?) then param['xs'] else 0
ys : if (param['ys']?) then param['ys'] else 0
zs : if (param['zs']?) then param['zs'] else 0
visible : if (param['visible']?) then param['visible'] else true
scaleX : if (param['scaleX']?) then param['scaleX'] else 1.0
scaleY : if (param['scaleY']?) then param['scaleY'] else 1.0
scaleZ : if (param['scaleZ']?) then param['scaleZ'] else 1.0
radius : if (param['radius']?) then param['radius'] else 0.0
radius2 : if (param['radius2']?) then param['radius2'] else 0.0
size : if (param['size']?) then param['size'] else 1.0
gravity : if (param['gravity']?) then param['gravity'] else 0
intersectFlag : if (param['intersectFlag']?) then param['intersectFlag'] else true
width : if (param['width']?) then param['width'] else SCREEN_WIDTH
height : if (param['height']?) then param['height'] else SCREEN_HEIGHT
animlist : if (param['animlist']?) then param['animlist'] else undefined
animnum : if (param['animnum']?) then param['animnum'] else 0
image : if (param['image']?) then param['image'] else undefined
visible : if (param['visible']?) then param['visible'] else true
opacity : if (param['opacity']?) then param['opacity'] else 0
rotation : if (param['rotation']?) then param['rotation'] else 0.0
rotate : if (param['rotate']?) then param['rotate'] else 0.0
motionsprite : if (param['motionsprite']?) then param['motionsprite'] else 0
fontsize : if (param['fontsize']?) then param['fontsize'] else '16'
color : if (param['color']?) then param['color'] else 'white'
labeltext : if (param['labeltext']?) then param['labeltext'] else 'text'
textalign : if (param['textalign']?) then param['textalign'] else 'left'
parent : if (param['parent']?) then param['parent'] else undefined
density : if (param['density']?) then param['density'] else 1.0
friction : if (param['friction']?) then param['friction'] else 0.5
restitution : if (param['restitution']?) then param['restitution'] else 0.1
active : if (param['active']?) then param['active'] else true
kind : if (param['kind']?) then param['kind'] else undefined
rigid : if (param['rigid']?) then param['rigid'] else undefined
context : if (param['context']?) then param['context'] else undefined
surface : if (param['surface']?) then param['surface'] else undefined
collider : if (param['collider']?) then param['collider'] else undefined
offsetx : if (param['offsetx']?) then param['offsetx'] else 0
offsety : if (param['offsety']?) then param['offsety'] else 0
worldview : if (param['worldview']?) then param['worldview'] else false
touchEnabled : if (param['touchEnabled']?) then param['touchEnabled'] else true
scene = if (param['scene']?) then param['scene'] else GAMESCENE_SUB1
_type = if (param['_type']?) then param['_type'] else SPRITE
initparam._type = _type
motionObj = if (param['motionObj']?) then param['motionObj'] else undefined
map = if (param['map']?) then param['map'] else []
if (_type == MAP || _type == EXMAP)
mapwidth = map[0].length * initparam.width
mapheight = map.length * initparam.height
initparam.diffx = Math.floor(mapwidth / 2)
initparam.diffy = Math.floor(mapheight / 2)
else
initparam.diffx = Math.floor(initparam.width / 2)
initparam.diffy = Math.floor(initparam.height / 2)
objnum = __getNullObject()
if (objnum < 0)
return undefined
obj = _objects[objnum]
obj.active = true
if (motionObj?)
obj.motionObj = new motionObj(initparam)
else
obj.motionObj = new _stationary(initparam)
uid = uniqueID()
obj.motionObj._uniqueID = uid
obj.motionObj._scene = scene
obj.motionObj._type = _type
return obj.motionObj
#**********************************************************************
# オブジェクト削除(画面からも消える)
#**********************************************************************
removeObject = (motionObj)->
if (!motionObj?)
return
# 削除しようとしているmotionObjがオブジェクトリストのどこに入っているか探す
ret = false
for object in _objects
if (!object.motionObj?)
continue
if (object.motionObj._uniqueID == motionObj._uniqueID)
ret = true
break
if (ret == false)
return
if (motionObj.collider._uniqueID != motionObj._uniqueID)
removeObject(motionObj.collider)
if (typeof(motionObj.destructor) == 'function')
motionObj.destructor()
if (motionObj.rigid)
object.motionObj.sprite.destroy()
else
switch (motionObj._type)
when CONTROL, SPRITE, LABEL, MAP, EXMAP, PRIMITIVE, COLLADA, COLLIDER2D
_scenes[object.motionObj._scene].removeChild(object.motionObj.sprite)
object.motionObj.sprite = undefined
object.motionObj = undefined
object.active = false
#**********************************************************************
# オブジェクトリストの指定した番号のオブジェクトを返す
#**********************************************************************
getObject = (id)->
ret = undefined
for i in [0..._objects.length]
if (!_objects[i]?)
continue
if (!_objects[i].motionObj?)
continue
if (_objects[i].motionObj._uniqueID == id)
ret = _objects[i].motionObj
break
return ret
#**********************************************************************
# サウンド再生
#**********************************************************************
playSound = (name, vol = 1.0, flag = false)->
soundfile = MEDIALIST[name]
sound = core.assets[soundfile].clone()
if (sound.src?)
sound.play()
sound.volume = vol
sound.src.loop = flag
return sound
#**********************************************************************
# サウンド一時停止
#**********************************************************************
pauseSound = (obj)->
obj.pause()
#**********************************************************************
# サウンド再開
#**********************************************************************
resumeSound = (obj, flag = false)->
obj.play()
#obj.src.loop = flag
obj.loop = flag
#**********************************************************************
# サウンド停止
#**********************************************************************
stopSound = (obj)->
obj.stop()
#**********************************************************************
# サウンド音量設定
#**********************************************************************
setSoundLoudness = (obj, num)->
obj.volume = num
#**********************************************************************
# サウンド再生位置(時間)取得
#**********************************************************************
getSoundCurrenttime = (obj)->
return obj.currenttime
#**********************************************************************
# サウンド再生位置(時間)設定
#**********************************************************************
setSoundCurrenttime = (obj, num)->
obj.currenttime = num
#**********************************************************************
# ゲーム一時停止
#**********************************************************************
pauseGame =->
ACTIVATE = false
core.pause()
#**********************************************************************
# ゲーム再開
#**********************************************************************
resumeGame =->
ACTIVATE = true
core.resume()
#**********************************************************************
# ワールドビューの設定
#**********************************************************************
setWorldView = (cx, cy)->
if (!cx?)
cx = SCREEN_WIDTH / 2
if (!cy?)
cy = SCREEN_HEIGHT / 2
_WORLDVIEW =
centerx: cx
centery: cy
#**********************************************************************
# バーチャルゲームパッド
#**********************************************************************
createVirtualGamepad = (param)->
if (param?)
scale = if (param.scale?) then param.scale else 1
x = if (param.x?) then param.x else (100 / 2) * scale
y = if (param.y?) then param.y else SCREEN_HEIGHT - ((100 / 2) * scale)
visible = if (param.visible?) then param.visible else true
kind = if (param.kind?) then param.kind else 0
analog = if (param.analog?) then param.analog else false
button = if (param.button?) then param.button else 0
buttonscale = if (param.buttonscale?) then param.buttonscale else 1
image = if (param.image?) then param.image else undefined
coord = if (param.coord?) then param.coord else []
else
param = []
scale = param.scale = 1.0
x = param.x = (100 / 2) * scale
y = param.y = SCREEN_HEIGHT - ((100 / 2) * scale)
visible = param.visible = true
kind = param.kind = 0
analog = param.analog = false
button = param.button = 0
image = param.image = undefined
buttonscale = param.buttonscale = 1
coord = param.coord = []
if (button > 6)
button = param.button = 6
if (!_VGAMEPADCONTROL?)
_VGAMEPADCONTROL = addObject
x: x
y: y
type: CONTROL
motionObj: _vgamepadcontrol
_VGAMEPADCONTROL.createGamePad(param)
#**********************************************************************
# バーチャルゲームパッドの表示制御
#**********************************************************************
dispVirtualGamepad = (flag)->
_VGAMEPADCONTROL.setVisible(flag) if (_VGAMEPADCONTROL?)
#**********************************************************************
# 標準ブラウザは非推奨というダイアログ表示
#**********************************************************************
dispDefaultBrowserCheck = (func)->
if (_defaultbrowser)
cautionscale = SCREEN_WIDTH / 320
caution = addObject
image: '_notice'
x: SCREEN_WIDTH / 2
y: 200
width: 300
height: 140
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton = addObject
image: '_execbutton'
x: SCREEN_WIDTH / 2
y: 320
width: 80
height: 32
animlist: [
[100, [0]]
]
scaleX: cautionscale
scaleY: cautionscale
okbutton.sprite.ontouchstart = (e)->
removeObject(caution)
removeObject(okbutton)
func()
else
func()
#**********************************************************************
#**********************************************************************
#**********************************************************************
# 以下は内部使用ライブラリ関数
#**********************************************************************
#**********************************************************************
#**********************************************************************
#**********************************************************************
# オブジェクトリストの中で未使用のものの配列番号を返す。
# 無かった場合は-1を返す
#**********************************************************************
__getNullObject = ->
ret = -1
for i in [0..._objects.length]
if (_objects[i].active == false)
ret = i
break
return ret
|
[
{
"context": " p = new RootNamespaceProvider([{\n name: 'Myapp'\n folder: 'app'\n }])\n\n expect(p).toBeD",
"end": 192,
"score": 0.6692420244216919,
"start": 187,
"tag": "USERNAME",
"value": "Myapp"
},
{
"context": " p = new RootNamespaceProvider([{\n name:... | spec/root-namespace-provider-spec.coffee | Sighter/extjs4-autocomplete | 0 | RootNamespaceProvider = require('../lib/root-namespace-provider')
describe "RootNamespaceProvider", ->
it "should be createable", ->
p = new RootNamespaceProvider([{
name: 'Myapp'
folder: 'app'
}])
expect(p).toBeDefined()
it "should give the right suggestions", ->
p = new RootNamespaceProvider([{
name: 'Myapp'
folder: 'app'
}])
got = p.getSuggestions('My')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ap')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ex')
expect(got).toEqual([{text: 'Ext'}])
| 201893 | RootNamespaceProvider = require('../lib/root-namespace-provider')
describe "RootNamespaceProvider", ->
it "should be createable", ->
p = new RootNamespaceProvider([{
name: 'Myapp'
folder: 'app'
}])
expect(p).toBeDefined()
it "should give the right suggestions", ->
p = new RootNamespaceProvider([{
name: '<NAME>app'
folder: 'app'
}])
got = p.getSuggestions('My')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ap')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ex')
expect(got).toEqual([{text: 'Ext'}])
| true | RootNamespaceProvider = require('../lib/root-namespace-provider')
describe "RootNamespaceProvider", ->
it "should be createable", ->
p = new RootNamespaceProvider([{
name: 'Myapp'
folder: 'app'
}])
expect(p).toBeDefined()
it "should give the right suggestions", ->
p = new RootNamespaceProvider([{
name: 'PI:NAME:<NAME>END_PIapp'
folder: 'app'
}])
got = p.getSuggestions('My')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ap')
expect(got).toEqual([{text: 'Myapp'}])
got = p.getSuggestions('ex')
expect(got).toEqual([{text: 'Ext'}])
|
[
{
"context": "q) ->\n\tteamcity\n\t\turl: 'http://fb.com',\n\t\temail: 'test@test.com',\n\t\tpassword: '1',\n\t\trequest: req\n\ncreate2 = (req",
"end": 689,
"score": 0.999920666217804,
"start": 676,
"tag": "EMAIL",
"value": "test@test.com"
},
{
"context": "//fb.com',\n\t\temail: 'te... | test/tests.coffee | asadahmad123/teamcity.js | 0 | teamcity = require '../teamcity'
should = require 'should'
_ = require 'underscore'
# creates fake request
fakeRequest = ->
responses = []
req = (url, opts, cb) ->
r = _.find responses, (x) ->
return x[0](url) if typeof x[0] is 'function'
return x[0].test(url)
return cb('#{url} is not routed', null, null) if !r
# TODO provide response object
return cb null, {}, r[1] if typeof r[1] is 'string'
throw new Error('not implemented!')
req.get = req
req.on = (matcher, response) ->
matcher = new RegExp(matcher) if typeof matcher is 'string'
responses.push [matcher, response]
return req
create = (req) ->
teamcity
url: 'http://fb.com',
email: 'test@test.com',
password: '1',
request: req
create2 = (req) ->
teamcity
url: 'http://fb.com',
token: 'token',
request: req
describe 'with teamcity client', ->
it 'check required options', ->
(-> teamcity()).should.throw('Options are not specified.')
(-> teamcity({url: ''})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 123})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 'abc', user: ''})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 123})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: ''})).should.throw("Required 'password' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: 123})).should.throw("Required 'password' option is not specified.")
| 115327 | teamcity = require '../teamcity'
should = require 'should'
_ = require 'underscore'
# creates fake request
fakeRequest = ->
responses = []
req = (url, opts, cb) ->
r = _.find responses, (x) ->
return x[0](url) if typeof x[0] is 'function'
return x[0].test(url)
return cb('#{url} is not routed', null, null) if !r
# TODO provide response object
return cb null, {}, r[1] if typeof r[1] is 'string'
throw new Error('not implemented!')
req.get = req
req.on = (matcher, response) ->
matcher = new RegExp(matcher) if typeof matcher is 'string'
responses.push [matcher, response]
return req
create = (req) ->
teamcity
url: 'http://fb.com',
email: '<EMAIL>',
password: '<PASSWORD>',
request: req
create2 = (req) ->
teamcity
url: 'http://fb.com',
token: 'token',
request: req
describe 'with teamcity client', ->
it 'check required options', ->
(-> teamcity()).should.throw('Options are not specified.')
(-> teamcity({url: ''})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 123})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 'abc', user: ''})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 123})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: ''})).should.throw("Required 'password' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: <PASSWORD>})).should.throw("Required 'password' option is not specified.")
| true | teamcity = require '../teamcity'
should = require 'should'
_ = require 'underscore'
# creates fake request
fakeRequest = ->
responses = []
req = (url, opts, cb) ->
r = _.find responses, (x) ->
return x[0](url) if typeof x[0] is 'function'
return x[0].test(url)
return cb('#{url} is not routed', null, null) if !r
# TODO provide response object
return cb null, {}, r[1] if typeof r[1] is 'string'
throw new Error('not implemented!')
req.get = req
req.on = (matcher, response) ->
matcher = new RegExp(matcher) if typeof matcher is 'string'
responses.push [matcher, response]
return req
create = (req) ->
teamcity
url: 'http://fb.com',
email: 'PI:EMAIL:<EMAIL>END_PI',
password: 'PI:PASSWORD:<PASSWORD>END_PI',
request: req
create2 = (req) ->
teamcity
url: 'http://fb.com',
token: 'token',
request: req
describe 'with teamcity client', ->
it 'check required options', ->
(-> teamcity()).should.throw('Options are not specified.')
(-> teamcity({url: ''})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 123})).should.throw("Required 'endpoint' option is not specified.")
(-> teamcity({url: 'abc', user: ''})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 123})).should.throw("Required 'user' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: ''})).should.throw("Required 'password' option is not specified.")
(-> teamcity({url: 'abc', user: 'abc', password: PI:PASSWORD:<PASSWORD>END_PI})).should.throw("Required 'password' option is not specified.")
|
[
{
"context": " starts the server\n\n[clientKey, clientSecret] = [\"officialApiClient\", \"C0FFEE\"]\n[username, password] = [\"AzureDiamond",
"end": 173,
"score": 0.9944678544998169,
"start": 156,
"tag": "KEY",
"value": "officialApiClient"
},
{
"context": "clientKey, clientSecret] = ... | test/ropc-integration.coffee | nqminds/nqm-restify-oauth | 143 | "use strict"
apiEasy = require("api-easy")
require("chai").should()
require("../examples/ropc/server") # starts the server
[clientKey, clientSecret] = ["officialApiClient", "C0FFEE"]
[username, password] = ["AzureDiamond", "hunter2"]
basicAuth = (new Buffer("#{clientKey}:#{clientSecret}")).toString("base64")
# State modified by some tests, and then used by later ones
accessToken = null
suite = apiEasy.describe("Restify–OAuth2 Example Server")
suite.before "Set token if available", (outgoing) ->
if accessToken
outgoing.headers.Authorization = "Bearer #{accessToken}"
return outgoing
suite
.use("localhost", 8080) # TODO: https!!
.get("/secret")
.expect(401)
.expect("should respond with WWW-Authenticate and Link headers", (err, res, body) ->
expectedLink = '</token>; rel="oauth2-token"; grant-types="password"; token-types="bearer"'
res.headers.should.have.property("www-authenticate").that.equals('Bearer realm="Who goes there?"')
res.headers.should.have.property("link").that.equals(expectedLink)
)
.next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"oauth2-token":
href: "/token"
"grant-types": "password"
"token-types": "bearer"
)
.next()
.get("/public")
.expect(200)
.next()
.path("/token")
.discuss("with valid client credentials")
.setHeader("Authorization", "Basic #{basicAuth}")
.setHeader("Content-Type", "application/json")
.discuss("and valid user credentials")
.post({ grant_type: "password", username, password })
.expect(200)
.expect("should respond with the token", (err, res, body) ->
result = JSON.parse(body)
result.should.have.property("token_type", "Bearer")
result.should.have.property("access_token")
accessToken = result.access_token
)
.undiscuss()
.discuss("but invalid user credentials")
.post({ grant_type: "password", username: "blargh", password: "asdf" })
.expect(401)
.expect("should respond with error: invalid_grant", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_grant")
)
.undiscuss()
.undiscuss()
.discuss("with invalid client credentials")
.setHeader("Authorization", "Basic MTIzOjQ1Ng==")
.setHeader("Content-Type", "application/json")
.post({ grant_type: "password", username, password })
.expect(401)
.expect("should respond with error: invalid_client", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_client")
)
.undiscuss()
.unpath().next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"http://rel.example.com/secret": href: "/secret"
)
.get("/secret")
.expect(200)
.next()
.get("/public")
.expect(200)
.next()
.discuss('test cleanup')
.post("/close")
.expect(200)
.next()
.export(module)
| 52254 | "use strict"
apiEasy = require("api-easy")
require("chai").should()
require("../examples/ropc/server") # starts the server
[clientKey, clientSecret] = ["<KEY>", "<KEY>"]
[username, password] = ["AzureDiamond", "hunter2"]
basicAuth = (new Buffer("#{clientKey}:#{clientSecret}")).toString("base64")
# State modified by some tests, and then used by later ones
accessToken = null
suite = apiEasy.describe("Restify–OAuth2 Example Server")
suite.before "Set token if available", (outgoing) ->
if accessToken
outgoing.headers.Authorization = "Bearer #{accessToken}"
return outgoing
suite
.use("localhost", 8080) # TODO: https!!
.get("/secret")
.expect(401)
.expect("should respond with WWW-Authenticate and Link headers", (err, res, body) ->
expectedLink = '</token>; rel="oauth2-token"; grant-types="password"; token-types="bearer"'
res.headers.should.have.property("www-authenticate").that.equals('Bearer realm="Who goes there?"')
res.headers.should.have.property("link").that.equals(expectedLink)
)
.next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"oauth2-token":
href: "/token"
"grant-types": "password"
"token-types": "bearer"
)
.next()
.get("/public")
.expect(200)
.next()
.path("/token")
.discuss("with valid client credentials")
.setHeader("Authorization", "Basic #{basicAuth}")
.setHeader("Content-Type", "application/json")
.discuss("and valid user credentials")
.post({ grant_type: "password", username, password })
.expect(200)
.expect("should respond with the token", (err, res, body) ->
result = JSON.parse(body)
result.should.have.property("token_type", "Bearer")
result.should.have.property("access_token")
accessToken = result.access_token
)
.undiscuss()
.discuss("but invalid user credentials")
.post({ grant_type: "password", username: "blargh", password: "<PASSWORD>" })
.expect(401)
.expect("should respond with error: invalid_grant", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_grant")
)
.undiscuss()
.undiscuss()
.discuss("with invalid client credentials")
.setHeader("Authorization", "Basic MTIzOjQ1Ng==")
.setHeader("Content-Type", "application/json")
.post({ grant_type: "password", username, password })
.expect(401)
.expect("should respond with error: invalid_client", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_client")
)
.undiscuss()
.unpath().next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"http://rel.example.com/secret": href: "/secret"
)
.get("/secret")
.expect(200)
.next()
.get("/public")
.expect(200)
.next()
.discuss('test cleanup')
.post("/close")
.expect(200)
.next()
.export(module)
| true | "use strict"
apiEasy = require("api-easy")
require("chai").should()
require("../examples/ropc/server") # starts the server
[clientKey, clientSecret] = ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
[username, password] = ["AzureDiamond", "hunter2"]
basicAuth = (new Buffer("#{clientKey}:#{clientSecret}")).toString("base64")
# State modified by some tests, and then used by later ones
accessToken = null
suite = apiEasy.describe("Restify–OAuth2 Example Server")
suite.before "Set token if available", (outgoing) ->
if accessToken
outgoing.headers.Authorization = "Bearer #{accessToken}"
return outgoing
suite
.use("localhost", 8080) # TODO: https!!
.get("/secret")
.expect(401)
.expect("should respond with WWW-Authenticate and Link headers", (err, res, body) ->
expectedLink = '</token>; rel="oauth2-token"; grant-types="password"; token-types="bearer"'
res.headers.should.have.property("www-authenticate").that.equals('Bearer realm="Who goes there?"')
res.headers.should.have.property("link").that.equals(expectedLink)
)
.next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"oauth2-token":
href: "/token"
"grant-types": "password"
"token-types": "bearer"
)
.next()
.get("/public")
.expect(200)
.next()
.path("/token")
.discuss("with valid client credentials")
.setHeader("Authorization", "Basic #{basicAuth}")
.setHeader("Content-Type", "application/json")
.discuss("and valid user credentials")
.post({ grant_type: "password", username, password })
.expect(200)
.expect("should respond with the token", (err, res, body) ->
result = JSON.parse(body)
result.should.have.property("token_type", "Bearer")
result.should.have.property("access_token")
accessToken = result.access_token
)
.undiscuss()
.discuss("but invalid user credentials")
.post({ grant_type: "password", username: "blargh", password: "PI:PASSWORD:<PASSWORD>END_PI" })
.expect(401)
.expect("should respond with error: invalid_grant", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_grant")
)
.undiscuss()
.undiscuss()
.discuss("with invalid client credentials")
.setHeader("Authorization", "Basic MTIzOjQ1Ng==")
.setHeader("Content-Type", "application/json")
.post({ grant_type: "password", username, password })
.expect(401)
.expect("should respond with error: invalid_client", (err, res, body) ->
JSON.parse(body).should.have.property("error", "invalid_client")
)
.undiscuss()
.unpath().next()
.get("/")
.expect(
200,
_links:
self: href: "/"
"http://rel.example.com/public": href: "/public"
"http://rel.example.com/secret": href: "/secret"
)
.get("/secret")
.expect(200)
.next()
.get("/public")
.expect(200)
.next()
.discuss('test cleanup')
.post("/close")
.expect(200)
.next()
.export(module)
|
[
{
"context": "(\n\t{\n\t\tpassReqToCallback: true,\n\t\tusernameField: 'email',\n\t\tpasswordField: 'password'\n\t},\n\tAuthentication",
"end": 2949,
"score": 0.9455346465110779,
"start": 2944,
"tag": "USERNAME",
"value": "email"
},
{
"context": "true,\n\t\tusernameField: 'email',\n\... | app/coffee/infrastructure/Server.coffee | davidmehren/web-sharelatex | 0 | Path = require "path"
express = require('express')
Settings = require('settings-sharelatex')
logger = require 'logger-sharelatex'
metrics = require('metrics-sharelatex')
crawlerLogger = require('./CrawlerLogger')
expressLocals = require('./ExpressLocals')
Router = require('../router')
helmet = require "helmet"
metrics.inc("startup")
UserSessionsRedis = require('../Features/User/UserSessionsRedis')
sessionsRedisClient = UserSessionsRedis.client()
session = require("express-session")
RedisStore = require('connect-redis')(session)
bodyParser = require('body-parser')
multer = require('multer')
methodOverride = require('method-override')
csrf = require('csurf')
csrfProtection = csrf()
cookieParser = require('cookie-parser')
# Init the session store
sessionStore = new RedisStore(client:sessionsRedisClient)
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
LdapStrategy = require('passport-ldapauth')
Mongoose = require("./Mongoose")
oneDayInMilliseconds = 86400000
ReferalConnect = require('../Features/Referal/ReferalConnect')
RedirectManager = require("./RedirectManager")
ProxyManager = require("./ProxyManager")
translations = require("translations-sharelatex").setup(Settings.i18n)
Modules = require "./Modules"
ErrorController = require "../Features/Errors/ErrorController"
UserSessionsManager = require "../Features/User/UserSessionsManager"
AuthenticationController = require "../Features/Authentication/AuthenticationController"
metrics.event_loop?.monitor(logger)
Settings.editorIsOpen ||= true
if Settings.cacheStaticAssets
staticCacheAge = (oneDayInMilliseconds * 365)
else
staticCacheAge = 0
app = express()
webRouter = express.Router()
privateApiRouter = express.Router()
publicApiRouter = express.Router()
if Settings.behindProxy
app.enable('trust proxy')
webRouter.use express.static(__dirname + '/../../../public', {maxAge: staticCacheAge })
app.set 'views', __dirname + '/../../views'
app.set 'view engine', 'pug'
Modules.loadViewIncludes app
app.use bodyParser.urlencoded({ extended: true, limit: "2mb"})
# Make sure we can process the max doc length plus some overhead for JSON encoding
app.use bodyParser.json({limit: Settings.max_doc_length + 16 * 1024}) # 16kb overhead
app.use multer(dest: Settings.path.uploadFolder)
app.use methodOverride()
app.use metrics.http.monitor(logger)
app.use RedirectManager
app.use ProxyManager.call
webRouter.use cookieParser(Settings.security.sessionSecret)
webRouter.use session
resave: false
saveUninitialized:false
secret:Settings.security.sessionSecret
proxy: Settings.behindProxy
cookie:
domain: Settings.cookieDomain
maxAge: Settings.cookieSessionLength
secure: Settings.secureCookie
store: sessionStore
key: Settings.cookieName
rolling: true
# passport
webRouter.use passport.initialize()
webRouter.use passport.session()
passport.use(new LocalStrategy(
{
passReqToCallback: true,
usernameField: 'email',
passwordField: 'password'
},
AuthenticationController.doPassportLogin
))
getLDAPConfiguration = (req, callback) ->
process.nextTick(() ->
password = Settings.ldap.server.bindCredentials
password = req.body.ldapPassword if Settings.ldap.server.bindCredentials == "{{password}}"
opts = {
server: {
url: Settings.ldap.server.url
bindDn: Settings.ldap.server.bindDn.replace(/{{username}}/g, req.body.ldapUsername)
bindCredentials: password
searchBase: Settings.ldap.server.searchBase
searchFilter: Settings.ldap.server.searchFilter
}
usernameField: 'ldapUsername'
passwordField: 'ldapPassword'
passReqToCallback: true
}
callback null, opts
)
###
LDAP Strategy
###
passport.use(new LdapStrategy(
getLDAPConfiguration,
AuthenticationController.doLdapLogin
))
passport.serializeUser(AuthenticationController.serializeUser)
passport.deserializeUser(AuthenticationController.deserializeUser)
Modules.hooks.fire 'passportSetup', passport, (err) ->
if err?
logger.err {err}, "error setting up passport in modules"
Modules.applyNonCsrfRouter(webRouter, privateApiRouter, publicApiRouter)
webRouter.use csrfProtection
webRouter.use translations.expressMiddlewear
webRouter.use translations.setLangBasedOnDomainMiddlewear
# Measure expiry from last request, not last login
webRouter.use (req, res, next) ->
req.session.touch()
if AuthenticationController.isUserLoggedIn(req)
UserSessionsManager.touch(AuthenticationController.getSessionUser(req), (err)->)
next()
webRouter.use ReferalConnect.use
expressLocals(app, webRouter, privateApiRouter, publicApiRouter)
if app.get('env') == 'production'
logger.info "Production Enviroment"
app.enable('view cache')
app.use (req, res, next)->
metrics.inc "http-request"
crawlerLogger.log(req)
next()
webRouter.use (req, res, next) ->
if Settings.editorIsOpen
next()
else if req.url.indexOf("/admin") == 0
next()
else
res.status(503)
res.render("general/closed", {title:"maintenance"})
# add security headers using Helmet
webRouter.use (req, res, next) ->
isLoggedIn = AuthenticationController.isUserLoggedIn(req)
isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$')
helmet({ # note that more headers are added by default
dnsPrefetchControl: false
referrerPolicy: { policy: 'origin-when-cross-origin' }
noCache: isLoggedIn || isProjectPage
noSniff: false
hsts: false
frameguard: false
})(req, res, next)
profiler = require "v8-profiler"
privateApiRouter.get "/profile", (req, res) ->
time = parseInt(req.query.time || "1000")
profiler.startProfiling("test")
setTimeout () ->
profile = profiler.stopProfiling("test")
res.json(profile)
, time
app.get "/heapdump", (req, res)->
require('heapdump').writeSnapshot '/tmp/' + Date.now() + '.web.heapsnapshot', (err, filename)->
res.send filename
logger.info ("creating HTTP server").yellow
server = require('http').createServer(app)
# provide settings for separate web and api processes
# if enableApiRouter and enableWebRouter are not defined they default
# to true.
notDefined = (x) -> !x?
enableApiRouter = Settings.web?.enableApiRouter
if enableApiRouter or notDefined(enableApiRouter)
logger.info("providing api router");
app.use(privateApiRouter)
app.use(ErrorController.handleApiError)
enableWebRouter = Settings.web?.enableWebRouter
if enableWebRouter or notDefined(enableWebRouter)
logger.info("providing web router");
app.use(publicApiRouter) # public API goes with web router for public access
app.use(ErrorController.handleApiError)
app.use(webRouter)
app.use(ErrorController.handleError)
router = new Router(webRouter, privateApiRouter, publicApiRouter)
module.exports =
app: app
server: server
| 40898 | Path = require "path"
express = require('express')
Settings = require('settings-sharelatex')
logger = require 'logger-sharelatex'
metrics = require('metrics-sharelatex')
crawlerLogger = require('./CrawlerLogger')
expressLocals = require('./ExpressLocals')
Router = require('../router')
helmet = require "helmet"
metrics.inc("startup")
UserSessionsRedis = require('../Features/User/UserSessionsRedis')
sessionsRedisClient = UserSessionsRedis.client()
session = require("express-session")
RedisStore = require('connect-redis')(session)
bodyParser = require('body-parser')
multer = require('multer')
methodOverride = require('method-override')
csrf = require('csurf')
csrfProtection = csrf()
cookieParser = require('cookie-parser')
# Init the session store
sessionStore = new RedisStore(client:sessionsRedisClient)
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
LdapStrategy = require('passport-ldapauth')
Mongoose = require("./Mongoose")
oneDayInMilliseconds = 86400000
ReferalConnect = require('../Features/Referal/ReferalConnect')
RedirectManager = require("./RedirectManager")
ProxyManager = require("./ProxyManager")
translations = require("translations-sharelatex").setup(Settings.i18n)
Modules = require "./Modules"
ErrorController = require "../Features/Errors/ErrorController"
UserSessionsManager = require "../Features/User/UserSessionsManager"
AuthenticationController = require "../Features/Authentication/AuthenticationController"
metrics.event_loop?.monitor(logger)
Settings.editorIsOpen ||= true
if Settings.cacheStaticAssets
staticCacheAge = (oneDayInMilliseconds * 365)
else
staticCacheAge = 0
app = express()
webRouter = express.Router()
privateApiRouter = express.Router()
publicApiRouter = express.Router()
if Settings.behindProxy
app.enable('trust proxy')
webRouter.use express.static(__dirname + '/../../../public', {maxAge: staticCacheAge })
app.set 'views', __dirname + '/../../views'
app.set 'view engine', 'pug'
Modules.loadViewIncludes app
app.use bodyParser.urlencoded({ extended: true, limit: "2mb"})
# Make sure we can process the max doc length plus some overhead for JSON encoding
app.use bodyParser.json({limit: Settings.max_doc_length + 16 * 1024}) # 16kb overhead
app.use multer(dest: Settings.path.uploadFolder)
app.use methodOverride()
app.use metrics.http.monitor(logger)
app.use RedirectManager
app.use ProxyManager.call
webRouter.use cookieParser(Settings.security.sessionSecret)
webRouter.use session
resave: false
saveUninitialized:false
secret:Settings.security.sessionSecret
proxy: Settings.behindProxy
cookie:
domain: Settings.cookieDomain
maxAge: Settings.cookieSessionLength
secure: Settings.secureCookie
store: sessionStore
key: Settings.cookieName
rolling: true
# passport
webRouter.use passport.initialize()
webRouter.use passport.session()
passport.use(new LocalStrategy(
{
passReqToCallback: true,
usernameField: 'email',
passwordField: '<PASSWORD>'
},
AuthenticationController.doPassportLogin
))
getLDAPConfiguration = (req, callback) ->
process.nextTick(() ->
password = Settings.ldap.server.bindCredentials
password = req.body.ldapPassword if Settings.ldap.server.bindCredentials == "{{password}}"
opts = {
server: {
url: Settings.ldap.server.url
bindDn: Settings.ldap.server.bindDn.replace(/{{username}}/g, req.body.ldapUsername)
bindCredentials: password
searchBase: Settings.ldap.server.searchBase
searchFilter: Settings.ldap.server.searchFilter
}
usernameField: 'ldapUsername'
passwordField: '<PASSWORD>'
passReqToCallback: true
}
callback null, opts
)
###
LDAP Strategy
###
passport.use(new LdapStrategy(
getLDAPConfiguration,
AuthenticationController.doLdapLogin
))
passport.serializeUser(AuthenticationController.serializeUser)
passport.deserializeUser(AuthenticationController.deserializeUser)
Modules.hooks.fire 'passportSetup', passport, (err) ->
if err?
logger.err {err}, "error setting up passport in modules"
Modules.applyNonCsrfRouter(webRouter, privateApiRouter, publicApiRouter)
webRouter.use csrfProtection
webRouter.use translations.expressMiddlewear
webRouter.use translations.setLangBasedOnDomainMiddlewear
# Measure expiry from last request, not last login
webRouter.use (req, res, next) ->
req.session.touch()
if AuthenticationController.isUserLoggedIn(req)
UserSessionsManager.touch(AuthenticationController.getSessionUser(req), (err)->)
next()
webRouter.use ReferalConnect.use
expressLocals(app, webRouter, privateApiRouter, publicApiRouter)
if app.get('env') == 'production'
logger.info "Production Enviroment"
app.enable('view cache')
app.use (req, res, next)->
metrics.inc "http-request"
crawlerLogger.log(req)
next()
webRouter.use (req, res, next) ->
if Settings.editorIsOpen
next()
else if req.url.indexOf("/admin") == 0
next()
else
res.status(503)
res.render("general/closed", {title:"maintenance"})
# add security headers using Helmet
webRouter.use (req, res, next) ->
isLoggedIn = AuthenticationController.isUserLoggedIn(req)
isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$')
helmet({ # note that more headers are added by default
dnsPrefetchControl: false
referrerPolicy: { policy: 'origin-when-cross-origin' }
noCache: isLoggedIn || isProjectPage
noSniff: false
hsts: false
frameguard: false
})(req, res, next)
profiler = require "v8-profiler"
privateApiRouter.get "/profile", (req, res) ->
time = parseInt(req.query.time || "1000")
profiler.startProfiling("test")
setTimeout () ->
profile = profiler.stopProfiling("test")
res.json(profile)
, time
app.get "/heapdump", (req, res)->
require('heapdump').writeSnapshot '/tmp/' + Date.now() + '.web.heapsnapshot', (err, filename)->
res.send filename
logger.info ("creating HTTP server").yellow
server = require('http').createServer(app)
# provide settings for separate web and api processes
# if enableApiRouter and enableWebRouter are not defined they default
# to true.
notDefined = (x) -> !x?
enableApiRouter = Settings.web?.enableApiRouter
if enableApiRouter or notDefined(enableApiRouter)
logger.info("providing api router");
app.use(privateApiRouter)
app.use(ErrorController.handleApiError)
enableWebRouter = Settings.web?.enableWebRouter
if enableWebRouter or notDefined(enableWebRouter)
logger.info("providing web router");
app.use(publicApiRouter) # public API goes with web router for public access
app.use(ErrorController.handleApiError)
app.use(webRouter)
app.use(ErrorController.handleError)
router = new Router(webRouter, privateApiRouter, publicApiRouter)
module.exports =
app: app
server: server
| true | Path = require "path"
express = require('express')
Settings = require('settings-sharelatex')
logger = require 'logger-sharelatex'
metrics = require('metrics-sharelatex')
crawlerLogger = require('./CrawlerLogger')
expressLocals = require('./ExpressLocals')
Router = require('../router')
helmet = require "helmet"
metrics.inc("startup")
UserSessionsRedis = require('../Features/User/UserSessionsRedis')
sessionsRedisClient = UserSessionsRedis.client()
session = require("express-session")
RedisStore = require('connect-redis')(session)
bodyParser = require('body-parser')
multer = require('multer')
methodOverride = require('method-override')
csrf = require('csurf')
csrfProtection = csrf()
cookieParser = require('cookie-parser')
# Init the session store
sessionStore = new RedisStore(client:sessionsRedisClient)
passport = require('passport')
LocalStrategy = require('passport-local').Strategy
LdapStrategy = require('passport-ldapauth')
Mongoose = require("./Mongoose")
oneDayInMilliseconds = 86400000
ReferalConnect = require('../Features/Referal/ReferalConnect')
RedirectManager = require("./RedirectManager")
ProxyManager = require("./ProxyManager")
translations = require("translations-sharelatex").setup(Settings.i18n)
Modules = require "./Modules"
ErrorController = require "../Features/Errors/ErrorController"
UserSessionsManager = require "../Features/User/UserSessionsManager"
AuthenticationController = require "../Features/Authentication/AuthenticationController"
metrics.event_loop?.monitor(logger)
Settings.editorIsOpen ||= true
if Settings.cacheStaticAssets
staticCacheAge = (oneDayInMilliseconds * 365)
else
staticCacheAge = 0
app = express()
webRouter = express.Router()
privateApiRouter = express.Router()
publicApiRouter = express.Router()
if Settings.behindProxy
app.enable('trust proxy')
webRouter.use express.static(__dirname + '/../../../public', {maxAge: staticCacheAge })
app.set 'views', __dirname + '/../../views'
app.set 'view engine', 'pug'
Modules.loadViewIncludes app
app.use bodyParser.urlencoded({ extended: true, limit: "2mb"})
# Make sure we can process the max doc length plus some overhead for JSON encoding
app.use bodyParser.json({limit: Settings.max_doc_length + 16 * 1024}) # 16kb overhead
app.use multer(dest: Settings.path.uploadFolder)
app.use methodOverride()
app.use metrics.http.monitor(logger)
app.use RedirectManager
app.use ProxyManager.call
webRouter.use cookieParser(Settings.security.sessionSecret)
webRouter.use session
resave: false
saveUninitialized:false
secret:Settings.security.sessionSecret
proxy: Settings.behindProxy
cookie:
domain: Settings.cookieDomain
maxAge: Settings.cookieSessionLength
secure: Settings.secureCookie
store: sessionStore
key: Settings.cookieName
rolling: true
# passport
webRouter.use passport.initialize()
webRouter.use passport.session()
passport.use(new LocalStrategy(
{
passReqToCallback: true,
usernameField: 'email',
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
},
AuthenticationController.doPassportLogin
))
getLDAPConfiguration = (req, callback) ->
process.nextTick(() ->
password = Settings.ldap.server.bindCredentials
password = req.body.ldapPassword if Settings.ldap.server.bindCredentials == "{{password}}"
opts = {
server: {
url: Settings.ldap.server.url
bindDn: Settings.ldap.server.bindDn.replace(/{{username}}/g, req.body.ldapUsername)
bindCredentials: password
searchBase: Settings.ldap.server.searchBase
searchFilter: Settings.ldap.server.searchFilter
}
usernameField: 'ldapUsername'
passwordField: 'PI:PASSWORD:<PASSWORD>END_PI'
passReqToCallback: true
}
callback null, opts
)
###
LDAP Strategy
###
passport.use(new LdapStrategy(
getLDAPConfiguration,
AuthenticationController.doLdapLogin
))
passport.serializeUser(AuthenticationController.serializeUser)
passport.deserializeUser(AuthenticationController.deserializeUser)
Modules.hooks.fire 'passportSetup', passport, (err) ->
if err?
logger.err {err}, "error setting up passport in modules"
Modules.applyNonCsrfRouter(webRouter, privateApiRouter, publicApiRouter)
webRouter.use csrfProtection
webRouter.use translations.expressMiddlewear
webRouter.use translations.setLangBasedOnDomainMiddlewear
# Measure expiry from last request, not last login
webRouter.use (req, res, next) ->
req.session.touch()
if AuthenticationController.isUserLoggedIn(req)
UserSessionsManager.touch(AuthenticationController.getSessionUser(req), (err)->)
next()
webRouter.use ReferalConnect.use
expressLocals(app, webRouter, privateApiRouter, publicApiRouter)
if app.get('env') == 'production'
logger.info "Production Enviroment"
app.enable('view cache')
app.use (req, res, next)->
metrics.inc "http-request"
crawlerLogger.log(req)
next()
webRouter.use (req, res, next) ->
if Settings.editorIsOpen
next()
else if req.url.indexOf("/admin") == 0
next()
else
res.status(503)
res.render("general/closed", {title:"maintenance"})
# add security headers using Helmet
webRouter.use (req, res, next) ->
isLoggedIn = AuthenticationController.isUserLoggedIn(req)
isProjectPage = !!req.path.match('^/project/[a-f0-9]{24}$')
helmet({ # note that more headers are added by default
dnsPrefetchControl: false
referrerPolicy: { policy: 'origin-when-cross-origin' }
noCache: isLoggedIn || isProjectPage
noSniff: false
hsts: false
frameguard: false
})(req, res, next)
profiler = require "v8-profiler"
privateApiRouter.get "/profile", (req, res) ->
time = parseInt(req.query.time || "1000")
profiler.startProfiling("test")
setTimeout () ->
profile = profiler.stopProfiling("test")
res.json(profile)
, time
app.get "/heapdump", (req, res)->
require('heapdump').writeSnapshot '/tmp/' + Date.now() + '.web.heapsnapshot', (err, filename)->
res.send filename
logger.info ("creating HTTP server").yellow
server = require('http').createServer(app)
# provide settings for separate web and api processes
# if enableApiRouter and enableWebRouter are not defined they default
# to true.
notDefined = (x) -> !x?
enableApiRouter = Settings.web?.enableApiRouter
if enableApiRouter or notDefined(enableApiRouter)
logger.info("providing api router");
app.use(privateApiRouter)
app.use(ErrorController.handleApiError)
enableWebRouter = Settings.web?.enableWebRouter
if enableWebRouter or notDefined(enableWebRouter)
logger.info("providing web router");
app.use(publicApiRouter) # public API goes with web router for public access
app.use(ErrorController.handleApiError)
app.use(webRouter)
app.use(ErrorController.handleError)
router = new Router(webRouter, privateApiRouter, publicApiRouter)
module.exports =
app: app
server: server
|
[
{
"context": "###\n Front-end handlebars parser\n @author: K.Perov <fe3dback@yandex.ru>\n###\n\nclass MoreDraw\n\n parti",
"end": 52,
"score": 0.9998577833175659,
"start": 45,
"tag": "NAME",
"value": "K.Perov"
},
{
"context": " Front-end handlebars parser\n @author: K.Perov <fe3... | handlebars.coffee | ahelhot/moredraw | 2 | ###
Front-end handlebars parser
@author: K.Perov <fe3dback@yandex.ru>
###
class MoreDraw
partials = null
dataCache = null
constructor: ->
#noinspection JSUnresolvedVariable
if (__handlebars_server_partials?)
@partials = __handlebars_server_partials;
#noinspection JSUnresolvedVariable
if (__handlebars_server_data?)
@dataCache = __handlebars_server_data;
render: (name, data) ->
name = name.split('/').join('__')
$el = $("#hb-#{name}");
return "" unless $el?
tpl = Handlebars.compile($el.html())
return tpl(data, {
'partials': @partials
})
getData: (name, index) ->
return unless @dataCache?
data = @dataCache[name]?[index]
return unless data?
return data
setData: (name, index, data) ->
return unless @dataCache?
@dataCache[name][index] = data
window.MoreDraw = new MoreDraw() | 206147 | ###
Front-end handlebars parser
@author: <NAME> <<EMAIL>>
###
class MoreDraw
partials = null
dataCache = null
constructor: ->
#noinspection JSUnresolvedVariable
if (__handlebars_server_partials?)
@partials = __handlebars_server_partials;
#noinspection JSUnresolvedVariable
if (__handlebars_server_data?)
@dataCache = __handlebars_server_data;
render: (name, data) ->
name = name.split('/').join('__')
$el = $("#hb-#{name}");
return "" unless $el?
tpl = Handlebars.compile($el.html())
return tpl(data, {
'partials': @partials
})
getData: (name, index) ->
return unless @dataCache?
data = @dataCache[name]?[index]
return unless data?
return data
setData: (name, index, data) ->
return unless @dataCache?
@dataCache[name][index] = data
window.MoreDraw = new MoreDraw() | true | ###
Front-end handlebars parser
@author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
class MoreDraw
partials = null
dataCache = null
constructor: ->
#noinspection JSUnresolvedVariable
if (__handlebars_server_partials?)
@partials = __handlebars_server_partials;
#noinspection JSUnresolvedVariable
if (__handlebars_server_data?)
@dataCache = __handlebars_server_data;
render: (name, data) ->
name = name.split('/').join('__')
$el = $("#hb-#{name}");
return "" unless $el?
tpl = Handlebars.compile($el.html())
return tpl(data, {
'partials': @partials
})
getData: (name, index) ->
return unless @dataCache?
data = @dataCache[name]?[index]
return unless data?
return data
setData: (name, index, data) ->
return unless @dataCache?
@dataCache[name][index] = data
window.MoreDraw = new MoreDraw() |
[
{
"context": "cmd\": res[1], \"content\": res[2]}\n\n\tend_token = \"__[[END_TOKEN]]__\"\n\n\t#text=text.replace /\\#\\{/g,\"__AROBAS_ATOM__{\"\n",
"end": 299,
"score": 0.8835864663124084,
"start": 286,
"tag": "KEY",
"value": "END_TOKEN]]__"
}
] | lib/render-dyndoc.coffee | rcqls/atom-dyndoc-viewer | 0 | DyndocRunner = require './dyndoc-runner'
exports.eval = (text='', filePath, callback) ->
DyndocRunner.started()
decode_cmd = (cmd) ->
regexp = /^__send_cmd__\[\[([a-zA-Z0-9_]*)\]\]__([\s\S]*)/m
res = cmd.match(regexp)
{"cmd": res[1], "content": res[2]}
end_token = "__[[END_TOKEN]]__"
#text=text.replace /\#\{/g,"__AROBAS_ATOM__{"
net = require 'net'
#util = require 'util'
if atom.config.get 'dyndoc-viewer.localServer'
host = atom.config.get 'dyndoc-viewer.localServerUrl'
port = atom.config.get 'dyndoc-viewer.localServerPort'
else
host = atom.config.get 'dyndoc-viewer.remoteServerUrl'
port = atom.config.get 'dyndoc-viewer.remoteServerPort'
client = net.connect {port: port, host: host}, () ->
#console.log (util.inspect '__send_cmd__[[dyndoc]]__' + text + end_token)
client.write '__send_cmd__[[dyndoc]]__' + text + end_token + '\n'
client.on 'data', (data) ->
#console.log "data:" + data.toString()
data.toString().split(end_token).slice(0,-1).map (cmd) ->
#console.log("<<"+cmd+">>")
resCmd = decode_cmd(cmd)
if resCmd["cmd"] != "windows_platform"
#console.log("data: "+resCmd["content"])
callback(null, resCmd["content"])
client.end()
resCmd
client.on 'error', (err) ->
#console.log('error:', err.message)
callback error,err.message
DyndocRunner.dyndoc_client = client | 53310 | DyndocRunner = require './dyndoc-runner'
exports.eval = (text='', filePath, callback) ->
DyndocRunner.started()
decode_cmd = (cmd) ->
regexp = /^__send_cmd__\[\[([a-zA-Z0-9_]*)\]\]__([\s\S]*)/m
res = cmd.match(regexp)
{"cmd": res[1], "content": res[2]}
end_token = "__[[<KEY>"
#text=text.replace /\#\{/g,"__AROBAS_ATOM__{"
net = require 'net'
#util = require 'util'
if atom.config.get 'dyndoc-viewer.localServer'
host = atom.config.get 'dyndoc-viewer.localServerUrl'
port = atom.config.get 'dyndoc-viewer.localServerPort'
else
host = atom.config.get 'dyndoc-viewer.remoteServerUrl'
port = atom.config.get 'dyndoc-viewer.remoteServerPort'
client = net.connect {port: port, host: host}, () ->
#console.log (util.inspect '__send_cmd__[[dyndoc]]__' + text + end_token)
client.write '__send_cmd__[[dyndoc]]__' + text + end_token + '\n'
client.on 'data', (data) ->
#console.log "data:" + data.toString()
data.toString().split(end_token).slice(0,-1).map (cmd) ->
#console.log("<<"+cmd+">>")
resCmd = decode_cmd(cmd)
if resCmd["cmd"] != "windows_platform"
#console.log("data: "+resCmd["content"])
callback(null, resCmd["content"])
client.end()
resCmd
client.on 'error', (err) ->
#console.log('error:', err.message)
callback error,err.message
DyndocRunner.dyndoc_client = client | true | DyndocRunner = require './dyndoc-runner'
exports.eval = (text='', filePath, callback) ->
DyndocRunner.started()
decode_cmd = (cmd) ->
regexp = /^__send_cmd__\[\[([a-zA-Z0-9_]*)\]\]__([\s\S]*)/m
res = cmd.match(regexp)
{"cmd": res[1], "content": res[2]}
end_token = "__[[PI:KEY:<KEY>END_PI"
#text=text.replace /\#\{/g,"__AROBAS_ATOM__{"
net = require 'net'
#util = require 'util'
if atom.config.get 'dyndoc-viewer.localServer'
host = atom.config.get 'dyndoc-viewer.localServerUrl'
port = atom.config.get 'dyndoc-viewer.localServerPort'
else
host = atom.config.get 'dyndoc-viewer.remoteServerUrl'
port = atom.config.get 'dyndoc-viewer.remoteServerPort'
client = net.connect {port: port, host: host}, () ->
#console.log (util.inspect '__send_cmd__[[dyndoc]]__' + text + end_token)
client.write '__send_cmd__[[dyndoc]]__' + text + end_token + '\n'
client.on 'data', (data) ->
#console.log "data:" + data.toString()
data.toString().split(end_token).slice(0,-1).map (cmd) ->
#console.log("<<"+cmd+">>")
resCmd = decode_cmd(cmd)
if resCmd["cmd"] != "windows_platform"
#console.log("data: "+resCmd["content"])
callback(null, resCmd["content"])
client.end()
resCmd
client.on 'error', (err) ->
#console.log('error:', err.message)
callback error,err.message
DyndocRunner.dyndoc_client = client |
[
{
"context": "\"}\n\t\t\t\tconstructor: ->\n\t\t\t\t\t@_initInstantiable \"Buick\"\n\t\t\t\t\tdep = @instantiable\n\n\t\t\tclass Instantiable\n",
"end": 3735,
"score": 0.6477090716362,
"start": 3732,
"tag": "NAME",
"value": "ick"
},
{
"context": "e]\n\t\t\tcc.prepare()\n\n\t\t\texpec... | test/Dee.coffee | AriaMinaei/dee | 1 | ComponentComposer = require '../src/ComponentComposer'
about = describe
they = it
describe "ComponentComposer", ->
cc = null
beforeEach ->
cc = new ComponentComposer
describe "constructor()", ->
it "should work", ->
(-> new ComponentComposer).should.not.throw()
about "All components", ->
they "should have unique componentId-s", ->
cc.register "a", {}
(-> cc.register "a", {}).should.throw()
they "should only have componentId-s containing only alphanumerics and slashes", ->
(->
cc.register class A
@componentId: "s "
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "0s"
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: ""
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: 5
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "S0/Pack"
@componentType: "Instantiable"
).should.not.throw()
about "Global values", ->
they "are recognized by calling #ComponentComposer.register(id, value)", ->
cc.register "a", a = {}
cc.isGlobal("a").should.equal true
they "are returned untouched", ->
cc.register "a", a = {}
cc.get("a").should.equal a
about "All class components (singletons, attachments, instantiables)", ->
they "should have a Class.componentId", ->
class A
(-> cc.register A).should.throw()
class B
@componentId: "B"
@componentType: "Instantiable"
(-> cc.register B).should.not.throw()
they "can depend on globals", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "b"}
constructor: ->
bi = @bi
cc.register A
cc.register "b", {}
cc.prepare()
cc.get("b").should.equal bi
they "can depend on singletons", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
class B
@componentId: "B"
@componentType: "Singleton"
cc.register [A, B]
cc.prepare()
cc.get("B").should.equal bi
they "can depend on instantiables", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep).to.be.instanceOf Instantiable
they "inherit component properties from their parents", ->
class A
@componentId: "A"
@deps: {"one"}
@traits: ["B"]
class B
@componentType: "Singleton"
@componentId: "B"
@deps: {"two"}
class C
@deps: {"three"}
@componentType: "Instantiable"
@traits: ["C"]
B:: = Object.create C::
B::constructor = C
A:: = Object.create B::
A::constructor = B
cc.register A
A.componentId.should.equal "A"
A.componentType.should.equal "Singleton"
A.traits.should.be.like ["B", "C"]
A.deps.should.be.like {"one", "two", "three"}
they "use an extension of the original class", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register Instantiable
cc.prepare()
cc.instantiate("Instantiable").constructor.should.not.equal Instantiable
about "Dependency on instantiables", ->
it "should have customizable initializers", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
@_initInstantiable "Buick"
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
constructor: (@name) ->
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep.name).to.equal "Buick"
about "Singleton-s", ->
they "are recognized by having Class.componentType == 'Singleton'", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.isSingleton("S").should.equal true
they "are instantiated by calling #ComponentComposer.get()", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.be.instanceof S
they "are only instantiated once", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.equal cc.get("S")
they "can have circular dependencies with each other", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
aa = null
class B
@componentId: "B"
@componentType: "Singleton"
@deps: {"aa": "A"}
constructor: ->
aa = @aa
cc.register [A, B]
cc.prepare()
bi.should.equal cc.get("B")
aa.should.equal cc.get("A")
about "Instantiables", ->
they "are recognized when Class.componentType == 'Instantiable'", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Instantiable, Singleton, Attachment]
cc.isInstantiable("Instantiable").should.equal true
cc.isInstantiable("Attachment").should.equal false
cc.isInstantiable("Singleton").should.equal false
they "can depend on other instantiables", ->
class A
@componentId: "A"
@componentType: "Instantiable"
@deps: {"b": "B"}
class B
@componentId: "B"
@componentType: "Instantiable"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").b.should.be.instanceOf B
about "Attachments", ->
they "are recognized by typeof Class.attachesTo === 'object'", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class AA
@componentId: "AA"
@componentType: "Attachment"
@attachesTo: "A":
as: "aa"
cc.register [A, AA]
cc.isAttachment("AA").should.equal true
they "can attach to singletons", ->
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Attachment, Singleton]
cc.prepare()
expect(cc.get("Singleton").attachment).to.be.instanceOf Attachment
they "can attach to instantiables", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
cc.register [Attachment, Instantiable]
cc.prepare()
expect(cc.instantiate("Instantiable").attachment).to.be.instanceOf Attachment
they "cannot attach to global values", ->
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "valueObject":
as: "attachment"
cc.register Attachment
(-> cc.register 'valueObject', {}).should.throw()
they "are called with their target's instance", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
constructor: (@target) ->
cc.register [Attachment, Instantiable]
cc.prepare()
instantiable = cc.instantiate("Instantiable")
attachment = instantiable.attachment
expect(attachment.target).to.be.equal instantiable
they "can have peer deps", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
peerDeps: {c: "C"}
class C
@componentId: "C"
@componentType: "Instantiable"
cc.register [A, B, C]
cc.prepare()
expect(cc.instantiate("A").c).to.be.instanceOf C
about "Reacting to traits", ->
they "should work", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model":
performs: (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should support shorthand functions", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should allow creation of repos", ->
class BaseRepo
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
class ModelFelange
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
cls = container.getClass()
cls.repo = "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
constructor: ->
BaseRepo.apply this, arguments
ModelRepo.prototype = Object.create BaseRepo.prototype
ModelRepo::constructor = BaseRepo
componentComposer.register ModelRepo
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Model, ModelFelange]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
about "Repos", ->
they "should work", ->
class Model
@componentId: "Model"
@componentType: "Instantiable"
@repo: "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
cc.register [Model, ModelRepo]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
cc.instantiate("Model", [10]).should.equal cc.get("ModelRepo").getInstance(10)
cc.instantiate("Model", [11]).should.not.equal cc.get("ModelRepo").getInstance(10)
about "Method patching", ->
it "should only be allowed if method does exist", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should ensure invokation of patched functionality precedes original method's invokation", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
it "should support using attachment's methods instead of anonymous function", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches: {"sayHi"}
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
about "Method providing", ->
it "should only be allowed if no original method by the name exists", ->
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: ->
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should add functionality", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
it "should support using attachment's methods instead of anonymous function", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: {"sayHi"}
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
about "Accessing #ComponentComposer itself", ->
it "is possible by calling #ComponentComposer.get('ComponentComposer')", ->
cc.get("ComponentComposer").should.equal cc | 51683 | ComponentComposer = require '../src/ComponentComposer'
about = describe
they = it
describe "ComponentComposer", ->
cc = null
beforeEach ->
cc = new ComponentComposer
describe "constructor()", ->
it "should work", ->
(-> new ComponentComposer).should.not.throw()
about "All components", ->
they "should have unique componentId-s", ->
cc.register "a", {}
(-> cc.register "a", {}).should.throw()
they "should only have componentId-s containing only alphanumerics and slashes", ->
(->
cc.register class A
@componentId: "s "
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "0s"
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: ""
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: 5
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "S0/Pack"
@componentType: "Instantiable"
).should.not.throw()
about "Global values", ->
they "are recognized by calling #ComponentComposer.register(id, value)", ->
cc.register "a", a = {}
cc.isGlobal("a").should.equal true
they "are returned untouched", ->
cc.register "a", a = {}
cc.get("a").should.equal a
about "All class components (singletons, attachments, instantiables)", ->
they "should have a Class.componentId", ->
class A
(-> cc.register A).should.throw()
class B
@componentId: "B"
@componentType: "Instantiable"
(-> cc.register B).should.not.throw()
they "can depend on globals", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "b"}
constructor: ->
bi = @bi
cc.register A
cc.register "b", {}
cc.prepare()
cc.get("b").should.equal bi
they "can depend on singletons", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
class B
@componentId: "B"
@componentType: "Singleton"
cc.register [A, B]
cc.prepare()
cc.get("B").should.equal bi
they "can depend on instantiables", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep).to.be.instanceOf Instantiable
they "inherit component properties from their parents", ->
class A
@componentId: "A"
@deps: {"one"}
@traits: ["B"]
class B
@componentType: "Singleton"
@componentId: "B"
@deps: {"two"}
class C
@deps: {"three"}
@componentType: "Instantiable"
@traits: ["C"]
B:: = Object.create C::
B::constructor = C
A:: = Object.create B::
A::constructor = B
cc.register A
A.componentId.should.equal "A"
A.componentType.should.equal "Singleton"
A.traits.should.be.like ["B", "C"]
A.deps.should.be.like {"one", "two", "three"}
they "use an extension of the original class", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register Instantiable
cc.prepare()
cc.instantiate("Instantiable").constructor.should.not.equal Instantiable
about "Dependency on instantiables", ->
it "should have customizable initializers", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
@_initInstantiable "Bu<NAME>"
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
constructor: (@name) ->
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep.name).to.equal "<NAME>"
about "Singleton-s", ->
they "are recognized by having Class.componentType == 'Singleton'", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.isSingleton("S").should.equal true
they "are instantiated by calling #ComponentComposer.get()", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.be.instanceof S
they "are only instantiated once", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.equal cc.get("S")
they "can have circular dependencies with each other", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
aa = null
class B
@componentId: "B"
@componentType: "Singleton"
@deps: {"aa": "A"}
constructor: ->
aa = @aa
cc.register [A, B]
cc.prepare()
bi.should.equal cc.get("B")
aa.should.equal cc.get("A")
about "Instantiables", ->
they "are recognized when Class.componentType == 'Instantiable'", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Instantiable, Singleton, Attachment]
cc.isInstantiable("Instantiable").should.equal true
cc.isInstantiable("Attachment").should.equal false
cc.isInstantiable("Singleton").should.equal false
they "can depend on other instantiables", ->
class A
@componentId: "A"
@componentType: "Instantiable"
@deps: {"b": "B"}
class B
@componentId: "B"
@componentType: "Instantiable"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").b.should.be.instanceOf B
about "Attachments", ->
they "are recognized by typeof Class.attachesTo === 'object'", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class AA
@componentId: "AA"
@componentType: "Attachment"
@attachesTo: "A":
as: "aa"
cc.register [A, AA]
cc.isAttachment("AA").should.equal true
they "can attach to singletons", ->
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Attachment, Singleton]
cc.prepare()
expect(cc.get("Singleton").attachment).to.be.instanceOf Attachment
they "can attach to instantiables", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
cc.register [Attachment, Instantiable]
cc.prepare()
expect(cc.instantiate("Instantiable").attachment).to.be.instanceOf Attachment
they "cannot attach to global values", ->
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "valueObject":
as: "attachment"
cc.register Attachment
(-> cc.register 'valueObject', {}).should.throw()
they "are called with their target's instance", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
constructor: (@target) ->
cc.register [Attachment, Instantiable]
cc.prepare()
instantiable = cc.instantiate("Instantiable")
attachment = instantiable.attachment
expect(attachment.target).to.be.equal instantiable
they "can have peer deps", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
peerDeps: {c: "C"}
class C
@componentId: "C"
@componentType: "Instantiable"
cc.register [A, B, C]
cc.prepare()
expect(cc.instantiate("A").c).to.be.instanceOf C
about "Reacting to traits", ->
they "should work", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model":
performs: (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should support shorthand functions", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should allow creation of repos", ->
class BaseRepo
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
class ModelFelange
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
cls = container.getClass()
cls.repo = "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
constructor: ->
BaseRepo.apply this, arguments
ModelRepo.prototype = Object.create BaseRepo.prototype
ModelRepo::constructor = BaseRepo
componentComposer.register ModelRepo
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Model, ModelFelange]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
about "Repos", ->
they "should work", ->
class Model
@componentId: "Model"
@componentType: "Instantiable"
@repo: "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
cc.register [Model, ModelRepo]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
cc.instantiate("Model", [10]).should.equal cc.get("ModelRepo").getInstance(10)
cc.instantiate("Model", [11]).should.not.equal cc.get("ModelRepo").getInstance(10)
about "Method patching", ->
it "should only be allowed if method does exist", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should ensure invokation of patched functionality precedes original method's invokation", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
it "should support using attachment's methods instead of anonymous function", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches: {"sayHi"}
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
about "Method providing", ->
it "should only be allowed if no original method by the name exists", ->
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: ->
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should add functionality", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
it "should support using attachment's methods instead of anonymous function", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: {"sayHi"}
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
about "Accessing #ComponentComposer itself", ->
it "is possible by calling #ComponentComposer.get('ComponentComposer')", ->
cc.get("ComponentComposer").should.equal cc | true | ComponentComposer = require '../src/ComponentComposer'
about = describe
they = it
describe "ComponentComposer", ->
cc = null
beforeEach ->
cc = new ComponentComposer
describe "constructor()", ->
it "should work", ->
(-> new ComponentComposer).should.not.throw()
about "All components", ->
they "should have unique componentId-s", ->
cc.register "a", {}
(-> cc.register "a", {}).should.throw()
they "should only have componentId-s containing only alphanumerics and slashes", ->
(->
cc.register class A
@componentId: "s "
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "0s"
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: ""
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: 5
@componentType: "Instantiable"
).should.throw()
(->
cc.register class A
@componentId: "S0/Pack"
@componentType: "Instantiable"
).should.not.throw()
about "Global values", ->
they "are recognized by calling #ComponentComposer.register(id, value)", ->
cc.register "a", a = {}
cc.isGlobal("a").should.equal true
they "are returned untouched", ->
cc.register "a", a = {}
cc.get("a").should.equal a
about "All class components (singletons, attachments, instantiables)", ->
they "should have a Class.componentId", ->
class A
(-> cc.register A).should.throw()
class B
@componentId: "B"
@componentType: "Instantiable"
(-> cc.register B).should.not.throw()
they "can depend on globals", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "b"}
constructor: ->
bi = @bi
cc.register A
cc.register "b", {}
cc.prepare()
cc.get("b").should.equal bi
they "can depend on singletons", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
class B
@componentId: "B"
@componentType: "Singleton"
cc.register [A, B]
cc.prepare()
cc.get("B").should.equal bi
they "can depend on instantiables", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep).to.be.instanceOf Instantiable
they "inherit component properties from their parents", ->
class A
@componentId: "A"
@deps: {"one"}
@traits: ["B"]
class B
@componentType: "Singleton"
@componentId: "B"
@deps: {"two"}
class C
@deps: {"three"}
@componentType: "Instantiable"
@traits: ["C"]
B:: = Object.create C::
B::constructor = C
A:: = Object.create B::
A::constructor = B
cc.register A
A.componentId.should.equal "A"
A.componentType.should.equal "Singleton"
A.traits.should.be.like ["B", "C"]
A.deps.should.be.like {"one", "two", "three"}
they "use an extension of the original class", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
cc.register Instantiable
cc.prepare()
cc.instantiate("Instantiable").constructor.should.not.equal Instantiable
about "Dependency on instantiables", ->
it "should have customizable initializers", ->
dep = null
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
@deps: {"instantiable": "Instantiable"}
constructor: ->
@_initInstantiable "BuPI:NAME:<NAME>END_PI"
dep = @instantiable
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
constructor: (@name) ->
cc.register [Singleton, Instantiable]
cc.prepare()
expect(dep.name).to.equal "PI:NAME:<NAME>END_PI"
about "Singleton-s", ->
they "are recognized by having Class.componentType == 'Singleton'", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.isSingleton("S").should.equal true
they "are instantiated by calling #ComponentComposer.get()", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.be.instanceof S
they "are only instantiated once", ->
class S
@componentId: "S"
@componentType: "Singleton"
cc.register S
cc.get("S").should.equal cc.get("S")
they "can have circular dependencies with each other", ->
bi = null
class A
@componentId: "A"
@componentType: "Singleton"
@deps: {"bi": "B"}
constructor: ->
bi = @bi
aa = null
class B
@componentId: "B"
@componentType: "Singleton"
@deps: {"aa": "A"}
constructor: ->
aa = @aa
cc.register [A, B]
cc.prepare()
bi.should.equal cc.get("B")
aa.should.equal cc.get("A")
about "Instantiables", ->
they "are recognized when Class.componentType == 'Instantiable'", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Instantiable, Singleton, Attachment]
cc.isInstantiable("Instantiable").should.equal true
cc.isInstantiable("Attachment").should.equal false
cc.isInstantiable("Singleton").should.equal false
they "can depend on other instantiables", ->
class A
@componentId: "A"
@componentType: "Instantiable"
@deps: {"b": "B"}
class B
@componentId: "B"
@componentType: "Instantiable"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").b.should.be.instanceOf B
about "Attachments", ->
they "are recognized by typeof Class.attachesTo === 'object'", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class AA
@componentId: "AA"
@componentType: "Attachment"
@attachesTo: "A":
as: "aa"
cc.register [A, AA]
cc.isAttachment("AA").should.equal true
they "can attach to singletons", ->
class Singleton
@componentId: "Singleton"
@componentType: "Singleton"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Singleton":
as: "attachment"
cc.register [Attachment, Singleton]
cc.prepare()
expect(cc.get("Singleton").attachment).to.be.instanceOf Attachment
they "can attach to instantiables", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
cc.register [Attachment, Instantiable]
cc.prepare()
expect(cc.instantiate("Instantiable").attachment).to.be.instanceOf Attachment
they "cannot attach to global values", ->
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "valueObject":
as: "attachment"
cc.register Attachment
(-> cc.register 'valueObject', {}).should.throw()
they "are called with their target's instance", ->
class Instantiable
@componentId: "Instantiable"
@componentType: "Instantiable"
class Attachment
@componentId: "Attachment"
@componentType: "Attachment"
@attachesTo: "Instantiable":
as: "attachment"
constructor: (@target) ->
cc.register [Attachment, Instantiable]
cc.prepare()
instantiable = cc.instantiate("Instantiable")
attachment = instantiable.attachment
expect(attachment.target).to.be.equal instantiable
they "can have peer deps", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
peerDeps: {c: "C"}
class C
@componentId: "C"
@componentType: "Instantiable"
cc.register [A, B, C]
cc.prepare()
expect(cc.instantiate("A").c).to.be.instanceOf C
about "Reacting to traits", ->
they "should work", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model":
performs: (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should support shorthand functions", ->
class Trait
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
container.getClass().newProp = "newValue"
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Trait, Model]
cc.prepare()
expect(cc.instantiate('Model').constructor.newProp).to.equal "newValue"
they "should allow creation of repos", ->
class BaseRepo
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
class ModelFelange
@componentId: "Trait"
@componentType: "Felange"
@forTraits: "Model": (container, componentComposer) ->
cls = container.getClass()
cls.repo = "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
constructor: ->
BaseRepo.apply this, arguments
ModelRepo.prototype = Object.create BaseRepo.prototype
ModelRepo::constructor = BaseRepo
componentComposer.register ModelRepo
class Model
@componentId: "Model"
@componentType: "Instantiable"
@traits: ["Model"]
cc.register [Model, ModelFelange]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
about "Repos", ->
they "should work", ->
class Model
@componentId: "Model"
@componentType: "Instantiable"
@repo: "ModelRepo"
class ModelRepo
@componentId: "ModelRepo"
@componentType: "Singleton"
@deps: {"componentComposer": "ComponentComposer"}
constructor: ->
@_instances = {}
@_instantiator = null
_setInstantiator: (@_instantiator) ->
getInstance: ->
@componentComposer.instantiate "Model", arguments
_getOrCreateInstance: (id) ->
id = arguments[0]
if @_instances[id]?
return @_instances[id]
instance = @_instantiator.instantiate arguments
@_instances[id] = instance
instance
cc.register [Model, ModelRepo]
cc.prepare()
cc.instantiate("Model", [10]).should.equal cc.instantiate("Model", [10])
cc.instantiate("Model", [10]).should.equal cc.get("ModelRepo").getInstance(10)
cc.instantiate("Model", [11]).should.not.equal cc.get("ModelRepo").getInstance(10)
about "Method patching", ->
it "should only be allowed if method does exist", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should ensure invokation of patched functionality precedes original method's invokation", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches:
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
it "should support using attachment's methods instead of anonymous function", ->
text = ''
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
text += 'A'
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
patches: {"sayHi"}
sayHi: -> text += 'B'
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi()
text.should.equal "BA"
about "Method providing", ->
it "should only be allowed if no original method by the name exists", ->
class A
@componentId: "A"
@componentType: "Instantiable"
sayHi: ->
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: ->
cc.register [A, B]
cc.prepare()
(-> cc.instantiate("A")).should.throw()
it "should add functionality", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
it "should support using attachment's methods instead of anonymous function", ->
class A
@componentId: "A"
@componentType: "Instantiable"
class B
@componentId: "B"
@componentType: "Attachment"
@attachesTo: "A":
as: "b"
provides: {"sayHi"}
sayHi: -> "hi"
cc.register [A, B]
cc.prepare()
cc.instantiate("A").sayHi().should.equal "hi"
about "Accessing #ComponentComposer itself", ->
it "is possible by calling #ComponentComposer.get('ComponentComposer')", ->
cc.get("ComponentComposer").should.equal cc |
[
{
"context": "Quo Module\n\n@namespace Quo\n@class Element\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n",
"end": 82,
"score": 0.9998377561569214,
"start": 61,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "uo\n@class Elem... | source/quo.element.coffee | TNT-RoX/QuoJS | 1 | ###
Basic Quo Module
@namespace Quo
@class Element
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
$$.fn.rotateChildrenUp = ->
@insertBefore @lastElementChild, @firstElementChild
$$.fn.rotateChildrenDown = ->
@appendChild @removeChild(@firstElementChild)
$$.fn.moveUp = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.moveDown = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.scaleFont = ->
scaleFactor = 0.35
scaleSource = @offsetWidth
maxScale = 100
minScale = 1
fontSize = maxScale - (scaleSource * scaleFactor)
(if fontSize < minScale then fontSize = minScale else null))
@style.fontSize = fontSize + "%"
| 135757 | ###
Basic Quo Module
@namespace Quo
@class Element
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
$$.fn.rotateChildrenUp = ->
@insertBefore @lastElementChild, @firstElementChild
$$.fn.rotateChildrenDown = ->
@appendChild @removeChild(@firstElementChild)
$$.fn.moveUp = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.moveDown = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.scaleFont = ->
scaleFactor = 0.35
scaleSource = @offsetWidth
maxScale = 100
minScale = 1
fontSize = maxScale - (scaleSource * scaleFactor)
(if fontSize < minScale then fontSize = minScale else null))
@style.fontSize = fontSize + "%"
| true | ###
Basic Quo Module
@namespace Quo
@class Element
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
$$.fn.rotateChildrenUp = ->
@insertBefore @lastElementChild, @firstElementChild
$$.fn.rotateChildrenDown = ->
@appendChild @removeChild(@firstElementChild)
$$.fn.moveUp = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.moveDown = ->
@parentNode.insertBefore @parentNode.removeChild(this), @previousElementSibling
$$.fn.scaleFont = ->
scaleFactor = 0.35
scaleSource = @offsetWidth
maxScale = 100
minScale = 1
fontSize = maxScale - (scaleSource * scaleFactor)
(if fontSize < minScale then fontSize = minScale else null))
@style.fontSize = fontSize + "%"
|
[
{
"context": " API.server + '/' + key\n\n get: (key) ->\n key = genKey key\n value = localStorage.getItem key\n JSON",
"end": 188,
"score": 0.48933202028274536,
"start": 182,
"tag": "KEY",
"value": "genKey"
},
{
"context": "SON.parse(value)\n\n set: (key, value) ->\n ke... | www/app/commom/services/storage.service.coffee | ouzhenkun/ionic-nodeclub | 1 | angular.module('ionic-nodeclub')
.factory 'storage', ($window, API) ->
localStorage = $window.localStorage
genKey = (key) -> API.server + '/' + key
get: (key) ->
key = genKey key
value = localStorage.getItem key
JSON.parse(value)
set: (key, value) ->
key = genKey key
value = JSON.stringify value
localStorage.setItem(key, value)
remove: (key) ->
key = genKey key
localStorage.removeItem key
| 169699 | angular.module('ionic-nodeclub')
.factory 'storage', ($window, API) ->
localStorage = $window.localStorage
genKey = (key) -> API.server + '/' + key
get: (key) ->
key = <KEY> key
value = localStorage.getItem key
JSON.parse(value)
set: (key, value) ->
key = <KEY>Key key
value = JSON.stringify value
localStorage.setItem(key, value)
remove: (key) ->
key = <KEY>Key key
localStorage.removeItem key
| true | angular.module('ionic-nodeclub')
.factory 'storage', ($window, API) ->
localStorage = $window.localStorage
genKey = (key) -> API.server + '/' + key
get: (key) ->
key = PI:KEY:<KEY>END_PI key
value = localStorage.getItem key
JSON.parse(value)
set: (key, value) ->
key = PI:KEY:<KEY>END_PIKey key
value = JSON.stringify value
localStorage.setItem(key, value)
remove: (key) ->
key = PI:KEY:<KEY>END_PIKey key
localStorage.removeItem key
|
[
{
"context": "models.asset, 8\n assets.create({id:'7777', name:'aardvark',status:'active'});\n assets.create({id:'8888', n",
"end": 173,
"score": 0.9996359348297119,
"start": 165,
"tag": "NAME",
"value": "aardvark"
},
{
"context": "tus:'active'});\n assets.create({id:'8888', name:... | examples/assets/spec/backend.coffee | codekoala/glujs | 4 | (glu.ns 'examples.assets').createMockBackend = (auto, recordNum)->
assets = glu.test.createTable examples.assets.models.asset, 8
assets.create({id:'7777', name:'aardvark',status:'active'});
assets.create({id:'8888', name:'aare',status:'active'});
assets.create({id:'9999', name:'aarf',status:'active'});
backend = glu.test.createBackend
defaultRoot: '/json/',
fallbackToAjax: auto,
autoRespond: auto,
routes:
'removeAssets':
url: 'assets/action/remove',
handle: (req) -> assets.remove req.params.ids
,
'requestVerification':
url: 'assets/action/requestVerification',
handle: (req) -> assets.update req.params.ids , {status:'verifying'}
,
#TODO: Support "put" method
'assetSave':
url: 'assets/:id/action/save',
handle: (req) -> assets.replace req.params.id , req.jsonData
,
'assets':
url: 'assets',
handle: (req) -> assets.list req.params
,
'asset':
url: 'assets/:id',
handle: (req) -> assets.get req.params.id
backend.capture()
return {backend: backend, assets: assets}
| 65957 | (glu.ns 'examples.assets').createMockBackend = (auto, recordNum)->
assets = glu.test.createTable examples.assets.models.asset, 8
assets.create({id:'7777', name:'<NAME>',status:'active'});
assets.create({id:'8888', name:'<NAME>',status:'active'});
assets.create({id:'9999', name:'<NAME>',status:'active'});
backend = glu.test.createBackend
defaultRoot: '/json/',
fallbackToAjax: auto,
autoRespond: auto,
routes:
'removeAssets':
url: 'assets/action/remove',
handle: (req) -> assets.remove req.params.ids
,
'requestVerification':
url: 'assets/action/requestVerification',
handle: (req) -> assets.update req.params.ids , {status:'verifying'}
,
#TODO: Support "put" method
'assetSave':
url: 'assets/:id/action/save',
handle: (req) -> assets.replace req.params.id , req.jsonData
,
'assets':
url: 'assets',
handle: (req) -> assets.list req.params
,
'asset':
url: 'assets/:id',
handle: (req) -> assets.get req.params.id
backend.capture()
return {backend: backend, assets: assets}
| true | (glu.ns 'examples.assets').createMockBackend = (auto, recordNum)->
assets = glu.test.createTable examples.assets.models.asset, 8
assets.create({id:'7777', name:'PI:NAME:<NAME>END_PI',status:'active'});
assets.create({id:'8888', name:'PI:NAME:<NAME>END_PI',status:'active'});
assets.create({id:'9999', name:'PI:NAME:<NAME>END_PI',status:'active'});
backend = glu.test.createBackend
defaultRoot: '/json/',
fallbackToAjax: auto,
autoRespond: auto,
routes:
'removeAssets':
url: 'assets/action/remove',
handle: (req) -> assets.remove req.params.ids
,
'requestVerification':
url: 'assets/action/requestVerification',
handle: (req) -> assets.update req.params.ids , {status:'verifying'}
,
#TODO: Support "put" method
'assetSave':
url: 'assets/:id/action/save',
handle: (req) -> assets.replace req.params.id , req.jsonData
,
'assets':
url: 'assets',
handle: (req) -> assets.list req.params
,
'asset':
url: 'assets/:id',
handle: (req) -> assets.get req.params.id
backend.capture()
return {backend: backend, assets: assets}
|
[
{
"context": "rats = {}\n\n\n\nstrats.meanbot = (v) -> \n \n name: 'meanie'\n frames: required_frames(v.long_weight) \n\n # r",
"end": 338,
"score": 0.9369126558303833,
"start": 332,
"tag": "USERNAME",
"value": "meanie"
},
{
"context": " true\n exit_if_entry_empty_after: 60\n\... | example_project/strategies.coffee | invisible-college/meth | 7 | # Your trading strategies
# This file has a bunch of trading strategies which don't work very well, but
# may help you know what is possible. Apologies for lack of documentation
# beyond the code itself.
require '../shared'
series = require '../strategizer'
module.exports = strats = {}
strats.meanbot = (v) ->
name: 'meanie'
frames: required_frames(v.long_weight)
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: Math.to_precision(v.long_weight, 1)
short = f.price weight: Math.to_precision(v.short_weight, 1)
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
trending_up = long < short
min = f.min_price(); max = f.max_price(); last = f.last_price()
if trending_up
sell_at = max - Math.to_precision(v.backoff, 1) * (max - short)
buy_at = short
else
buy_at = min + Math.to_precision(v.backoff, 1) * (short - min)
sell_at = short
buy_at = Math.min last, buy_at
sell_at = Math.max last, sell_at
if v.ratio # enforce trading within a ratio if desired
args.buy = trending_up
allowed = allowable_entries args, v.ratio
return null if (!trending_up && !allowed.sell) || (trending_up && !allowed.buy)
pos =
sell:
rate: sell_at
entry: !trending_up
amount: get_amount(args)
buy:
rate: buy_at
entry: trending_up
amount: get_amount(args)
return pos
null
evaluate_open_position: strats.evaluate_open_position
strats.pure_rebalance = (v) ->
# v has:
# ratio: the ETH/BTC ratio to maintain
# thresh: the % threshold overwhich a rebalance is needed
# frequency: the number of minutes separating rebalancing can happen
# period: price aggregation to rebalance against
# mark_when_changed: if true, system considers a rebalancing event only to occur
# when system determines it is needed. If false, system considers
# a rebalancing event to have occurred when it is checked just
# after it is due.
# rebalance_to_threshold: if true, rebalances the accounts just back to the ratio + thresh.
# if false, rebalances all the way back to ratio
v = defaults v,
ratio: .5
thresh: .04
frequency: 24 * 60 * 60 # per day
period: .5
mark_when_changed: false
rebalance_to_threshold: false
never_exits: true
exit_if_entry_empty_after: 60
name: 'pure_rebalance'
frames: required_frames(Math.min(v.period,(v.ADX_weight or 1), (v.velocity_weight or 1), (v.volume_weight or 1)))
max_t2: 1
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
dealer = args.dealer
dealer_data = dealers[dealer]
dealer_balance = args.balance[dealer].balances
if !dealer_data.last_rebalanced || dealer_data.last_rebalanced < tick.time - v.frequency
if !v.mark_when_changed
dealer_data.last_rebalanced = tick.time
price = f.price weight: Math.to_precision(v.period, 1)
vETH = dealer_balance.c2
vBTC = dealer_balance.c1 / price
if Math.abs(vETH / (vETH + vBTC) - v.ratio) > v.thresh
deth = v.ratio * (vETH + vBTC) - vETH
buy = sell_enters = deth > 0
if v.mark_when_changed
dealer_data.last_rebalanced = tick.time
if buy # need to buy deth ETH
if v.rebalance_to_threshold
deth -= v.thresh * (vETH + vBTC)
pos =
buy:
rate: f.last_price() - .002 * f.last_price()
entry: true
amount: deth
else
if v.rebalance_to_threshold
deth += v.thresh * (vETH + vBTC)
pos =
sell:
rate: f.last_price() + .002 * f.last_price()
entry: true
amount: -deth
return pos
null
evaluate_open_position: (args) ->
pos = args.position
v = get_settings(pos.dealer)
# console.log pos.dealer, v.exit_if_entry_empty_after
# try to get out of this position since it couldn't enter properly
if v.exit_if_entry_empty_after? && v.exit_if_entry_empty_after < 9999 && \
pos.entry.fills.length == 0 && pos.exit.fills.length == 0 && \
tick.time - pos.created > v.exit_if_entry_empty_after * 60
return {action: 'cancel_unfilled'}
strats.RSI = (v) ->
alpha = 1 / v.periods
name: 'RSI'
frames: Math.max(v.periods, required_frames(alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
RSI = f.RSI {weight: alpha, t: 0}
is_high = RSI > 100 - v.thresh
is_low = RSI < v.thresh
previous_RSI = f.RSI {weight: alpha, t: 1}
crossed_high = !is_high && previous_RSI > 100 - v.thresh
crossed_low = !is_low && previous_RSI < v.thresh
crossed_into_high = RSI > 100 - v.thresh - v.opportune_thresh && previous_RSI < 100 - v.thresh - v.opportune_thresh
crossed_into_low = RSI < v.thresh + v.opportune_thresh && previous_RSI > v.thresh + v.opportune_thresh
action = null
# overbought
if crossed_high
action = 'sell'
# oversold
else if crossed_low
action = 'buy'
else if v.buy_in
if crossed_into_high
action = 'buy'
else if crossed_into_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
evaluate_open_position: (args) ->
pos = args.position
f = args.features
if cancel_unfilled(v, pos)
return {action: 'cancel_unfilled'}
if !v.never_exits
exit = false
action = strats.RSI(v).eval_whether_to_enter_new_position(args)
if action
entry = action.buy or action.sell
if action?.buy && pos.entry.type == 'sell' && \
entry.rate + entry.rate * (v.greed or 0) < pos.entry.rate
exit = true
if action?.sell && pos.entry.type == 'buy' && \
entry.rate - entry.rate * (v.greed or 0) > pos.entry.rate
exit = true
return {action: 'exit', rate: f.last_price()} if exit
strats.RSIxADX = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_up = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_up'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_down = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_down'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxDI = (v) ->
fast_alpha = 1 / v.fast_periods
slow_alpha = 1 / v.slow_periods
name: 'RSIxDI'
frames: v.slow_periods + 2 #required_frames(slow_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
DI_plus = f.DI_plus {weight: slow_alpha, t: 0}
DI_minus = f.DI_minus {weight: slow_alpha, t: 0}
prev_DI_plus = f.DI_plus {weight: slow_alpha, t: 1}
prev_DI_minus = f.DI_minus {weight: slow_alpha, t: 1}
RSI = f.RSI {weight: fast_alpha, t: 0}
RSI_is_high = RSI > 100 - v.RSI_thresh
RSI_is_low = RSI < v.RSI_thresh
DI_crossed_low = DI_plus < DI_minus && prev_DI_plus > prev_DI_minus
DI_crossed_up = DI_plus > DI_minus && prev_DI_plus < prev_DI_minus
action = null
# let's buy into this emerging up trend!
if DI_crossed_up && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if DI_crossed_low && RSI_is_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.ADX_cross = (v) ->
ADX_alpha = v.alpha
name: 'ADX_cross'
frames: required_frames(ADX_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
ADX = f.ADX({weight: ADX_alpha})
prev_ADX = f.ADX({t: 1, weight: ADX_alpha})
trending = ADX > v.ADX_thresh
prev_trending = prev_ADX > v.ADX_thresh
action = null
if trending || prev_trending
trending_up = f.DM_plus({weight: ADX_alpha, t: 0}) > f.DM_minus({weight: ADX_alpha, t: 0})
prev_trending_up = f.DM_plus({weight: ADX_alpha, t: 1}) > f.DM_minus({weight: ADX_alpha, t: 1})
if trending && (!prev_trending || trending_up != prev_trending_up)
action = if trending_up then 'buy' else 'sell'
else if !trending && prev_trending
action = if prev_trending_up then 'sell' else 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.DM_crossover = (v) ->
alpha = v.weight
name: 'DM_crossover'
frames: required_frames(alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
cur = f.DM_plus({weight: alpha, t: 0}) - f.DM_minus({weight: alpha, t: 0})
```
key = `${f.last}-${f.last}-${alpha}-`
```
return if !f.cache.DM_plus[key]? || !f.cache.DM_minus[key]?
prev = f.cache.DM_plus[key] - f.cache.DM_minus[key]
bear_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'buy' in (p.entry.type for p in args.open_positions))
bull_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'sell' in (p.entry.type for p in args.open_positions))
action = null
# let's buy into this emerging up trend!
if bull_cross # && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if bear_cross # && RSI_is_low
action = 'sell'
if action && action not in (p.entry.type for p in args.open_positions)
last = f.last_price()
pos = {}
pos[action] =
entry: true
rate: last
amount: if action == 'buy' then .4 * args.balance[args.dealer].balances.c1 / last else .4 * args.balance[args.dealer].balances.c2
flags:
market: true
return pos
evaluate_open_position: (args) -> null
strats.crossover = (v) ->
frames: required_frames(Math.min(v.long_weight, v.short_weight)) + 2
max_t2: (v.num_consecutive or 0) + 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
last = f.last_price()
opts =
f: f[v.feature]
f_weight: v.short_weight
num_consecutive: v.num_consecutive
f2: f[v.feature]
f2_weight: v.long_weight
pos = null
if v.predict_long
act1 = 'buy'
act2 = 'sell'
else
act1 = 'sell'
act2 = 'buy'
if crossover(false , opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act1
closer ||= o.entry.type != act1 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act1] =
rate: last
entry: true
amount: get_amount(args)
return pos
else if crossover(true, opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act2
closer ||= o.entry.type != act2 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act2] =
rate: last
entry: true
amount: get_amount(args)
return pos
strats.gunslinger = (v) ->
defaults:
minimum_separation: 0
resolution: v.frame * 60
frames: required_frames(v.long_weight)
position_amount: get_amount
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: v.long_weight
short = f.price weight: v.short_weight
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
last = f.last_price()
accel = f.acceleration weight: (Math.to_precision(v.accel_weight) or .8)
vel = f.velocity weight: (Math.to_precision(v.vel_weight) or .8)
if vel > 0 && accel > 0 && short > long
sell_at = last + v.greed
buy_at = last
pos =
sell:
rate: sell_at
amount: get_amount(args)
buy:
rate: buy_at
entry: true
amount: get_amount(args)
else if vel < 0 && accel < 0 && short < long
buy_at = last - v.greed
sell_at = last
pos =
sell:
rate: sell_at
entry: true
amount: get_amount(args)
buy:
rate: buy_at
amount: get_amount(args)
evaluate_open_position: strats.evaluate_open_position
| 69566 | # Your trading strategies
# This file has a bunch of trading strategies which don't work very well, but
# may help you know what is possible. Apologies for lack of documentation
# beyond the code itself.
require '../shared'
series = require '../strategizer'
module.exports = strats = {}
strats.meanbot = (v) ->
name: 'meanie'
frames: required_frames(v.long_weight)
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: Math.to_precision(v.long_weight, 1)
short = f.price weight: Math.to_precision(v.short_weight, 1)
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
trending_up = long < short
min = f.min_price(); max = f.max_price(); last = f.last_price()
if trending_up
sell_at = max - Math.to_precision(v.backoff, 1) * (max - short)
buy_at = short
else
buy_at = min + Math.to_precision(v.backoff, 1) * (short - min)
sell_at = short
buy_at = Math.min last, buy_at
sell_at = Math.max last, sell_at
if v.ratio # enforce trading within a ratio if desired
args.buy = trending_up
allowed = allowable_entries args, v.ratio
return null if (!trending_up && !allowed.sell) || (trending_up && !allowed.buy)
pos =
sell:
rate: sell_at
entry: !trending_up
amount: get_amount(args)
buy:
rate: buy_at
entry: trending_up
amount: get_amount(args)
return pos
null
evaluate_open_position: strats.evaluate_open_position
strats.pure_rebalance = (v) ->
# v has:
# ratio: the ETH/BTC ratio to maintain
# thresh: the % threshold overwhich a rebalance is needed
# frequency: the number of minutes separating rebalancing can happen
# period: price aggregation to rebalance against
# mark_when_changed: if true, system considers a rebalancing event only to occur
# when system determines it is needed. If false, system considers
# a rebalancing event to have occurred when it is checked just
# after it is due.
# rebalance_to_threshold: if true, rebalances the accounts just back to the ratio + thresh.
# if false, rebalances all the way back to ratio
v = defaults v,
ratio: .5
thresh: .04
frequency: 24 * 60 * 60 # per day
period: .5
mark_when_changed: false
rebalance_to_threshold: false
never_exits: true
exit_if_entry_empty_after: 60
name: 'pure_rebalance'
frames: required_frames(Math.min(v.period,(v.ADX_weight or 1), (v.velocity_weight or 1), (v.volume_weight or 1)))
max_t2: 1
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
dealer = args.dealer
dealer_data = dealers[dealer]
dealer_balance = args.balance[dealer].balances
if !dealer_data.last_rebalanced || dealer_data.last_rebalanced < tick.time - v.frequency
if !v.mark_when_changed
dealer_data.last_rebalanced = tick.time
price = f.price weight: Math.to_precision(v.period, 1)
vETH = dealer_balance.c2
vBTC = dealer_balance.c1 / price
if Math.abs(vETH / (vETH + vBTC) - v.ratio) > v.thresh
deth = v.ratio * (vETH + vBTC) - vETH
buy = sell_enters = deth > 0
if v.mark_when_changed
dealer_data.last_rebalanced = tick.time
if buy # need to buy deth ETH
if v.rebalance_to_threshold
deth -= v.thresh * (vETH + vBTC)
pos =
buy:
rate: f.last_price() - .002 * f.last_price()
entry: true
amount: deth
else
if v.rebalance_to_threshold
deth += v.thresh * (vETH + vBTC)
pos =
sell:
rate: f.last_price() + .002 * f.last_price()
entry: true
amount: -deth
return pos
null
evaluate_open_position: (args) ->
pos = args.position
v = get_settings(pos.dealer)
# console.log pos.dealer, v.exit_if_entry_empty_after
# try to get out of this position since it couldn't enter properly
if v.exit_if_entry_empty_after? && v.exit_if_entry_empty_after < 9999 && \
pos.entry.fills.length == 0 && pos.exit.fills.length == 0 && \
tick.time - pos.created > v.exit_if_entry_empty_after * 60
return {action: 'cancel_unfilled'}
strats.RSI = (v) ->
alpha = 1 / v.periods
name: '<NAME>SI'
frames: Math.max(v.periods, required_frames(alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
RSI = f.RSI {weight: alpha, t: 0}
is_high = RSI > 100 - v.thresh
is_low = RSI < v.thresh
previous_RSI = f.RSI {weight: alpha, t: 1}
crossed_high = !is_high && previous_RSI > 100 - v.thresh
crossed_low = !is_low && previous_RSI < v.thresh
crossed_into_high = RSI > 100 - v.thresh - v.opportune_thresh && previous_RSI < 100 - v.thresh - v.opportune_thresh
crossed_into_low = RSI < v.thresh + v.opportune_thresh && previous_RSI > v.thresh + v.opportune_thresh
action = null
# overbought
if crossed_high
action = 'sell'
# oversold
else if crossed_low
action = 'buy'
else if v.buy_in
if crossed_into_high
action = 'buy'
else if crossed_into_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
evaluate_open_position: (args) ->
pos = args.position
f = args.features
if cancel_unfilled(v, pos)
return {action: 'cancel_unfilled'}
if !v.never_exits
exit = false
action = strats.RSI(v).eval_whether_to_enter_new_position(args)
if action
entry = action.buy or action.sell
if action?.buy && pos.entry.type == 'sell' && \
entry.rate + entry.rate * (v.greed or 0) < pos.entry.rate
exit = true
if action?.sell && pos.entry.type == 'buy' && \
entry.rate - entry.rate * (v.greed or 0) > pos.entry.rate
exit = true
return {action: 'exit', rate: f.last_price()} if exit
strats.RSIxADX = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_up = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_up'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_down = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_down'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxDI = (v) ->
fast_alpha = 1 / v.fast_periods
slow_alpha = 1 / v.slow_periods
name: 'RSIxDI'
frames: v.slow_periods + 2 #required_frames(slow_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
DI_plus = f.DI_plus {weight: slow_alpha, t: 0}
DI_minus = f.DI_minus {weight: slow_alpha, t: 0}
prev_DI_plus = f.DI_plus {weight: slow_alpha, t: 1}
prev_DI_minus = f.DI_minus {weight: slow_alpha, t: 1}
RSI = f.RSI {weight: fast_alpha, t: 0}
RSI_is_high = RSI > 100 - v.RSI_thresh
RSI_is_low = RSI < v.RSI_thresh
DI_crossed_low = DI_plus < DI_minus && prev_DI_plus > prev_DI_minus
DI_crossed_up = DI_plus > DI_minus && prev_DI_plus < prev_DI_minus
action = null
# let's buy into this emerging up trend!
if DI_crossed_up && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if DI_crossed_low && RSI_is_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.ADX_cross = (v) ->
ADX_alpha = v.alpha
name: 'ADX_cross'
frames: required_frames(ADX_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
ADX = f.ADX({weight: ADX_alpha})
prev_ADX = f.ADX({t: 1, weight: ADX_alpha})
trending = ADX > v.ADX_thresh
prev_trending = prev_ADX > v.ADX_thresh
action = null
if trending || prev_trending
trending_up = f.DM_plus({weight: ADX_alpha, t: 0}) > f.DM_minus({weight: ADX_alpha, t: 0})
prev_trending_up = f.DM_plus({weight: ADX_alpha, t: 1}) > f.DM_minus({weight: ADX_alpha, t: 1})
if trending && (!prev_trending || trending_up != prev_trending_up)
action = if trending_up then 'buy' else 'sell'
else if !trending && prev_trending
action = if prev_trending_up then 'sell' else 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.DM_crossover = (v) ->
alpha = v.weight
name: 'DM_crossover'
frames: required_frames(alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
cur = f.DM_plus({weight: alpha, t: 0}) - f.DM_minus({weight: alpha, t: 0})
```
key = <KEY>`
```
return if !f.cache.DM_plus[key]? || !f.cache.DM_minus[key]?
prev = f.cache.DM_plus[key] - f.cache.DM_minus[key]
bear_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'buy' in (p.entry.type for p in args.open_positions))
bull_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'sell' in (p.entry.type for p in args.open_positions))
action = null
# let's buy into this emerging up trend!
if bull_cross # && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if bear_cross # && RSI_is_low
action = 'sell'
if action && action not in (p.entry.type for p in args.open_positions)
last = f.last_price()
pos = {}
pos[action] =
entry: true
rate: last
amount: if action == 'buy' then .4 * args.balance[args.dealer].balances.c1 / last else .4 * args.balance[args.dealer].balances.c2
flags:
market: true
return pos
evaluate_open_position: (args) -> null
strats.crossover = (v) ->
frames: required_frames(Math.min(v.long_weight, v.short_weight)) + 2
max_t2: (v.num_consecutive or 0) + 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
last = f.last_price()
opts =
f: f[v.feature]
f_weight: v.short_weight
num_consecutive: v.num_consecutive
f2: f[v.feature]
f2_weight: v.long_weight
pos = null
if v.predict_long
act1 = 'buy'
act2 = 'sell'
else
act1 = 'sell'
act2 = 'buy'
if crossover(false , opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act1
closer ||= o.entry.type != act1 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act1] =
rate: last
entry: true
amount: get_amount(args)
return pos
else if crossover(true, opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act2
closer ||= o.entry.type != act2 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act2] =
rate: last
entry: true
amount: get_amount(args)
return pos
strats.gunslinger = (v) ->
defaults:
minimum_separation: 0
resolution: v.frame * 60
frames: required_frames(v.long_weight)
position_amount: get_amount
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: v.long_weight
short = f.price weight: v.short_weight
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
last = f.last_price()
accel = f.acceleration weight: (Math.to_precision(v.accel_weight) or .8)
vel = f.velocity weight: (Math.to_precision(v.vel_weight) or .8)
if vel > 0 && accel > 0 && short > long
sell_at = last + v.greed
buy_at = last
pos =
sell:
rate: sell_at
amount: get_amount(args)
buy:
rate: buy_at
entry: true
amount: get_amount(args)
else if vel < 0 && accel < 0 && short < long
buy_at = last - v.greed
sell_at = last
pos =
sell:
rate: sell_at
entry: true
amount: get_amount(args)
buy:
rate: buy_at
amount: get_amount(args)
evaluate_open_position: strats.evaluate_open_position
| true | # Your trading strategies
# This file has a bunch of trading strategies which don't work very well, but
# may help you know what is possible. Apologies for lack of documentation
# beyond the code itself.
require '../shared'
series = require '../strategizer'
module.exports = strats = {}
strats.meanbot = (v) ->
name: 'meanie'
frames: required_frames(v.long_weight)
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: Math.to_precision(v.long_weight, 1)
short = f.price weight: Math.to_precision(v.short_weight, 1)
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
trending_up = long < short
min = f.min_price(); max = f.max_price(); last = f.last_price()
if trending_up
sell_at = max - Math.to_precision(v.backoff, 1) * (max - short)
buy_at = short
else
buy_at = min + Math.to_precision(v.backoff, 1) * (short - min)
sell_at = short
buy_at = Math.min last, buy_at
sell_at = Math.max last, sell_at
if v.ratio # enforce trading within a ratio if desired
args.buy = trending_up
allowed = allowable_entries args, v.ratio
return null if (!trending_up && !allowed.sell) || (trending_up && !allowed.buy)
pos =
sell:
rate: sell_at
entry: !trending_up
amount: get_amount(args)
buy:
rate: buy_at
entry: trending_up
amount: get_amount(args)
return pos
null
evaluate_open_position: strats.evaluate_open_position
strats.pure_rebalance = (v) ->
# v has:
# ratio: the ETH/BTC ratio to maintain
# thresh: the % threshold overwhich a rebalance is needed
# frequency: the number of minutes separating rebalancing can happen
# period: price aggregation to rebalance against
# mark_when_changed: if true, system considers a rebalancing event only to occur
# when system determines it is needed. If false, system considers
# a rebalancing event to have occurred when it is checked just
# after it is due.
# rebalance_to_threshold: if true, rebalances the accounts just back to the ratio + thresh.
# if false, rebalances all the way back to ratio
v = defaults v,
ratio: .5
thresh: .04
frequency: 24 * 60 * 60 # per day
period: .5
mark_when_changed: false
rebalance_to_threshold: false
never_exits: true
exit_if_entry_empty_after: 60
name: 'pure_rebalance'
frames: required_frames(Math.min(v.period,(v.ADX_weight or 1), (v.velocity_weight or 1), (v.volume_weight or 1)))
max_t2: 1
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
dealer = args.dealer
dealer_data = dealers[dealer]
dealer_balance = args.balance[dealer].balances
if !dealer_data.last_rebalanced || dealer_data.last_rebalanced < tick.time - v.frequency
if !v.mark_when_changed
dealer_data.last_rebalanced = tick.time
price = f.price weight: Math.to_precision(v.period, 1)
vETH = dealer_balance.c2
vBTC = dealer_balance.c1 / price
if Math.abs(vETH / (vETH + vBTC) - v.ratio) > v.thresh
deth = v.ratio * (vETH + vBTC) - vETH
buy = sell_enters = deth > 0
if v.mark_when_changed
dealer_data.last_rebalanced = tick.time
if buy # need to buy deth ETH
if v.rebalance_to_threshold
deth -= v.thresh * (vETH + vBTC)
pos =
buy:
rate: f.last_price() - .002 * f.last_price()
entry: true
amount: deth
else
if v.rebalance_to_threshold
deth += v.thresh * (vETH + vBTC)
pos =
sell:
rate: f.last_price() + .002 * f.last_price()
entry: true
amount: -deth
return pos
null
evaluate_open_position: (args) ->
pos = args.position
v = get_settings(pos.dealer)
# console.log pos.dealer, v.exit_if_entry_empty_after
# try to get out of this position since it couldn't enter properly
if v.exit_if_entry_empty_after? && v.exit_if_entry_empty_after < 9999 && \
pos.entry.fills.length == 0 && pos.exit.fills.length == 0 && \
tick.time - pos.created > v.exit_if_entry_empty_after * 60
return {action: 'cancel_unfilled'}
strats.RSI = (v) ->
alpha = 1 / v.periods
name: 'PI:NAME:<NAME>END_PISI'
frames: Math.max(v.periods, required_frames(alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
RSI = f.RSI {weight: alpha, t: 0}
is_high = RSI > 100 - v.thresh
is_low = RSI < v.thresh
previous_RSI = f.RSI {weight: alpha, t: 1}
crossed_high = !is_high && previous_RSI > 100 - v.thresh
crossed_low = !is_low && previous_RSI < v.thresh
crossed_into_high = RSI > 100 - v.thresh - v.opportune_thresh && previous_RSI < 100 - v.thresh - v.opportune_thresh
crossed_into_low = RSI < v.thresh + v.opportune_thresh && previous_RSI > v.thresh + v.opportune_thresh
action = null
# overbought
if crossed_high
action = 'sell'
# oversold
else if crossed_low
action = 'buy'
else if v.buy_in
if crossed_into_high
action = 'buy'
else if crossed_into_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
evaluate_open_position: (args) ->
pos = args.position
f = args.features
if cancel_unfilled(v, pos)
return {action: 'cancel_unfilled'}
if !v.never_exits
exit = false
action = strats.RSI(v).eval_whether_to_enter_new_position(args)
if action
entry = action.buy or action.sell
if action?.buy && pos.entry.type == 'sell' && \
entry.rate + entry.rate * (v.greed or 0) < pos.entry.rate
exit = true
if action?.sell && pos.entry.type == 'buy' && \
entry.rate - entry.rate * (v.greed or 0) > pos.entry.rate
exit = true
return {action: 'exit', rate: f.last_price()} if exit
strats.RSIxADX = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_up = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_up'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && trending_up
# RSI goes over some lower thresh that is confirmed by ADX trending signal
if RSI > 100 - trending_thresh && \
prev_RSI < 100 - trending_thresh
action = 'buy'
# We might be slightly overbought, take a moment to sell off
else if RSI < 100 - opportune_thresh &&
prev_RSI > 100 - opportune_thresh
action = 'sell'
# No discernable trend and RSI is showing overbought
else if (!trending || !trending_up) && \
RSI > 100 - over_thresh && \
prev_RSI < 100 - over_thresh
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxADX_down = (v) ->
ADX_alpha = v.ADX_alpha
RSI_alpha = v.RSI_alpha
trending_thresh = v.trending_thresh
opportune_thresh = v.opportune_thresh
over_thresh = v.over_thresh
name: 'RSIxADX_down'
frames: required_frames(Math.min(ADX_alpha, RSI_alpha)) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
action = null
RSI = f.RSI {weight: RSI_alpha, t: 0}
prev_RSI = f.RSI {weight: RSI_alpha, t: 1}
ADX = f.ADX({weight: ADX_alpha})
trending = ADX > v.ADX_thresh
if trending
trending_up = f.DI_plus({weight: ADX_alpha, t: 0}) > f.DI_minus({weight: ADX_alpha, t: 0})
if trending && !trending_up
# RSI goes under some high thresh that is confirmed by ADX trending signal
if RSI < trending_thresh && \
prev_RSI > trending_thresh
action = 'sell'
# We might be slightly oversold, take a moment to sell off
else if RSI > opportune_thresh &&
prev_RSI < opportune_thresh
action = 'buy'
# # No discernable trend and RSI is showing overbought
else if (!trending || trending_up) && \
RSI < over_thresh && \
prev_RSI > over_thresh
action = 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.RSIxDI = (v) ->
fast_alpha = 1 / v.fast_periods
slow_alpha = 1 / v.slow_periods
name: 'RSIxDI'
frames: v.slow_periods + 2 #required_frames(slow_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
DI_plus = f.DI_plus {weight: slow_alpha, t: 0}
DI_minus = f.DI_minus {weight: slow_alpha, t: 0}
prev_DI_plus = f.DI_plus {weight: slow_alpha, t: 1}
prev_DI_minus = f.DI_minus {weight: slow_alpha, t: 1}
RSI = f.RSI {weight: fast_alpha, t: 0}
RSI_is_high = RSI > 100 - v.RSI_thresh
RSI_is_low = RSI < v.RSI_thresh
DI_crossed_low = DI_plus < DI_minus && prev_DI_plus > prev_DI_minus
DI_crossed_up = DI_plus > DI_minus && prev_DI_plus < prev_DI_minus
action = null
# let's buy into this emerging up trend!
if DI_crossed_up && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if DI_crossed_low && RSI_is_low
action = 'sell'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.ADX_cross = (v) ->
ADX_alpha = v.alpha
name: 'ADX_cross'
frames: required_frames(ADX_alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
ADX = f.ADX({weight: ADX_alpha})
prev_ADX = f.ADX({t: 1, weight: ADX_alpha})
trending = ADX > v.ADX_thresh
prev_trending = prev_ADX > v.ADX_thresh
action = null
if trending || prev_trending
trending_up = f.DM_plus({weight: ADX_alpha, t: 0}) > f.DM_minus({weight: ADX_alpha, t: 0})
prev_trending_up = f.DM_plus({weight: ADX_alpha, t: 1}) > f.DM_minus({weight: ADX_alpha, t: 1})
if trending && (!prev_trending || trending_up != prev_trending_up)
action = if trending_up then 'buy' else 'sell'
else if !trending && prev_trending
action = if prev_trending_up then 'sell' else 'buy'
if action && (!v.clear_signal || open.length == 0 || open[open.length - 1].entry.type != action || open.length == 1 || open[open.length - 2].entry.type != action)
pos = {}
pos[action] =
entry: true
rate: f.last_price()
amount: get_amount(args)
return pos
strats.DM_crossover = (v) ->
alpha = v.weight
name: 'DM_crossover'
frames: required_frames(alpha) + 2
max_t2: 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
cur = f.DM_plus({weight: alpha, t: 0}) - f.DM_minus({weight: alpha, t: 0})
```
key = PI:KEY:<KEY>END_PI`
```
return if !f.cache.DM_plus[key]? || !f.cache.DM_minus[key]?
prev = f.cache.DM_plus[key] - f.cache.DM_minus[key]
bear_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'buy' in (p.entry.type for p in args.open_positions))
bull_cross = (cur > 0 && prev <= 0) || (cur == prev == 0 && 'sell' in (p.entry.type for p in args.open_positions))
action = null
# let's buy into this emerging up trend!
if bull_cross # && RSI_is_high
action = 'buy'
# let's sell into this emerging down trend!
else if bear_cross # && RSI_is_low
action = 'sell'
if action && action not in (p.entry.type for p in args.open_positions)
last = f.last_price()
pos = {}
pos[action] =
entry: true
rate: last
amount: if action == 'buy' then .4 * args.balance[args.dealer].balances.c1 / last else .4 * args.balance[args.dealer].balances.c2
flags:
market: true
return pos
evaluate_open_position: (args) -> null
strats.crossover = (v) ->
frames: required_frames(Math.min(v.long_weight, v.short_weight)) + 2
max_t2: (v.num_consecutive or 0) + 1
eval_whether_to_enter_new_position: (args) ->
f = args.features
open = args.open_positions
last = f.last_price()
opts =
f: f[v.feature]
f_weight: v.short_weight
num_consecutive: v.num_consecutive
f2: f[v.feature]
f2_weight: v.long_weight
pos = null
if v.predict_long
act1 = 'buy'
act2 = 'sell'
else
act1 = 'sell'
act2 = 'buy'
if crossover(false , opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act1
closer ||= o.entry.type != act1 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act1] =
rate: last
entry: true
amount: get_amount(args)
return pos
else if crossover(true, opts)
if v.clear_signal
duplicate = false
closer = false
for o in open
duplicate ||= o.entry.type == act2
closer ||= o.entry.type != act2 && !o.exit
if !v.clear_signal || !duplicate || closer
pos = {}
pos[act2] =
rate: last
entry: true
amount: get_amount(args)
return pos
strats.gunslinger = (v) ->
defaults:
minimum_separation: 0
resolution: v.frame * 60
frames: required_frames(v.long_weight)
position_amount: get_amount
# return a new position if this strategy determines it is a good time to do so
eval_whether_to_enter_new_position: (args) ->
f = args.features
long = f.price weight: v.long_weight
short = f.price weight: v.short_weight
plateau = Math.abs(long - short) / long < v.plateau_thresh
if !plateau
last = f.last_price()
accel = f.acceleration weight: (Math.to_precision(v.accel_weight) or .8)
vel = f.velocity weight: (Math.to_precision(v.vel_weight) or .8)
if vel > 0 && accel > 0 && short > long
sell_at = last + v.greed
buy_at = last
pos =
sell:
rate: sell_at
amount: get_amount(args)
buy:
rate: buy_at
entry: true
amount: get_amount(args)
else if vel < 0 && accel < 0 && short < long
buy_at = last - v.greed
sell_at = last
pos =
sell:
rate: sell_at
entry: true
amount: get_amount(args)
buy:
rate: buy_at
amount: get_amount(args)
evaluate_open_position: strats.evaluate_open_position
|
[
{
"context": "c'\n @encrypted = encryption.encrypt username: 'sqrtofsaturn', secrets: {}\n\n @apiStrategy = new MockStrateg",
"end": 691,
"score": 0.9996986389160156,
"start": 679,
"tag": "USERNAME",
"value": "sqrtofsaturn"
},
{
"context": " .send uuid: 'cred-uuid', 'endo.auth... | node_modules/endo-core/test/integration/credentials-device-spec.coffee | ratokeshi/endo-google-cloud-platform | 0 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Credentials Device Spec', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encrypted = encryption.encrypt username: 'sqrtofsaturn', secrets: {}
@apiStrategy = new MockStrategy {name: 'lib'}
@octobluStrategy = new MockStrategy {name: 'octoblu'}
serverOptions =
logFn: ->
messageHandler: {}
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
apiName: 'github'
deviceType: 'endo-core'
octobluStrategy: @octobluStrategy
serviceUrl: 'http://octoblu.xxx'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'service-uuid'
token: 'service-token'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.luxury'
userDeviceManagerUrl: 'http://manage-my.endo'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /credentials/cred-uuid', ->
describe 'when authorized', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': "LF0GppVttGA+pNVhaRQ9zUOVQBP+e0jJCu3MDA0hQrbDQ3+lDWui1SQ2cpTyA0KtZ1hyFGtAi5AoL39knIxtaQ=="
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'cred-uuid'
endoSignature: 'dg5gJq4J6mNvdwy3l6l6IgeeCzdi7gSnEUmGObyB+6YswwaqYqsYS1y1Y2aWXWZcT+gEzS5zW7iB4Ii0if5CKg=='
endo:
authorizedKey: 'user-uuid'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: 'cred-token2'
@meshblu
.get '/v2/devices/service-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.reply 200, {
uuid: 'service-uuid'
options:
name: 'API Name'
imageUrl: 'http://bit.ly/1SDctTa'
}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
auth:
username: 'user-uuid'
password: 'user-token'
request.get '/credentials/cred-uuid', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify(@body)
it 'should return a public version of the credentials device', ->
expect(@body).to.deep.equal {
name: 'API Name'
imageUrl: 'http://bit.ly/1SDctTa'
username: 'sqrtofsaturn'
}
describe 'when inauthentic', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': 'LF0GppVttGA+pNVhaRQ9zUOVQBP+e0jJCu3MDA0hQrbDQ3+lDWui1SQ2cpTyA0KtZ1hyFGtAi5AoL39knIxtaQ=='
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, []
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: 'cred-token2'
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: 'user-token'
request.get '/credentials/cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404
describe 'when authorized, but with a bad credentials device', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'bad-cred-uuid', 'endo.authorizedKey': "LF0GppVttGA+pNVhaRQ9zUOVQBP+e0jJCu3MDA0hQrbDQ3+lDWui1SQ2cpTyA0KtZ1hyFGtAi5AoL39knIxtaQ=="
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'bad-cred-uuid'
endo:
authorizedKey: 'user-uuid'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: 'user-token'
request.get '/credentials/bad-cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
| 49109 | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Credentials Device Spec', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encrypted = encryption.encrypt username: 'sqrtofsaturn', secrets: {}
@apiStrategy = new MockStrategy {name: 'lib'}
@octobluStrategy = new MockStrategy {name: 'octoblu'}
serverOptions =
logFn: ->
messageHandler: {}
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
apiName: 'github'
deviceType: 'endo-core'
octobluStrategy: @octobluStrategy
serviceUrl: 'http://octoblu.xxx'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'service-uuid'
token: 'service-token'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.luxury'
userDeviceManagerUrl: 'http://manage-my.endo'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /credentials/cred-uuid', ->
describe 'when authorized', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': "<KEY>
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'cred-uuid'
endoSignature: 'dg5gJq4J6mNvdwy3l6l6IgeeCzdi7gSnEUmGObyB+6YswwaqYqsYS1y1Y2aWXWZcT+gEzS5zW7iB4Ii0if5CKg=='
endo:
authorizedKey: '<KEY>'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: '<PASSWORD>'
@meshblu
.get '/v2/devices/service-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.reply 200, {
uuid: 'service-uuid'
options:
name: '<NAME> Name'
imageUrl: 'http://bit.ly/1SDctTa'
}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
auth:
username: 'user-uuid'
password: '<PASSWORD>'
request.get '/credentials/cred-uuid', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify(@body)
it 'should return a public version of the credentials device', ->
expect(@body).to.deep.equal {
name: 'API Name'
imageUrl: 'http://bit.ly/1SDctTa'
username: 'sqrtofsaturn'
}
describe 'when inauthentic', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': '<KEY>
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, []
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: 'cred-token2'
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: '<PASSWORD>'
request.get '/credentials/cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404
describe 'when authorized, but with a bad credentials device', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'bad-cred-uuid', 'endo.authorizedKey': "<KEY>
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'bad-cred-uuid'
endo:
authorizedKey: '<KEY>'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: '<PASSWORD>'
request.get '/credentials/bad-cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
| true | {afterEach, beforeEach, describe, it} = global
{expect} = require 'chai'
fs = require 'fs'
Encryption = require 'meshblu-encryption'
request = require 'request'
enableDestroy = require 'server-destroy'
shmock = require 'shmock'
MockStrategy = require '../mock-strategy'
Server = require '../..'
describe 'Credentials Device Spec', ->
beforeEach (done) ->
@meshblu = shmock 0xd00d
enableDestroy @meshblu
@privateKey = fs.readFileSync "#{__dirname}/../data/private-key.pem", 'utf8'
encryption = Encryption.fromPem @privateKey
@publicKey = encryption.key.exportKey 'public'
@encrypted = encryption.encrypt username: 'sqrtofsaturn', secrets: {}
@apiStrategy = new MockStrategy {name: 'lib'}
@octobluStrategy = new MockStrategy {name: 'octoblu'}
serverOptions =
logFn: ->
messageHandler: {}
port: undefined,
disableLogging: true
apiStrategy: @apiStrategy
apiName: 'github'
deviceType: 'endo-core'
octobluStrategy: @octobluStrategy
serviceUrl: 'http://octoblu.xxx'
meshbluConfig:
hostname: 'localhost'
protocol: 'http'
port: 0xd00d
uuid: 'service-uuid'
token: 'service-token'
privateKey: @privateKey
appOctobluHost: 'http://app.octoblu.luxury'
userDeviceManagerUrl: 'http://manage-my.endo'
meshbluPublicKeyUri: 'http://localhost:53261/publickey'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.get '/v2/whoami'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, {
options:
imageUrl: "http://this-is-an-image.exe"
}
@meshblu
.get '/publickey'
.reply 200, {@publicKey}
@server = new Server serverOptions
@server.run (error) =>
return done error if error?
@serverPort = @server.address().port
done()
afterEach (done) ->
@server.stop done
afterEach (done) ->
@meshblu.destroy done
describe 'On GET /credentials/cred-uuid', ->
describe 'when authorized', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
credentialsDeviceAuth = new Buffer('cred-uuid:cred-token2').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': "PI:KEY:<KEY>END_PI
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'cred-uuid'
endoSignature: 'dg5gJq4J6mNvdwy3l6l6IgeeCzdi7gSnEUmGObyB+6YswwaqYqsYS1y1Y2aWXWZcT+gEzS5zW7iB4Ii0if5CKg=='
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: 'PI:PASSWORD:<PASSWORD>END_PI'
@meshblu
.get '/v2/devices/service-uuid'
.set 'Authorization', "Basic #{credentialsDeviceAuth}"
.reply 200, {
uuid: 'service-uuid'
options:
name: 'PI:NAME:<NAME>END_PI Name'
imageUrl: 'http://bit.ly/1SDctTa'
}
options =
baseUrl: "http://localhost:#{@serverPort}"
followRedirect: false
json: true
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get '/credentials/cred-uuid', options, (error, @response, @body) =>
done error
it 'should return a 200', ->
expect(@response.statusCode).to.equal 200, JSON.stringify(@body)
it 'should return a public version of the credentials device', ->
expect(@body).to.deep.equal {
name: 'API Name'
imageUrl: 'http://bit.ly/1SDctTa'
username: 'sqrtofsaturn'
}
describe 'when inauthentic', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'cred-uuid', 'endo.authorizedKey': 'PI:KEY:<KEY>END_PI
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, []
@meshblu
.post '/devices/cred-uuid/tokens'
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, uuid: 'cred-uuid', token: 'cred-token2'
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get '/credentials/cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404
describe 'when authorized, but with a bad credentials device', ->
beforeEach (done) ->
userAuth = new Buffer('user-uuid:user-token').toString 'base64'
serviceAuth = new Buffer('service-uuid:service-token').toString 'base64'
@meshblu
.post '/authenticate'
.set 'Authorization', "Basic #{userAuth}"
.reply 204
@meshblu
.post '/search/devices'
.send uuid: 'bad-cred-uuid', 'endo.authorizedKey': "PI:KEY:<KEY>END_PI
.set 'Authorization', "Basic #{serviceAuth}"
.reply 200, [
uuid: 'bad-cred-uuid'
endo:
authorizedKey: 'PI:KEY:<KEY>END_PI'
credentialsDeviceUuid: 'cred-uuid'
encrypted: @encrypted
]
options =
baseUrl: "http://localhost:#{@serverPort}"
json: true
auth:
username: 'user-uuid'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
request.get '/credentials/bad-cred-uuid/user-devices', options, (error, @response, @body) =>
done error
it 'should return a 404', ->
expect(@response.statusCode).to.equal 404, JSON.stringify @body
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9984789490699768,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-http-head-request.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
test = (headers) ->
port = common.PORT + id++
server = http.createServer((req, res) ->
console.error "req: %s headers: %j", req.method, headers
res.writeHead 200, headers
res.end()
server.close()
return
)
gotEnd = false
server.listen port, ->
request = http.request(
port: port
method: "HEAD"
path: "/"
, (response) ->
console.error "response start"
response.on "end", ->
console.error "response end"
gotEnd = true
return
response.resume()
return
)
request.end()
return
process.on "exit", ->
assert.ok gotEnd
return
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world\n"
id = 0
test "Transfer-Encoding": "chunked"
test "Content-Length": body.length
| 82174 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
test = (headers) ->
port = common.PORT + id++
server = http.createServer((req, res) ->
console.error "req: %s headers: %j", req.method, headers
res.writeHead 200, headers
res.end()
server.close()
return
)
gotEnd = false
server.listen port, ->
request = http.request(
port: port
method: "HEAD"
path: "/"
, (response) ->
console.error "response start"
response.on "end", ->
console.error "response end"
gotEnd = true
return
response.resume()
return
)
request.end()
return
process.on "exit", ->
assert.ok gotEnd
return
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world\n"
id = 0
test "Transfer-Encoding": "chunked"
test "Content-Length": body.length
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
test = (headers) ->
port = common.PORT + id++
server = http.createServer((req, res) ->
console.error "req: %s headers: %j", req.method, headers
res.writeHead 200, headers
res.end()
server.close()
return
)
gotEnd = false
server.listen port, ->
request = http.request(
port: port
method: "HEAD"
path: "/"
, (response) ->
console.error "response start"
response.on "end", ->
console.error "response end"
gotEnd = true
return
response.resume()
return
)
request.end()
return
process.on "exit", ->
assert.ok gotEnd
return
return
common = require("../common")
assert = require("assert")
http = require("http")
util = require("util")
body = "hello world\n"
id = 0
test "Transfer-Encoding": "chunked"
test "Content-Length": body.length
|
[
{
"context": " # 'secret' used to sign the JWT\n jwtSecret: 'my_random_and_uber_secret_string_to_sign_the_json_web_tokens'\n\n # Path to the frontend public dir (called '",
"end": 263,
"score": 0.8814383149147034,
"start": 203,
"tag": "KEY",
"value": "my_random_and_uber_secret_string_... | Gruntfile.coffee | mosaiqo/frontend-devServer | 0 | module.exports = (grunt) ->
_ = require('lodash')
# Defaults:
# ================================================================
defaults =
# 'secret' used to sign the JWT
jwtSecret: 'my_random_and_uber_secret_string_to_sign_the_json_web_tokens'
# Path to the frontend public dir (called 'dist')
frontendAppPublicDir: '../frontend'
# Redis settings
redis:
host: 'localhost'
port: 6379
# Mongo settings
mongo:
host: 'localhost'
port: 27017
user: null
password: null
database: 'mosaiqoFront'
# New Relic settings
newRelic:
enabled: false
appName: ''
licenceKey: ''
# The defaults can be overrided so you can place the frontendApp wherever you
# want, or to use a redis or mongo running on another machine.
#
# Just create a file called 'env.json' at the project root and overwrite any
# default settings you want
#
envConfigFile = 'env.json'
if grunt.file.exists envConfigFile
envConfig = grunt.file.readJSON(envConfigFile)
else
envConfig = {}
config = _.defaults envConfig, defaults
# Travis fixup
# ================================================================
# on travis, the frontendAppPublicDir path obviously does not
# exist so some tests will make explode the app. So:
unless grunt.file.exists config.frontendAppPublicDir
grunt.file.mkdir 'tmpPublic'
grunt.file.write 'tmpPublic/index.html', '...'
config.frontendAppPublicDir = './tmpPublic'
# Actual tasks config...
# ================================================================
# Data available to the tasks:
# The previous config plus some aditional params.
config = _.extend config,
# Directories:
rootDir: __dirname
srcDir: './src'
assetsDir: config.frontendAppPublicDir + '/assets'
docsDir: 'docs'
# Dev. server settings:
serverPort: 9000
browserSyncUIPort: 9002
weinrePort: 9003
banner: '/*! <%= package.name %> <%= package.version %> |
© <%= package.author %> - All rights reserved |
<%= package.homepage %> */\n'
# Autoloading for the grunt tasks, jitGrunt enables loading them on demand
require('load-grunt-config') grunt,
jitGrunt: true
data: config
# Display the elapsed execution time of grunt tasks
require('time-grunt') grunt
# Load explicitly the notify tasks,
# otherwise, no notifications will be fired or errors
grunt.loadNpmTasks('grunt-notify')
# Load explicitly the istanbul tasks,
# because istanbul exposes more tasks like 'instrument' and others
# that are not recognised otherwise by jitGrunt
grunt.loadNpmTasks('grunt-istanbul')
# Override some istanbul stuff because it does not support ES6
istanbulHarmony = require('istanbul-harmony')
usedIstanbul = undefined
Instrumenter = undefined
grunt.registerTask 'istanbul:override', ->
usedIstanbul = require('grunt-istanbul/node_modules/istanbul')
Instrumenter = usedIstanbul.Instrumenter
# Overrides `Instrumenter`
usedIstanbul.Instrumenter = istanbulHarmony.Instrumenter
return
grunt.registerTask 'istanbul:restore', ->
# Restores original `Instrumenter`
usedIstanbul.Instrumenter = Instrumenter
return
| 60980 | module.exports = (grunt) ->
_ = require('lodash')
# Defaults:
# ================================================================
defaults =
# 'secret' used to sign the JWT
jwtSecret: '<KEY>'
# Path to the frontend public dir (called 'dist')
frontendAppPublicDir: '../frontend'
# Redis settings
redis:
host: 'localhost'
port: 6379
# Mongo settings
mongo:
host: 'localhost'
port: 27017
user: null
password: <PASSWORD>
database: 'mosaiqoFront'
# New Relic settings
newRelic:
enabled: false
appName: ''
licenceKey: ''
# The defaults can be overrided so you can place the frontendApp wherever you
# want, or to use a redis or mongo running on another machine.
#
# Just create a file called 'env.json' at the project root and overwrite any
# default settings you want
#
envConfigFile = 'env.json'
if grunt.file.exists envConfigFile
envConfig = grunt.file.readJSON(envConfigFile)
else
envConfig = {}
config = _.defaults envConfig, defaults
# Travis fixup
# ================================================================
# on travis, the frontendAppPublicDir path obviously does not
# exist so some tests will make explode the app. So:
unless grunt.file.exists config.frontendAppPublicDir
grunt.file.mkdir 'tmpPublic'
grunt.file.write 'tmpPublic/index.html', '...'
config.frontendAppPublicDir = './tmpPublic'
# Actual tasks config...
# ================================================================
# Data available to the tasks:
# The previous config plus some aditional params.
config = _.extend config,
# Directories:
rootDir: __dirname
srcDir: './src'
assetsDir: config.frontendAppPublicDir + '/assets'
docsDir: 'docs'
# Dev. server settings:
serverPort: 9000
browserSyncUIPort: 9002
weinrePort: 9003
banner: '/*! <%= package.name %> <%= package.version %> |
© <%= package.author %> - All rights reserved |
<%= package.homepage %> */\n'
# Autoloading for the grunt tasks, jitGrunt enables loading them on demand
require('load-grunt-config') grunt,
jitGrunt: true
data: config
# Display the elapsed execution time of grunt tasks
require('time-grunt') grunt
# Load explicitly the notify tasks,
# otherwise, no notifications will be fired or errors
grunt.loadNpmTasks('grunt-notify')
# Load explicitly the istanbul tasks,
# because istanbul exposes more tasks like 'instrument' and others
# that are not recognised otherwise by jitGrunt
grunt.loadNpmTasks('grunt-istanbul')
# Override some istanbul stuff because it does not support ES6
istanbulHarmony = require('istanbul-harmony')
usedIstanbul = undefined
Instrumenter = undefined
grunt.registerTask 'istanbul:override', ->
usedIstanbul = require('grunt-istanbul/node_modules/istanbul')
Instrumenter = usedIstanbul.Instrumenter
# Overrides `Instrumenter`
usedIstanbul.Instrumenter = istanbulHarmony.Instrumenter
return
grunt.registerTask 'istanbul:restore', ->
# Restores original `Instrumenter`
usedIstanbul.Instrumenter = Instrumenter
return
| true | module.exports = (grunt) ->
_ = require('lodash')
# Defaults:
# ================================================================
defaults =
# 'secret' used to sign the JWT
jwtSecret: 'PI:KEY:<KEY>END_PI'
# Path to the frontend public dir (called 'dist')
frontendAppPublicDir: '../frontend'
# Redis settings
redis:
host: 'localhost'
port: 6379
# Mongo settings
mongo:
host: 'localhost'
port: 27017
user: null
password: PI:PASSWORD:<PASSWORD>END_PI
database: 'mosaiqoFront'
# New Relic settings
newRelic:
enabled: false
appName: ''
licenceKey: ''
# The defaults can be overrided so you can place the frontendApp wherever you
# want, or to use a redis or mongo running on another machine.
#
# Just create a file called 'env.json' at the project root and overwrite any
# default settings you want
#
envConfigFile = 'env.json'
if grunt.file.exists envConfigFile
envConfig = grunt.file.readJSON(envConfigFile)
else
envConfig = {}
config = _.defaults envConfig, defaults
# Travis fixup
# ================================================================
# on travis, the frontendAppPublicDir path obviously does not
# exist so some tests will make explode the app. So:
unless grunt.file.exists config.frontendAppPublicDir
grunt.file.mkdir 'tmpPublic'
grunt.file.write 'tmpPublic/index.html', '...'
config.frontendAppPublicDir = './tmpPublic'
# Actual tasks config...
# ================================================================
# Data available to the tasks:
# The previous config plus some aditional params.
config = _.extend config,
# Directories:
rootDir: __dirname
srcDir: './src'
assetsDir: config.frontendAppPublicDir + '/assets'
docsDir: 'docs'
# Dev. server settings:
serverPort: 9000
browserSyncUIPort: 9002
weinrePort: 9003
banner: '/*! <%= package.name %> <%= package.version %> |
© <%= package.author %> - All rights reserved |
<%= package.homepage %> */\n'
# Autoloading for the grunt tasks, jitGrunt enables loading them on demand
require('load-grunt-config') grunt,
jitGrunt: true
data: config
# Display the elapsed execution time of grunt tasks
require('time-grunt') grunt
# Load explicitly the notify tasks,
# otherwise, no notifications will be fired or errors
grunt.loadNpmTasks('grunt-notify')
# Load explicitly the istanbul tasks,
# because istanbul exposes more tasks like 'instrument' and others
# that are not recognised otherwise by jitGrunt
grunt.loadNpmTasks('grunt-istanbul')
# Override some istanbul stuff because it does not support ES6
istanbulHarmony = require('istanbul-harmony')
usedIstanbul = undefined
Instrumenter = undefined
grunt.registerTask 'istanbul:override', ->
usedIstanbul = require('grunt-istanbul/node_modules/istanbul')
Instrumenter = usedIstanbul.Instrumenter
# Overrides `Instrumenter`
usedIstanbul.Instrumenter = istanbulHarmony.Instrumenter
return
grunt.registerTask 'istanbul:restore', ->
# Restores original `Instrumenter`
usedIstanbul.Instrumenter = Instrumenter
return
|
[
{
"context": "lies with a random Bob Ross quote.\n#\n# Author:\n# Tyler Crammond\n\nmodule.exports = (robot) ->\n robot.respond /ros",
"end": 179,
"score": 0.9998829960823059,
"start": 165,
"tag": "NAME",
"value": "Tyler Crammond"
},
{
"context": "t it to be, that\\'s just right.'... | src/ross.coffee | tcrammond/hubot-ross | 3 | # Description
# A hubot script to fill your life with joy and happy trees.
#
# Commands:
# hubot ross me - Replies with a random Bob Ross quote.
#
# Author:
# Tyler Crammond
module.exports = (robot) ->
robot.respond /ross me/, (msg) ->
# Such happy little quotes. You can put as few or as many as you want in your world.
quotes = [
"That'll be our little secret.",
"In painting, you have unlimited power. You have the ability to move mountains. You can bend rivers. But when I get home, the only thing I have power over, is the garbage.",
"Remember our Golden Rule: A thin paint sticks to a thick paint.",
"And that makes it look like birch trees, isn't that sneaky? Heh. Ha. It's gorgeous.",
"You know me, I gotta put in a big tree.",
"Here\'s your bravery test!",
'Gotta give him a friend. Like I always say \'everyone needs a friend\'.',
'We don\'t know where it goes. We don\'t really care.',
'Any time ya learn, ya gain.',
'Any way you want it to be, that\'s just right.',
'As my son Steve says, just \'smoosh\' it in there. It\'s not a real word, but people seem to know what it means.',
'Be sure to use odorless paint-thinner. If it\'s not odorless, you\'ll find yourself working alone very, very quick.',
'Let\'s just blend this little rascal here, ha! Happy as we can be.',
'Clouds are very, very free.',
'Just put a few do-ers in there...',
'Decide where your little footy hills live.',
'Haha, and just beat the devil out of it.',
'I like to beat the brush.',
'You can use a brush rack to hit the brush on. Otherwise you will become unpopular real fast.',
'If you did this with yellow, and you went over it with blue, you would end up with a .. with a translucent... green. And it\'s gorgeous. It is GORGEOUS.',
'If you did this with blue, and you went over it with yellow, you would end up with a nice green sky. And that\'s not the thing we are looking for.',
'Just lightly blend it, one hair and some air.',
'Tender as a mothers love... And with my mother, that was certainly true.',
'Let\'s do a little cabinectomy here.',
'Oh, you\'d be in Agony City by now.',
'Just scrape in a few indications of sticks and twigs and other little things in there. People will think you spend hours doing this.',
'Little raccoons and old possums \'n\' stuff all live up in here. They\'ve got to have a little place to sit.',
'Little squirrels \'n\' rabbits, and if this was in Florida or Georgia somewhere down there, might be an alligator or two hid back here.',
'Maybe in our world there lives a happy little tree over there.',
'Oh, green water... oh that\'s pretty. Boy, I like that, just alive with algae.',
'Oh, that would make a nice place to fish. I like fishing, but I\'m not a very good fisherman. I always throw the fish back into the water, just put a band-aid on his mouth, tap \'im on the patootie and let him on his way. And maybe some day, if I\'m lucky, I\'ll get to catch him again.',
'Oooh, if you have never been to Alaska, go there while it is still wild. My favorite uncle asked me if I wanted to go there, Uncle Sam. He said if you don\'t go, you\'re going to jail. That is how Uncle Sam asks you.',
'People look at me like I\'m a little strange, when I go around talking to squirrels and rabbits and stuff. That\'s ok. Thaaaat\'s just ok.',
'People might look at you a bit funny, but it\'s okay. Artists are allowed to be a bit different.',
'Shwooop. Hehe. You have to make those little noises, or it just doesn\'t work.',
'Talk to the tree, make friends with it.',
'I taught my son to paint mountains like these, and guess what? Now he paints the best darn mountains in the industry.',
'That\'s a crooked tree. We\'ll send him to Washington.',
'That\'s where the crows will sit. But we\'ll have to put an elevator to put them up there because they can\'t fly, but they don\'t know that, so they still try.',
'The only thing worse than yellow snow is green snow.',
'The secret to doing anything is believing that you can do it. Anything that you believe you can do strong enough, you can do. Anything. As long as you believe.',
'The trees are oh so soft, oh so soft I freakin\' love it.',
'There\'s nothing wrong with having a tree as a friend.',
'Trees cover up a multitude of sins.',
'Try to imagine that you are a tree. How do you want to look out here?',
'Water\'s like me. It\'s laaazy... Boy, it always looks for the easiest way to do things.',
'We don\'t make mistakes, we just have happy accidents.',
'We tell people sometimes: we\'re like drug dealers, come into town and get everybody absolutely addicted to painting. It doesn\'t take much to get you addicted.',
'We want happy paintings. Happy paintings. If you want sad things, watch the news.',
'We\'re gonna make some big decisions in our little world.',
'Well, the little clock on the wall says we\'re just about out of time. God bless you my friend.',
'From all of us here I\'d like to wish you happy painting...and God bless my friend.',
'When I was teaching my son Steve to paint, I used to tell him, just pretend he was a whisper, and he floated right across the mountain, that easy, gentle, make love to it, caress it.',
'You can do anything you want to do. This is your world.',
'I can\'t go over 30 minutes, because we have a mean ol\' director with no sense of humor.',
'You can put as many or as few as you want in your world.',
'Even if you\'ve never painted before, this one you can do.',
'This is the hardest part of this method. If you can do this, you can do anything.',
'Roll it in a little bright red and lets sign this right in here. Luckily I have a short name so it\'s easy to sign.',
'And just go straight in like your going to stab it. And barely touch it...barely touch it.',
'When we teach people to paint this is the one they fall in love with. It works so well.'
]
# Let's find one of those little quotes
quoteIndex = Math.floor(Math.random() * quotes.length)
# Ross them
msg.reply quotes[quoteIndex]
| 221864 | # Description
# A hubot script to fill your life with joy and happy trees.
#
# Commands:
# hubot ross me - Replies with a random Bob Ross quote.
#
# Author:
# <NAME>
module.exports = (robot) ->
robot.respond /ross me/, (msg) ->
# Such happy little quotes. You can put as few or as many as you want in your world.
quotes = [
"That'll be our little secret.",
"In painting, you have unlimited power. You have the ability to move mountains. You can bend rivers. But when I get home, the only thing I have power over, is the garbage.",
"Remember our Golden Rule: A thin paint sticks to a thick paint.",
"And that makes it look like birch trees, isn't that sneaky? Heh. Ha. It's gorgeous.",
"You know me, I gotta put in a big tree.",
"Here\'s your bravery test!",
'Gotta give him a friend. Like I always say \'everyone needs a friend\'.',
'We don\'t know where it goes. We don\'t really care.',
'Any time ya learn, ya gain.',
'Any way you want it to be, that\'s just right.',
'As my son <NAME> says, just \'smoosh\' it in there. It\'s not a real word, but people seem to know what it means.',
'Be sure to use odorless paint-thinner. If it\'s not odorless, you\'ll find yourself working alone very, very quick.',
'Let\'s just blend this little rascal here, ha! Happy as we can be.',
'Clouds are very, very free.',
'Just put a few do-ers in there...',
'Decide where your little footy hills live.',
'Haha, and just beat the devil out of it.',
'I like to beat the brush.',
'You can use a brush rack to hit the brush on. Otherwise you will become unpopular real fast.',
'If you did this with yellow, and you went over it with blue, you would end up with a .. with a translucent... green. And it\'s gorgeous. It is GORGEOUS.',
'If you did this with blue, and you went over it with yellow, you would end up with a nice green sky. And that\'s not the thing we are looking for.',
'Just lightly blend it, one hair and some air.',
'Tender as a mothers love... And with my mother, that was certainly true.',
'Let\'s do a little cabinectomy here.',
'Oh, you\'d be in Agony City by now.',
'Just scrape in a few indications of sticks and twigs and other little things in there. People will think you spend hours doing this.',
'Little raccoons and old possums \'n\' stuff all live up in here. They\'ve got to have a little place to sit.',
'Little squirrels \'n\' rabbits, and if this was in Florida or Georgia somewhere down there, might be an alligator or two hid back here.',
'Maybe in our world there lives a happy little tree over there.',
'Oh, green water... oh that\'s pretty. Boy, I like that, just alive with algae.',
'Oh, that would make a nice place to fish. I like fishing, but I\'m not a very good fisherman. I always throw the fish back into the water, just put a band-aid on his mouth, tap \'im on the patootie and let him on his way. And maybe some day, if I\'m lucky, I\'ll get to catch him again.',
'Oooh, if you have never been to Alaska, go there while it is still wild. My favorite uncle asked me if I wanted to go there, <NAME>. He said if you don\'t go, you\'re going to jail. That is how Uncle Sam asks you.',
'People look at me like I\'m a little strange, when I go around talking to squirrels and rabbits and stuff. That\'s ok. Thaaaat\'s just ok.',
'People might look at you a bit funny, but it\'s okay. Artists are allowed to be a bit different.',
'Shwooop. Hehe. You have to make those little noises, or it just doesn\'t work.',
'Talk to the tree, make friends with it.',
'I taught my son to paint mountains like these, and guess what? Now he paints the best darn mountains in the industry.',
'That\'s a crooked tree. We\'ll send him to Washington.',
'That\'s where the crows will sit. But we\'ll have to put an elevator to put them up there because they can\'t fly, but they don\'t know that, so they still try.',
'The only thing worse than yellow snow is green snow.',
'The secret to doing anything is believing that you can do it. Anything that you believe you can do strong enough, you can do. Anything. As long as you believe.',
'The trees are oh so soft, oh so soft I freakin\' love it.',
'There\'s nothing wrong with having a tree as a friend.',
'Trees cover up a multitude of sins.',
'Try to imagine that you are a tree. How do you want to look out here?',
'Water\'s like me. It\'s laaazy... Boy, it always looks for the easiest way to do things.',
'We don\'t make mistakes, we just have happy accidents.',
'We tell people sometimes: we\'re like drug dealers, come into town and get everybody absolutely addicted to painting. It doesn\'t take much to get you addicted.',
'We want happy paintings. Happy paintings. If you want sad things, watch the news.',
'We\'re gonna make some big decisions in our little world.',
'Well, the little clock on the wall says we\'re just about out of time. God bless you my friend.',
'From all of us here I\'d like to wish you happy painting...and God bless my friend.',
'When I was teaching my son <NAME> to paint, I used to tell him, just pretend he was a whisper, and he floated right across the mountain, that easy, gentle, make love to it, caress it.',
'You can do anything you want to do. This is your world.',
'I can\'t go over 30 minutes, because we have a mean ol\' director with no sense of humor.',
'You can put as many or as few as you want in your world.',
'Even if you\'ve never painted before, this one you can do.',
'This is the hardest part of this method. If you can do this, you can do anything.',
'Roll it in a little bright red and lets sign this right in here. Luckily I have a short name so it\'s easy to sign.',
'And just go straight in like your going to stab it. And barely touch it...barely touch it.',
'When we teach people to paint this is the one they fall in love with. It works so well.'
]
# Let's find one of those little quotes
quoteIndex = Math.floor(Math.random() * quotes.length)
# Ross them
msg.reply quotes[quoteIndex]
| true | # Description
# A hubot script to fill your life with joy and happy trees.
#
# Commands:
# hubot ross me - Replies with a random Bob Ross quote.
#
# Author:
# PI:NAME:<NAME>END_PI
module.exports = (robot) ->
robot.respond /ross me/, (msg) ->
# Such happy little quotes. You can put as few or as many as you want in your world.
quotes = [
"That'll be our little secret.",
"In painting, you have unlimited power. You have the ability to move mountains. You can bend rivers. But when I get home, the only thing I have power over, is the garbage.",
"Remember our Golden Rule: A thin paint sticks to a thick paint.",
"And that makes it look like birch trees, isn't that sneaky? Heh. Ha. It's gorgeous.",
"You know me, I gotta put in a big tree.",
"Here\'s your bravery test!",
'Gotta give him a friend. Like I always say \'everyone needs a friend\'.',
'We don\'t know where it goes. We don\'t really care.',
'Any time ya learn, ya gain.',
'Any way you want it to be, that\'s just right.',
'As my son PI:NAME:<NAME>END_PI says, just \'smoosh\' it in there. It\'s not a real word, but people seem to know what it means.',
'Be sure to use odorless paint-thinner. If it\'s not odorless, you\'ll find yourself working alone very, very quick.',
'Let\'s just blend this little rascal here, ha! Happy as we can be.',
'Clouds are very, very free.',
'Just put a few do-ers in there...',
'Decide where your little footy hills live.',
'Haha, and just beat the devil out of it.',
'I like to beat the brush.',
'You can use a brush rack to hit the brush on. Otherwise you will become unpopular real fast.',
'If you did this with yellow, and you went over it with blue, you would end up with a .. with a translucent... green. And it\'s gorgeous. It is GORGEOUS.',
'If you did this with blue, and you went over it with yellow, you would end up with a nice green sky. And that\'s not the thing we are looking for.',
'Just lightly blend it, one hair and some air.',
'Tender as a mothers love... And with my mother, that was certainly true.',
'Let\'s do a little cabinectomy here.',
'Oh, you\'d be in Agony City by now.',
'Just scrape in a few indications of sticks and twigs and other little things in there. People will think you spend hours doing this.',
'Little raccoons and old possums \'n\' stuff all live up in here. They\'ve got to have a little place to sit.',
'Little squirrels \'n\' rabbits, and if this was in Florida or Georgia somewhere down there, might be an alligator or two hid back here.',
'Maybe in our world there lives a happy little tree over there.',
'Oh, green water... oh that\'s pretty. Boy, I like that, just alive with algae.',
'Oh, that would make a nice place to fish. I like fishing, but I\'m not a very good fisherman. I always throw the fish back into the water, just put a band-aid on his mouth, tap \'im on the patootie and let him on his way. And maybe some day, if I\'m lucky, I\'ll get to catch him again.',
'Oooh, if you have never been to Alaska, go there while it is still wild. My favorite uncle asked me if I wanted to go there, PI:NAME:<NAME>END_PI. He said if you don\'t go, you\'re going to jail. That is how Uncle Sam asks you.',
'People look at me like I\'m a little strange, when I go around talking to squirrels and rabbits and stuff. That\'s ok. Thaaaat\'s just ok.',
'People might look at you a bit funny, but it\'s okay. Artists are allowed to be a bit different.',
'Shwooop. Hehe. You have to make those little noises, or it just doesn\'t work.',
'Talk to the tree, make friends with it.',
'I taught my son to paint mountains like these, and guess what? Now he paints the best darn mountains in the industry.',
'That\'s a crooked tree. We\'ll send him to Washington.',
'That\'s where the crows will sit. But we\'ll have to put an elevator to put them up there because they can\'t fly, but they don\'t know that, so they still try.',
'The only thing worse than yellow snow is green snow.',
'The secret to doing anything is believing that you can do it. Anything that you believe you can do strong enough, you can do. Anything. As long as you believe.',
'The trees are oh so soft, oh so soft I freakin\' love it.',
'There\'s nothing wrong with having a tree as a friend.',
'Trees cover up a multitude of sins.',
'Try to imagine that you are a tree. How do you want to look out here?',
'Water\'s like me. It\'s laaazy... Boy, it always looks for the easiest way to do things.',
'We don\'t make mistakes, we just have happy accidents.',
'We tell people sometimes: we\'re like drug dealers, come into town and get everybody absolutely addicted to painting. It doesn\'t take much to get you addicted.',
'We want happy paintings. Happy paintings. If you want sad things, watch the news.',
'We\'re gonna make some big decisions in our little world.',
'Well, the little clock on the wall says we\'re just about out of time. God bless you my friend.',
'From all of us here I\'d like to wish you happy painting...and God bless my friend.',
'When I was teaching my son PI:NAME:<NAME>END_PI to paint, I used to tell him, just pretend he was a whisper, and he floated right across the mountain, that easy, gentle, make love to it, caress it.',
'You can do anything you want to do. This is your world.',
'I can\'t go over 30 minutes, because we have a mean ol\' director with no sense of humor.',
'You can put as many or as few as you want in your world.',
'Even if you\'ve never painted before, this one you can do.',
'This is the hardest part of this method. If you can do this, you can do anything.',
'Roll it in a little bright red and lets sign this right in here. Luckily I have a short name so it\'s easy to sign.',
'And just go straight in like your going to stab it. And barely touch it...barely touch it.',
'When we teach people to paint this is the one they fall in love with. It works so well.'
]
# Let's find one of those little quotes
quoteIndex = Math.floor(Math.random() * quotes.length)
# Ross them
msg.reply quotes[quoteIndex]
|
[
{
"context": "020002cc'\n contributing_authors: [ {name: 'Kana', profile_id: 'user345'} ]\n sd: {CURRENT_PAT",
"end": 852,
"score": 0.9303516745567322,
"start": 848,
"tag": "NAME",
"value": "Kana"
},
{
"context": "ntributing_authors: [ {name: 'Kana', profile_id: 'user345'... | src/mobile/components/article_figure/test/templates.coffee | kanaabe/force | 1 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
Article = require '../../../models/article'
fixtures = require '../../../test/helpers/fixtures'
render = (templateName) ->
filename = path.resolve __dirname, "../#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article figure template', ->
it 'renders article fields', ->
html = render('template')
article: new Article _.extend fixtures.article, thumbnail_title: 'hi'
sd: {}
html.should.containEql 'hi'
it 'handles contributing author section from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '503f86e462d56000020002cc'
contributing_authors: [ {name: 'Kana', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.not.containEql "\"article-figure-author\""
it 'handles contributing author not from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '123'
contributing_authors: [ {name: 'Kana', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.containEql 'article-item-author'
it 'handles one contributing author', ->
html = render('template')
article: new Article
contributing_authors: [ {name: 'Kana', profile_id: 'user345'} ]
sd: {}
html.should.not.containEql 'Kana,'
it 'handles two contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{name: 'Kana', profile_id: 'user345'}
{name: 'Kina', profile_id: 'user355'}
]
sd: {}
html.should.containEql ' and '
html.should.containEql 'class="article-item-contributing-name">Kina'
html.should.containEql 'class="article-item-contributing-name">Kana'
it 'handles three or more contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{ name: 'Kana', profile_id: 'user345' }
{ name: 'Kina', profile_id: 'user355' }
{ name: 'Yoshie', profile_id: 'user356' }
]
sd: {}
html.should.containEql 'class="article-item-contributing-name">Kana'
html.should.containEql 'class="article-item-contributing-name">Kina'
html.should.containEql 'class="article-item-contributing-name">Yoshie'
| 46857 | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
Article = require '../../../models/article'
fixtures = require '../../../test/helpers/fixtures'
render = (templateName) ->
filename = path.resolve __dirname, "../#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article figure template', ->
it 'renders article fields', ->
html = render('template')
article: new Article _.extend fixtures.article, thumbnail_title: 'hi'
sd: {}
html.should.containEql 'hi'
it 'handles contributing author section from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '503f86e462d56000020002cc'
contributing_authors: [ {name: '<NAME>', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.not.containEql "\"article-figure-author\""
it 'handles contributing author not from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '123'
contributing_authors: [ {name: '<NAME>', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.containEql 'article-item-author'
it 'handles one contributing author', ->
html = render('template')
article: new Article
contributing_authors: [ {name: '<NAME>', profile_id: 'user345'} ]
sd: {}
html.should.not.containEql 'Kana,'
it 'handles two contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{name: '<NAME>', profile_id: 'user345'}
{name: '<NAME>', profile_id: 'user355'}
]
sd: {}
html.should.containEql ' and '
html.should.containEql 'class="article-item-contributing-name">K<NAME>'
html.should.containEql 'class="article-item-contributing-name">Kana'
it 'handles three or more contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{ name: '<NAME>', profile_id: 'user345' }
{ name: '<NAME>', profile_id: 'user355' }
{ name: '<NAME>', profile_id: 'user356' }
]
sd: {}
html.should.containEql 'class="article-item-contributing-name">Kana'
html.should.containEql 'class="article-item-contributing-name"><NAME>'
html.should.containEql 'class="article-item-contributing-name">Yoshie'
| true | _ = require 'underscore'
cheerio = require 'cheerio'
path = require 'path'
jade = require 'jade'
fs = require 'fs'
Article = require '../../../models/article'
fixtures = require '../../../test/helpers/fixtures'
render = (templateName) ->
filename = path.resolve __dirname, "../#{templateName}.jade"
jade.compile(
fs.readFileSync(filename),
{ filename: filename }
)
describe 'article figure template', ->
it 'renders article fields', ->
html = render('template')
article: new Article _.extend fixtures.article, thumbnail_title: 'hi'
sd: {}
html.should.containEql 'hi'
it 'handles contributing author section from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '503f86e462d56000020002cc'
contributing_authors: [ {name: 'PI:NAME:<NAME>END_PI', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.not.containEql "\"article-figure-author\""
it 'handles contributing author not from Artsy Editorial', ->
html = render('template')
article: new Article
thumbnail_title: 'hi'
author_id: '123'
contributing_authors: [ {name: 'PI:NAME:<NAME>END_PI', profile_id: 'user345'} ]
sd: {CURRENT_PATH: '/articles'}
html.should.containEql 'article-item-author'
it 'handles one contributing author', ->
html = render('template')
article: new Article
contributing_authors: [ {name: 'PI:NAME:<NAME>END_PI', profile_id: 'user345'} ]
sd: {}
html.should.not.containEql 'Kana,'
it 'handles two contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{name: 'PI:NAME:<NAME>END_PI', profile_id: 'user345'}
{name: 'PI:NAME:<NAME>END_PI', profile_id: 'user355'}
]
sd: {}
html.should.containEql ' and '
html.should.containEql 'class="article-item-contributing-name">KPI:NAME:<NAME>END_PI'
html.should.containEql 'class="article-item-contributing-name">Kana'
it 'handles three or more contributing authors', ->
html = render('template')
article: new Article
contributing_authors: [
{ name: 'PI:NAME:<NAME>END_PI', profile_id: 'user345' }
{ name: 'PI:NAME:<NAME>END_PI', profile_id: 'user355' }
{ name: 'PI:NAME:<NAME>END_PI', profile_id: 'user356' }
]
sd: {}
html.should.containEql 'class="article-item-contributing-name">Kana'
html.should.containEql 'class="article-item-contributing-name">PI:NAME:<NAME>END_PI'
html.should.containEql 'class="article-item-contributing-name">Yoshie'
|
[
{
"context": "g-a-grammar/\n\n'scopeName': 'source.jack'\n'name': 'Jack'\n'fileTypes': [\n 'jack'\n]\n'patterns': [\n {\n ",
"end": 187,
"score": 0.966097354888916,
"start": 183,
"tag": "NAME",
"value": "Jack"
}
] | grammars/jack-grammar.cson | abir0/jack-language-syntax-highlighting | 0 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.jack'
'name': 'Jack'
'fileTypes': [
'jack'
]
'patterns': [
{
'comment': 'one line comment'
'match': '//.*$'
'name': 'comment.line.jack'
}
{
'comment': 'multi-line comment'
'begin': '/\\*'
'end': '\\*/'
'name': 'comment.block.jack'
}
{
'comment': 'documantation comment'
'begin': '/\\*\\*'
'end': '\\*/'
'name': 'comment.block.documentation.jack'
}
{
'comment': 'numeric constant'
'match': '\\b[0-9]+\\b'
'name': 'constant.numeric.jack'
}
{
'comment': 'boolean and null constant'
'match': '\\b(null|true|false)\\b'
'name': 'constant.language.jack'
}
{
'comment': 'string constant'
'match': '\\".*?\\"'
'name': 'string.quoted.jack'
}
{
'comment': 'pointer variable'
'match': '\\b(this)\\b'
'captures':
'1':
'name': 'variable.language.jack'
}
{
'comment': 'symbolic operator'
'match': '(\\+|\\-|\\*|\\/|\\>|\\<|\\~|\\&|\\|)'
'captures':
'1':
'name': 'variable.operator.jack'
}
{
'comment': 'language keyword'
'match': '\\b(class|function|method|constructor|var|static|field|let|do|else|if|return|while)\\b'
'captures':
'1':
'name': 'keyword.jack'
}
{
'comment': 'variable type'
'match': '\\b(void|boolean|int|char)\\b'
'captures':
'1':
'name': 'support.type.jack'
}
{
'comment': 'class identifier'
'match': '\\b([A-Z][a-zA-Z]*)\\b \\{'
'captures':
'1':
'name': 'support.class.jack'
}
{
'comment': 'function identifier'
'match': '\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b *\\('
'captures':
'1':
'name': 'entity.name.function.jack'
}
]
| 200236 | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.jack'
'name': '<NAME>'
'fileTypes': [
'jack'
]
'patterns': [
{
'comment': 'one line comment'
'match': '//.*$'
'name': 'comment.line.jack'
}
{
'comment': 'multi-line comment'
'begin': '/\\*'
'end': '\\*/'
'name': 'comment.block.jack'
}
{
'comment': 'documantation comment'
'begin': '/\\*\\*'
'end': '\\*/'
'name': 'comment.block.documentation.jack'
}
{
'comment': 'numeric constant'
'match': '\\b[0-9]+\\b'
'name': 'constant.numeric.jack'
}
{
'comment': 'boolean and null constant'
'match': '\\b(null|true|false)\\b'
'name': 'constant.language.jack'
}
{
'comment': 'string constant'
'match': '\\".*?\\"'
'name': 'string.quoted.jack'
}
{
'comment': 'pointer variable'
'match': '\\b(this)\\b'
'captures':
'1':
'name': 'variable.language.jack'
}
{
'comment': 'symbolic operator'
'match': '(\\+|\\-|\\*|\\/|\\>|\\<|\\~|\\&|\\|)'
'captures':
'1':
'name': 'variable.operator.jack'
}
{
'comment': 'language keyword'
'match': '\\b(class|function|method|constructor|var|static|field|let|do|else|if|return|while)\\b'
'captures':
'1':
'name': 'keyword.jack'
}
{
'comment': 'variable type'
'match': '\\b(void|boolean|int|char)\\b'
'captures':
'1':
'name': 'support.type.jack'
}
{
'comment': 'class identifier'
'match': '\\b([A-Z][a-zA-Z]*)\\b \\{'
'captures':
'1':
'name': 'support.class.jack'
}
{
'comment': 'function identifier'
'match': '\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b *\\('
'captures':
'1':
'name': 'entity.name.function.jack'
}
]
| true | # If this is your first time writing a language grammar, check out:
# - https://flight-manual.atom.io/hacking-atom/sections/creating-a-grammar/
'scopeName': 'source.jack'
'name': 'PI:NAME:<NAME>END_PI'
'fileTypes': [
'jack'
]
'patterns': [
{
'comment': 'one line comment'
'match': '//.*$'
'name': 'comment.line.jack'
}
{
'comment': 'multi-line comment'
'begin': '/\\*'
'end': '\\*/'
'name': 'comment.block.jack'
}
{
'comment': 'documantation comment'
'begin': '/\\*\\*'
'end': '\\*/'
'name': 'comment.block.documentation.jack'
}
{
'comment': 'numeric constant'
'match': '\\b[0-9]+\\b'
'name': 'constant.numeric.jack'
}
{
'comment': 'boolean and null constant'
'match': '\\b(null|true|false)\\b'
'name': 'constant.language.jack'
}
{
'comment': 'string constant'
'match': '\\".*?\\"'
'name': 'string.quoted.jack'
}
{
'comment': 'pointer variable'
'match': '\\b(this)\\b'
'captures':
'1':
'name': 'variable.language.jack'
}
{
'comment': 'symbolic operator'
'match': '(\\+|\\-|\\*|\\/|\\>|\\<|\\~|\\&|\\|)'
'captures':
'1':
'name': 'variable.operator.jack'
}
{
'comment': 'language keyword'
'match': '\\b(class|function|method|constructor|var|static|field|let|do|else|if|return|while)\\b'
'captures':
'1':
'name': 'keyword.jack'
}
{
'comment': 'variable type'
'match': '\\b(void|boolean|int|char)\\b'
'captures':
'1':
'name': 'support.type.jack'
}
{
'comment': 'class identifier'
'match': '\\b([A-Z][a-zA-Z]*)\\b \\{'
'captures':
'1':
'name': 'support.class.jack'
}
{
'comment': 'function identifier'
'match': '\\b([a-zA-Z_][a-zA-Z0-9_]*)\\b *\\('
'captures':
'1':
'name': 'entity.name.function.jack'
}
]
|
[
{
"context": "ormation, please see the LICENSE file\n\n@author Bryan Conrad <bkconrad@gmail.com>\n@copyright 2016 Bryan Conra",
"end": 156,
"score": 0.9998842477798462,
"start": 144,
"tag": "NAME",
"value": "Bryan Conrad"
},
{
"context": "e see the LICENSE file\n\n@author Br... | gruntfile.coffee | pieterbrandsen/screeps-grafana | 70 | ###
hopsoft\screeps-statsd
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author Bryan Conrad <bkconrad@gmail.com>
@copyright 2016 Bryan Conrad
@link https://github.com/hopsoft/docker-graphite-statsd
@license http://choosealicense.com/licenses/MIT MIT License
###
module.exports = ( grunt ) ->
### ALIASES ###
jsonFile = grunt.file.readJSON # Read a json file
define = grunt.registerTask # Register a local task
log = grunt.log.writeln # Write a single line to STDOUT
### GRUNT CONFIGURATION ###
config =
# Define aliases for known fs locations
srcDir: 'src/' # CoffeeScript or other source files to be compiled or processed
tstDir: 'test/' # Project's tests
resDir: 'res/' # Static resources - images, text files, external deps etc.
docDir: 'docs/' # Automatically-generated or compiled documentation
srcFiles: ['<%= srcDir %>**/*.coffee', 'index.coffee']
tstFiles: '<%= tstDir %>**/*.test.coffee'
pkg: jsonFile 'package.json'
### TASKS DEFINITION ###
# grunt-contrib-watch: Run tasks on filesystem changes
watch:
options:
# Define default tasks here, then point targets' "tasks" attribute here: '<%= watch.options.tasks %>'
tasks: ['lint', 'test'] # Run these tasks when a change is detected
interrupt: true # Restarts any running tasks on next event
atBegin: true # Runs all defined watch tasks on startup
dateFormat: ( time ) -> log "Done in #{time}ms"
# Targets
gruntfile: # Watch the gruntfile for changes ( also dynamically reloads grunt-watch config )
files: 'gruntfile.coffee'
tasks: '<%= watch.options.tasks %>'
project: # Watch the project's source files for changes
files: ['<%= srcFiles %>', '<%= tstFiles %>']
tasks: '<%= watch.options.tasks %>'
# grunt-coffeelint: Lint CoffeeScript files
coffeelint:
options: jsonFile 'coffeelint.json'
# Targets
gruntfile: 'gruntfile.coffee' # Lint this file
project: ['<%= srcFiles %>', '<%= tstFiles %>'] # Lint application's project files
# grunt-mocha-cli: Run tests with Mocha framework
mochacli:
options:
reporter: 'spec' # This report is nice and human-readable
require: ['should'] # Run the tests using Should.js
compilers: ['coffee:coffee-script/register']
# Targets
project: # Run the project's tests
src: ['<%= tstFiles %>']
# grunt-codo: CoffeeScript API documentation generator
codo:
options:
title: 'screeps-statsd'
debug: false
inputs: ['<%= srcDir %>']
output: '<%= docDir %>'
# grunt-contrib-coffee: Compile CoffeeScript into native JavaScript
coffee:
# Targets
build: # Compile CoffeeScript into target build directory
expand: true
ext: '.js'
src: '<%= srcFiles %>'
dest: '<%= libDir %>'
# grunt-contrib-uglify: Compress and mangle JavaScript files
uglify:
# Targets
build:
files: [
expand: true
src: '<%= srcDir %>**/*.js'
]
# grunt-contrib-clean: Clean the target files & folders, deleting anything inside
clean:
# Targets
build: ['<%= srcDir %>**/*.js', 'index.js'] # Clean the build products
docs: ['<%= docDir %>']
###############################################################################
### CUSTOM FUNCTIONS ###
### GRUNT MODULES ###
# Loads all grunt tasks from devDependencies starting with "grunt-"
require( 'load-grunt-tasks' )( grunt )
### GRUNT TASKS ###
define 'lint', ['coffeelint']
define 'test', ['mochacli']
define 'docs', ['codo']
define 'build:dev', ['clean:build', 'lint', 'test', 'coffee:build']
define 'build', ['build:dev', 'uglify:build']
define 'default', ['build']
###############################################################################
grunt.initConfig config
| 36378 | ###
hopsoft\screeps-statsd
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author <NAME> <<EMAIL>>
@copyright 2016 <NAME>
@link https://github.com/hopsoft/docker-graphite-statsd
@license http://choosealicense.com/licenses/MIT MIT License
###
module.exports = ( grunt ) ->
### ALIASES ###
jsonFile = grunt.file.readJSON # Read a json file
define = grunt.registerTask # Register a local task
log = grunt.log.writeln # Write a single line to STDOUT
### GRUNT CONFIGURATION ###
config =
# Define aliases for known fs locations
srcDir: 'src/' # CoffeeScript or other source files to be compiled or processed
tstDir: 'test/' # Project's tests
resDir: 'res/' # Static resources - images, text files, external deps etc.
docDir: 'docs/' # Automatically-generated or compiled documentation
srcFiles: ['<%= srcDir %>**/*.coffee', 'index.coffee']
tstFiles: '<%= tstDir %>**/*.test.coffee'
pkg: jsonFile 'package.json'
### TASKS DEFINITION ###
# grunt-contrib-watch: Run tasks on filesystem changes
watch:
options:
# Define default tasks here, then point targets' "tasks" attribute here: '<%= watch.options.tasks %>'
tasks: ['lint', 'test'] # Run these tasks when a change is detected
interrupt: true # Restarts any running tasks on next event
atBegin: true # Runs all defined watch tasks on startup
dateFormat: ( time ) -> log "Done in #{time}ms"
# Targets
gruntfile: # Watch the gruntfile for changes ( also dynamically reloads grunt-watch config )
files: 'gruntfile.coffee'
tasks: '<%= watch.options.tasks %>'
project: # Watch the project's source files for changes
files: ['<%= srcFiles %>', '<%= tstFiles %>']
tasks: '<%= watch.options.tasks %>'
# grunt-coffeelint: Lint CoffeeScript files
coffeelint:
options: jsonFile 'coffeelint.json'
# Targets
gruntfile: 'gruntfile.coffee' # Lint this file
project: ['<%= srcFiles %>', '<%= tstFiles %>'] # Lint application's project files
# grunt-mocha-cli: Run tests with Mocha framework
mochacli:
options:
reporter: 'spec' # This report is nice and human-readable
require: ['should'] # Run the tests using Should.js
compilers: ['coffee:coffee-script/register']
# Targets
project: # Run the project's tests
src: ['<%= tstFiles %>']
# grunt-codo: CoffeeScript API documentation generator
codo:
options:
title: 'screeps-statsd'
debug: false
inputs: ['<%= srcDir %>']
output: '<%= docDir %>'
# grunt-contrib-coffee: Compile CoffeeScript into native JavaScript
coffee:
# Targets
build: # Compile CoffeeScript into target build directory
expand: true
ext: '.js'
src: '<%= srcFiles %>'
dest: '<%= libDir %>'
# grunt-contrib-uglify: Compress and mangle JavaScript files
uglify:
# Targets
build:
files: [
expand: true
src: '<%= srcDir %>**/*.js'
]
# grunt-contrib-clean: Clean the target files & folders, deleting anything inside
clean:
# Targets
build: ['<%= srcDir %>**/*.js', 'index.js'] # Clean the build products
docs: ['<%= docDir %>']
###############################################################################
### CUSTOM FUNCTIONS ###
### GRUNT MODULES ###
# Loads all grunt tasks from devDependencies starting with "grunt-"
require( 'load-grunt-tasks' )( grunt )
### GRUNT TASKS ###
define 'lint', ['coffeelint']
define 'test', ['mochacli']
define 'docs', ['codo']
define 'build:dev', ['clean:build', 'lint', 'test', 'coffee:build']
define 'build', ['build:dev', 'uglify:build']
define 'default', ['build']
###############################################################################
grunt.initConfig config
| true | ###
hopsoft\screeps-statsd
Licensed under the MIT license
For full copyright and license information, please see the LICENSE file
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
@copyright 2016 PI:NAME:<NAME>END_PI
@link https://github.com/hopsoft/docker-graphite-statsd
@license http://choosealicense.com/licenses/MIT MIT License
###
module.exports = ( grunt ) ->
### ALIASES ###
jsonFile = grunt.file.readJSON # Read a json file
define = grunt.registerTask # Register a local task
log = grunt.log.writeln # Write a single line to STDOUT
### GRUNT CONFIGURATION ###
config =
# Define aliases for known fs locations
srcDir: 'src/' # CoffeeScript or other source files to be compiled or processed
tstDir: 'test/' # Project's tests
resDir: 'res/' # Static resources - images, text files, external deps etc.
docDir: 'docs/' # Automatically-generated or compiled documentation
srcFiles: ['<%= srcDir %>**/*.coffee', 'index.coffee']
tstFiles: '<%= tstDir %>**/*.test.coffee'
pkg: jsonFile 'package.json'
### TASKS DEFINITION ###
# grunt-contrib-watch: Run tasks on filesystem changes
watch:
options:
# Define default tasks here, then point targets' "tasks" attribute here: '<%= watch.options.tasks %>'
tasks: ['lint', 'test'] # Run these tasks when a change is detected
interrupt: true # Restarts any running tasks on next event
atBegin: true # Runs all defined watch tasks on startup
dateFormat: ( time ) -> log "Done in #{time}ms"
# Targets
gruntfile: # Watch the gruntfile for changes ( also dynamically reloads grunt-watch config )
files: 'gruntfile.coffee'
tasks: '<%= watch.options.tasks %>'
project: # Watch the project's source files for changes
files: ['<%= srcFiles %>', '<%= tstFiles %>']
tasks: '<%= watch.options.tasks %>'
# grunt-coffeelint: Lint CoffeeScript files
coffeelint:
options: jsonFile 'coffeelint.json'
# Targets
gruntfile: 'gruntfile.coffee' # Lint this file
project: ['<%= srcFiles %>', '<%= tstFiles %>'] # Lint application's project files
# grunt-mocha-cli: Run tests with Mocha framework
mochacli:
options:
reporter: 'spec' # This report is nice and human-readable
require: ['should'] # Run the tests using Should.js
compilers: ['coffee:coffee-script/register']
# Targets
project: # Run the project's tests
src: ['<%= tstFiles %>']
# grunt-codo: CoffeeScript API documentation generator
codo:
options:
title: 'screeps-statsd'
debug: false
inputs: ['<%= srcDir %>']
output: '<%= docDir %>'
# grunt-contrib-coffee: Compile CoffeeScript into native JavaScript
coffee:
# Targets
build: # Compile CoffeeScript into target build directory
expand: true
ext: '.js'
src: '<%= srcFiles %>'
dest: '<%= libDir %>'
# grunt-contrib-uglify: Compress and mangle JavaScript files
uglify:
# Targets
build:
files: [
expand: true
src: '<%= srcDir %>**/*.js'
]
# grunt-contrib-clean: Clean the target files & folders, deleting anything inside
clean:
# Targets
build: ['<%= srcDir %>**/*.js', 'index.js'] # Clean the build products
docs: ['<%= docDir %>']
###############################################################################
### CUSTOM FUNCTIONS ###
### GRUNT MODULES ###
# Loads all grunt tasks from devDependencies starting with "grunt-"
require( 'load-grunt-tasks' )( grunt )
### GRUNT TASKS ###
define 'lint', ['coffeelint']
define 'test', ['mochacli']
define 'docs', ['codo']
define 'build:dev', ['clean:build', 'lint', 'test', 'coffee:build']
define 'build', ['build:dev', 'uglify:build']
define 'default', ['build']
###############################################################################
grunt.initConfig config
|
[
{
"context": "Doris Ursula Camilla Eugenia Iris Amphitrite\"\n\t\n\t\"Shakespeare\"\n\t\"Two households, both alike in dignity,\\nIn fai",
"end": 484,
"score": 0.8725191950798035,
"start": 473,
"tag": "NAME",
"value": "Shakespeare"
},
{
"context": "n (discrete-time Markov chain or DT... | word-generator.coffee | SyntaxColoring/Markov-Word-Generator | 33 | ### Corpus Presets: ###
# For conciseness, the corpus presets are defined as a flat array
# containing name/content pairs. The last element is always treated as
# the "custom" user-input corpus.
corpora = [
"Astronomy"
"Sun Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto Ceres Pallas Vesta Hygiea Interamnia Europa Davida Sylvia Cybele Eunomia Juno Euphrosyne Hektor Thisbe Bamberga Patientia Herculina Doris Ursula Camilla Eugenia Iris Amphitrite"
"Shakespeare"
"Two households, both alike in dignity,\nIn fair Verona, where we lay our scene,\nFrom ancient grudge break to new mutiny,\nWhere civil blood makes civil hands unclean.\nFrom forth the fatal loins of these two foes\nA pair of star-cross'd lovers take their life;\nWhose misadventured piteous overthrows\nDo with their death bury their parents' strife.\nThe fearful passage of their death-mark'd love,\nAnd the continuance of their parents' rage,\nWhich, but their children's end, nought could remove,\nIs now the two hours' traffic of our stage;\nThe which if you with patient ears attend,\nWhat here shall miss, our toil shall strive to mend."
"Lorem ipsum"
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique a massa in feugiat. Donec rhoncus ante at lectus sollicitudin fermentum. Donec non massa arcu. Vestibulum sodales eros quis lacus cursus, egestas varius felis tincidunt. Donec pulvinar erat risus. Sed eu odio sit amet velit accumsan gravida. Ut eu tempor justo, in dignissim elit. Nam sollicitudin, sapien id tincidunt bibendum, purus elit feugiat mauris, vitae congue nibh massa ac ligula. Vestibulum auctor ultricies nunc non fermentum. Ut ultrices, magna et interdum varius, elit nisi dignissim augue, nec rutrum erat tortor eu nisl. In sed convallis sapien. Morbi adipiscing erat sed imperdiet feugiat. Ut ac interdum justo. Vestibulum in mauris in nulla viverra consequat. Nullam ultricies malesuada nulla, eu sollicitudin purus scelerisque bibendum."
"Wikipedia"
'A Markov chain (discrete-time Markov chain or DTMC) named after Andrey Markov, is a mathematical system that undergoes transitions from one state to another, among a finite or countable number of possible states. It is a random process usually characterized as memoryless: the next state depends only on the current state and not on the sequence of events that preceded it. This specific kind of "memorylessness" is called the Markov property. Markov chains have many applications as statistical models of real-world processes.'
"(Custom)"
""
]
# This flat array is an annoying format to work with later on, though,
# so it is "unflattened" here into an array of {name, content} objects.
# Note that although this could be avoided by defining the corpora as
# properties of a corpus object, doing it that way would lose their ordering.
corpora = ({ name: x, content: corpora[i+1] } for x, i in corpora by 2)
### UI And Initialization: ###
$ ->
$word = $("#word")
$button = $("#button")
$corpusName = $("#corpusName")
$corpora = $("#corpora")
$corpusInput = $("#corpusInput")
$order = $("#order")
$maxLength = $("#maxLength")
parseWords = (rawInput) ->
rawInput.toLowerCase().replace(/[^a-z\s]/g, "").split(/\s/g)
capitalize = (string) ->
if string.length > 0 then string[0].toUpperCase() + string.slice(1)
else ""
selectCorpus = (index) ->
$corpusName.text(corpora[index].name)
$corpusInput.val(corpora[index].content)
markovChain.sequences = parseWords corpora[index].content
populatePresetDropdown = ->
for corpus, index in corpora
do (corpus, index) ->
if index is corpora.length - 1
$corpora.append('<li class = "divider">')
newLink = $("<a href = \"#\">#{corpus.name}</a>")
newLink.click((event) -> event.preventDefault(); selectCorpus index)
$("<li>").append(newLink).appendTo($corpora)
generateAndShow = ->
$word.text capitalize markovChain.generate().join("")
# If the user types in the <textarea>, copy the updates into the custom
# corpus and select that as the active corpus.
$corpusInput.on "input propertychange", ->
text = $corpusInput.val();
corpora[corpora.length-1].content = $corpusInput.val();
selectCorpus corpora.length-1;
$order.change ->
markovChain.n = +@value
@value = markovChain.n
$maxLength.change ->
markovChain.maxLength = Math.max +@value , 1
@value = markovChain.maxLength
$button.click generateAndShow
markovChain = new Markov
populatePresetDropdown();
selectCorpus 0
$order.change()
$maxLength.change()
generateAndShow()
| 225560 | ### Corpus Presets: ###
# For conciseness, the corpus presets are defined as a flat array
# containing name/content pairs. The last element is always treated as
# the "custom" user-input corpus.
corpora = [
"Astronomy"
"Sun Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto Ceres Pallas Vesta Hygiea Interamnia Europa Davida Sylvia Cybele Eunomia Juno Euphrosyne Hektor Thisbe Bamberga Patientia Herculina Doris Ursula Camilla Eugenia Iris Amphitrite"
"<NAME>"
"Two households, both alike in dignity,\nIn fair Verona, where we lay our scene,\nFrom ancient grudge break to new mutiny,\nWhere civil blood makes civil hands unclean.\nFrom forth the fatal loins of these two foes\nA pair of star-cross'd lovers take their life;\nWhose misadventured piteous overthrows\nDo with their death bury their parents' strife.\nThe fearful passage of their death-mark'd love,\nAnd the continuance of their parents' rage,\nWhich, but their children's end, nought could remove,\nIs now the two hours' traffic of our stage;\nThe which if you with patient ears attend,\nWhat here shall miss, our toil shall strive to mend."
"Lorem ipsum"
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique a massa in feugiat. Donec rhoncus ante at lectus sollicitudin fermentum. Donec non massa arcu. Vestibulum sodales eros quis lacus cursus, egestas varius felis tincidunt. Donec pulvinar erat risus. Sed eu odio sit amet velit accumsan gravida. Ut eu tempor justo, in dignissim elit. Nam sollicitudin, sapien id tincidunt bibendum, purus elit feugiat mauris, vitae congue nibh massa ac ligula. Vestibulum auctor ultricies nunc non fermentum. Ut ultrices, magna et interdum varius, elit nisi dignissim augue, nec rutrum erat tortor eu nisl. In sed convallis sapien. Morbi adipiscing erat sed imperdiet feugiat. Ut ac interdum justo. Vestibulum in mauris in nulla viverra consequat. Nullam ultricies malesuada nulla, eu sollicitudin purus scelerisque bibendum."
"Wikipedia"
'A Markov chain (discrete-time Markov chain or DTMC) named after <NAME>, is a mathematical system that undergoes transitions from one state to another, among a finite or countable number of possible states. It is a random process usually characterized as memoryless: the next state depends only on the current state and not on the sequence of events that preceded it. This specific kind of "memorylessness" is called the Markov property. Markov chains have many applications as statistical models of real-world processes.'
"(Custom)"
""
]
# This flat array is an annoying format to work with later on, though,
# so it is "unflattened" here into an array of {name, content} objects.
# Note that although this could be avoided by defining the corpora as
# properties of a corpus object, doing it that way would lose their ordering.
corpora = ({ name: x, content: corpora[i+1] } for x, i in corpora by 2)
### UI And Initialization: ###
$ ->
$word = $("#word")
$button = $("#button")
$corpusName = $("#corpusName")
$corpora = $("#corpora")
$corpusInput = $("#corpusInput")
$order = $("#order")
$maxLength = $("#maxLength")
parseWords = (rawInput) ->
rawInput.toLowerCase().replace(/[^a-z\s]/g, "").split(/\s/g)
capitalize = (string) ->
if string.length > 0 then string[0].toUpperCase() + string.slice(1)
else ""
selectCorpus = (index) ->
$corpusName.text(corpora[index].name)
$corpusInput.val(corpora[index].content)
markovChain.sequences = parseWords corpora[index].content
populatePresetDropdown = ->
for corpus, index in corpora
do (corpus, index) ->
if index is corpora.length - 1
$corpora.append('<li class = "divider">')
newLink = $("<a href = \"#\">#{corpus.name}</a>")
newLink.click((event) -> event.preventDefault(); selectCorpus index)
$("<li>").append(newLink).appendTo($corpora)
generateAndShow = ->
$word.text capitalize markovChain.generate().join("")
# If the user types in the <textarea>, copy the updates into the custom
# corpus and select that as the active corpus.
$corpusInput.on "input propertychange", ->
text = $corpusInput.val();
corpora[corpora.length-1].content = $corpusInput.val();
selectCorpus corpora.length-1;
$order.change ->
markovChain.n = +@value
@value = markovChain.n
$maxLength.change ->
markovChain.maxLength = Math.max +@value , 1
@value = markovChain.maxLength
$button.click generateAndShow
markovChain = new Markov
populatePresetDropdown();
selectCorpus 0
$order.change()
$maxLength.change()
generateAndShow()
| true | ### Corpus Presets: ###
# For conciseness, the corpus presets are defined as a flat array
# containing name/content pairs. The last element is always treated as
# the "custom" user-input corpus.
corpora = [
"Astronomy"
"Sun Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto Ceres Pallas Vesta Hygiea Interamnia Europa Davida Sylvia Cybele Eunomia Juno Euphrosyne Hektor Thisbe Bamberga Patientia Herculina Doris Ursula Camilla Eugenia Iris Amphitrite"
"PI:NAME:<NAME>END_PI"
"Two households, both alike in dignity,\nIn fair Verona, where we lay our scene,\nFrom ancient grudge break to new mutiny,\nWhere civil blood makes civil hands unclean.\nFrom forth the fatal loins of these two foes\nA pair of star-cross'd lovers take their life;\nWhose misadventured piteous overthrows\nDo with their death bury their parents' strife.\nThe fearful passage of their death-mark'd love,\nAnd the continuance of their parents' rage,\nWhich, but their children's end, nought could remove,\nIs now the two hours' traffic of our stage;\nThe which if you with patient ears attend,\nWhat here shall miss, our toil shall strive to mend."
"Lorem ipsum"
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tristique a massa in feugiat. Donec rhoncus ante at lectus sollicitudin fermentum. Donec non massa arcu. Vestibulum sodales eros quis lacus cursus, egestas varius felis tincidunt. Donec pulvinar erat risus. Sed eu odio sit amet velit accumsan gravida. Ut eu tempor justo, in dignissim elit. Nam sollicitudin, sapien id tincidunt bibendum, purus elit feugiat mauris, vitae congue nibh massa ac ligula. Vestibulum auctor ultricies nunc non fermentum. Ut ultrices, magna et interdum varius, elit nisi dignissim augue, nec rutrum erat tortor eu nisl. In sed convallis sapien. Morbi adipiscing erat sed imperdiet feugiat. Ut ac interdum justo. Vestibulum in mauris in nulla viverra consequat. Nullam ultricies malesuada nulla, eu sollicitudin purus scelerisque bibendum."
"Wikipedia"
'A Markov chain (discrete-time Markov chain or DTMC) named after PI:NAME:<NAME>END_PI, is a mathematical system that undergoes transitions from one state to another, among a finite or countable number of possible states. It is a random process usually characterized as memoryless: the next state depends only on the current state and not on the sequence of events that preceded it. This specific kind of "memorylessness" is called the Markov property. Markov chains have many applications as statistical models of real-world processes.'
"(Custom)"
""
]
# This flat array is an annoying format to work with later on, though,
# so it is "unflattened" here into an array of {name, content} objects.
# Note that although this could be avoided by defining the corpora as
# properties of a corpus object, doing it that way would lose their ordering.
corpora = ({ name: x, content: corpora[i+1] } for x, i in corpora by 2)
### UI And Initialization: ###
$ ->
$word = $("#word")
$button = $("#button")
$corpusName = $("#corpusName")
$corpora = $("#corpora")
$corpusInput = $("#corpusInput")
$order = $("#order")
$maxLength = $("#maxLength")
parseWords = (rawInput) ->
rawInput.toLowerCase().replace(/[^a-z\s]/g, "").split(/\s/g)
capitalize = (string) ->
if string.length > 0 then string[0].toUpperCase() + string.slice(1)
else ""
selectCorpus = (index) ->
$corpusName.text(corpora[index].name)
$corpusInput.val(corpora[index].content)
markovChain.sequences = parseWords corpora[index].content
populatePresetDropdown = ->
for corpus, index in corpora
do (corpus, index) ->
if index is corpora.length - 1
$corpora.append('<li class = "divider">')
newLink = $("<a href = \"#\">#{corpus.name}</a>")
newLink.click((event) -> event.preventDefault(); selectCorpus index)
$("<li>").append(newLink).appendTo($corpora)
generateAndShow = ->
$word.text capitalize markovChain.generate().join("")
# If the user types in the <textarea>, copy the updates into the custom
# corpus and select that as the active corpus.
$corpusInput.on "input propertychange", ->
text = $corpusInput.val();
corpora[corpora.length-1].content = $corpusInput.val();
selectCorpus corpora.length-1;
$order.change ->
markovChain.n = +@value
@value = markovChain.n
$maxLength.change ->
markovChain.maxLength = Math.max +@value , 1
@value = markovChain.maxLength
$button.click generateAndShow
markovChain = new Markov
populatePresetDropdown();
selectCorpus 0
$order.change()
$maxLength.change()
generateAndShow()
|
[
{
"context": "# Description:\n# Display quote from \"Dans Ton Chat <http://danstonchat.com>\".\n#\n# Dependencies:\n# ",
"end": 52,
"score": 0.9952050447463989,
"start": 39,
"tag": "NAME",
"value": "Dans Ton Chat"
},
{
"context": " hubot dtc - Returns random quote\n#\n# Author:\... | src/dtc.coffee | eunomie/hubot-dtc | 0 | # Description:
# Display quote from "Dans Ton Chat <http://danstonchat.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot dernier dans ton chat- Returns last quote
# hubot dtc - Returns random quote
#
# Author:
# Eunomie
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /dernier dans ton chat/i, (message)->
send_quote message, 'http://danstonchat.com', (text)->
message.send text
robot.respond /dtc/i, (message)->
send_quote message, 'http://danstonchat.com/random.html', (text)->
message.send text
send_quote = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_quote(message, location, response_handler)
txt = get_quote(body, "p.item-content a")
response_handler txt
get_quote = (body, selector)->
$ = cheerio.load(body)
res = []
$(selector).first().contents().map((i, el) ->
$(this).text()
).filter((i, txt) ->
txt != ''
).map((i, txt) ->
res.push txt
)
he.decode res.join '\n'
| 43948 | # Description:
# Display quote from "<NAME> <http://danstonchat.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot dernier dans ton chat- Returns last quote
# hubot dtc - Returns random quote
#
# Author:
# Eunomie
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /dernier dans ton chat/i, (message)->
send_quote message, 'http://danstonchat.com', (text)->
message.send text
robot.respond /dtc/i, (message)->
send_quote message, 'http://danstonchat.com/random.html', (text)->
message.send text
send_quote = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_quote(message, location, response_handler)
txt = get_quote(body, "p.item-content a")
response_handler txt
get_quote = (body, selector)->
$ = cheerio.load(body)
res = []
$(selector).first().contents().map((i, el) ->
$(this).text()
).filter((i, txt) ->
txt != ''
).map((i, txt) ->
res.push txt
)
he.decode res.join '\n'
| true | # Description:
# Display quote from "PI:NAME:<NAME>END_PI <http://danstonchat.com>".
#
# Dependencies:
# "cheerio": "0.7.0"
# "he": "0.4.1"
#
# Configuration:
# None
#
# Commands:
# hubot dernier dans ton chat- Returns last quote
# hubot dtc - Returns random quote
#
# Author:
# Eunomie
cheerio = require('cheerio')
he = require('he')
module.exports = (robot)->
robot.respond /dernier dans ton chat/i, (message)->
send_quote message, 'http://danstonchat.com', (text)->
message.send text
robot.respond /dtc/i, (message)->
send_quote message, 'http://danstonchat.com/random.html', (text)->
message.send text
send_quote = (message, location, response_handler)->
url = location
message.http(url).get() (error, response, body)->
return response_handler "Sorry, something went wrong" if error
if response.statusCode == 302 || response.statusCode == 301
location = response.headers['location']
return send_quote(message, location, response_handler)
txt = get_quote(body, "p.item-content a")
response_handler txt
get_quote = (body, selector)->
$ = cheerio.load(body)
res = []
$(selector).first().contents().map((i, el) ->
$(this).text()
).filter((i, txt) ->
txt != ''
).map((i, txt) ->
res.push txt
)
he.decode res.join '\n'
|
[
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author greggman / http://",
"end": 17,
"score": 0.8696086406707764,
"start": 10,
"tag": "USERNAME",
"value": "mr.doob"
},
{
"context": "# @author mr.doob / http://mrdoob.com/\n# @author greggman / http://games.greggman.com/\n# ... | source/javascripts/new_src/cameras/perspective.coffee | andrew-aladev/three.js | 0 | # @author mr.doob / http://mrdoob.com/
# @author greggman / http://games.greggman.com/
# @author zz85 / http://www.lab4games.net/zz85/blog
# @author aladjev.andrew@gmail.com
#= require new_src/cameras/camera
class PerspectiveCamera extends THREE.Camera
constructor: (fov, aspect, near, far) ->
super()
@fov = (if fov isnt undefined then fov else 50)
@aspect = (if aspect isnt undefined then aspect else 1)
@near = (if near isnt undefined then near else 0.1)
@far = (if far isnt undefined then far else 2000)
@updateProjectionMatrix()
# Uses Focal Length (in mm) to estimate and set FOV
# 35mm (fullframe) camera is used if frame size is not specified;
# Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
setLens: (focalLength, frameHeight) ->
frameHeight = (if frameHeight isnt undefined then frameHeight else 24)
@fov = 2 * Math.atan(frameHeight / (focalLength * 2)) * (180 / Math.PI)
@updateProjectionMatrix()
# Sets an offset in a larger frustum. This is useful for multi-window or
# multi-monitor/multi-machine setups.
#
# For example, if you have 3x2 monitors and each monitor is 1920x1080 and
# the monitors are in grid like this
#
# +---+---+---+
# | A | B | C |
# +---+---+---+
# | D | E | F |
# +---+---+---+
#
# then for each monitor you would call it like this
#
# var w = 1920;
# var h = 1080;
# var fullWidth = w * 3;
# var fullHeight = h * 2;
#
# --A--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
# --B--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
# --C--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
# --D--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
# --E--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
# --F--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
#
# Note there is no reason monitors have to be the same size or in a grid.
setViewOffset: (fullWidth, fullHeight, x, y, width, height) ->
@fullWidth = fullWidth
@fullHeight = fullHeight
@x = x
@y = y
@width = width
@height = height
@updateProjectionMatrix()
updateProjectionMatrix: ->
if @fullWidth
aspect = @fullWidth / @fullHeight
top = Math.tan(@fov * Math.PI / 360) * @near
bottom = -top
left = aspect * bottom
right = aspect * top
width = Math.abs(right - left)
height = Math.abs(top - bottom)
@projectionMatrix.makeFrustum(
left + @x * width / @fullWidth
left + (@x + @width) * width / @fullWidth
top - (@y + @height) * height / @fullHeight
top - @y * height / @fullHeight
@near
@far
)
else
@projectionMatrix.makePerspective @fov, @aspect, @near, @far
namespace "THREE", (exports) ->
exports.PerspectiveCamera = PerspectiveCamera | 118594 | # @author mr.doob / http://mrdoob.com/
# @author greggman / http://games.greggman.com/
# @author zz85 / http://www.lab4games.net/zz85/blog
# @author <EMAIL>
#= require new_src/cameras/camera
class PerspectiveCamera extends THREE.Camera
constructor: (fov, aspect, near, far) ->
super()
@fov = (if fov isnt undefined then fov else 50)
@aspect = (if aspect isnt undefined then aspect else 1)
@near = (if near isnt undefined then near else 0.1)
@far = (if far isnt undefined then far else 2000)
@updateProjectionMatrix()
# Uses Focal Length (in mm) to estimate and set FOV
# 35mm (fullframe) camera is used if frame size is not specified;
# Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
setLens: (focalLength, frameHeight) ->
frameHeight = (if frameHeight isnt undefined then frameHeight else 24)
@fov = 2 * Math.atan(frameHeight / (focalLength * 2)) * (180 / Math.PI)
@updateProjectionMatrix()
# Sets an offset in a larger frustum. This is useful for multi-window or
# multi-monitor/multi-machine setups.
#
# For example, if you have 3x2 monitors and each monitor is 1920x1080 and
# the monitors are in grid like this
#
# +---+---+---+
# | A | B | C |
# +---+---+---+
# | D | E | F |
# +---+---+---+
#
# then for each monitor you would call it like this
#
# var w = 1920;
# var h = 1080;
# var fullWidth = w * 3;
# var fullHeight = h * 2;
#
# --A--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
# --B--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
# --C--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
# --D--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
# --E--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
# --F--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
#
# Note there is no reason monitors have to be the same size or in a grid.
setViewOffset: (fullWidth, fullHeight, x, y, width, height) ->
@fullWidth = fullWidth
@fullHeight = fullHeight
@x = x
@y = y
@width = width
@height = height
@updateProjectionMatrix()
updateProjectionMatrix: ->
if @fullWidth
aspect = @fullWidth / @fullHeight
top = Math.tan(@fov * Math.PI / 360) * @near
bottom = -top
left = aspect * bottom
right = aspect * top
width = Math.abs(right - left)
height = Math.abs(top - bottom)
@projectionMatrix.makeFrustum(
left + @x * width / @fullWidth
left + (@x + @width) * width / @fullWidth
top - (@y + @height) * height / @fullHeight
top - @y * height / @fullHeight
@near
@far
)
else
@projectionMatrix.makePerspective @fov, @aspect, @near, @far
namespace "THREE", (exports) ->
exports.PerspectiveCamera = PerspectiveCamera | true | # @author mr.doob / http://mrdoob.com/
# @author greggman / http://games.greggman.com/
# @author zz85 / http://www.lab4games.net/zz85/blog
# @author PI:EMAIL:<EMAIL>END_PI
#= require new_src/cameras/camera
class PerspectiveCamera extends THREE.Camera
constructor: (fov, aspect, near, far) ->
super()
@fov = (if fov isnt undefined then fov else 50)
@aspect = (if aspect isnt undefined then aspect else 1)
@near = (if near isnt undefined then near else 0.1)
@far = (if far isnt undefined then far else 2000)
@updateProjectionMatrix()
# Uses Focal Length (in mm) to estimate and set FOV
# 35mm (fullframe) camera is used if frame size is not specified;
# Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
setLens: (focalLength, frameHeight) ->
frameHeight = (if frameHeight isnt undefined then frameHeight else 24)
@fov = 2 * Math.atan(frameHeight / (focalLength * 2)) * (180 / Math.PI)
@updateProjectionMatrix()
# Sets an offset in a larger frustum. This is useful for multi-window or
# multi-monitor/multi-machine setups.
#
# For example, if you have 3x2 monitors and each monitor is 1920x1080 and
# the monitors are in grid like this
#
# +---+---+---+
# | A | B | C |
# +---+---+---+
# | D | E | F |
# +---+---+---+
#
# then for each monitor you would call it like this
#
# var w = 1920;
# var h = 1080;
# var fullWidth = w * 3;
# var fullHeight = h * 2;
#
# --A--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
# --B--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
# --C--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
# --D--
# camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
# --E--
# camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
# --F--
# camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
#
# Note there is no reason monitors have to be the same size or in a grid.
setViewOffset: (fullWidth, fullHeight, x, y, width, height) ->
@fullWidth = fullWidth
@fullHeight = fullHeight
@x = x
@y = y
@width = width
@height = height
@updateProjectionMatrix()
updateProjectionMatrix: ->
if @fullWidth
aspect = @fullWidth / @fullHeight
top = Math.tan(@fov * Math.PI / 360) * @near
bottom = -top
left = aspect * bottom
right = aspect * top
width = Math.abs(right - left)
height = Math.abs(top - bottom)
@projectionMatrix.makeFrustum(
left + @x * width / @fullWidth
left + (@x + @width) * width / @fullWidth
top - (@y + @height) * height / @fullHeight
top - @y * height / @fullHeight
@near
@far
)
else
@projectionMatrix.makePerspective @fov, @aspect, @near, @far
namespace "THREE", (exports) ->
exports.PerspectiveCamera = PerspectiveCamera |
[
{
"context": "ample\n <input ts-validate-password-confirmation=\"password\">\n\n The directive requires the password variable",
"end": 171,
"score": 0.9941399097442627,
"start": 163,
"tag": "PASSWORD",
"value": "password"
}
] | src/app/directives/tsValidatePasswordConfirmation.directive.coffee | pavelkuchin/tracktrains-ui | 0 | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
@desc Validate a confirm password field
@example
<input ts-validate-password-confirmation="password">
The directive requires the password variable
The $error object will have an additional 'confirmed' field.
###
tsValidatePasswordConfirmation = () ->
restrict: 'A'
require: 'ngModel'
scope:
tsValidatePasswordConfirmation: '='
link: tsValidatePasswordConfirmationLink
# XXX Needs refactoring because this function is in the global scope
tsValidatePasswordConfirmationLink = (scope, element, attrs, ctrl) ->
ctrl.$validators.confirmed = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue)
true
else if modelValue == scope.tsValidatePasswordConfirmation
true
else
false
angular
.module('trackSeatsApp')
.directive('tsValidatePasswordConfirmation', tsValidatePasswordConfirmation)
| 121871 | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
@desc Validate a confirm password field
@example
<input ts-validate-password-confirmation="<PASSWORD>">
The directive requires the password variable
The $error object will have an additional 'confirmed' field.
###
tsValidatePasswordConfirmation = () ->
restrict: 'A'
require: 'ngModel'
scope:
tsValidatePasswordConfirmation: '='
link: tsValidatePasswordConfirmationLink
# XXX Needs refactoring because this function is in the global scope
tsValidatePasswordConfirmationLink = (scope, element, attrs, ctrl) ->
ctrl.$validators.confirmed = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue)
true
else if modelValue == scope.tsValidatePasswordConfirmation
true
else
false
angular
.module('trackSeatsApp')
.directive('tsValidatePasswordConfirmation', tsValidatePasswordConfirmation)
| true | ###
The MIT License (MIT)
Copyright (c) 2015 TrackSeats.info
@desc Validate a confirm password field
@example
<input ts-validate-password-confirmation="PI:PASSWORD:<PASSWORD>END_PI">
The directive requires the password variable
The $error object will have an additional 'confirmed' field.
###
tsValidatePasswordConfirmation = () ->
restrict: 'A'
require: 'ngModel'
scope:
tsValidatePasswordConfirmation: '='
link: tsValidatePasswordConfirmationLink
# XXX Needs refactoring because this function is in the global scope
tsValidatePasswordConfirmationLink = (scope, element, attrs, ctrl) ->
ctrl.$validators.confirmed = (modelValue, viewValue) ->
if ctrl.$isEmpty(modelValue)
true
else if modelValue == scope.tsValidatePasswordConfirmation
true
else
false
angular
.module('trackSeatsApp')
.directive('tsValidatePasswordConfirmation', tsValidatePasswordConfirmation)
|
[
{
"context": " 1\n age : 29\n gender: \"male\"\n name : \"John Doe\"\n\n actual = stringify obj\n expected = \"",
"end": 755,
"score": 0.9996106624603271,
"start": 747,
"tag": "NAME",
"value": "John Doe"
}
] | src/specs/omit.coffee | Omega3k/backwards.js | 0 | test = require "tape"
omit = require( "../../build/backwards.dev" ).omit
txt = "backwards.omit should"
stringify = (obj) ->
acc = "{ "
for key, value of obj
acc += "#{ key }: #{ value }, "
return "#{ acc } }"
test "#{ txt } be a function", (t) ->
t.equal typeof omit, "function"
t.end()
test "#{ txt } work on Arrays", (t) ->
t.equal omit( 3, [1, 2, 3, 4, 5] ).toString(), [4, 5].toString()
t.equal omit( -2, [1, 2, 3, 4, 5] ).toString(), [1, 2, 3].toString()
t.end()
test "#{ txt } work on Strings", (t) ->
t.equal omit( 6, "Hello World!" ), "World!"
t.equal omit( -7, "Hello World!" ), "Hello"
t.end()
test "#{ txt } work on Objects", (t) ->
obj =
id : 1
age : 29
gender: "male"
name : "John Doe"
actual = stringify obj
expected = "{ name: #{ obj.name }, }"
omitpedObj1 = omit( ['id', 'age', 'gender'], obj )
omitpedObj2 = omit( ['occupation'], omitpedObj1 )
t.equal stringify( omitpedObj1 ), expected
t.equal stringify( omitpedObj2 ), expected
t.equal stringify( obj ) , actual
t.end() | 104613 | test = require "tape"
omit = require( "../../build/backwards.dev" ).omit
txt = "backwards.omit should"
stringify = (obj) ->
acc = "{ "
for key, value of obj
acc += "#{ key }: #{ value }, "
return "#{ acc } }"
test "#{ txt } be a function", (t) ->
t.equal typeof omit, "function"
t.end()
test "#{ txt } work on Arrays", (t) ->
t.equal omit( 3, [1, 2, 3, 4, 5] ).toString(), [4, 5].toString()
t.equal omit( -2, [1, 2, 3, 4, 5] ).toString(), [1, 2, 3].toString()
t.end()
test "#{ txt } work on Strings", (t) ->
t.equal omit( 6, "Hello World!" ), "World!"
t.equal omit( -7, "Hello World!" ), "Hello"
t.end()
test "#{ txt } work on Objects", (t) ->
obj =
id : 1
age : 29
gender: "male"
name : "<NAME>"
actual = stringify obj
expected = "{ name: #{ obj.name }, }"
omitpedObj1 = omit( ['id', 'age', 'gender'], obj )
omitpedObj2 = omit( ['occupation'], omitpedObj1 )
t.equal stringify( omitpedObj1 ), expected
t.equal stringify( omitpedObj2 ), expected
t.equal stringify( obj ) , actual
t.end() | true | test = require "tape"
omit = require( "../../build/backwards.dev" ).omit
txt = "backwards.omit should"
stringify = (obj) ->
acc = "{ "
for key, value of obj
acc += "#{ key }: #{ value }, "
return "#{ acc } }"
test "#{ txt } be a function", (t) ->
t.equal typeof omit, "function"
t.end()
test "#{ txt } work on Arrays", (t) ->
t.equal omit( 3, [1, 2, 3, 4, 5] ).toString(), [4, 5].toString()
t.equal omit( -2, [1, 2, 3, 4, 5] ).toString(), [1, 2, 3].toString()
t.end()
test "#{ txt } work on Strings", (t) ->
t.equal omit( 6, "Hello World!" ), "World!"
t.equal omit( -7, "Hello World!" ), "Hello"
t.end()
test "#{ txt } work on Objects", (t) ->
obj =
id : 1
age : 29
gender: "male"
name : "PI:NAME:<NAME>END_PI"
actual = stringify obj
expected = "{ name: #{ obj.name }, }"
omitpedObj1 = omit( ['id', 'age', 'gender'], obj )
omitpedObj2 = omit( ['occupation'], omitpedObj1 )
t.equal stringify( omitpedObj1 ), expected
t.equal stringify( omitpedObj2 ), expected
t.equal stringify( obj ) , actual
t.end() |
[
{
"context": "#\n# Page CoffeeScript file.\n#\n# @author Matthew Casey\n#\n# (c) University of Surrey 2019\n#\n\nVMV.Page ||=",
"end": 53,
"score": 0.9998691082000732,
"start": 40,
"tag": "NAME",
"value": "Matthew Casey"
}
] | app/assets/javascripts/shared/page.coffee | saschneider/VMVLedger | 0 | #
# Page CoffeeScript file.
#
# @author Matthew Casey
#
# (c) University of Surrey 2019
#
VMV.Page ||= {}
#
# Initialise whenever the page is loaded.
#
$ ->
$(document).ajaxStart(->
$('#spinner').attr("style", "display: block !important;")
)
$(document).ajaxStop(->
$('#spinner').attr("style", "display: none !important;")
)
| 16933 | #
# Page CoffeeScript file.
#
# @author <NAME>
#
# (c) University of Surrey 2019
#
VMV.Page ||= {}
#
# Initialise whenever the page is loaded.
#
$ ->
$(document).ajaxStart(->
$('#spinner').attr("style", "display: block !important;")
)
$(document).ajaxStop(->
$('#spinner').attr("style", "display: none !important;")
)
| true | #
# Page CoffeeScript file.
#
# @author PI:NAME:<NAME>END_PI
#
# (c) University of Surrey 2019
#
VMV.Page ||= {}
#
# Initialise whenever the page is loaded.
#
$ ->
$(document).ajaxStart(->
$('#spinner').attr("style", "display: block !important;")
)
$(document).ajaxStop(->
$('#spinner').attr("style", "display: none !important;")
)
|
[
{
"context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c",
"end": 124,
"score": 0.999527096748352,
"start": 111,
"tag": "NAME",
"value": "Fedor Indutny"
}
] | node_modules/index/lib/index/core/get.coffee | beshrkayali/monkey-release-action | 12 | ###
Get functionality for Node Index module
This software is licensed under the MIT License.
Copyright Fedor Indutny, 2011.
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.
###
utils = require '../../index/utils'
step = require 'step'
###
Get value by key
###
exports.get = (key, callback) ->
sort = @sort
storage = @storage
iterate = (err, index) ->
if err
return callback err
item_index = utils.search index, sort, key
item = index[item_index]
# Item not found
unless item
return callback 'Not found'
value = item[1]
if item[2]
# Key Value - return value
if sort(item[0], key) isnt 0
return callback 'Not found'
# Read actual value
storage.read value, (err, value) ->
if err
return callback err
# value = [value, link-to-previous-value]
callback null, value[0]
else
# Key Pointer - go further
storage.read value, iterate
storage.readRoot iterate
###
Traverse btree
filter can call callback w/ following result:
true - if `traverse` should go deeper
undefined - if `traverse` should skip element
false - if `traverse` should stop traversing and return to higher level
filter can
@return promise.
###
exports.traverse = (filter) ->
that = @
promise = new process.EventEmitter
# If no filter were provided - match all
filter = filter || (kp, callback) -> callback(null, true)
process.nextTick =>
sort = @sort
storage = @storage
iterate = (callback) ->
(err, page) ->
if err
promise.emit 'error', err
promise.emit 'end'
return
index = -1
pagelen = page.length
asyncFilter = ->
if ++index >= pagelen
if callback
callback null
else
promise.emit 'end'
return
current = page[index]
filter.call that, current, (err, filter_value) ->
if filter_value is true
if current[2]
# emit value
storage.read current[1], (err, value) ->
# value = [value, link-to-previous-value]
promise.emit 'data', value[0], current
asyncFilter()
else
# go deeper
storage.read current[1], iterate asyncFilter
else
if filter_value is false
index = pagelen
asyncFilter()
asyncFilter()
storage.readRoot iterate()
promise
###
Get in range
###
exports.rangeGet = (start_key, end_key) ->
sort = @sort
promise = new process.EventEmitter
traverse_promise = @traverse (kp, callback) ->
start_cmp = sort kp[0], start_key
end_cmp = sort kp[0], end_key
if kp[2]
if start_cmp >= 0 and end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
else
if end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
callback null
traverse_promise.on 'data', (value) ->
promise.emit 'data', value
traverse_promise.on 'end', ->
promise.emit 'end'
promise
| 80939 | ###
Get functionality for Node Index module
This software is licensed under the MIT License.
Copyright <NAME>, 2011.
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.
###
utils = require '../../index/utils'
step = require 'step'
###
Get value by key
###
exports.get = (key, callback) ->
sort = @sort
storage = @storage
iterate = (err, index) ->
if err
return callback err
item_index = utils.search index, sort, key
item = index[item_index]
# Item not found
unless item
return callback 'Not found'
value = item[1]
if item[2]
# Key Value - return value
if sort(item[0], key) isnt 0
return callback 'Not found'
# Read actual value
storage.read value, (err, value) ->
if err
return callback err
# value = [value, link-to-previous-value]
callback null, value[0]
else
# Key Pointer - go further
storage.read value, iterate
storage.readRoot iterate
###
Traverse btree
filter can call callback w/ following result:
true - if `traverse` should go deeper
undefined - if `traverse` should skip element
false - if `traverse` should stop traversing and return to higher level
filter can
@return promise.
###
exports.traverse = (filter) ->
that = @
promise = new process.EventEmitter
# If no filter were provided - match all
filter = filter || (kp, callback) -> callback(null, true)
process.nextTick =>
sort = @sort
storage = @storage
iterate = (callback) ->
(err, page) ->
if err
promise.emit 'error', err
promise.emit 'end'
return
index = -1
pagelen = page.length
asyncFilter = ->
if ++index >= pagelen
if callback
callback null
else
promise.emit 'end'
return
current = page[index]
filter.call that, current, (err, filter_value) ->
if filter_value is true
if current[2]
# emit value
storage.read current[1], (err, value) ->
# value = [value, link-to-previous-value]
promise.emit 'data', value[0], current
asyncFilter()
else
# go deeper
storage.read current[1], iterate asyncFilter
else
if filter_value is false
index = pagelen
asyncFilter()
asyncFilter()
storage.readRoot iterate()
promise
###
Get in range
###
exports.rangeGet = (start_key, end_key) ->
sort = @sort
promise = new process.EventEmitter
traverse_promise = @traverse (kp, callback) ->
start_cmp = sort kp[0], start_key
end_cmp = sort kp[0], end_key
if kp[2]
if start_cmp >= 0 and end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
else
if end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
callback null
traverse_promise.on 'data', (value) ->
promise.emit 'data', value
traverse_promise.on 'end', ->
promise.emit 'end'
promise
| true | ###
Get functionality for Node Index module
This software is licensed under the MIT License.
Copyright PI:NAME:<NAME>END_PI, 2011.
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.
###
utils = require '../../index/utils'
step = require 'step'
###
Get value by key
###
exports.get = (key, callback) ->
sort = @sort
storage = @storage
iterate = (err, index) ->
if err
return callback err
item_index = utils.search index, sort, key
item = index[item_index]
# Item not found
unless item
return callback 'Not found'
value = item[1]
if item[2]
# Key Value - return value
if sort(item[0], key) isnt 0
return callback 'Not found'
# Read actual value
storage.read value, (err, value) ->
if err
return callback err
# value = [value, link-to-previous-value]
callback null, value[0]
else
# Key Pointer - go further
storage.read value, iterate
storage.readRoot iterate
###
Traverse btree
filter can call callback w/ following result:
true - if `traverse` should go deeper
undefined - if `traverse` should skip element
false - if `traverse` should stop traversing and return to higher level
filter can
@return promise.
###
exports.traverse = (filter) ->
that = @
promise = new process.EventEmitter
# If no filter were provided - match all
filter = filter || (kp, callback) -> callback(null, true)
process.nextTick =>
sort = @sort
storage = @storage
iterate = (callback) ->
(err, page) ->
if err
promise.emit 'error', err
promise.emit 'end'
return
index = -1
pagelen = page.length
asyncFilter = ->
if ++index >= pagelen
if callback
callback null
else
promise.emit 'end'
return
current = page[index]
filter.call that, current, (err, filter_value) ->
if filter_value is true
if current[2]
# emit value
storage.read current[1], (err, value) ->
# value = [value, link-to-previous-value]
promise.emit 'data', value[0], current
asyncFilter()
else
# go deeper
storage.read current[1], iterate asyncFilter
else
if filter_value is false
index = pagelen
asyncFilter()
asyncFilter()
storage.readRoot iterate()
promise
###
Get in range
###
exports.rangeGet = (start_key, end_key) ->
sort = @sort
promise = new process.EventEmitter
traverse_promise = @traverse (kp, callback) ->
start_cmp = sort kp[0], start_key
end_cmp = sort kp[0], end_key
if kp[2]
if start_cmp >= 0 and end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
else
if end_cmp <= 0
return callback null, true
if end_cmp > 0
return callback null, false
callback null
traverse_promise.on 'data', (value) ->
promise.emit 'data', value
traverse_promise.on 'end', ->
promise.emit 'end'
promise
|
[
{
"context": "i'\n kind: 'asset'\n unique: false\n name: 'Mokujin'\n price: '0'\n strength: '2'\n influence: ",
"end": 168,
"score": 0.9997044801712036,
"start": 161,
"tag": "NAME",
"value": "Mokujin"
}
] | src/javascripts/models/card.coffee | yonbergman/self-modifying-card | 11 | class App.Models.Card extends Backbone.Model
defaults:
side: 'corp'
side: 'corp'
faction: 'jinteki'
kind: 'asset'
unique: false
name: 'Mokujin'
price: '0'
strength: '2'
influence: 2
mu: 1
type: 'ambush'
text: "If you pay 2 [c] when the Runner accesses Mokujin,the runner must take Mokujin.\nWhile the runner has Mokujin he can't run on central servers.\n[click] [click] [click]: Trash Mokujin"
fluff: '"I was completely stumped" - Whizzard'
# y: 272
# scale: 2.5
# img: "https://scontent-b-lhr.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/p235x350/10516676_10152217464281010_8925684994098200246_n.jpg?oh=8d345c197e82f74a375b5c79ac04461a&oe=545D9E1D"
options:
side: ['corp', 'runner']
faction:
corp: ['neutral', 'weyland', 'haas', 'jinteki', 'nbn'],
runner: ['neutral', 'anarch', 'criminal', 'shaper'],
kind:
corp: ['agenda', 'asset', 'operation', 'upgrade', 'ice', 'identity'],
runner: ['event', 'hardware', 'program', 'resource', 'identity'],
@strengthMeaning:
agenda: 'Agenda Points'
asset: 'Trash Cost'
upgrade: 'Trash Cost'
ice: 'Strength'
program: 'Strength'
resetFactionKind: ->
@set(kind: (if @isRunner() then 'event' else 'agenda'), faction: 'neutral')
isRunner: ->
@get('side') == 'runner'
isNeutralIdentity: ->
@get('kind') == 'identity' and @get('faction') == 'neutral'
isUnique: ->
!!@get('unique')
hasInfluence: ->
@get('kind')!='identity' and (@get('kind')!='agenda' or @get('faction') == 'neutral')
image: ->
if @get('kind')
"/img/#{@get('kind')}/#{@get('kind')}_#{@get('faction')}.png"
else
"/img/#{@get('side')}-back.jpg"
| 145213 | class App.Models.Card extends Backbone.Model
defaults:
side: 'corp'
side: 'corp'
faction: 'jinteki'
kind: 'asset'
unique: false
name: '<NAME>'
price: '0'
strength: '2'
influence: 2
mu: 1
type: 'ambush'
text: "If you pay 2 [c] when the Runner accesses Mokujin,the runner must take Mokujin.\nWhile the runner has Mokujin he can't run on central servers.\n[click] [click] [click]: Trash Mokujin"
fluff: '"I was completely stumped" - Whizzard'
# y: 272
# scale: 2.5
# img: "https://scontent-b-lhr.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/p235x350/10516676_10152217464281010_8925684994098200246_n.jpg?oh=8d345c197e82f74a375b5c79ac04461a&oe=545D9E1D"
options:
side: ['corp', 'runner']
faction:
corp: ['neutral', 'weyland', 'haas', 'jinteki', 'nbn'],
runner: ['neutral', 'anarch', 'criminal', 'shaper'],
kind:
corp: ['agenda', 'asset', 'operation', 'upgrade', 'ice', 'identity'],
runner: ['event', 'hardware', 'program', 'resource', 'identity'],
@strengthMeaning:
agenda: 'Agenda Points'
asset: 'Trash Cost'
upgrade: 'Trash Cost'
ice: 'Strength'
program: 'Strength'
resetFactionKind: ->
@set(kind: (if @isRunner() then 'event' else 'agenda'), faction: 'neutral')
isRunner: ->
@get('side') == 'runner'
isNeutralIdentity: ->
@get('kind') == 'identity' and @get('faction') == 'neutral'
isUnique: ->
!!@get('unique')
hasInfluence: ->
@get('kind')!='identity' and (@get('kind')!='agenda' or @get('faction') == 'neutral')
image: ->
if @get('kind')
"/img/#{@get('kind')}/#{@get('kind')}_#{@get('faction')}.png"
else
"/img/#{@get('side')}-back.jpg"
| true | class App.Models.Card extends Backbone.Model
defaults:
side: 'corp'
side: 'corp'
faction: 'jinteki'
kind: 'asset'
unique: false
name: 'PI:NAME:<NAME>END_PI'
price: '0'
strength: '2'
influence: 2
mu: 1
type: 'ambush'
text: "If you pay 2 [c] when the Runner accesses Mokujin,the runner must take Mokujin.\nWhile the runner has Mokujin he can't run on central servers.\n[click] [click] [click]: Trash Mokujin"
fluff: '"I was completely stumped" - Whizzard'
# y: 272
# scale: 2.5
# img: "https://scontent-b-lhr.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/p235x350/10516676_10152217464281010_8925684994098200246_n.jpg?oh=8d345c197e82f74a375b5c79ac04461a&oe=545D9E1D"
options:
side: ['corp', 'runner']
faction:
corp: ['neutral', 'weyland', 'haas', 'jinteki', 'nbn'],
runner: ['neutral', 'anarch', 'criminal', 'shaper'],
kind:
corp: ['agenda', 'asset', 'operation', 'upgrade', 'ice', 'identity'],
runner: ['event', 'hardware', 'program', 'resource', 'identity'],
@strengthMeaning:
agenda: 'Agenda Points'
asset: 'Trash Cost'
upgrade: 'Trash Cost'
ice: 'Strength'
program: 'Strength'
resetFactionKind: ->
@set(kind: (if @isRunner() then 'event' else 'agenda'), faction: 'neutral')
isRunner: ->
@get('side') == 'runner'
isNeutralIdentity: ->
@get('kind') == 'identity' and @get('faction') == 'neutral'
isUnique: ->
!!@get('unique')
hasInfluence: ->
@get('kind')!='identity' and (@get('kind')!='agenda' or @get('faction') == 'neutral')
image: ->
if @get('kind')
"/img/#{@get('kind')}/#{@get('kind')}_#{@get('faction')}.png"
else
"/img/#{@get('side')}-back.jpg"
|
[
{
"context": "rs'\n body: JSON.stringify\n name: 'guest1'\n email: 'guest1@somedomain.com'\n r",
"end": 357,
"score": 0.9978289008140564,
"start": 351,
"tag": "USERNAME",
"value": "guest1"
},
{
"context": "ingify\n name: 'guest1'\n emai... | talk-api2x/test/controllers/guest/user.coffee | ikingye/talk-os | 3,084 | should = require 'should'
limbo = require 'limbo'
db = limbo.use 'talk'
async = require 'async'
app = require '../../app'
{clear, request} = app
prepare = (done) ->
async.auto
prepare: app.prepare
createGuestUser: (callback) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest1'
email: 'guest1@somedomain.com'
request options, (err, res, user) ->
app.guest1 = user
callback err
, done
describe 'guest/user#create', ->
before app.prepare
it 'should create a guest user', (done) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest'
email: 'guest@somedomain.com'
request options, (err, res, user) ->
user.should.have.properties 'name', 'email'
user.isGuest.should.eql true
done err
after clear
describe 'guest/user#update', ->
before prepare
it 'should update a guest user', (done) ->
options =
method: 'put'
url: "guest/users/#{app.guest1._id}"
body: JSON.stringify
_sessionUserId: app.guest1._id
name: 'newguest'
email: 'newguest@a.com'
request options, (err, res, user) ->
user.name.should.eql 'newguest'
user.email.should.eql 'newguest@a.com'
done err
after clear
describe 'guest1/user#signout', ->
before prepare
it 'should signout the user and leave the rooms', (done) ->
async.auto
broadcast: (callback) ->
app.broadcast = (room, event, data) ->
if event is 'room:leave'
data.should.have.properties '_roomId', '_userId'
data._userId.should.eql app.guest1._id
callback()
joinRoom: (callback) ->
options =
method: 'post'
url: "guest/rooms/#{app.room1.guestToken}/join"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
signout: ['joinRoom', (callback) ->
options =
method: 'post'
url: "guest/users/signout"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
]
, done
after clear
| 173856 | should = require 'should'
limbo = require 'limbo'
db = limbo.use 'talk'
async = require 'async'
app = require '../../app'
{clear, request} = app
prepare = (done) ->
async.auto
prepare: app.prepare
createGuestUser: (callback) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest1'
email: '<EMAIL>'
request options, (err, res, user) ->
app.guest1 = user
callback err
, done
describe 'guest/user#create', ->
before app.prepare
it 'should create a guest user', (done) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest'
email: '<EMAIL>'
request options, (err, res, user) ->
user.should.have.properties 'name', 'email'
user.isGuest.should.eql true
done err
after clear
describe 'guest/user#update', ->
before prepare
it 'should update a guest user', (done) ->
options =
method: 'put'
url: "guest/users/#{app.guest1._id}"
body: JSON.stringify
_sessionUserId: app.guest1._id
name: 'newguest'
email: '<EMAIL>'
request options, (err, res, user) ->
user.name.should.eql 'newguest'
user.email.should.eql '<EMAIL>'
done err
after clear
describe 'guest1/user#signout', ->
before prepare
it 'should signout the user and leave the rooms', (done) ->
async.auto
broadcast: (callback) ->
app.broadcast = (room, event, data) ->
if event is 'room:leave'
data.should.have.properties '_roomId', '_userId'
data._userId.should.eql app.guest1._id
callback()
joinRoom: (callback) ->
options =
method: 'post'
url: "guest/rooms/#{app.room1.guestToken}/join"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
signout: ['joinRoom', (callback) ->
options =
method: 'post'
url: "guest/users/signout"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
]
, done
after clear
| true | should = require 'should'
limbo = require 'limbo'
db = limbo.use 'talk'
async = require 'async'
app = require '../../app'
{clear, request} = app
prepare = (done) ->
async.auto
prepare: app.prepare
createGuestUser: (callback) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest1'
email: 'PI:EMAIL:<EMAIL>END_PI'
request options, (err, res, user) ->
app.guest1 = user
callback err
, done
describe 'guest/user#create', ->
before app.prepare
it 'should create a guest user', (done) ->
options =
method: 'post'
url: 'guest/users'
body: JSON.stringify
name: 'guest'
email: 'PI:EMAIL:<EMAIL>END_PI'
request options, (err, res, user) ->
user.should.have.properties 'name', 'email'
user.isGuest.should.eql true
done err
after clear
describe 'guest/user#update', ->
before prepare
it 'should update a guest user', (done) ->
options =
method: 'put'
url: "guest/users/#{app.guest1._id}"
body: JSON.stringify
_sessionUserId: app.guest1._id
name: 'newguest'
email: 'PI:EMAIL:<EMAIL>END_PI'
request options, (err, res, user) ->
user.name.should.eql 'newguest'
user.email.should.eql 'PI:EMAIL:<EMAIL>END_PI'
done err
after clear
describe 'guest1/user#signout', ->
before prepare
it 'should signout the user and leave the rooms', (done) ->
async.auto
broadcast: (callback) ->
app.broadcast = (room, event, data) ->
if event is 'room:leave'
data.should.have.properties '_roomId', '_userId'
data._userId.should.eql app.guest1._id
callback()
joinRoom: (callback) ->
options =
method: 'post'
url: "guest/rooms/#{app.room1.guestToken}/join"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
signout: ['joinRoom', (callback) ->
options =
method: 'post'
url: "guest/users/signout"
body: JSON.stringify
_sessionUserId: app.guest1._id
request options, callback
]
, done
after clear
|
[
{
"context": "client', utils.wrap (done) ->\n json = { name: 'name', email: 'e@mail.com' }\n [res, body] = yield r",
"end": 776,
"score": 0.9522035121917725,
"start": 772,
"tag": "NAME",
"value": "name"
},
{
"context": "wrap (done) ->\n json = { name: 'name', email: 'e@mail.... | spec/server/functional/api.spec.coffee | l34kr/codecombat | 0 | User = require '../../../server/models/User'
APIClient = require '../../../server/models/APIClient'
OAuthProvider = require '../../../server/models/OAuthProvider'
utils = require '../utils'
nock = require 'nock'
request = require '../request'
mongoose = require 'mongoose'
moment = require 'moment'
Prepaid = require '../../../server/models/Prepaid'
describe 'POST /api/users', ->
url = utils.getURL('/api/users')
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
done()
it 'creates a user that is marked as having been created by the API client', utils.wrap (done) ->
json = { name: 'name', email: 'e@mail.com' }
[res, body] = yield request.postAsync({url, json, @auth})
expect(res.statusCode).toBe(201)
expect(body.clientCreator).toBe(@client.id)
expect(body.name).toBe(json.name)
expect(body.email).toBe(json.email)
done()
describe 'GET /api/users/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
@otherClient = new APIClient()
secret = @otherClient.setNewSecret()
@otherClientAuth = { user: @otherClient.id, pass: secret }
yield @otherClient.save()
url = utils.getURL('/api/users')
json = { name: 'name', email: 'e@mail.com' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
done()
it 'returns the user, including stats', utils.wrap (done) ->
yield @user.update({$set: {'stats.gamesCompleted':1}})
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, @auth})
expect(res.statusCode).toBe(200)
expect(body._id).toBe(@user.id)
expect(body.name).toBe(@user.get('name'))
expect(body.email).toBe(@user.get('email'))
expect(body.stats.gamesCompleted).toBe(1)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
done()
it 'returns 200 if the client is Israel and the user has an israelId', utils.wrap (done) ->
israelClient = new APIClient({_id: new mongoose.Types.ObjectId('582a134eb9bce324006210e7')})
secret = israelClient.setNewSecret()
israelAuth = { user: israelClient.id, pass: secret }
yield israelClient.save()
url = utils.getURL("/api/users/#{@user.id}")
# when user does not have an israel id
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(403)
# when the client is not israel
yield @user.update({$set: {israelId: '12345'}})
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
# when both conditions are met
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(200)
done()
describe 'POST /api/users/:handle/o-auth-identities', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: @secret }
url = utils.getURL('/api/users')
json = { name: 'name', email: 'e@mail.com' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/o-auth-identities")
@provider = new OAuthProvider({
lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>'
tokenUrl: 'https://oauth.provider/oauth2/token'
})
yield @provider.save()
@json = { provider: @provider.id, accessToken: '1234' }
@providerNock = nock('https://oauth.provider')
@providerLookupRequest = @providerNock.get('/user?t=1234')
done()
it 'adds a new identity to the user if everything checks out', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'can take a code and do a token lookup', utils.wrap (done) ->
@providerNock.get('/oauth2/token').reply(200, {access_token: '1234'})
@providerLookupRequest.reply(200, ->
expect(@req.headers.authorization).toBeUndefined() # should only be provided if tokenAuth is set
return {id: 'abcd'}
)
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'can send basic http auth if specified in OAuthProvider tokenAuth property', utils.wrap (done) ->
yield @provider.update({$set: {tokenAuth: { user: 'abcd', pass: '1234' }}})
@providerNock.get('/oauth2/token').reply(200, ->
expect(@req.headers.authorization).toBeDefined()
return {access_token: '1234'}
)
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'sends the token request POST if tokenMethod is set to "post" on provider', utils.wrap (done) ->
yield @provider.update({$set: {tokenMethod: 'post'}})
@providerNock.post('/oauth2/token').reply(200, {access_token: '1234'})
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'uses the property specified by lookupIdProperty to get the user id from the response', utils.wrap (done) ->
yield @provider.update({$set: {lookupIdProperty: 'custom_user_ID'}})
@providerLookupRequest.reply(200, {custom_user_ID: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/users/dne/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the client did not create the given user', utils.wrap (done) ->
user = yield utils.initUser()
url = utils.getURL("/api/users/#{user.id}/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) ->
json = {}
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 404 if the provider is not found', utils.wrap (done) ->
json = { provider: new mongoose.Types.ObjectId() + '', accessToken: '1234' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 422 if the token lookup fails', utils.wrap (done) ->
@providerLookupRequest.reply(400, {})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: null})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) ->
yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]})
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(409)
done()
describe 'PUT /api/users/:handle/subscription', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
yield utils.populateProducts()
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: @secret }
url = utils.getURL('/api/users')
json = { name: 'name', email: 'e@mail.com' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/subscription")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.hasSubscription()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.subscription.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.hasSubscription()).toBe(true)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/subscription')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user already has free premium access', utils.wrap (done) ->
yield @user.update({$set: {stripe: {free:true}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
describe 'when the user has a terminal subscription already', ->
it 'returns 422 if the user has access beyond the ends', utils.wrap (done) ->
free = moment().add(13, 'months').toISOString()
yield @user.update({$set: {stripe: {free}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) ->
originalFreeUntil = moment().add(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).toBe(originalFreeUntil)
done()
it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) ->
originalFreeUntil = moment().subtract(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).not.toBe(originalFreeUntil)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
done()
describe 'PUT /api/users/:handle/license', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: @secret }
url = utils.getURL('/api/users')
json = { name: 'name', email: 'e@mail.com' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/license")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.isEnrolled()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.license.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('type')).toBe('course')
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.isEnrolled()).toBe(true)
expect(user.get('role')).toBe('student')
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/license')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: moment().subtract(1, 'day').toISOString() }
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user is already enrolled', utils.wrap (done) ->
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().add(1, 'month').toISOString()
startDate: moment().subtract(1, 'month').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().subtract(1, 'month').toISOString()
startDate: moment().subtract(2, 'months').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
done()
describe 'GET /api/user-lookup/israel-id/:israelId', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
json = { name: 'name', email: 'e@mail.com' }
url = utils.getURL('/api/users')
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@israelId = '12345'
yield @user.update({ $set: { @israelId }})
done()
it 'redirects to the user with the given israelId', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/#{@israelId}")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(301)
expect(res.headers.location).toBe("/api/users/#{@user.id}")
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/54321")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(404)
done()
| 77662 | User = require '../../../server/models/User'
APIClient = require '../../../server/models/APIClient'
OAuthProvider = require '../../../server/models/OAuthProvider'
utils = require '../utils'
nock = require 'nock'
request = require '../request'
mongoose = require 'mongoose'
moment = require 'moment'
Prepaid = require '../../../server/models/Prepaid'
describe 'POST /api/users', ->
url = utils.getURL('/api/users')
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
done()
it 'creates a user that is marked as having been created by the API client', utils.wrap (done) ->
json = { name: '<NAME>', email: '<EMAIL>' }
[res, body] = yield request.postAsync({url, json, @auth})
expect(res.statusCode).toBe(201)
expect(body.clientCreator).toBe(@client.id)
expect(body.name).toBe(json.name)
expect(body.email).toBe(json.email)
done()
describe 'GET /api/users/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
@otherClient = new APIClient()
secret = @otherClient.setNewSecret()
@otherClientAuth = { user: @otherClient.id, pass: secret }
yield @otherClient.save()
url = utils.getURL('/api/users')
json = { name: '<NAME>', email: '<EMAIL>' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
done()
it 'returns the user, including stats', utils.wrap (done) ->
yield @user.update({$set: {'stats.gamesCompleted':1}})
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, @auth})
expect(res.statusCode).toBe(200)
expect(body._id).toBe(@user.id)
expect(body.name).toBe(@user.get('name'))
expect(body.email).toBe(@user.get('email'))
expect(body.stats.gamesCompleted).toBe(1)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
done()
it 'returns 200 if the client is Israel and the user has an israelId', utils.wrap (done) ->
israelClient = new APIClient({_id: new mongoose.Types.ObjectId('582a134eb9bce324006210e7')})
secret = israelClient.setNewSecret()
israelAuth = { user: israelClient.id, pass: <PASSWORD> }
yield israelClient.save()
url = utils.getURL("/api/users/#{@user.id}")
# when user does not have an israel id
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(403)
# when the client is not israel
yield @user.update({$set: {israelId: '12345'}})
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
# when both conditions are met
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(200)
done()
describe 'POST /api/users/:handle/o-auth-identities', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: <PASSWORD> }
url = utils.getURL('/api/users')
json = { name: 'name', email: '<EMAIL>' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/o-auth-identities")
@provider = new OAuthProvider({
lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>'
tokenUrl: 'https://oauth.provider/oauth2/token'
})
yield @provider.save()
@json = { provider: @provider.id, accessToken: '<KEY> <PASSWORD>' }
@providerNock = nock('https://oauth.provider')
@providerLookupRequest = @providerNock.get('/user?t=1234')
done()
it 'adds a new identity to the user if everything checks out', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'can take a code and do a token lookup', utils.wrap (done) ->
@providerNock.get('/oauth2/token').reply(200, {access_token: '<PASSWORD>'})
@providerLookupRequest.reply(200, ->
expect(@req.headers.authorization).toBeUndefined() # should only be provided if tokenAuth is set
return {id: 'abcd'}
)
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'can send basic http auth if specified in OAuthProvider tokenAuth property', utils.wrap (done) ->
yield @provider.update({$set: {tokenAuth: { user: 'abcd', pass: '<PASSWORD>' }}})
@providerNock.get('/oauth2/token').reply(200, ->
expect(@req.headers.authorization).toBeDefined()
return {access_token: '<PASSWORD>'}
)
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'sends the token request POST if tokenMethod is set to "post" on provider', utils.wrap (done) ->
yield @provider.update({$set: {tokenMethod: 'post'}})
@providerNock.post('/oauth2/token').reply(200, {access_token: '<PASSWORD>'})
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'uses the property specified by lookupIdProperty to get the user id from the response', utils.wrap (done) ->
yield @provider.update({$set: {lookupIdProperty: 'custom_user_ID'}})
@providerLookupRequest.reply(200, {custom_user_ID: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/users/dne/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the client did not create the given user', utils.wrap (done) ->
user = yield utils.initUser()
url = utils.getURL("/api/users/#{user.id}/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) ->
json = {}
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 404 if the provider is not found', utils.wrap (done) ->
json = { provider: new mongoose.Types.ObjectId() + '', accessToken: '<PASSWORD>' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 422 if the token lookup fails', utils.wrap (done) ->
@providerLookupRequest.reply(400, {})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: null})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) ->
yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]})
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(409)
done()
describe 'PUT /api/users/:handle/subscription', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
yield utils.populateProducts()
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: <PASSWORD> }
url = utils.getURL('/api/users')
json = { name: '<NAME>', email: '<EMAIL>' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/subscription")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.hasSubscription()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.subscription.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.hasSubscription()).toBe(true)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/subscription')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user already has free premium access', utils.wrap (done) ->
yield @user.update({$set: {stripe: {free:true}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
describe 'when the user has a terminal subscription already', ->
it 'returns 422 if the user has access beyond the ends', utils.wrap (done) ->
free = moment().add(13, 'months').toISOString()
yield @user.update({$set: {stripe: {free}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) ->
originalFreeUntil = moment().add(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).toBe(originalFreeUntil)
done()
it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) ->
originalFreeUntil = moment().subtract(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).not.toBe(originalFreeUntil)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
done()
describe 'PUT /api/users/:handle/license', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: @secret }
url = utils.getURL('/api/users')
json = { name: '<NAME>', email: '<EMAIL>' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/license")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.isEnrolled()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.license.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('type')).toBe('course')
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.isEnrolled()).toBe(true)
expect(user.get('role')).toBe('student')
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/license')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: moment().subtract(1, 'day').toISOString() }
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user is already enrolled', utils.wrap (done) ->
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().add(1, 'month').toISOString()
startDate: moment().subtract(1, 'month').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().subtract(1, 'month').toISOString()
startDate: moment().subtract(2, 'months').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
done()
describe 'GET /api/user-lookup/israel-id/:israelId', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
json = { name: '<NAME>', email: '<EMAIL>' }
url = utils.getURL('/api/users')
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@israelId = '12345'
yield @user.update({ $set: { @israelId }})
done()
it 'redirects to the user with the given israelId', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/#{@israelId}")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(301)
expect(res.headers.location).toBe("/api/users/#{@user.id}")
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/54321")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(404)
done()
| true | User = require '../../../server/models/User'
APIClient = require '../../../server/models/APIClient'
OAuthProvider = require '../../../server/models/OAuthProvider'
utils = require '../utils'
nock = require 'nock'
request = require '../request'
mongoose = require 'mongoose'
moment = require 'moment'
Prepaid = require '../../../server/models/Prepaid'
describe 'POST /api/users', ->
url = utils.getURL('/api/users')
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
done()
it 'creates a user that is marked as having been created by the API client', utils.wrap (done) ->
json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
[res, body] = yield request.postAsync({url, json, @auth})
expect(res.statusCode).toBe(201)
expect(body.clientCreator).toBe(@client.id)
expect(body.name).toBe(json.name)
expect(body.email).toBe(json.email)
done()
describe 'GET /api/users/:handle', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
@otherClient = new APIClient()
secret = @otherClient.setNewSecret()
@otherClientAuth = { user: @otherClient.id, pass: secret }
yield @otherClient.save()
url = utils.getURL('/api/users')
json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
done()
it 'returns the user, including stats', utils.wrap (done) ->
yield @user.update({$set: {'stats.gamesCompleted':1}})
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, @auth})
expect(res.statusCode).toBe(200)
expect(body._id).toBe(@user.id)
expect(body.name).toBe(@user.get('name'))
expect(body.email).toBe(@user.get('email'))
expect(body.stats.gamesCompleted).toBe(1)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
url = utils.getURL("/api/users/#{@user.id}")
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
done()
it 'returns 200 if the client is Israel and the user has an israelId', utils.wrap (done) ->
israelClient = new APIClient({_id: new mongoose.Types.ObjectId('582a134eb9bce324006210e7')})
secret = israelClient.setNewSecret()
israelAuth = { user: israelClient.id, pass: PI:PASSWORD:<PASSWORD>END_PI }
yield israelClient.save()
url = utils.getURL("/api/users/#{@user.id}")
# when user does not have an israel id
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(403)
# when the client is not israel
yield @user.update({$set: {israelId: '12345'}})
[res, body] = yield request.getAsync({url, json: true, auth: @otherClientAuth})
expect(res.statusCode).toBe(403)
# when both conditions are met
[res, body] = yield request.getAsync({url, json: true, auth: israelAuth})
expect(res.statusCode).toBe(200)
done()
describe 'POST /api/users/:handle/o-auth-identities', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: PI:PASSWORD:<PASSWORD>END_PI }
url = utils.getURL('/api/users')
json = { name: 'name', email: 'PI:EMAIL:<EMAIL>END_PI' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/o-auth-identities")
@provider = new OAuthProvider({
lookupUrlTemplate: 'https://oauth.provider/user?t=<%= accessToken %>'
tokenUrl: 'https://oauth.provider/oauth2/token'
})
yield @provider.save()
@json = { provider: @provider.id, accessToken: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' }
@providerNock = nock('https://oauth.provider')
@providerLookupRequest = @providerNock.get('/user?t=1234')
done()
it 'adds a new identity to the user if everything checks out', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'can take a code and do a token lookup', utils.wrap (done) ->
@providerNock.get('/oauth2/token').reply(200, {access_token: 'PI:PASSWORD:<PASSWORD>END_PI'})
@providerLookupRequest.reply(200, ->
expect(@req.headers.authorization).toBeUndefined() # should only be provided if tokenAuth is set
return {id: 'abcd'}
)
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'can send basic http auth if specified in OAuthProvider tokenAuth property', utils.wrap (done) ->
yield @provider.update({$set: {tokenAuth: { user: 'abcd', pass: 'PI:PASSWORD:<PASSWORD>END_PI' }}})
@providerNock.get('/oauth2/token').reply(200, ->
expect(@req.headers.authorization).toBeDefined()
return {access_token: 'PI:PASSWORD:<PASSWORD>END_PI'}
)
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'sends the token request POST if tokenMethod is set to "post" on provider', utils.wrap (done) ->
yield @provider.update({$set: {tokenMethod: 'post'}})
@providerNock.post('/oauth2/token').reply(200, {access_token: 'PI:PASSWORD:<PASSWORD>END_PI'})
@providerLookupRequest.reply(200, {id: 'abcd'})
json = { provider: @provider.id, code: 'xyzzy' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
done()
it 'uses the property specified by lookupIdProperty to get the user id from the response', utils.wrap (done) ->
yield @provider.update({$set: {lookupIdProperty: 'custom_user_ID'}})
@providerLookupRequest.reply(200, {custom_user_ID: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
expect(res.body.oAuthIdentities.length).toBe(1)
expect(res.body.oAuthIdentities[0].id).toBe('abcd')
expect(res.body.oAuthIdentities[0].provider).toBe(@provider.id)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/users/dne/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the client did not create the given user', utils.wrap (done) ->
user = yield utils.initUser()
url = utils.getURL("/api/users/#{user.id}/o-auth-identities")
[res, body] = yield request.postAsync({ url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if "provider" and "accessToken" are not provided', utils.wrap (done) ->
json = {}
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 404 if the provider is not found', utils.wrap (done) ->
json = { provider: new mongoose.Types.ObjectId() + '', accessToken: 'PI:KEY:<PASSWORD>END_PI' }
[res, body] = yield request.postAsync({ @url, json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 422 if the token lookup fails', utils.wrap (done) ->
@providerLookupRequest.reply(400, {})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the token lookup does not return an object with an id', utils.wrap (done) ->
@providerLookupRequest.reply(200, {id: null})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 409 if a user already exists with the given id/provider', utils.wrap (done) ->
yield utils.initUser({oAuthIdentities: [{ provider: @provider._id, id: 'abcd'}]})
@providerLookupRequest.reply(200, {id: 'abcd'})
[res, body] = yield request.postAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(409)
done()
describe 'PUT /api/users/:handle/subscription', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
yield utils.populateProducts()
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: PI:PASSWORD:<PASSWORD>END_PI }
url = utils.getURL('/api/users')
json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/subscription")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.hasSubscription()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.subscription.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.hasSubscription()).toBe(true)
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/subscription')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user already has free premium access', utils.wrap (done) ->
yield @user.update({$set: {stripe: {free:true}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
describe 'when the user has a terminal subscription already', ->
it 'returns 422 if the user has access beyond the ends', utils.wrap (done) ->
free = moment().add(13, 'months').toISOString()
yield @user.update({$set: {stripe: {free}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'sets the prepaid startDate to the user\'s old terminal subscription end date', utils.wrap (done) ->
originalFreeUntil = moment().add(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).toBe(originalFreeUntil)
done()
it 'sets the prepaid startDate to now if the user\'s subscription ended already', utils.wrap (done) ->
originalFreeUntil = moment().subtract(6, 'months').toISOString()
yield @user.update({$set: {stripe: {free: originalFreeUntil}}})
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid.get('startDate')).not.toBe(originalFreeUntil)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
done()
describe 'PUT /api/users/:handle/license', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
yield @client.save()
@auth = { user: @client.id, pass: @secret }
url = utils.getURL('/api/users')
json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@url = utils.getURL("/api/users/#{@user.id}/license")
@ends = moment().add(12, 'months').toISOString()
@json = { @ends }
done()
it 'provides the user with premium access until the given end date, and creates a prepaid', utils.wrap (done) ->
expect(@user.isEnrolled()).toBe(false)
t0 = new Date().toISOString()
[res, body] = yield request.putAsync({ @url, @json, @auth })
t1 = new Date().toISOString()
expect(res.body.license.ends).toBe(@ends)
expect(res.statusCode).toBe(200)
prepaid = yield Prepaid.findOne({'redeemers.userID': @user._id})
expect(prepaid).toBeDefined()
expect(prepaid.get('clientCreator').equals(@client._id)).toBe(true)
expect(prepaid.get('redeemers')[0].userID.equals(@user._id)).toBe(true)
expect(prepaid.get('startDate')).toBeGreaterThan(t0)
expect(prepaid.get('startDate')).toBeLessThan(t1)
expect(prepaid.get('type')).toBe('course')
expect(prepaid.get('endDate')).toBe(@ends)
user = yield User.findById(@user.id)
expect(user.isEnrolled()).toBe(true)
expect(user.get('role')).toBe('student')
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL('/api/users/dne/license')
[res, body] = yield request.putAsync({ url, @json, @auth })
expect(res.statusCode).toBe(404)
done()
it 'returns 403 if the user was not created by the client', utils.wrap (done) ->
yield @user.update({$unset: {clientCreator:1}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(403)
done()
it 'returns 422 if ends is not provided or incorrectly formatted or in the past', utils.wrap (done) ->
json = {}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: '2014-01-01T00:00:00.00Z'}
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
json = { ends: moment().subtract(1, 'day').toISOString() }
[res, body] = yield request.putAsync({ @url, json, @auth })
expect(res.statusCode).toBe(422)
done()
it 'returns 422 if the user is already enrolled', utils.wrap (done) ->
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().add(1, 'month').toISOString()
startDate: moment().subtract(1, 'month').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(422)
yield @user.update({$set: {coursePrepaid:{
_id: new mongoose.Types.ObjectId()
endDate: moment().subtract(1, 'month').toISOString()
startDate: moment().subtract(2, 'months').toISOString()
}}})
[res, body] = yield request.putAsync({ @url, @json, @auth })
expect(res.statusCode).toBe(200)
done()
describe 'GET /api/user-lookup/israel-id/:israelId', ->
beforeEach utils.wrap (done) ->
yield utils.clearModels([User, APIClient])
@client = new APIClient()
@secret = @client.setNewSecret()
@auth = { user: @client.id, pass: @secret }
yield @client.save()
json = { name: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' }
url = utils.getURL('/api/users')
[res, body] = yield request.postAsync({url, json, @auth})
@user = yield User.findById(res.body._id)
@israelId = '12345'
yield @user.update({ $set: { @israelId }})
done()
it 'redirects to the user with the given israelId', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/#{@israelId}")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(301)
expect(res.headers.location).toBe("/api/users/#{@user.id}")
done()
it 'returns 404 if the user is not found', utils.wrap (done) ->
url = utils.getURL("/api/user-lookup/israel-id/54321")
[res, body] = yield request.getAsync({url, json: true, @auth, followRedirect: false })
expect(res.statusCode).toBe(404)
done()
|
[
{
"context": "lastName] = name.split ' '\n\n fake = new XFAKE(\"Valtid\", \"Caushi\")\n\n expect(fake.length).toBe 1\n f",
"end": 526,
"score": 0.9996895790100098,
"start": 520,
"tag": "NAME",
"value": "Valtid"
},
{
"context": "= name.split ' '\n\n fake = new XFAKE(\"Valt... | test/unit/utils.coffee | valtido/ason-js | 0 | describe "Other things", ->
it "should cover helper get/set stuff", ->
expect(Function.setter).toBeDefined()
expect(Function.getter).toBeDefined()
expect(Function.property).toBeDefined()
class XFAKE
constructor: (@firstName, @lastName) ->
@getter "length",-> 1
@getter "add",-> 5
@setter "add", (value)-> @value = 5
@property "fullname",
get: -> "#{@firstName} #{@lastName}"
set: (name) -> [@firstName, @lastName] = name.split ' '
fake = new XFAKE("Valtid", "Caushi")
expect(fake.length).toBe 1
fake.add = 10
expect(fake.value).toBe 5
expect(fake.firstName).toBe "Valtid"
expect(fake.lastName).toBe "Caushi"
it "should cover jQuery stuff", ->
expect($.fn.findAll).toBeDefined()
expect($("*").findAll("*")).toBeDefined()
expect($("div").value).toBeDefined()
expect($("div").value("a")).toBeDefined()
expect($("div").value("a",true)).toBeDefined()
expect($("div").value("a",false)).toBeDefined()
expect($("div").value("a","woof")).toBeDefined()
expect($("div").value()).not.toBeDefined()
| 198571 | describe "Other things", ->
it "should cover helper get/set stuff", ->
expect(Function.setter).toBeDefined()
expect(Function.getter).toBeDefined()
expect(Function.property).toBeDefined()
class XFAKE
constructor: (@firstName, @lastName) ->
@getter "length",-> 1
@getter "add",-> 5
@setter "add", (value)-> @value = 5
@property "fullname",
get: -> "#{@firstName} #{@lastName}"
set: (name) -> [@firstName, @lastName] = name.split ' '
fake = new XFAKE("<NAME>", "<NAME>")
expect(fake.length).toBe 1
fake.add = 10
expect(fake.value).toBe 5
expect(fake.firstName).toBe "<NAME>"
expect(fake.lastName).toBe "<NAME>"
it "should cover jQuery stuff", ->
expect($.fn.findAll).toBeDefined()
expect($("*").findAll("*")).toBeDefined()
expect($("div").value).toBeDefined()
expect($("div").value("a")).toBeDefined()
expect($("div").value("a",true)).toBeDefined()
expect($("div").value("a",false)).toBeDefined()
expect($("div").value("a","woof")).toBeDefined()
expect($("div").value()).not.toBeDefined()
| true | describe "Other things", ->
it "should cover helper get/set stuff", ->
expect(Function.setter).toBeDefined()
expect(Function.getter).toBeDefined()
expect(Function.property).toBeDefined()
class XFAKE
constructor: (@firstName, @lastName) ->
@getter "length",-> 1
@getter "add",-> 5
@setter "add", (value)-> @value = 5
@property "fullname",
get: -> "#{@firstName} #{@lastName}"
set: (name) -> [@firstName, @lastName] = name.split ' '
fake = new XFAKE("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI")
expect(fake.length).toBe 1
fake.add = 10
expect(fake.value).toBe 5
expect(fake.firstName).toBe "PI:NAME:<NAME>END_PI"
expect(fake.lastName).toBe "PI:NAME:<NAME>END_PI"
it "should cover jQuery stuff", ->
expect($.fn.findAll).toBeDefined()
expect($("*").findAll("*")).toBeDefined()
expect($("div").value).toBeDefined()
expect($("div").value("a")).toBeDefined()
expect($("div").value("a",true)).toBeDefined()
expect($("div").value("a",false)).toBeDefined()
expect($("div").value("a","woof")).toBeDefined()
expect($("div").value()).not.toBeDefined()
|
[
{
"context": ")->\n ss.rpc \"user.login\", {userid:uid,password:ups},(result)->\n if result.login\n #",
"end": 6672,
"score": 0.9973722100257874,
"start": 6669,
"tag": "PASSWORD",
"value": "ups"
}
] | client/code/app/app.coffee | Yukimir/jinrou | 0 | # Client-side Code
# Bind to socket events
app=require '/app'
util=require '/util'
ss.server.on 'disconnect', ->
util.message "服务器","连接已断开。"
ss.server.on 'reconnect', ->
util.message "服务器","连接已恢复,请刷新页面。"
# 全体告知
ss.event.on 'grandalert', (msg)->
util.message msg.title,msg.message
# This method is called automatically when the websocket connection is established. Do not rename/delete
my_userid=null
exports.init = ->
# 固定リンク
$("a").live "click", (je)->
t=je.currentTarget
return if je.isDefaultPrevented()
return if t.target=="_blank"
je.preventDefault()
app.showUrl t.href
return
# ヘルプアイコン
$("i[data-helpicon]").live "click", (je)->
t = je.currentTarget
util.message "帮助", t.title
if localStorage.userid && localStorage.password
login localStorage.userid, localStorage.password,(result)->
if result
p = location.pathname
if p=="/" then p="/my"
else
#p="/"
# 無効
localStorage.removeItem "userid"
localStorage.removeItem "password"
showUrl decodeURIComponent p
else
showUrl decodeURIComponent location.pathname
# ユーザーCSS指定
cp=useColorProfile getCurrentColorProfile()
window.addEventListener "popstate",((e)->
# location.pathname
showUrl location.pathname,true
),false
exports.page=page=(templatename,params=null,pageobj,startparam)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(JT["#{templatename}"](params)).appendTo("#content")
if pageobj
pageobj.start(startparam)
jQuery.data cdom, "end", pageobj.end
# マニュアルを表示
manualpage=(pagename)->
resp=(tmp)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(tmp).appendTo("#content")
pageobj=Index.manual
if pageobj
pageobj.start()
jQuery.data cdom, "end", pageobj.end
if sessionStorage["manual_#{pagename}"]
# すでに取得済み
resp sessionStorage["manual_#{pagename}"]
return
xhr=new XMLHttpRequest()
xhr.open "GET","/rawmanual/#{pagename}"
xhr.responseType="text"
xhr.onload=(e)->
#if e.status==200
sessionStorage["manual_#{pagename}"]=xhr.response
resp xhr.response
xhr.send()
exports.showUrl=showUrl=(url,nohistory=false)->
if result=url.match /(https?:\/\/.+?)(\/.+)$/
if result[1]=="#{location.protocol}//#{location.host}" #location.origin
url=result[2]
else
location.href=url
unless $("div#content div.game").length
$("#content").removeAttr "style"
switch url
when "/my"
# プロフィールとか
pf = ()=>
ss.rpc "user.myProfile", (user)->
unless user?
# ログインしていない
showUrl "/",nohistory
return
user[x]?="" for x in ["userid","name","comment"]
page "user-profile",user,Index.user.profile,user
if location.href.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
ss.rpc "user.confirmMail",location.href, (result)->
if result?.error?
Index.util.message "错误",result.error
return
if result?.info?
Index.util.message "通知",result.info
if result?.reset
showUrl "/",nohistory
else
pf()
else
pf()
when "/reset"
# 重置密码
page "reset",null,Index.reset, null
when "/rooms"
# 部屋一览
page "game-rooms",null,Index.game.rooms, null
when "/rooms/old"
# 古い部屋
page "game-rooms",null,Index.game.rooms,"old"
when "/rooms/log"
# 終わった部屋
page "game-rooms",null,Index.game.rooms,"log"
when "/rooms/my"
# ぼくの部屋
page "game-rooms",null,Index.game.rooms,"my"
when "/newroom"
# 新しい部屋
page "game-newroom",null,Index.game.newroom,null
when "/lobby"
# ロビー
page "lobby",null,Index.lobby,null
when "/manual"
# マニュアルトップ
#page "manual-top",null,Index.manual,null
manualpage "top"
when "/admin"
# 管理者ページ
page "admin",null,Index.admin,null
when "/logout"
# ログアウト
ss.rpc "user.logout", ->
my_userid=null
localStorage.removeItem "userid"
localStorage.removeItem "password"
$("#username").empty()
showUrl "/",nohistory
when "/logs"
# ログ検索
page "logs",null,Index.logs,null
else
if result=url.match /^\/room\/-?(\d+)$/
# 房间
page "game-game",null,Index.game.game,parseInt result[1]
$("#content").css "max-width","95%"
else if result=url.match /^\/user\/(\w+)$/
# ユーザー
page "user-view",null,Index.user.view,result[1]
else if result=url.match /^\/manual\/job\/(\w+)$/
# ジョブ情報
win=util.blankWindow "职业说明"
$(JT["jobs-#{result[1]}"]()).appendTo win
return
else if result=url.match /^\/manual\/casting\/(.*)$/
# キャスティング情報
if result[1]=="index" || result[1]==""
# 一览
page "pages-castlist",null,Index.pages.castlist
else
page "pages-casting",null,Index.pages.casting,result[1]
else if result=url.match /^\/manual\/([-\w]+)$/
#page "manual-#{result[1]}",null,Index.manual,null
manualpage result[1]
else if result=url.match /^\/backdoor\/(\w+)$/
ss.rpc "app.backdoor", result[1],(url)->
if url?
location.replace url
else
page "top",null,Index.top,null
unless nohistory
history.pushState null,null,url
exports.refresh=->showUrl location.pathname,true
exports.login=login=(uid,ups,cb)->
ss.rpc "user.login", {userid:uid,password:ups},(result)->
if result.login
# OK
my_userid=uid
$("#username").text uid
if result.lastNews && localStorage.latestNews
# 最終ニュースを比較
last=new Date result.lastNews
latest=new Date localStorage.latestNews
if last.getTime() > latest.getTime()
# 新着ニュースあり
# お知らせを入れる
notice=document.createElement "div"
notice.classList.add "notice"
notice.id="newNewsNotice"
notice.textContent="有新的通知,请前往个人页面查看。"
$("#content").before notice
cb? true
else
cb? false
exports.userid=->my_userid
exports.setUserid=(id)->my_userid=id
# カラー设定を読み込む
exports.getCurrentColorProfile=getCurrentColorProfile=->
p=localStorage.colorProfile || "{}"
obj=null
try
obj=JSON.parse p
catch e
# default setting
obj={}
unless obj.day?
obj.day=
bg:"#ffd953"
color:"#000000"
unless obj.night?
obj.night=
bg:"#000044"
color:"#ffffff"
unless obj.heaven?
obj.heaven=
bg:"#fffff0"
color:"#000000"
return obj
# 保存する
exports.setCurrentColorProfile=(cp)->
localStorage.colorProfile=JSON.stringify cp
# カラー设定反映
exports.useColorProfile=useColorProfile=(cp)->
st=$("#profilesheet").get 0
if st?
sheet=st.sheet
# 设定されているものを利用
while sheet.cssRules.length>0
sheet.deleteRule 0
else
# 新規に作る
st=$("<style id='profilesheet'>").appendTo(document.head).get 0
sheet=st.sheet
# 规则を定義
sheet.insertRule """
body.day, #logs .day {
background-color: #{cp.day.bg};
color: #{cp.day.color};
}""",0
sheet.insertRule """
body.night, #logs .werewolf, #logs .monologue {
background-color: #{cp.night.bg};
color: #{cp.night.color};
}""",1
sheet.insertRule """
body.night:not(.heaven) a, #logs .werewolf a, #logs .monologue a{
color: #{cp.night.color};
}""",2
sheet.insertRule """
body.heaven, #logs .heaven, #logs .prepare {
background-color: #{cp.heaven.bg};
color: #{cp.heaven.color};
}""",3
return
| 74038 | # Client-side Code
# Bind to socket events
app=require '/app'
util=require '/util'
ss.server.on 'disconnect', ->
util.message "服务器","连接已断开。"
ss.server.on 'reconnect', ->
util.message "服务器","连接已恢复,请刷新页面。"
# 全体告知
ss.event.on 'grandalert', (msg)->
util.message msg.title,msg.message
# This method is called automatically when the websocket connection is established. Do not rename/delete
my_userid=null
exports.init = ->
# 固定リンク
$("a").live "click", (je)->
t=je.currentTarget
return if je.isDefaultPrevented()
return if t.target=="_blank"
je.preventDefault()
app.showUrl t.href
return
# ヘルプアイコン
$("i[data-helpicon]").live "click", (je)->
t = je.currentTarget
util.message "帮助", t.title
if localStorage.userid && localStorage.password
login localStorage.userid, localStorage.password,(result)->
if result
p = location.pathname
if p=="/" then p="/my"
else
#p="/"
# 無効
localStorage.removeItem "userid"
localStorage.removeItem "password"
showUrl decodeURIComponent p
else
showUrl decodeURIComponent location.pathname
# ユーザーCSS指定
cp=useColorProfile getCurrentColorProfile()
window.addEventListener "popstate",((e)->
# location.pathname
showUrl location.pathname,true
),false
exports.page=page=(templatename,params=null,pageobj,startparam)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(JT["#{templatename}"](params)).appendTo("#content")
if pageobj
pageobj.start(startparam)
jQuery.data cdom, "end", pageobj.end
# マニュアルを表示
manualpage=(pagename)->
resp=(tmp)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(tmp).appendTo("#content")
pageobj=Index.manual
if pageobj
pageobj.start()
jQuery.data cdom, "end", pageobj.end
if sessionStorage["manual_#{pagename}"]
# すでに取得済み
resp sessionStorage["manual_#{pagename}"]
return
xhr=new XMLHttpRequest()
xhr.open "GET","/rawmanual/#{pagename}"
xhr.responseType="text"
xhr.onload=(e)->
#if e.status==200
sessionStorage["manual_#{pagename}"]=xhr.response
resp xhr.response
xhr.send()
exports.showUrl=showUrl=(url,nohistory=false)->
if result=url.match /(https?:\/\/.+?)(\/.+)$/
if result[1]=="#{location.protocol}//#{location.host}" #location.origin
url=result[2]
else
location.href=url
unless $("div#content div.game").length
$("#content").removeAttr "style"
switch url
when "/my"
# プロフィールとか
pf = ()=>
ss.rpc "user.myProfile", (user)->
unless user?
# ログインしていない
showUrl "/",nohistory
return
user[x]?="" for x in ["userid","name","comment"]
page "user-profile",user,Index.user.profile,user
if location.href.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
ss.rpc "user.confirmMail",location.href, (result)->
if result?.error?
Index.util.message "错误",result.error
return
if result?.info?
Index.util.message "通知",result.info
if result?.reset
showUrl "/",nohistory
else
pf()
else
pf()
when "/reset"
# 重置密码
page "reset",null,Index.reset, null
when "/rooms"
# 部屋一览
page "game-rooms",null,Index.game.rooms, null
when "/rooms/old"
# 古い部屋
page "game-rooms",null,Index.game.rooms,"old"
when "/rooms/log"
# 終わった部屋
page "game-rooms",null,Index.game.rooms,"log"
when "/rooms/my"
# ぼくの部屋
page "game-rooms",null,Index.game.rooms,"my"
when "/newroom"
# 新しい部屋
page "game-newroom",null,Index.game.newroom,null
when "/lobby"
# ロビー
page "lobby",null,Index.lobby,null
when "/manual"
# マニュアルトップ
#page "manual-top",null,Index.manual,null
manualpage "top"
when "/admin"
# 管理者ページ
page "admin",null,Index.admin,null
when "/logout"
# ログアウト
ss.rpc "user.logout", ->
my_userid=null
localStorage.removeItem "userid"
localStorage.removeItem "password"
$("#username").empty()
showUrl "/",nohistory
when "/logs"
# ログ検索
page "logs",null,Index.logs,null
else
if result=url.match /^\/room\/-?(\d+)$/
# 房间
page "game-game",null,Index.game.game,parseInt result[1]
$("#content").css "max-width","95%"
else if result=url.match /^\/user\/(\w+)$/
# ユーザー
page "user-view",null,Index.user.view,result[1]
else if result=url.match /^\/manual\/job\/(\w+)$/
# ジョブ情報
win=util.blankWindow "职业说明"
$(JT["jobs-#{result[1]}"]()).appendTo win
return
else if result=url.match /^\/manual\/casting\/(.*)$/
# キャスティング情報
if result[1]=="index" || result[1]==""
# 一览
page "pages-castlist",null,Index.pages.castlist
else
page "pages-casting",null,Index.pages.casting,result[1]
else if result=url.match /^\/manual\/([-\w]+)$/
#page "manual-#{result[1]}",null,Index.manual,null
manualpage result[1]
else if result=url.match /^\/backdoor\/(\w+)$/
ss.rpc "app.backdoor", result[1],(url)->
if url?
location.replace url
else
page "top",null,Index.top,null
unless nohistory
history.pushState null,null,url
exports.refresh=->showUrl location.pathname,true
exports.login=login=(uid,ups,cb)->
ss.rpc "user.login", {userid:uid,password:<PASSWORD>},(result)->
if result.login
# OK
my_userid=uid
$("#username").text uid
if result.lastNews && localStorage.latestNews
# 最終ニュースを比較
last=new Date result.lastNews
latest=new Date localStorage.latestNews
if last.getTime() > latest.getTime()
# 新着ニュースあり
# お知らせを入れる
notice=document.createElement "div"
notice.classList.add "notice"
notice.id="newNewsNotice"
notice.textContent="有新的通知,请前往个人页面查看。"
$("#content").before notice
cb? true
else
cb? false
exports.userid=->my_userid
exports.setUserid=(id)->my_userid=id
# カラー设定を読み込む
exports.getCurrentColorProfile=getCurrentColorProfile=->
p=localStorage.colorProfile || "{}"
obj=null
try
obj=JSON.parse p
catch e
# default setting
obj={}
unless obj.day?
obj.day=
bg:"#ffd953"
color:"#000000"
unless obj.night?
obj.night=
bg:"#000044"
color:"#ffffff"
unless obj.heaven?
obj.heaven=
bg:"#fffff0"
color:"#000000"
return obj
# 保存する
exports.setCurrentColorProfile=(cp)->
localStorage.colorProfile=JSON.stringify cp
# カラー设定反映
exports.useColorProfile=useColorProfile=(cp)->
st=$("#profilesheet").get 0
if st?
sheet=st.sheet
# 设定されているものを利用
while sheet.cssRules.length>0
sheet.deleteRule 0
else
# 新規に作る
st=$("<style id='profilesheet'>").appendTo(document.head).get 0
sheet=st.sheet
# 规则を定義
sheet.insertRule """
body.day, #logs .day {
background-color: #{cp.day.bg};
color: #{cp.day.color};
}""",0
sheet.insertRule """
body.night, #logs .werewolf, #logs .monologue {
background-color: #{cp.night.bg};
color: #{cp.night.color};
}""",1
sheet.insertRule """
body.night:not(.heaven) a, #logs .werewolf a, #logs .monologue a{
color: #{cp.night.color};
}""",2
sheet.insertRule """
body.heaven, #logs .heaven, #logs .prepare {
background-color: #{cp.heaven.bg};
color: #{cp.heaven.color};
}""",3
return
| true | # Client-side Code
# Bind to socket events
app=require '/app'
util=require '/util'
ss.server.on 'disconnect', ->
util.message "服务器","连接已断开。"
ss.server.on 'reconnect', ->
util.message "服务器","连接已恢复,请刷新页面。"
# 全体告知
ss.event.on 'grandalert', (msg)->
util.message msg.title,msg.message
# This method is called automatically when the websocket connection is established. Do not rename/delete
my_userid=null
exports.init = ->
# 固定リンク
$("a").live "click", (je)->
t=je.currentTarget
return if je.isDefaultPrevented()
return if t.target=="_blank"
je.preventDefault()
app.showUrl t.href
return
# ヘルプアイコン
$("i[data-helpicon]").live "click", (je)->
t = je.currentTarget
util.message "帮助", t.title
if localStorage.userid && localStorage.password
login localStorage.userid, localStorage.password,(result)->
if result
p = location.pathname
if p=="/" then p="/my"
else
#p="/"
# 無効
localStorage.removeItem "userid"
localStorage.removeItem "password"
showUrl decodeURIComponent p
else
showUrl decodeURIComponent location.pathname
# ユーザーCSS指定
cp=useColorProfile getCurrentColorProfile()
window.addEventListener "popstate",((e)->
# location.pathname
showUrl location.pathname,true
),false
exports.page=page=(templatename,params=null,pageobj,startparam)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(JT["#{templatename}"](params)).appendTo("#content")
if pageobj
pageobj.start(startparam)
jQuery.data cdom, "end", pageobj.end
# マニュアルを表示
manualpage=(pagename)->
resp=(tmp)->
cdom=$("#content").get(0)
jQuery.data(cdom,"end")?()
jQuery.removeData cdom,"end"
$("#content").empty()
$(tmp).appendTo("#content")
pageobj=Index.manual
if pageobj
pageobj.start()
jQuery.data cdom, "end", pageobj.end
if sessionStorage["manual_#{pagename}"]
# すでに取得済み
resp sessionStorage["manual_#{pagename}"]
return
xhr=new XMLHttpRequest()
xhr.open "GET","/rawmanual/#{pagename}"
xhr.responseType="text"
xhr.onload=(e)->
#if e.status==200
sessionStorage["manual_#{pagename}"]=xhr.response
resp xhr.response
xhr.send()
exports.showUrl=showUrl=(url,nohistory=false)->
if result=url.match /(https?:\/\/.+?)(\/.+)$/
if result[1]=="#{location.protocol}//#{location.host}" #location.origin
url=result[2]
else
location.href=url
unless $("div#content div.game").length
$("#content").removeAttr "style"
switch url
when "/my"
# プロフィールとか
pf = ()=>
ss.rpc "user.myProfile", (user)->
unless user?
# ログインしていない
showUrl "/",nohistory
return
user[x]?="" for x in ["userid","name","comment"]
page "user-profile",user,Index.user.profile,user
if location.href.match /\/my\?token\=(\w){128}\×tamp\=(\d){13}$/
ss.rpc "user.confirmMail",location.href, (result)->
if result?.error?
Index.util.message "错误",result.error
return
if result?.info?
Index.util.message "通知",result.info
if result?.reset
showUrl "/",nohistory
else
pf()
else
pf()
when "/reset"
# 重置密码
page "reset",null,Index.reset, null
when "/rooms"
# 部屋一览
page "game-rooms",null,Index.game.rooms, null
when "/rooms/old"
# 古い部屋
page "game-rooms",null,Index.game.rooms,"old"
when "/rooms/log"
# 終わった部屋
page "game-rooms",null,Index.game.rooms,"log"
when "/rooms/my"
# ぼくの部屋
page "game-rooms",null,Index.game.rooms,"my"
when "/newroom"
# 新しい部屋
page "game-newroom",null,Index.game.newroom,null
when "/lobby"
# ロビー
page "lobby",null,Index.lobby,null
when "/manual"
# マニュアルトップ
#page "manual-top",null,Index.manual,null
manualpage "top"
when "/admin"
# 管理者ページ
page "admin",null,Index.admin,null
when "/logout"
# ログアウト
ss.rpc "user.logout", ->
my_userid=null
localStorage.removeItem "userid"
localStorage.removeItem "password"
$("#username").empty()
showUrl "/",nohistory
when "/logs"
# ログ検索
page "logs",null,Index.logs,null
else
if result=url.match /^\/room\/-?(\d+)$/
# 房间
page "game-game",null,Index.game.game,parseInt result[1]
$("#content").css "max-width","95%"
else if result=url.match /^\/user\/(\w+)$/
# ユーザー
page "user-view",null,Index.user.view,result[1]
else if result=url.match /^\/manual\/job\/(\w+)$/
# ジョブ情報
win=util.blankWindow "职业说明"
$(JT["jobs-#{result[1]}"]()).appendTo win
return
else if result=url.match /^\/manual\/casting\/(.*)$/
# キャスティング情報
if result[1]=="index" || result[1]==""
# 一览
page "pages-castlist",null,Index.pages.castlist
else
page "pages-casting",null,Index.pages.casting,result[1]
else if result=url.match /^\/manual\/([-\w]+)$/
#page "manual-#{result[1]}",null,Index.manual,null
manualpage result[1]
else if result=url.match /^\/backdoor\/(\w+)$/
ss.rpc "app.backdoor", result[1],(url)->
if url?
location.replace url
else
page "top",null,Index.top,null
unless nohistory
history.pushState null,null,url
exports.refresh=->showUrl location.pathname,true
exports.login=login=(uid,ups,cb)->
ss.rpc "user.login", {userid:uid,password:PI:PASSWORD:<PASSWORD>END_PI},(result)->
if result.login
# OK
my_userid=uid
$("#username").text uid
if result.lastNews && localStorage.latestNews
# 最終ニュースを比較
last=new Date result.lastNews
latest=new Date localStorage.latestNews
if last.getTime() > latest.getTime()
# 新着ニュースあり
# お知らせを入れる
notice=document.createElement "div"
notice.classList.add "notice"
notice.id="newNewsNotice"
notice.textContent="有新的通知,请前往个人页面查看。"
$("#content").before notice
cb? true
else
cb? false
exports.userid=->my_userid
exports.setUserid=(id)->my_userid=id
# カラー设定を読み込む
exports.getCurrentColorProfile=getCurrentColorProfile=->
p=localStorage.colorProfile || "{}"
obj=null
try
obj=JSON.parse p
catch e
# default setting
obj={}
unless obj.day?
obj.day=
bg:"#ffd953"
color:"#000000"
unless obj.night?
obj.night=
bg:"#000044"
color:"#ffffff"
unless obj.heaven?
obj.heaven=
bg:"#fffff0"
color:"#000000"
return obj
# 保存する
exports.setCurrentColorProfile=(cp)->
localStorage.colorProfile=JSON.stringify cp
# カラー设定反映
exports.useColorProfile=useColorProfile=(cp)->
st=$("#profilesheet").get 0
if st?
sheet=st.sheet
# 设定されているものを利用
while sheet.cssRules.length>0
sheet.deleteRule 0
else
# 新規に作る
st=$("<style id='profilesheet'>").appendTo(document.head).get 0
sheet=st.sheet
# 规则を定義
sheet.insertRule """
body.day, #logs .day {
background-color: #{cp.day.bg};
color: #{cp.day.color};
}""",0
sheet.insertRule """
body.night, #logs .werewolf, #logs .monologue {
background-color: #{cp.night.bg};
color: #{cp.night.color};
}""",1
sheet.insertRule """
body.night:not(.heaven) a, #logs .werewolf a, #logs .monologue a{
color: #{cp.night.color};
}""",2
sheet.insertRule """
body.heaven, #logs .heaven, #logs .prepare {
background-color: #{cp.heaven.bg};
color: #{cp.heaven.color};
}""",3
return
|
[
{
"context": " 'http://www.youtube.com/watch?v='\n apiKey: 'AIzaSyDCM8-WArIFRoA7xsPw92R2uhScwUOV_3o'\n\n`export default config`",
"end": 223,
"score": 0.9997616410255432,
"start": 184,
"tag": "KEY",
"value": "AIzaSyDCM8-WArIFRoA7xsPw92R2uhScwUOV_3o"
}
] | src/scripts/config.coffee | perspectivezoom/shipmentbuilder | 0 | config =
site:
rootPath: 'example.com'
firebase:
rootUrl: 'https://shipmenteditor.firebaseio.com'
youtube:
videoUrl: 'http://www.youtube.com/watch?v='
apiKey: 'AIzaSyDCM8-WArIFRoA7xsPw92R2uhScwUOV_3o'
`export default config` | 62932 | config =
site:
rootPath: 'example.com'
firebase:
rootUrl: 'https://shipmenteditor.firebaseio.com'
youtube:
videoUrl: 'http://www.youtube.com/watch?v='
apiKey: '<KEY>'
`export default config` | true | config =
site:
rootPath: 'example.com'
firebase:
rootUrl: 'https://shipmenteditor.firebaseio.com'
youtube:
videoUrl: 'http://www.youtube.com/watch?v='
apiKey: 'PI:KEY:<KEY>END_PI'
`export default config` |
[
{
"context": "\"></label>\n <label>Password <input type=\"password\" name=\"password\"></label>\n <button>Sign ",
"end": 1012,
"score": 0.9955463409423828,
"start": 1004,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " <label>Password <input type=\"pass... | spec/browser-spec.coffee | funkatron/zombie | 1 | require "./helpers"
{ vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows")
jsdom = require("jsdom")
brains.get "/static", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
</head>
<body>Hello World</body>
</html>
"""
brains.get "/scripted", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
<script src="/jquery.js"></script>
</head>
<body>Hello World</body>
<script>
document.title = "Nice";
$(function() { $("title").text("Awesome") })
</script>
</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("#/") });
"""
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 "/empty", (req, res)-> res.send ""
brains.get "/soup", (req, res)-> res.send """
<h1>Tag soup</h1>
<p>One paragraph
<p>And another
"""
brains.get "/useragent", (req, res)-> res.send "<body>#{req.headers["user-agent"]}</body>"
brains.get "/alert", (req, res)-> res.send """
<script>
alert("Hi");
alert("Me again");
</script>
"""
brains.get "/confirm", (req, res)-> res.send """
<script>
window.first = confirm("continue?");
window.second = confirm("more?");
window.third = confirm("silent?");
</script>
"""
brains.get "/prompt", (req, res)-> res.send """
<script>
window.first = prompt("age");
window.second = prompt("gender");
window.third = prompt("location");
window.fourth = prompt("weight");
</script>
"""
vows.describe("Browser").addBatch(
"open page":
zombie.wants "http://localhost:3003/scripted"
"should create HTML document": (browser)-> assert.instanceOf browser.document, jsdom.dom.level3.html.HTMLDocument
"should load document from server": (browser)-> assert.match browser.html(), /<body>Hello World/
"should load external scripts": (browser)->
assert.ok jQuery = browser.window.jQuery, "window.jQuery not available"
assert.typeOf jQuery.ajax, "function"
"should run jQuery.onready": (browser)-> assert.equal browser.document.title, "Awesome"
"should return status code of last request": (browser)-> assert.equal browser.statusCode, 200
"visit":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/scripted", =>
@callback null, arguments
"should pass three arguments to callback": (args)-> assert.length args, 3
"should not include an error": (args)-> assert.isNull args[0]
"should pass browser to callback": (args)-> assert.ok args[1] instanceof zombie.Browser
"should pass status code to callback": (args)-> assert.equal args[2], 200
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/missing", =>
@callback null, arguments
"should pass single argument to callback": (args)-> assert.length args, 1
"should pass error to callback": (args)-> assert.ok args[0] instanceof Error
"should include status code in error": (args)-> assert.equal args[0].statusCode, 404
"empty page":
zombie.wants "http://localhost:3003/empty"
"should load document": (browser)-> assert.ok browser.body
"event emitter":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "loaded", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
"should fire load event": (browser)-> assert.ok browser.visit
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "error", (err)=> @callback null, err
browser.window.location = "http://localhost:3003/deadend"
"should fire onerror event": (err)->
assert.ok err.message && err.stack
assert.equal err.message, "Could not load document at http://localhost:3003/deadend, got 404"
"wait over":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "done", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
browser.wait()
"should fire done event": (browser)-> assert.ok browser.visit
"content selection":
zombie.wants "http://localhost:3003/living"
"query text":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password "
"query html":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/dead\">Kill</a>"
"click link":
zombie.wants "http://localhost:3003/living"
topic: (browser)->
browser.clickLink "Kill", @callback
"should change location": (_, browser)-> assert.equal browser.location, "http://localhost:3003/dead"
"should run all events": (_, browser)-> assert.equal browser.document.title, "The Dead"
"should return status code": (_, browser, status)-> assert.equal status, 200
"tag soup":
zombie.wants "http://localhost:3003/soup"
"should parse to complete HTML": (browser)->
assert.ok browser.querySelector("html head")
assert.equal browser.text("html body h1"), "Tag soup"
"should close tags": (browser)->
paras = browser.querySelectorAll("body p").toArray().map((e)-> e.textContent.trim())
assert.deepEqual paras, ["One paragraph", "And another"]
"with options":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/scripted", { runScripts: false }, @callback
"should set options for the duration of the request": (browser)-> assert.equal browser.document.title, "Whatever"
"should reset options following the request": (browser)-> assert.isTrue browser.runScripts
"user agent":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/useragent", @callback
"should send own version to server": (browser)-> assert.match browser.text("body"), /Zombie.js\/\d\.\d/
"should be accessible from navigator": (browser)-> assert.match browser.window.navigator.userAgent, /Zombie.js\/\d\.\d/
"specified":
topic: (browser)->
browser.visit "http://localhost:3003/useragent", { userAgent: "imposter" }, @callback
"should send user agent to server": (browser)-> assert.equal browser.text("body"), "imposter"
"should be accessible from navigator": (browser)-> assert.equal browser.window.navigator.userAgent, "imposter"
"URL without path":
zombie.wants "http://localhost:3003"
"should resolve URL": (browser)-> assert.equal browser.location.href, "http://localhost:3003"
"should load page": (browser)-> assert.equal browser.text("title"), "Tap, Tap"
"window.title":
zombie.wants "http://localhost:3003/static"
"should return the document's title": (browser)-> assert.equal browser.window.title, "Whatever"
"should set the document's title": (browser)->
browser.window.title = "Overwritten"
assert.equal browser.window.title, browser.document.title
"window.alert":
topic: ->
browser = new zombie.Browser
browser.onalert (message)-> browser.window.first = true if message = "Me again"
browser.wants "http://localhost:3003/alert", @callback
"should record last alert show to user": (browser)-> assert.ok browser.prompted("Me again")
"should call onalert function with message": (browser)-> assert.ok browser.window.first
"window.confirm":
topic: ->
browser = new zombie.Browser
browser.onconfirm "continue?", true
browser.onconfirm (prompt)-> true if prompt == "more?"
browser.wants "http://localhost:3003/confirm", @callback
"should return canned response": (browser)-> assert.ok browser.window.first
"should return response from function": (browser)-> assert.ok browser.window.second
"should return false if no response/function": (browser)-> assert.equal browser.window.third, false
"should report prompted question": (browser)->
assert.ok browser.prompted("continue?")
assert.ok browser.prompted("silent?")
assert.ok !browser.prompted("missing?")
"window.prompt":
topic: ->
browser = new zombie.Browser
browser.onprompt "age", 31
browser.onprompt (message, def)-> "unknown" if message == "gender"
browser.onprompt "location", false
browser.wants "http://localhost:3003/prompt", @callback
"should return canned response": (browser)-> assert.equal browser.window.first, "31"
"should return response from function": (browser)-> assert.equal browser.window.second, "unknown"
"should return null if cancelled": (browser)-> assert.isNull browser.window.third
"should return empty string if no response/function": (browser)-> assert.equal browser.window.fourth, ""
"should report prompts": (browser)->
assert.ok browser.prompted("age")
assert.ok browser.prompted("gender")
assert.ok browser.prompted("location")
assert.ok !browser.prompted("not asked")
).export(module)
| 121597 | require "./helpers"
{ vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows")
jsdom = require("jsdom")
brains.get "/static", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
</head>
<body>Hello World</body>
</html>
"""
brains.get "/scripted", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
<script src="/jquery.js"></script>
</head>
<body>Hello World</body>
<script>
document.title = "Nice";
$(function() { $("title").text("Awesome") })
</script>
</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("#/") });
"""
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 "/empty", (req, res)-> res.send ""
brains.get "/soup", (req, res)-> res.send """
<h1>Tag soup</h1>
<p>One paragraph
<p>And another
"""
brains.get "/useragent", (req, res)-> res.send "<body>#{req.headers["user-agent"]}</body>"
brains.get "/alert", (req, res)-> res.send """
<script>
alert("Hi");
alert("Me again");
</script>
"""
brains.get "/confirm", (req, res)-> res.send """
<script>
window.first = confirm("continue?");
window.second = confirm("more?");
window.third = confirm("silent?");
</script>
"""
brains.get "/prompt", (req, res)-> res.send """
<script>
window.first = prompt("age");
window.second = prompt("gender");
window.third = prompt("location");
window.fourth = prompt("weight");
</script>
"""
vows.describe("Browser").addBatch(
"open page":
zombie.wants "http://localhost:3003/scripted"
"should create HTML document": (browser)-> assert.instanceOf browser.document, jsdom.dom.level3.html.HTMLDocument
"should load document from server": (browser)-> assert.match browser.html(), /<body>Hello World/
"should load external scripts": (browser)->
assert.ok jQuery = browser.window.jQuery, "window.jQuery not available"
assert.typeOf jQuery.ajax, "function"
"should run jQuery.onready": (browser)-> assert.equal browser.document.title, "Awesome"
"should return status code of last request": (browser)-> assert.equal browser.statusCode, 200
"visit":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/scripted", =>
@callback null, arguments
"should pass three arguments to callback": (args)-> assert.length args, 3
"should not include an error": (args)-> assert.isNull args[0]
"should pass browser to callback": (args)-> assert.ok args[1] instanceof zombie.Browser
"should pass status code to callback": (args)-> assert.equal args[2], 200
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/missing", =>
@callback null, arguments
"should pass single argument to callback": (args)-> assert.length args, 1
"should pass error to callback": (args)-> assert.ok args[0] instanceof Error
"should include status code in error": (args)-> assert.equal args[0].statusCode, 404
"empty page":
zombie.wants "http://localhost:3003/empty"
"should load document": (browser)-> assert.ok browser.body
"event emitter":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "loaded", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
"should fire load event": (browser)-> assert.ok browser.visit
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "error", (err)=> @callback null, err
browser.window.location = "http://localhost:3003/deadend"
"should fire onerror event": (err)->
assert.ok err.message && err.stack
assert.equal err.message, "Could not load document at http://localhost:3003/deadend, got 404"
"wait over":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "done", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
browser.wait()
"should fire done event": (browser)-> assert.ok browser.visit
"content selection":
zombie.wants "http://localhost:3003/living"
"query text":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password "
"query html":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/dead\">Kill</a>"
"click link":
zombie.wants "http://localhost:3003/living"
topic: (browser)->
browser.clickLink "Kill", @callback
"should change location": (_, browser)-> assert.equal browser.location, "http://localhost:3003/dead"
"should run all events": (_, browser)-> assert.equal browser.document.title, "The Dead"
"should return status code": (_, browser, status)-> assert.equal status, 200
"tag soup":
zombie.wants "http://localhost:3003/soup"
"should parse to complete HTML": (browser)->
assert.ok browser.querySelector("html head")
assert.equal browser.text("html body h1"), "Tag soup"
"should close tags": (browser)->
paras = browser.querySelectorAll("body p").toArray().map((e)-> e.textContent.trim())
assert.deepEqual paras, ["One paragraph", "And another"]
"with options":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/scripted", { runScripts: false }, @callback
"should set options for the duration of the request": (browser)-> assert.equal browser.document.title, "Whatever"
"should reset options following the request": (browser)-> assert.isTrue browser.runScripts
"user agent":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/useragent", @callback
"should send own version to server": (browser)-> assert.match browser.text("body"), /Zombie.js\/\d\.\d/
"should be accessible from navigator": (browser)-> assert.match browser.window.navigator.userAgent, /Zombie.js\/\d\.\d/
"specified":
topic: (browser)->
browser.visit "http://localhost:3003/useragent", { userAgent: "imposter" }, @callback
"should send user agent to server": (browser)-> assert.equal browser.text("body"), "imposter"
"should be accessible from navigator": (browser)-> assert.equal browser.window.navigator.userAgent, "imposter"
"URL without path":
zombie.wants "http://localhost:3003"
"should resolve URL": (browser)-> assert.equal browser.location.href, "http://localhost:3003"
"should load page": (browser)-> assert.equal browser.text("title"), "Tap, Tap"
"window.title":
zombie.wants "http://localhost:3003/static"
"should return the document's title": (browser)-> assert.equal browser.window.title, "Whatever"
"should set the document's title": (browser)->
browser.window.title = "Overwritten"
assert.equal browser.window.title, browser.document.title
"window.alert":
topic: ->
browser = new zombie.Browser
browser.onalert (message)-> browser.window.first = true if message = "Me again"
browser.wants "http://localhost:3003/alert", @callback
"should record last alert show to user": (browser)-> assert.ok browser.prompted("Me again")
"should call onalert function with message": (browser)-> assert.ok browser.window.first
"window.confirm":
topic: ->
browser = new zombie.Browser
browser.onconfirm "continue?", true
browser.onconfirm (prompt)-> true if prompt == "more?"
browser.wants "http://localhost:3003/confirm", @callback
"should return canned response": (browser)-> assert.ok browser.window.first
"should return response from function": (browser)-> assert.ok browser.window.second
"should return false if no response/function": (browser)-> assert.equal browser.window.third, false
"should report prompted question": (browser)->
assert.ok browser.prompted("continue?")
assert.ok browser.prompted("silent?")
assert.ok !browser.prompted("missing?")
"window.prompt":
topic: ->
browser = new zombie.Browser
browser.onprompt "age", 31
browser.onprompt (message, def)-> "unknown" if message == "gender"
browser.onprompt "location", false
browser.wants "http://localhost:3003/prompt", @callback
"should return canned response": (browser)-> assert.equal browser.window.first, "31"
"should return response from function": (browser)-> assert.equal browser.window.second, "unknown"
"should return null if cancelled": (browser)-> assert.isNull browser.window.third
"should return empty string if no response/function": (browser)-> assert.equal browser.window.fourth, ""
"should report prompts": (browser)->
assert.ok browser.prompted("age")
assert.ok browser.prompted("gender")
assert.ok browser.prompted("location")
assert.ok !browser.prompted("not asked")
).export(module)
| true | require "./helpers"
{ vows: vows, assert: assert, zombie: zombie, brains: brains } = require("vows")
jsdom = require("jsdom")
brains.get "/static", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
</head>
<body>Hello World</body>
</html>
"""
brains.get "/scripted", (req, res)-> res.send """
<html>
<head>
<title>Whatever</title>
<script src="/jquery.js"></script>
</head>
<body>Hello World</body>
<script>
document.title = "Nice";
$(function() { $("title").text("Awesome") })
</script>
</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("#/") });
"""
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 "/empty", (req, res)-> res.send ""
brains.get "/soup", (req, res)-> res.send """
<h1>Tag soup</h1>
<p>One paragraph
<p>And another
"""
brains.get "/useragent", (req, res)-> res.send "<body>#{req.headers["user-agent"]}</body>"
brains.get "/alert", (req, res)-> res.send """
<script>
alert("Hi");
alert("Me again");
</script>
"""
brains.get "/confirm", (req, res)-> res.send """
<script>
window.first = confirm("continue?");
window.second = confirm("more?");
window.third = confirm("silent?");
</script>
"""
brains.get "/prompt", (req, res)-> res.send """
<script>
window.first = prompt("age");
window.second = prompt("gender");
window.third = prompt("location");
window.fourth = prompt("weight");
</script>
"""
vows.describe("Browser").addBatch(
"open page":
zombie.wants "http://localhost:3003/scripted"
"should create HTML document": (browser)-> assert.instanceOf browser.document, jsdom.dom.level3.html.HTMLDocument
"should load document from server": (browser)-> assert.match browser.html(), /<body>Hello World/
"should load external scripts": (browser)->
assert.ok jQuery = browser.window.jQuery, "window.jQuery not available"
assert.typeOf jQuery.ajax, "function"
"should run jQuery.onready": (browser)-> assert.equal browser.document.title, "Awesome"
"should return status code of last request": (browser)-> assert.equal browser.statusCode, 200
"visit":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/scripted", =>
@callback null, arguments
"should pass three arguments to callback": (args)-> assert.length args, 3
"should not include an error": (args)-> assert.isNull args[0]
"should pass browser to callback": (args)-> assert.ok args[1] instanceof zombie.Browser
"should pass status code to callback": (args)-> assert.equal args[2], 200
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.visit "http://localhost:3003/missing", =>
@callback null, arguments
"should pass single argument to callback": (args)-> assert.length args, 1
"should pass error to callback": (args)-> assert.ok args[0] instanceof Error
"should include status code in error": (args)-> assert.equal args[0].statusCode, 404
"empty page":
zombie.wants "http://localhost:3003/empty"
"should load document": (browser)-> assert.ok browser.body
"event emitter":
"successful":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "loaded", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
"should fire load event": (browser)-> assert.ok browser.visit
"error":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "error", (err)=> @callback null, err
browser.window.location = "http://localhost:3003/deadend"
"should fire onerror event": (err)->
assert.ok err.message && err.stack
assert.equal err.message, "Could not load document at http://localhost:3003/deadend, got 404"
"wait over":
topic: ->
brains.ready =>
browser = new zombie.Browser
browser.on "done", (browser)=> @callback null, browser
browser.window.location = "http://localhost:3003/"
browser.wait()
"should fire done event": (browser)-> assert.ok browser.visit
"content selection":
zombie.wants "http://localhost:3003/living"
"query text":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.text(".now"), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.text(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.text("form label"), "Email Password "
"query html":
topic: (browser)-> browser
"should query from document": (browser)-> assert.equal browser.html(".now"), "<div class=\"now\">Walking Aimlessly</div>"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.body), "Walking Aimlessly"
"should query from context": (browser)-> assert.equal browser.html(".now", browser.querySelector("#main")), ""
"should combine multiple elements": (browser)-> assert.equal browser.html("title, #main a"), "<title>The Living</title><a href=\"/dead\">Kill</a>"
"click link":
zombie.wants "http://localhost:3003/living"
topic: (browser)->
browser.clickLink "Kill", @callback
"should change location": (_, browser)-> assert.equal browser.location, "http://localhost:3003/dead"
"should run all events": (_, browser)-> assert.equal browser.document.title, "The Dead"
"should return status code": (_, browser, status)-> assert.equal status, 200
"tag soup":
zombie.wants "http://localhost:3003/soup"
"should parse to complete HTML": (browser)->
assert.ok browser.querySelector("html head")
assert.equal browser.text("html body h1"), "Tag soup"
"should close tags": (browser)->
paras = browser.querySelectorAll("body p").toArray().map((e)-> e.textContent.trim())
assert.deepEqual paras, ["One paragraph", "And another"]
"with options":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/scripted", { runScripts: false }, @callback
"should set options for the duration of the request": (browser)-> assert.equal browser.document.title, "Whatever"
"should reset options following the request": (browser)-> assert.isTrue browser.runScripts
"user agent":
topic: ->
browser = new zombie.Browser
browser.wants "http://localhost:3003/useragent", @callback
"should send own version to server": (browser)-> assert.match browser.text("body"), /Zombie.js\/\d\.\d/
"should be accessible from navigator": (browser)-> assert.match browser.window.navigator.userAgent, /Zombie.js\/\d\.\d/
"specified":
topic: (browser)->
browser.visit "http://localhost:3003/useragent", { userAgent: "imposter" }, @callback
"should send user agent to server": (browser)-> assert.equal browser.text("body"), "imposter"
"should be accessible from navigator": (browser)-> assert.equal browser.window.navigator.userAgent, "imposter"
"URL without path":
zombie.wants "http://localhost:3003"
"should resolve URL": (browser)-> assert.equal browser.location.href, "http://localhost:3003"
"should load page": (browser)-> assert.equal browser.text("title"), "Tap, Tap"
"window.title":
zombie.wants "http://localhost:3003/static"
"should return the document's title": (browser)-> assert.equal browser.window.title, "Whatever"
"should set the document's title": (browser)->
browser.window.title = "Overwritten"
assert.equal browser.window.title, browser.document.title
"window.alert":
topic: ->
browser = new zombie.Browser
browser.onalert (message)-> browser.window.first = true if message = "Me again"
browser.wants "http://localhost:3003/alert", @callback
"should record last alert show to user": (browser)-> assert.ok browser.prompted("Me again")
"should call onalert function with message": (browser)-> assert.ok browser.window.first
"window.confirm":
topic: ->
browser = new zombie.Browser
browser.onconfirm "continue?", true
browser.onconfirm (prompt)-> true if prompt == "more?"
browser.wants "http://localhost:3003/confirm", @callback
"should return canned response": (browser)-> assert.ok browser.window.first
"should return response from function": (browser)-> assert.ok browser.window.second
"should return false if no response/function": (browser)-> assert.equal browser.window.third, false
"should report prompted question": (browser)->
assert.ok browser.prompted("continue?")
assert.ok browser.prompted("silent?")
assert.ok !browser.prompted("missing?")
"window.prompt":
topic: ->
browser = new zombie.Browser
browser.onprompt "age", 31
browser.onprompt (message, def)-> "unknown" if message == "gender"
browser.onprompt "location", false
browser.wants "http://localhost:3003/prompt", @callback
"should return canned response": (browser)-> assert.equal browser.window.first, "31"
"should return response from function": (browser)-> assert.equal browser.window.second, "unknown"
"should return null if cancelled": (browser)-> assert.isNull browser.window.third
"should return empty string if no response/function": (browser)-> assert.equal browser.window.fourth, ""
"should report prompts": (browser)->
assert.ok browser.prompted("age")
assert.ok browser.prompted("gender")
assert.ok browser.prompted("location")
assert.ok !browser.prompted("not asked")
).export(module)
|
[
{
"context": " \n# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org) \n# ",
"end": 824,
"score": 0.9997563362121582,
"start": 814,
"tag": "NAME",
"value": "Mark Masse"
}
] | wrmldoc/js/app/entities/abstract/Button.coffee | wrml/wrml | 47 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 Mark Masse (OSS project WRML.org)
#
# 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.
#
# CoffeeScript
@Wrmldoc.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.Button extends Entities.Model
defaults:
buttonType: "button"
class Entities.ButtonsCollection extends Entities.Collection
model: Entities.Button
API =
getFormButtons: (buttons, model) ->
buttons = @getDefaultButtons buttons, model
array = []
array.push { type: "cancel", className: "button small secondary radius", text: buttons.cancel } unless buttons.cancel is false
array.push { type: "primary", className: "button small radius", text: buttons.primary, buttonType: "submit" } unless buttons.primary is false
array.reverse() if buttons.placement is "left"
buttonCollection = new Entities.ButtonsCollection array
buttonCollection.placement = buttons.placement
buttonCollection
getDefaultButtons: (buttons, model) ->
_.defaults buttons,
primary: if model.isNew() then "Create" else "Update"
cancel: "Cancel"
placement: "right"
App.reqres.setHandler "form:button:entities", (buttons = {}, model) ->
API.getFormButtons buttons, model | 97494 | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 <NAME> (OSS project WRML.org)
#
# 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.
#
# CoffeeScript
@Wrmldoc.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.Button extends Entities.Model
defaults:
buttonType: "button"
class Entities.ButtonsCollection extends Entities.Collection
model: Entities.Button
API =
getFormButtons: (buttons, model) ->
buttons = @getDefaultButtons buttons, model
array = []
array.push { type: "cancel", className: "button small secondary radius", text: buttons.cancel } unless buttons.cancel is false
array.push { type: "primary", className: "button small radius", text: buttons.primary, buttonType: "submit" } unless buttons.primary is false
array.reverse() if buttons.placement is "left"
buttonCollection = new Entities.ButtonsCollection array
buttonCollection.placement = buttons.placement
buttonCollection
getDefaultButtons: (buttons, model) ->
_.defaults buttons,
primary: if model.isNew() then "Create" else "Update"
cancel: "Cancel"
placement: "right"
App.reqres.setHandler "form:button:entities", (buttons = {}, model) ->
API.getFormButtons buttons, model | true | #
# WRML - Web Resource Modeling Language
# __ __ ______ __ __ __
# /\ \ _ \ \ /\ == \ /\ "-./ \ /\ \
# \ \ \/ ".\ \\ \ __< \ \ \-./\ \\ \ \____
# \ \__/".~\_\\ \_\ \_\\ \_\ \ \_\\ \_____\
# \/_/ \/_/ \/_/ /_/ \/_/ \/_/ \/_____/
#
# http://www.wrml.org
#
# Copyright 2011 - 2013 PI:NAME:<NAME>END_PI (OSS project WRML.org)
#
# 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.
#
# CoffeeScript
@Wrmldoc.module "Entities", (Entities, App, Backbone, Marionette, $, _) ->
class Entities.Button extends Entities.Model
defaults:
buttonType: "button"
class Entities.ButtonsCollection extends Entities.Collection
model: Entities.Button
API =
getFormButtons: (buttons, model) ->
buttons = @getDefaultButtons buttons, model
array = []
array.push { type: "cancel", className: "button small secondary radius", text: buttons.cancel } unless buttons.cancel is false
array.push { type: "primary", className: "button small radius", text: buttons.primary, buttonType: "submit" } unless buttons.primary is false
array.reverse() if buttons.placement is "left"
buttonCollection = new Entities.ButtonsCollection array
buttonCollection.placement = buttons.placement
buttonCollection
getDefaultButtons: (buttons, model) ->
_.defaults buttons,
primary: if model.isNew() then "Create" else "Update"
cancel: "Cancel"
placement: "right"
App.reqres.setHandler "form:button:entities", (buttons = {}, model) ->
API.getFormButtons buttons, model |
[
{
"context": "name: \"Roff\"\nscopeName: \"text.roff\"\nfileTypes: [\n\t\"1\", \"1b\", ",
"end": 11,
"score": 0.9995206594467163,
"start": 7,
"tag": "NAME",
"value": "Roff"
}
] | grammars/roff.cson | niilante/language-roff | 1 | name: "Roff"
scopeName: "text.roff"
fileTypes: [
"1", "1b", "1c", "1has", "1in", "1m", "1s", "1t", "1x",
"2",
"3", "3avl", "3bsm", "3c", "3in", "3m", "3qt", "3x",
"4",
"5",
"6",
"7", "7d", "7fs", "7i", "7ipp", "7m", "7p",
"8",
"9", "9e", "9f", "9p", "9s",
"groff",
"man",
"mandoc",
"mdoc",
"me",
"mmn", "mmt",
"ms",
"mom",
"n",
"nroff",
"roff", "rof",
"t",
"tmac", "tmac-u", "tmac.in",
"tr",
"troff"
]
firstLineMatch: """(?x)
# Manual page with .TH macro on first line
^\\.TH[ \t]+(?:\\S+)
|
# Preprocessor line
# See: https://www.gnu.org/software/groff/manual/html_node/Preprocessors-in-man-pages.html
^'\\\\\"\\x20[tre]+(?=\\s|$)
|
# “Aliased” manual page
^\\.so[ \t]+man(\\w+)/.+\\.\\1(?=\\s|$)
|
# Modeline
(?i:
# Emacs
-\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*)
[gnt]?roff
(?=[\\s;]|(?<![-*])-\\*-).*?-\\*-
|
# Vim
(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s))(?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:](?:filetype|ft|syntax)\\s*=
[gnt]?roff
(?=\\s|:|$)
)
"""
limitLineLength: no
patterns: [{ include: "#main" }]
repository:
# Common patterns
main:
patterns: [
{include: "#preprocessors"}
{include: "#escapes"}
{include: "#requests"}
{include: "#macros"}
]
# Control line parameters
params:
patterns: [
{include: "#escapes"}
{include: "#string"}
{include: "#number"}
{include: "#generic-parameter"}
]
# Numeric literal
number:
name: "constant.numeric.roff"
match: "(?!\\d+[cfimnPpsuvz]\\w)(\\|)?(?:(?<!\\w)[-+])?(?:\\d+(?:\\.\\d*)?|\\.\\d+|(?<=[-+])\\.)([cfimnPpsuvz])?"
captures:
1: name: "keyword.operator.absolute.roff"
2: name: "keyword.other.unit.roff"
# "Double-quoted string"
string:
patterns: [{
name: "string.quoted.double.empty.roff",
match: '(?<=(?<=[^\\\\]|^)\\s|^)(")(")(?=\\s|$)'
captures:
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
name: "string.quoted.double.roff",
begin: '(?<=(?<=[^\\\\]|^)\\s|^)"(?!")'
end: '(?<!")"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
patterns: [include: "#string-escapes"]
}]
# Escape sequences to match inside double-quoted strings
"string-escapes":
patterns: [
{match: '""', name: "constant.character.escape.quote.double.roff"}
{include: "#escapes"}
]
# Highlighting for macro arguments that don't match anything else
"generic-parameter":
name: "variable.parameter.roff"
match: "[^\\s\\\\]+"
# List of arguments passed to a request or macro
"param-group":
name: "function-call.arguments.roff"
begin: "\\G|^"
end: "\\Z|$"
patterns: [include: "#params"]
# Bracket-delimited long-name (GNU)
"long-name":
patterns: [{
name: "variable.parameter.other.roff"
begin: "\\G\\s*"
end: "(?=\\]|\\s)"
patterns: [include: "#escapes"]
}
{include: "#escapes"}
{include: "#string"}
{include: "#number"}]
# Group of strings delimited with an arbitrary character
"3-part-title":
name: "string.3-part.other.roff"
match: '\\G[ \t]*(.)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)'
captures:
1: name: "punctuation.definition.string.begin.roff"
2: name: "entity.string.left.roff", patterns: [include: "#escapes"]
3: name: "punctuation.definition.string.begin.roff"
4: name: "entity.string.centre.roff", patterns: [include: "#escapes"]
5: name: "punctuation.definition.string.end.roff"
6: name: "entity.string.right.roff", patterns: [include: "#escapes"]
7: name: "punctuation.definition.string.end.roff"
# Requests
requests:
patterns:[{
# GNU extensions
name: "meta.function.request.$2.gnu.roff"
begin: "(?x) ^([.'])[ \t]*
(aln|als|asciify|backtrace|blm|boxa|box|brp|cflags|chop|close|composite|color
|cp|devicem|device|do|ecs|ecr|evc|fam|fchar|fcolor|fschar|fspecial|ftr|fzoom
|gcolor|hcode|hla|hlm|hpfa|hpfcode|hpf|hym|hys|itc|kern|length|linetabs|lsm
|mso|nop|nroff|opena|open|output|pev|pnr|psbb|pso|ptr|pvs|rchar|rfschar|rj
|rnn|schar|shc|shift|sizes|special|spreadwarn|sty|substring|tkf|tm1|tmc|trf
|trin|trnt|troff|unformat|vpt|warnscale|warn|writec|writem|write)
(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
},{
# .class: Assign a name to a range of characters (GNU)
name: "meta.function.request.assign-class.gnu.roff"
begin: "^([.'])[ \t]*(class)[ \t]+(\\S+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff"}
patterns: [{
match: "[^\\s\\\\]+(-)[^\\s\\\\]+"
captures:
0: name: "string.unquoted.character-range.roff"
1: name: "punctuation.separator.dash.roff"
}, include: "#params"]
},{
# .char: Define character or glyph (GNU)
name: "meta.function.request.$2.gnu.roff"
begin: "^([.'])[ \t]*(char)[ \t]*(\\S+)?[ \t]*(.*)(?=$|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
patterns: [include: "$self"]
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "variable.parameter.roff"}
4: {patterns: [include: "#param-group"]}
},{
# .defcolor: Define colour (GNU)
name: "meta.function.request.define-colour.gnu.roff"
begin: "^([.'])[ \t]*(defcolor)(?=\\s)[ \t]*((?:[^\\s\\\\]|\\\\(?![\"#]).)*)[ \t]*(rgb|cmyk?|gr[ae]y)?"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "string.other.colour-name.roff", patterns: [include: "#escapes"]}
4: {name: "constant.language.colour-scheme.roff"}
patterns: [{
# Hexadecimal colour
name: "constant.other.colour.hex.roff"
match: "(\#{1,2})[A-Fa-f0-9]+"
captures: 1: name: "punctuation.definition.colour.roff"
}, include: "#params"]
},{
# Requests for controlling program flow (GNU)
begin: "^([.'])[ \t]*(break|continue|return|while)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
patterns: [include: "#param-group"]
beginCaptures:
0: {name: "meta.function.request.control.gnu.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
},{
# .tm/.ab: Print remainder of line to STDERR
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(ab|tm)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#escapes-copymode"}]
contentName: "string.unquoted.roff"
},{
# Generic requests without formatting
name: "meta.function.request.$2.roff"
begin: "(?x) ^([.'])[ \t]*
(ab|ad|af|bd|bp|br|c2|cc|ce|cf|ch|cs|da|di|dt|ec|em|eo|ev
|ex|fc|fi|fl|fp|ft|hc|hw|hy|in|it|lc|lg|lf|ll|ls|lt|mc|mk
|na|ne|nf|nh|nm|nn|ns|nx|os|pc|pi|pl|pm|pn|po|ps|rd|rm|rn
|rr|rs|rt|so|sp|ss|sv|sy|ta|tc|ti|tm|tr|uf|vs|wh)
(?=\\s|\\d+\\s*$|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
}
{ include: "#conditionals" }
{ include: "#definition" }
{ include: "#ignore" }
{ include: "#underlines" }
{
# Register assignment
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(nr)[ \t]*(?:(%|ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)|(c\\.)|(\\${2}|\\.[$aAbcdfFhHijklLnopRTstuvVwxyz])|(\\.[CgmMOPUxyY])|(\\S+))?[ \t]*(.*)$"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "constant.language.predefined.register.roff"}
4: {name: "constant.language.predefined.register.gnu.roff"}
5: {name: "invalid.illegal.readonly.register.roff"}
6: {name: "invalid.illegal.readonly.register.gnu.roff"}
7: {name: "variable.parameter.roff", patterns: [include: "#escapes"]}
8: {patterns: [{include: "#arithmetic"}, {include: "#param-group"}]}
},{
# String definition
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*([ad]s1?)[ \t]+(((?:[^\\s\\\\]|\\\\(?!\").)+))?"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "storage.type.var.roff"
3: name: "variable.parameter.roff"
4: name: "entity.name.roff", patterns: [include: "#escapes"]
contentName: "string.unquoted.roff"
patterns: [include: "#escapes"]
},{
# Three-part title
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(tl)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
contentName: "function-call.arguments.roff"
patterns: [
{include: "#3-part-title"}
{include: "#params"}
]
}]
# Conditional input
conditionals:
patterns: [{
# Conditional: If
begin: """(?x)^
([.']) [ \t]* # 1: punctuation.definition.request.roff
(ie|if) [ \t]* # 2: keyword.control.roff
(!)? # 3: keyword.operator.logical
(?:
# One-character built-in comparison name
([notev]) # 4: constant.language.builtin-comparison.$4.roff
|
# GNU extensions
([cdFmrS]) # 5: constant.language.builtin-comparison.$5.gnu.roff
# Name being validated
[ \t]*
((?:[^ \\t\\\\]|\\\\(?!["#]).)+) # 6: Include “#escapes”
|
# Arithmetic
( # 7: meta.equation.roff
# Starts with a bracket
(\\() # 8: punctuation.definition.begin.roff
(.*?) # 9: Include “#arithmetic”
(\\)) # 10: punctuation.definition.end.roff
# Anything else affixed to it
( # 11: Include “#arithmetic”
(?:
[^\\s\\(] | # Operators/numbers
\\(.*?\\) # More brackets
)*
)
|
# Doesn’t start with a bracket
(?:
# Starts with a long-form string/register
(\\|?\\\\+[n*]\\(\\S{2}) # 12: Include “#escapes”
|
# Starts with a digit or backslash
(?=\\d|\\\\)
)
([^\\s\\(]*) # 13: Sandwiched mathematical junk
(?: # Possible embedded brackets
(\\() # 14: punctuation.definition.begin.roff
(.*?) # 15: Include “#arithmetic”
(\\)) # 16: punctuation.definition.end.roff
)?
(?: # Possible trailing digits/operators
[^\\s\\(]*?
\\d+
)?
# Ends with a...
(?<=
# Digit
\\d |
# Unit suffix
(?<=[\\d.])
[A-Za-z] |
# Closing bracket
[\\)\\]] |
# String/register: Long-form
\\\\[n*]
\\(
\\S{2} |
# String/register: Short-form
\\\\[n*]\\S
)
)
|
# String/variable comparison
([^\\d\\s\\\\]) # 17: punctuation.definition.string.begin.roff
( # 18: variable.parameter.operand.left.roff
(.*?) # 19: Include “#escapes”
)
(\\17) # 20: punctuation.definition.string.roff
( # 21: variable.parameter.operand.right.roff
(.*?) # 22: Include “#escapes”
)
(\\17) # 23: punctuation.definition.string.end.roff
|
# Anything not recognised
(\\S) # 24: meta.operand.single.roff
)?
(.*) # 25: Include “#conditional-innards”
"""
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {name: "keyword.operator.logical"}
4: {name: "constant.language.builtin-comparison.$4.roff"}
5: {name: "constant.language.builtin-comparison.$5.gnu.roff"}
6: {patterns: [include: "#escapes"]}
7: {name: "meta.equation.roff"}
8: {name: "punctuation.definition.begin.roff"}
9: {patterns: [{include: "#arithmetic"}]}
10: {name: "punctuation.definition.end.roff"}
11: {patterns: [{include: "#arithmetic"}]}
12: {patterns: [{include: "#escapes"}]}
13: {patterns: [{include: "#arithmetic"}]}
14: {name: "punctuation.definition.begin.roff"}
15: {patterns: [{include: "#arithmetic"}]}
16: {name: "punctuation.definition.end.roff"}
17: {name: "punctuation.definition.string.begin.roff"}
18: {name: "variable.parameter.operand.left.roff"}
19: {patterns: [{include: "#escapes"}]}
20: {name: "punctuation.definition.string.roff"}
21: {name: "variable.parameter.operand.right.roff"}
22: {patterns: [{include: "#escapes"}]}
23: {name: "punctuation.definition.string.end.roff"}
24: {name: "meta.operand.single.roff"}
25: {patterns: [{include: "#conditional-innards"}]}
},{
# Conditional: Else
begin: "^([.'])[ \t]*(el)\\s*(.*)"
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {patterns: [{include: "#conditional-innards"}]}
}]
"conditional-innards":
patterns: [{
begin: "^\\s*(\\\\\\{(?:\\\\(?=\\n))?)?\\s*(.*)"
end: "$"
beginCaptures:
1: {name: "punctuation.section.conditional.begin.roff"}
2: {patterns: [{include: "$self"}]}
}]
# Basic arithmetic sequences
arithmetic:
patterns: [
{include: "#escapes"},
{
name: "meta.brackets.roff"
match: "(\\()(.*?)(\\))"
captures:
1: {name: "punctuation.arithmetic.begin.roff"}
2: {patterns: [{include: "#arithmetic"}]}
3: {name: "punctuation.arithmetic.end.roff"}
}
{include: "#number"}
{match: "<\\?", name: "keyword.operator.minimum.gnu.roff"}
{match: ">\\?", name: "keyword.operator.maximum.gnu.roff"}
{match: "[-/+*%]", name: "keyword.operator.arithmetic.roff"}
{match: ":|&|[<=>]=?", name: "keyword.operator.logical.roff"}
{match: "\\|", name: "keyword.operator.absolute.roff"}
{
# Change default scaling indicator (GNU)
name: "meta.scaling-indicator.gnu.roff"
match: "(?<=^|\\()([cfimnPpsuvz])(;)"
captures:
1: name: "keyword.other.unit.roff"
2: name: "punctuation.separator.semicolon.roff"
}
]
# Macro definitions
definition:
patterns: [{
# No terminator specified
name: "meta.function.definition.request.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+?)?\\s*(\\\\[\"#].*)?$"
end: "^(?:[ \t]*\\x5C{2})?\\.[ \t]*\\."
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {patterns: [include: "#escapes"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
0: {name: "punctuation.definition.request.roff"}
patterns: [include: "$self"]
},{
# Terminator included
name: "meta.function.definition.request.with-terminator.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+)\\s*(\"[^\"]+\"?|\\S+?(?=\\s|\\\\[\"#]))?(.*)$"
end: "^(\\.)[ \t]*((\\6)(?=$|\\s|\\\\(?:$|\")))"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {name: "keyword.control.terminator.roff", patterns: [include: "#string"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.terminator.roff"}
3: {patterns: [{include: "#string"}]}
patterns: [{include: "$self"}]
}]
# Ignored content
ignore:
patterns: [{
# Terminator specified
contentName: "comment.block.ignored-input.with-terminator.roff"
begin: "^([.'])[ \t]*(ig)[ \t]+(?!\\\\[\"#])((\"[^\"]+\")|\\S+?(?=\\s|\\\\[\"#]))(.*)$"
end: "^([.'])[ \t]*(\\3)(?=\\s|$|\\\\)"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: name: "keyword.control.terminator.roff"
4: patterns: [include: "#string"]
5: patterns: [include: "#params"]
endCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "keyword.control.terminator.roff", patterns: [include: "#string"]
},{
# No terminator given
contentName: "comment.block.ignored-input.roff"
begin: "^([.'])[ \t]*(ig)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*\\.(?=\\s|\\\\[\"#])"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#params"]
endCaptures:
0: name: "punctuation.definition.request.roff"
}]
# Underlined passages
underlines:
patterns: [{
# .ul/.cu 0: Empty request/noop
name: "meta.request.$2.roff"
match: "^([.'])[ \t]*(ul|cu)\\s*(0+)(?:(?!\\\\\")[\\D])*(?=\\s|$)(.*)$"
captures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [{include: "#params"}]}
}, {
# Underline following line
name: "meta.request.$2.roff"
begin: "^([.'])[ \t]*(ul|cu)(?=\\s|$|\\\\)(.*?)$\\n"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [{include: "#params"}]}
patterns: [{
# Ignore control-lines
begin: "^(?=[.']|\\\\!)(.*)$\\n"
end: "^"
beginCaptures:
1: {patterns: [{include: "$self"}]}
}, {
name: "markup.underline.roff"
begin: "^(?![.'])"
end: "(?<!\\\\)$"
}]
}]
# Escape sequences
escapes:
patterns: [
{include: "#escapes-copymode"}
{include: "#escapes-full"}
]
# Register interpolation
"register-expansion":
patterns: [{
# \n[xx] - Contents of number register "XX" (GNU)
name: "constant.character.escape.function.expand-register.gnu.roff"
begin: "(\\|)?(((?:(?<=\\|)\\\\*?)?\\\\)n([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \nX, \n(XX - Contents of number register "X" or "XX"
name: "constant.character.escape.function.expand-register.roff"
match: """(?x)
# 1: keyword.operator.absolute.roff
(\\|)?
# 2: entity.name.roff
(
# 3: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
([-+])? # 4: keyword.operator.arithmetic.roff
(\\() # 5: punctuation.definition.brace.roff
)
# Name of register
(?:
# 6: constant.language.predefined.register.roff
(ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)
|
# 7: constant.language.predefined.register.gnu.roff
(c\\.)
|
# 8: constant.language.predefined.register.readonly.roff
(\\${2} | \\.[$aAbcdfFhHijklLnopRTstuvVwxyz])
|
# 9: constant.language.predefined.register.readonly.gnu.roff
(\\.[CgmMOPUxyY])
|
# 10: variable.parameter.roff
(\\S{2})
)
|
# 11: keyword.operator.absolute.roff
(\\|)?
# 12: entity.name.roff
(
# 13: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
)
# 14: keyword.operator.arithmetic.roff
([-+])?
# Name of register
(?:
(%) | # 15: constant.language.predefined.register.roff
(\\S) # 16: variable.parameter.roff
)
"""
captures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.definition.brace.roff"}
6: {name: "constant.language.predefined.register.roff"}
7: {name: "constant.language.predefined.register.gnu.roff"}
8: {name: "constant.language.predefined.register.readonly.roff"}
9: {name: "constant.language.predefined.register.readonly.gnu.roff"}
10: {name: "variable.parameter.roff"}
11: {name: "keyword.operator.absolute.roff"}
12: {name: "entity.name.roff"}
13: {name: "punctuation.definition.escape.roff"}
14: {name: "keyword.operator.arithmetic.roff"}
15: {name: "constant.language.predefined.register.roff"}
16: {name: "variable.parameter.roff"}
}]
# Limited range of escape sequences permitted in copy-mode
"escapes-copymode":
patterns: [{
# Backslashed escape sequences: \t -> \\t
match: "(\\\\+?)(?=\\1\\S)"
name: "punctuation.definition.concealed.escape.backslash.roff"
},{
# Comments
name: "comment.line.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\")"
end: "$"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Newline-devouring comment (GNU)
name: "comment.line.number-sign.gnu.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\#).*$\\n?"
end: "^"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Empty control lines
name: "comment.empty.roff"
match: "^(\\.|'+)[ \t]*$"
captures:
1: {name: "punctuation.definition.comment.roff"}
},{
# Concealed newline
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^(?:[.'])?"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}
# Basic sequences
{include: "#register-expansion"}
{match: "(\\\\)\\1", name: "constant.character.escape.backslash.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)t", name: "constant.character.escape.tab.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)a", name: "constant.character.escape.leader-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\.", name: "constant.character.escape.dot.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \*[name].macro - Adhoc matching to improve tbl's "\*[3trans]" hack (GNU)
begin: "^(\\\\\\*\\[[^\\]]+\\])\\s*(\\.\\w+.*)"
end: "$"
beginCaptures:
1: patterns: [include: "#escapes"]
2: patterns: [include: "#conditional-innards"]
},{
# \*[xx args…] - Interpolate string "xx" with optional arguments (GNU)
name: "constant.character.escape.function.interpolate-string.gnu.roff"
begin: "((\\\\)\\*(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "function-call.arguments.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \*x, \*(xx - Interpolate string "x" or "xx"
name: "constant.character.escape.function.interpolate-string.roff"
match: "((\\\\)\\*(\\())(\\S{2})|((\\\\)\\*)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \$N - Interpolate argument number N (valid range: 1-9)
name: "constant.character.escape.function.interpolate-argument.roff"
match: "((\\\\)\\$\\d)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \m[X] - Alternate syntax for setting drawing/background colour (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
begin: "((\\\\)[Mm](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \mX, \m(XX - Set drawing or background colour to "X" (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
match: "((\\\\)[Mm](\\())(\\S{2})|((\\\\)[Mm])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \s[±n], \s±[n] - Set/adjust point-size (GNU)
name: "constant.character.escape.function.point-size.gnu.roff"
begin: "((\\\\)s([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "keyword.operator.arithmetic.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# "Parametric" escape sequences supported in Groff (GNU)
name: "constant.character.escape.function.check-identifier.gnu.roff"
begin: "((\\\\)(?!s[-+]?\\d)[ABRsZ])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# \ON - Suppress troff output with signal "N" (GNU)
name: "constant.character.escape.internal.gnu.roff"
match: "((\\\\)O([0-4]))"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
},{
# \O5[xyz] - Write file "xyz" to STDERR; grohtml-specific (GNU)
name: "constant.character.escape.internal.stderr-write-file.gnu.roff"
begin: "((\\\\)O(5)(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "string.unquoted.filename.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \V[x] - Alternate syntax for interpolating environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
begin: "((\\\\)[VY](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \Vx, \V(xx - Interpolate contents of environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
match: "((\\\\)[VY](\\())(\\S{2})|((\\\\)[VY])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \?code\? - Embed a chunk of code in diversion (GNU)
match: "((\\\\)(\\?))(.*)((\\\\)(\\?))"
captures:
1: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.script.roff"}
4: {name: "string.interpolated.roff", patterns: [include: "$self"]}
5: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "punctuation.definition.script.roff"}
},{
# \$*, \$@, \$^ - Argument concatenation for macros/strings (GNU)
name: "constant.character.escape.function.concatenated-arguments.gnu.roff"
match: "((\\\\)\\$[*@^])"
captures:
1: {name: "variable.language.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \$(nn - Expand n-th argument passed to macro or string (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
match: "((\\\\)\\$(\\())(\\S{2})"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \$[nnn] - Alternate syntax for expanding n-th macro/string argument (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
begin: "((\\\\)\\$(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
}]
# Every other escape sequence
"escapes-full":
patterns: [
# Basic sequences
{match: "(\\\\)e", name: "constant.character.escape.current-escape-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)´", name: "constant.character.escape.acute-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)`", name: "constant.character.escape.grave-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)-", name: "constant.character.escape.minus.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\) ", name: "constant.character.escape.space.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)0", name: "constant.character.escape.space.digit-width.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\|", name: "constant.character.escape.space.one-sixth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\^", name: "constant.character.escape.space.one-twelfth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)&", name: "constant.character.escape.zero-width-marker.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)%", name: "constant.character.escape.hyphenation-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)c", name: "constant.character.escape.connect.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)d", name: "constant.character.escape.downwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)p", name: "constant.character.escape.spread-line.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)r", name: "constant.character.escape.reverse.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)u", name: "constant.character.escape.upwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \(aa - Character named "aa"
name: "constant.character.escape.function.named-char.roff"
match: "(\\\\)(\\()(\\S{2})"
captures:
1: {name: "punctuation.definition.brace.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \[aa] - Character named "aa" (GNU)
name: "constant.character.escape.function.named-char.gnu.roff"
begin: "(\\\\)(\\[)"
end: "(\\S*?)(\\])|(?<!\\\\)(?=$)"
patterns: [
{include: "#params"}
{match: '(?:[^\\s\\]\\\\]|\\\\(?!["#]).)+', name: "variable.parameter.roff"}
]
beginCaptures:
1: {name: "punctuation.definition.escape.roff"}
2: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {patterns: [include: "#params"]}
2: {name: "punctuation.section.end.bracket.square.roff"}
},{
# Conditional input: Begin
name: "meta.function.begin.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\{(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.begin.roff"}
},{
# Conditional input: End
name: "meta.function.end.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\}(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.end.roff"}
},{
# Parametric/function-like escape sequences
name: "constant.character.escape.function.roff"
begin: "((\\\\)[bCDhHSlLovwxXN])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# Transparent throughput
name: "meta.throughput.roff"
begin: "(\\\\)!"
end: "(?<!\\\\)$"
beginCaptures:
0: {name: "constant.character.escape.transparent-line.roff"}
1: {name: "punctuation.definition.escape.roff"}
patterns: [{include: "#escapes-copymode"}]
},{
# Font: Roman/regular
name: "constant.character.escape.font.roff"
match: "(\\\\)f[RP1]"
captures:
0: {name: "entity.name.roff"}
1: {name: "punctuation.definition.escape.roff"}
}, {
# Font: Italics (typically rendered by nroff as underlined text)
begin: "((\\\\)f(?:[I2]|(\\()CI|(\\[)\\s*(?:[I2]|CI)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
4: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# Font: Bold
begin: "((\\\\)f(?:[B3]|(\\()CB|(\\[)\\s*(?:[B3]|CB)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# Font: Bold and italic
begin: "((\\\\)f(?:4|(\\()BI|(\\[)\\s*BI\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-italic-word"}
]
},{
# Font: Constant-width/monospaced
begin: "((\\\\)f(?:(\\()C[WR]|(\\[)\\s*C[WR]\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# \f[XX] - Change to font named "XX" (GNU)
name: "constant.character.escape.function.font.gnu.roff"
begin: "((\\\\)[Ff](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \fX, \f(XX, \fN - Change to font named "X" or "XX", or position N
name: "constant.character.escape.function.font.roff"
match: "((\\\\)[Ff](\\())(\\S{2})|((\\\\)[Ff])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \gx, \g(xx - Format of number register "x" or "xx"
name: "constant.character.escape.function.format-register.roff"
match: "((\\\\)g(\\())(\\S{2})|((\\\\)g)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \kX - Mark horizontal input place in register "X"
name: "constant.character.escape.function.mark-input.roff"
match: "((\\\\)k)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \sN, \s±N - Point-size change function; also \s(NN, \s±(NN
name: "constant.character.escape.function.point-size.roff"
match: "((\\\\)s[-+]?(\\()?)(\\d+)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \zC - Print "C" with zero width (without spacing)
name: "constant.character.escape.function.zero-width-print.roff"
match: "((\\\\)z)([^\\s\\\\])"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \Z - Any character not listed above
name: "constant.character.escape.misc.roff"
match: "(\\\\)\\S"
captures:
1: name: "punctuation.definition.escape.roff"
}]
# Macros
macros:
patterns: [
{include: "#man"}
{include: "#mdoc"}
{include: "#ms"}
{include: "#mm"}
{include: "#me"}
{include: "#www"}
# Generic macro highlighting
name: "meta.function.macro.roff"
begin: "^([.'])[ \t]*((?:[^\\s\\\\]|\\\\(?![#\"]).)+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
]
# Document macros
mdoc:
patterns: [{
# .Bf [ -emphasis | Em ]: Begin emphasised text
name: "meta.function.begin-emphasis.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-emphasis|Em)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Bf [ -literal | Li ]: Begin literal text
name: "meta.function.begin-literal.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-literal|Li)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Bf [ -symbolic | Sy ]: Begin symbolic text
name: "meta.function.begin-symbolic.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-symbolic|Sy)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Rs/.Re: Bibliographic block
begin: "^([.'])\\s*(Rs)(?=\\s)(.*)$"
end: "^([.'])\\s*(Re)(?=\\s)"
patterns: [include: "#refer"]
contentName: "meta.citation.mdoc.roff"
beginCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "entity.function.name.mdoc.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.mdoc.macro.roff"
2: name: "entity.function.name.mdoc.roff"
},{
# .Bd/.Ed: Ad-hoc rules to highlight embedded source code
begin: "^([.'])\\s*(Bd)\\s+(-literal)(?=\\s|$)(.*)"
end: "^([.'])\\s*(Ed)(?=\\s|$)"
beginCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#mdoc-args"]
4: patterns: [include: "#mdoc-unparsed"]
endCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [{
# HTML
name: "meta.html-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?HTML:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
name: "text.embedded.html.basic"
match: ".+"
captures:
0: patterns: [include: "text.html.basic"]
}]
},{
# JavaScript
name: "meta.js-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?JavaScript:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
match: ".+"
captures:
0: patterns: [include: "source.js"]
}]
},{
# CSS
name: "meta.css-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?CSS:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [include: "source.css"]
}, include: "#main"]
},{
# Unparsed macros: passing callable macros as arguments won't invoke them
name: "meta.function.$2.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(%[ABCDIJNOPQRTUV]|B[dfklt]|br|D[bdt]|E[dfklx]|F[do]|Hf|In|L[bp]|Nd|Os|Pp|R[esv]|Sm|sp|Ud)(?=\\s)"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [include: "#mdoc-unparsed"]
},{
# Parsed macros: will execute callable mdoc macros
name: "meta.function.$2.parsed.macro.mdoc.roff"
begin: """(?x)^([.'])\\s*
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|D1|Dc
|Dl|Do|Dq|Dv|Dx|Ec|Em|En|Eo|Eq|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic
|It|Li|Lk|Me|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc|Pf|Po|Pq|Qc
|Ql|Qo|Qq|Rd|Sc|Sh|So|Sq|Ss|St|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
(?=\\s)"""
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-callables"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
}]
# Mdoc macros that're executed as arguments by "parsed" macros
"mdoc-callables":
patterns: [{
# .Em: Emphasised text (Italic)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Em|Ar)\\G|(?<=\\s)(Em|Ar)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Sy: Symbolic text (Bold)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Sy|Fl|Cm)\\G|(?<=\\s)(Sy|Fl|Cm)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Li: Literal text (Monospaced)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Li)\\G|(?<=\\s)(Li)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Lk/.Mt: Hyperlink or mailto
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Lk|Mt)\\G|(?<=\\s)(Lk|Mt)(?=\\s)"
end: "$|(?=\\\\\")|(\\S+?)(?=$|\\s|\\\\\")"
beginCaptures:
1: name: "entity.function.name.roff"
endCaptures:
0: name: "markup.underline.link.hyperlink.mdoc.roff"
1: patterns: [include: "#escapes"]
},{
# Embedded macro name inside argument list
name: "meta.function.$1.callable.macro.mdoc.roff"
match: """(?x) (?<=[ \t])
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|En
|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc
|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)(?=\\s)"""
captures:
1: name: "entity.function.name.roff"
}]
# Arguments passed to mdoc macros
"mdoc-args":
patterns: [
{include: "#escapes"}
{include: "#string"}
{
# Document revision date
name: "string.quoted.other.date.roff"
begin: "\\$(?=Mdocdate)"
end: "\\$"
beginCaptures: 0: name: "punctuation.section.begin.date.roff"
endCaptures: 0: name: "punctuation.section.end.date.roff"
},{
# "Delimiters" (in mdoc's terms)
name: "punctuation.delimiter.mdoc.macro.roff"
match: "(?<=\\s)[(\\[.,:|;)\\]?!](?=\\s|$)"
},{
# Option flags used by some macros
name: "constant.language.option.mdoc.macro.roff"
match: """(?x)
(?<=\\s) (-)
(alpha|beta|bullet|centered|column|compact|dash|devel|diag|emphasis|enum|file|filled|hang
|hyphen|inset|item|literal|nested|nosplit|ohang|ragged|split|std|symbolic|tag|type|unfilled
|width|words|offset(?:\\s+(?:left|center|indent|indent-two|right))?)(?=\\s)"""
captures: 1: name: "punctuation.definition.dash.roff"
}]
# Arguments passed to "unparsed" mdoc macros
"mdoc-unparsed":
patterns: [
{include: "#mdoc-delimiters"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
# Manuscript macros
ms:
patterns: [{
name: "meta.function.${2:/downcase}.ms.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AB|AE|AI|AU|B1|B2|BT|BX|DA|DE|DS|EN|EQ|FE|FS|IP|KE|KF|KS|LG
|LP|MC|ND|NH|NL|P1|PE|PP|PS|PT|PX|QP|RP|SH|SM|TA|TC|TE|TL|TS|XA|XE
|XP|XS)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*([EO][FH])(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
},{
# Deprecated macros
name: "meta.deprecated.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*((De|Ds))(?=\\s)"
end: "(?<!\\\\)$|(?=\\s*\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [
{include: "#escapes"}
{include: "#string"}
]
},{
# Monospaced/constant-width text
name: "meta.function.cw.ms.macro.roff"
begin: "^([.'])[ \t]*(CW)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{
# Unquoted string
name: "markup.raw.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.raw.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.raw.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.raw.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
},{
# Underlined text
name: "meta.function.ul.ms.macro.roff"
begin: "^([.'])[ \t]*(UL)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
}]
# Memorandum macros
mm:
patterns: [{
name: "meta.function.${2:/downcase}.mm.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AE|AF|AL|APP|APPSK|AS|AST|AT|AU|AV|AVL|B1|B2|BE|BL|BS|BVL
|COVER|COVEND|DE|DF|DL|DS|EC|EF|EH|EN|EOP|EPIC|EQ|EX|FC|FD|FE|FG
|FS|GETHN|GETPN|GETR|GETST|H|HC|HM|HU|HX|HY|HZ|IA|IE|INITI|INITR
|IND|INDP|ISODATE|LB|LC|LE|LI|LT|LO|MC|ML|MT|MOVE|MULB|MULN|MULE
|nP|NCOL|NS|ND|OF|OH|OP|PGFORM|PGNH|PIC|PE|PF|PH|PS|PX?|RD|RF|RL
|RP|RS|S|SA|SETR|SG|SK|SM|SP|TA?B|TC|TE|TL|TM|TP|TS|TX|TY|VERBON
|VERBOFF|VL|VM|WA|WE|WC|\\)E)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
}]
# Paper-formatting macros
me:
patterns: [{
# Assorted macros without special highlighting or pattern-matching
name: "meta.function.${3:/downcase}.me.macro.roff"
begin: "(?x) ^([.'])[ \t]*
((?:[()][cdfqxz]|\\+\\+|\\+c)|
(1c|2c|EN|EQ|GE|GS|PE|PS|TE|TH|TS|ba|bc|bu|bx|hx
|hl|ip|lp|np|pd|pp|r|re|sk|sm|sz|tp|uh|xp)(?=\\s))"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
3: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .(l: List
begin: "^([.'])[ \t]*(\\(l)(?=\\s)"
end: "^([.'])[ \t]*(\\)l)(?=\\s)"
contentName: "markup.list.unnumbered.roff"
patterns: [include: "$self"]
beginCaptures:
0: {name: "meta.function.list.begin.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
endCaptures:
0: {name: "meta.function.list.end.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
},{
# .b: Bold
begin: "^([.'])[ \t]*(b)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-first"]
},{
# .i: Italic
begin: "^([.'])[ \t]*(i)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#italic-first"]
},{
# .bi: Bold/Italic
begin: "^([.'])[ \t]*(bi)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-italic-first"]
},{
# .u: Underline
begin: "^([.'])[ \t]*(u)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.underline-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# .sh: Section heading
name: "markup.heading.section.function.me.macro.roff"
begin: "^([.'])[ \t]*(sh)[ \t]+((?!\")\\S+)\\b[ \t]*(?!$|\\n|\\\\\")"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff", patterns: [include: "#params"]}
patterns: [include: "#bold-first"]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.me.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*(of|oh|he|eh|fo|ef)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
}]
# Webpage macros
www:
patterns: [{
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(ALN|BCL|BGIMG|DC|DLE|DLS|HEAD|HR|HTM?L|HX|JOBNAME
|LI|LINKSTYLE|LK|LNE|LNS|MPIMG|NHR|P?IMG|TAG)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# Macros that take URIs as their first argument
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "^([.'])[ \t]*(URL|FTP|MTO)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# Code blocks
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(CDS)(?=\\s|\\\\[\"#])\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(CDE)(?=\\s|\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Headings
name: "markup.heading.$3.www.macro.roff"
contentName: "string.unquoted.heading.roff"
begin: "^([.'])[ \t]*(HnS)(?=\\s)(?:\\s*(\\d+))?(?:\\s*(\\\\[#\"].*)$)?"
end: "^([.'])[ \t]*(HnE)(?=\\s)(.*)$"
beginCaptures:
0: {name: "meta.function.${2:/downcase}.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# Ordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(OLS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(OLE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Unordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(ULS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(ULE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
}]
# Manual-page macros
man:
patterns: [{
# Various macros that don't need special highlighting
name: "meta.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*(RE|RS|SM|BT|PT)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# Various deprecated macros
name: "meta.deprecated.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*((AT|DT|PD|UC))(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .TH: Title
name: "markup.heading.title.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(TH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SH: Section heading
name: "markup.heading.section.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SS: Subsection
name: "markup.heading.subsection.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SS)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EX: Example code
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(EX)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(EE)(?=\\s|\\\\[#\"])"
patterns: [{ include: "$self" }]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .LP/.PP/.P: Paragraph
name: "meta.function.paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(LP|PP?)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .IP: Indented paragraph
name: "meta.function.indented-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(IP)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# .TP: Titled paragraph
begin: "^([.'])[ \t]*(TP)(?=\\s|\\\\[\"#])(.*)?$\\n?"
end: "^(.*)(?<!\\\\)$"
patterns: [
match: ".+"
captures: 0: patterns: [include: "$self"]
]
beginCaptures:
0: {name: "meta.function.titled-paragraph.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#param-group"]}
endCaptures:
1: {patterns: [include: "$self"]}
},{
# .TQ: Header continuation for .TP (GNU extension)
name: "markup.list.unnumbered.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(TQ)[ \t]*(\\\\[#\"].*)?$"
end: "^(?=[.'][ \t]*TP(?:\\s|\\\\[#\"]))"
beginCaptures:
0: {name: "meta.function.header-continuation.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# .HP: Hanging paragraph (deprecated)
name: "meta.deprecated.function.hanging-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*((HP))(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .MT/.ME: Hyperlink (GNU extension)
name: "meta.function.mailto.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(MT)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(ME)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .UR/.UE: URL (GNU extension)
name: "meta.function.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(UR)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(UE)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .SY: Command synopsis (GNU extension)
name: "meta.command-synopsis.roff"
begin: "^([.'])[ \t]*(SY)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(YS)(?=\\s|\\\\[\"#])"
beginCaptures:
0: {name: "meta.function.begin.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
0: {name: "meta.function.end.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [include: "#bold-first", {
# .OP: Option description (GNU extension)
name: "meta.function.option-description.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(OP)(?=\\s)"
end: "(?<!\\\\)(?=\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [{
name: "function-call.arguments.roff"
begin: "\\G"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}, include: "#escapes"]
},{include: "$self"}]
},{
# .B/.SB: Bold
begin: "^([.'])[ \t]*(S?B)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.bold.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.bold.roff"}
2: {patterns: [{include: "#escapes"}]}
},{
# .I: Italic
begin: "^([.'])[ \t]*(I)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.italic.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.italic.roff"}
2: {patterns: [{include: "#escapes"}]}
}, include: "#alternating-fonts"]
# Repeating/combined-font macros
"alternating-fonts":
patterns: [{
# .BI: Bold + Italic
begin: "^([.'])[ \t]*(BI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
},{
# .BR: Bold + Roman
begin: "^([.'])[ \t]*(BR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-roman-after-bold"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .IB: Italic + Bold
begin: "^([.'])[ \t]*(IB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-bold-after-italic"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .IR: Italic + Roman
begin: "^([.'])[ \t]*(IR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-roman-after-italic"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .RB: Roman + Bold
begin: "^([.'])[ \t]*(RB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-bold-after-roman"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .RI: Roman + Italic
begin: "^([.'])[ \t]*(RI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-italic-after-roman"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}]
"bridge-escapes":
patterns: [{
name: "constant.character.escape.newline.roff"
begin: "[ \t]+(\\\\)$\\n?"
end: "^"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
},{
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^[ \t]*"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}]
"odd-bold":
patterns: [{
name: "markup.bold.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.bold.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.bold.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-italic":
patterns: [{
name: "markup.italic.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.italic.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.italic.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-roman":
patterns: [{
name: "markup.plain.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.plain.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.plain.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"even-bold":
patterns: [
name: "markup.bold.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-italic":
patterns: [
name: "markup.italic.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-roman":
patterns: [
name: "markup.plain.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-bold-after-italic":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-bold-after-roman":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-bold":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-roman":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-bold":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-italic":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
# Embolden first argument only
"bold-first":
patterns: [{
# Unquoted string
name: "markup.bold.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Italicise first argument only
"italic-first":
patterns: [{
# Unquoted string
name: "markup.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden and italicise first argument only
"bold-italic-first":
patterns: [{
# Unquoted string
name: "markup.bold.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden a word
"bold-word":
name: "markup.bold.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Italicise a word
"italic-word":
match: "\\S+?(?=\\\\|$|\\s)"
name: "markup.italic.roff"
# Embolden and italicise a word
"bold-italic-word":
name: "markup.bold.italic.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Render a word as raw/verbatim text
"monospace-word":
name: "markup.raw.monospaced.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Underline first argument only
"underline-first":
patterns: [{
# Unquoted string
contentName: "markup.underline.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "string.quoted.double.empty.roff"
match: '(")(")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.underline.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.underline.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Preprocessors for preparing Troff documents
preprocessors:
patterns: [{
# .TS/.TE: Tbl
begin: "^([.'])[ \t]*(TS)(?=\\s|\\\\[\"#])(.*)"
end: "^([.'])[ \t]*(TE)(?=\\s|\\\\[\"#])"
contentName: "markup.other.table.preprocessor.tbl.roff"
patterns: [include: "#tbl"]
beginCaptures:
0: {name: "meta.function.begin.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EQ/.EN: Eqn
begin: "^([.'])[ \t]*(EQ)(?=\\s|\\\\[\"#])[ \t]*([LIC]\\b)?\\s*([^\\\\\"]+|\\\\[^\"])*(\\\\\".*)?$"
end: "^([.'])[ \t]*(EN)(?=\\s|\\\\[\"#])"
contentName: "markup.other.math.preprocessor.eqn.roff"
patterns: [include: "#eqn"]
beginCaptures:
0: {name: "meta.function.begin.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.language.alignment-mode.eqn.roff"}
4: {name: "string.unquoted.equation-label.eqn.roff"}
5: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .[/.]: Refer
begin: "^([.'])[ \t]*(\\[)(.*?)\\s*(\\\\[\"#].*)?$"
end: "^([.'])[ \t]*(\\])(.*?)(?=\\s|$|\\\\\")"
contentName: "meta.citation.roff"
patterns: [{
# First line: Flags + Keywords
begin: "\\G"
end: "$|(?=\\\\[#\"])"
patterns: [{
name: "constant.character.flags.refer.gnu.roff"
match: "^[#\\[\\]]+"
}, include: "#params"]
}, include: "#refer"]
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.begin.roff"}
3: {name: "string.unquoted.opening-text.refer.roff", patterns: [include: "#escapes"]}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.end.roff"}
3: {name: "string.unquoted.closing-text.refer.roff", patterns: [include: "#escapes"]}
},{
# .GS/.GE: Gremlin pictures
begin: "^([.'])[ \t]*(GS)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(GE)(?=\\s|\\\\[\"#])"
beginCaptures:
0: name: "meta.function.begin.gremlin.macro.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: {name: "meta.function.end.gremlin.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
# Gremlin keywords
name: "keyword.operator.gremlin"
match: """(?x)
\\b((?:sun)?gremlinfile|ARC|BEZIER|BOTCENT|BOTLEFT|BOTRIGHT
|BSPLINE|CENTCENT|CENTLEFT|CENTRIGHT|CURVE|POLYGON|TOPCENT
|TOPLEFT|TOPRIGHT|VECTOR)\\b"""
{include: "#params"}
]
},{
# Perl (GNU)
begin: "^([.'])[ \t]*(Perl)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(Perl)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.perl.gnu.roff"
patterns: [include: "source.perl"]
beginCaptures:
0: name: "meta.function.begin.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
},{
# LilyPond (GNU)
begin: "^([.'])[ \t]*(lilypond)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(lilypond)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.lilypond.gnu.roff"
beginCaptures:
0: name: "meta.function.begin.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
patterns: [
{include: "source.AtLilyPond"}
{include: "source.lilypond"}
]
},{
# Pinyin (GNU)
begin: "^([.'])[ \t]*(pinyin)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(pinyin)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "meta.pinyin.gnu.roff"
patterns: [include: "#main"]
beginCaptures:
0: name: "meta.function.begin.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
}
{include: "source.pic#tags"}
{include: "source.ideal#tags"}]
# Equation preprocessor
eqn:
patterns: [{
# Greek letters
name: "constant.language.greek-letter.eqn.roff"
match: """(?x)\\b
(DELTA|GAMMA|LAMBDA|OMEGA|PHI|PI|PSI|SIGMA|THETA|UPSILON|XI|alpha|beta|chi
|delta|epsilon|eta|gamma|iota|kappa|lambda|mu|nu|omega|omicron|phi|pi|psi
|rho|sigma|tau|theta|upsilon|xi|zeta)\\b"""
},{
# Math symbols
name: "constant.character.math-symbol.eqn.roff"
match: """(?x)\\b
(sum|int|prod|union|inter|inf|partial|half|prime|approx|nothing|cdot
|times|del|grad|[><=!]=|\\+-|->|<-|<<|>>|\\.{3}|,\\.,)\\b"""
},{
# Punctuation
name: "punctuation.definition.eqn.roff"
match: "[~,^{}]"
},{
# Eqn keywords
name: "keyword.language.eqn.roff"
match: """(?x)\\b
(above|back|bar|bold|ccol|col|cpile|define|delim|dot|dotdot|down|dyad|fat|font|from
|fwd|gfont|gsize|hat|italic|lcol|left|lineup|lpile|mark|matrix|ndefine|over|pile
|rcol|right|roman|rpile|size|sqrt|sub|sup|tdefine|tilde|to|under|up|vec)\\b"""
},{
# GNU Eqn: Keywords
name: "keyword.language.eqn.gnu.roff"
match: """(?x)\\b
(accent|big|chartype|smallover|type|vcenter|uaccent|split|nosplit
|opprime|special|sdefine|include|ifdef|undef|g[rb]font|space)\\b"""
},{
# GNU Eqn: Character names
name: "constant.language.eqn.gnu.roff"
match: """(?x)\\b
(Alpha|Beta|Chi|Delta|Epsilon|Eta|Gamma|Iota|Kappa|Lambda|Mu|Nu
|Omega|Omicron|Phi|Pi|Psi|Rho|Sigma|Tau|Theta|Upsilon|Xi|Zeta
|ldots|dollar)\\b"""
},{
# GNU Eqn: Set MathML variables
name: "meta.set-variable.eqn.gnu.roff"
match: """(?x)\\b(set)[ \t]+
(accent_width|axis_height|baseline_sep|big_op_spacing[1-5]|body_depth|body_height|column_sep
|default_rule_thickness|delimiter_factor|delimiter_shortfall|denom[12]|draw_lines|fat_offset
|matrix_side_sep|medium_space|minimum_size|nroff|null_delimiter_space|num[12]|over_hang
|script_space|shift_down|su[bp]_drop|sub[12]|sup[1-3]|thick_space|thin_space|x_height)\\b"""
captures:
1: name: "storage.type.var.eqn.roff"
2: name: "variable.other.mathml.eqn.roff"
}, include: "#string"]
# Table preprocessor
tbl:
patterns: [{
# Options/Formats
name: "meta.function-call.arguments.tbl.roff"
begin: "\\G|^((\\.)T&)[ \t]*$"
end: "(\\.)$\\n?|^(?=[.'][ \t]*TE(?=\\s))"
beginCaptures:
1: {name: "entity.function.name.roff"}
2: {name: "punctuation.definition.macro.roff"}
endCaptures:
1: patterns: [include: "#params"]
2: name: "punctuation.terminator.section.tbl.roff"
patterns: [{
# Not preprocessor source; abandon ship
begin: "^(?=\\.)"
end: "^(?=[.'][ \t]*TE(?=\\s|\\\\[\"#]))"
patterns: [include: "$self"]},{
# Global options
match: "^(.+)(;)$"
captures:
1: patterns: [
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{match: "\\b(center|centre|expand|box|allbox|doublebox)\\b", name: "constant.language.$1.tbl.roff"}
{match: "\\b((tab|linesize|delim)(\\()([^\\)\\s]*)(\\)))"
captures:
1: name: "constant.language.$2.tbl.roff"
3: name: "punctuation.definition.arguments.begin.tbl.roff"
4: patterns: [include: "#params"]
5: name: "punctuation.definition.arguments.end.tbl.roff"}]
2: name: "punctuation.terminator.line.tbl.roff"}
# Field specifiers
{match: "[ABCEFILNPRSTUVWZabcefilnprstuvwz^]", name: "constant.language.key-letter.tbl.roff"}
{match: "[|_=]", name: "punctuation.keyword.tbl.roff"}
{match: "[-+]?\\d+", name: "constant.numeric.tbl.roff"}
{match: "\\.", name: "punctuation.delimiter.period.full-stop.tbl.roff"}
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{include: "#params"}
]
},{
# Horizontal line indicators
name: "punctuation.keyword.tbl.roff"
match: "^\\s*([=_]|\\\\_)\\s*$"
},{
# Column-filling repeated character sequence
name: "constant.character.escape.repeat.tbl.roff"
match: "(?<!\\\\)((\\\\)R)(.)"
captures:
1: {name: "keyword.operator.tbl.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.unquoted.tbl.roff"}
},{
# Vertically-spanned item indicator
name: "constant.character.escape.vertical-span.tbl.roff"
match: "(\\\\)\\^"
captures:
0: {name: "keyword.operator.tbl.roff"}
1: {name: "punctuation.definition.escape.roff"}
},{
# Multiline cell content
name: "meta.multiline-cell.tbl.roff"
contentName: "string.unquoted.tbl.roff"
begin: "T(\\{)"
end: "^T(\\})|^(?=[.'][ \t]*TE\\b)"
patterns: [include: "$self"]
beginCaptures:
0: name: "keyword.operator.section.begin.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
endCaptures:
0: name: "keyword.operator.section.end.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
}, include: "$self"]
# Bibliographic references
refer:
patterns: [{
# Comment
name: "comment.line.refer.roff"
begin: "#"
end: "$"
beginCaptures:
0: name: "punctuation.definition.comment.refer.roff"
},{
# Names of each author, concatenated with the string specified by `join-authors`
name: "variable.other.readonly.author-names.refer.roff"
match: "@"
},{
# %KEY Value
name: "meta.structure.dictionary.refer.roff"
contentName: "meta.structure.dictionary.value.refer.roff"
begin: "^([.'])?\\s*(%)([A-Z])(?=\\s)"
end: "(?<!\\\\)$"
patterns: [{
name: "string.unquoted.refer.roff"
begin: "\\G"
end: "(?<!\\\\)$"
patterns: [{
# Make sure "special" characters don't trigger refer patterns
name: "meta.symbol.refer.roff"
match: "[-+'\"<>\\].*\\[~!&?:]"
}, include: "#refer"]
}, include: "#escapes"]
beginCaptures:
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "punctuation.definition.percentage-sign.refer.roff"
3: name: "variable.other.readonly.key-letter.refer.roff"
},{
# Literal/single-quoted string
name: "string.quoted.single.refer.roff"
begin: "'"
end: "'"
beginCaptures: 0: name: "punctuation.definition.string.begin.roff"
endCaptures: 0: name: "punctuation.definition.string.end.roff"
},{
# Formatted/placeholder value
name: "variable.other.readonly.formatted.refer.roff"
match: "(%+)[\\daiA-Z]"
captures:
1: name: "punctuation.definition.percentage-sign.refer.roff"
},{
# Label expressions
name: "keyword.operator.label-expression.refer.roff"
match: """(?x)
(?<=\\S)(?:\\*|[-+]\\d+|(\\.)(?:[-+]?y|[lucran]))(?=\\s|$) |
(?<=\\S)[~!&?:](?=\\S)"""
captures:
1: name: "punctuation.separator.period.full-stop.refer.roff"
},{
# Angle brackets
begin: "<"
end: ">|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
endCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
patterns: [include: "#refer"]
},{
# Round brackets
begin: "\\("
end: "\\)|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.round.refer.roff"
endCaptures: 0: name: "punctuation.bracket.round.refer.roff"
patterns: [include: "#refer"]
},{
# Negatable commands
name: "keyword.operator.negatable.refer.roff"
match: """(?x)\\b
(?:no-)?
(?:abbreviate|abbreviate-label-ranges|accumulate|annotate|compatible|date-as-label
|default-database|discard|et-al|label-in-reference|label-in-text|move-punctuation
|reverse|search-ignore|search-truncate|short-label|sort|sort-adjacent-labels)\\b"""
captures:
0: name: "entity.function.name.refer.roff"
},{
# Non-negatable commands
name: "keyword.operator.refer.roff"
match: "\\b(articles|bibliography|capitalize|join-authors|label|separate-label-second-parts)\\b"
captures:
0: name: "entity.function.name.refer.roff"
},{
# Commands that take filenames as arguments
begin: "^\\s*\\b(database|include)\\b"
end: "(?<!\\\\)$"
beginCaptures:
0: name: "keyword.operator.refer.roff"
1: name: "entity.function.name.refer.roff"
patterns: [
{include: "#escapes"}
# Add underlines to filenames for themes supporting them
name: "string.unquoted.filename.refer.roff"
match: "((?:[^\\\\\\s]|\\\\(?!\").)+)"
captures:
0: name: "markup.link.underline.refer.roff"
1: patterns: [include: "#escapes"]
]
}
{include: "#string"}
{include: "#escapes"}]
| 113434 | name: "<NAME>"
scopeName: "text.roff"
fileTypes: [
"1", "1b", "1c", "1has", "1in", "1m", "1s", "1t", "1x",
"2",
"3", "3avl", "3bsm", "3c", "3in", "3m", "3qt", "3x",
"4",
"5",
"6",
"7", "7d", "7fs", "7i", "7ipp", "7m", "7p",
"8",
"9", "9e", "9f", "9p", "9s",
"groff",
"man",
"mandoc",
"mdoc",
"me",
"mmn", "mmt",
"ms",
"mom",
"n",
"nroff",
"roff", "rof",
"t",
"tmac", "tmac-u", "tmac.in",
"tr",
"troff"
]
firstLineMatch: """(?x)
# Manual page with .TH macro on first line
^\\.TH[ \t]+(?:\\S+)
|
# Preprocessor line
# See: https://www.gnu.org/software/groff/manual/html_node/Preprocessors-in-man-pages.html
^'\\\\\"\\x20[tre]+(?=\\s|$)
|
# “Aliased” manual page
^\\.so[ \t]+man(\\w+)/.+\\.\\1(?=\\s|$)
|
# Modeline
(?i:
# Emacs
-\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*)
[gnt]?roff
(?=[\\s;]|(?<![-*])-\\*-).*?-\\*-
|
# Vim
(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s))(?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:](?:filetype|ft|syntax)\\s*=
[gnt]?roff
(?=\\s|:|$)
)
"""
limitLineLength: no
patterns: [{ include: "#main" }]
repository:
# Common patterns
main:
patterns: [
{include: "#preprocessors"}
{include: "#escapes"}
{include: "#requests"}
{include: "#macros"}
]
# Control line parameters
params:
patterns: [
{include: "#escapes"}
{include: "#string"}
{include: "#number"}
{include: "#generic-parameter"}
]
# Numeric literal
number:
name: "constant.numeric.roff"
match: "(?!\\d+[cfimnPpsuvz]\\w)(\\|)?(?:(?<!\\w)[-+])?(?:\\d+(?:\\.\\d*)?|\\.\\d+|(?<=[-+])\\.)([cfimnPpsuvz])?"
captures:
1: name: "keyword.operator.absolute.roff"
2: name: "keyword.other.unit.roff"
# "Double-quoted string"
string:
patterns: [{
name: "string.quoted.double.empty.roff",
match: '(?<=(?<=[^\\\\]|^)\\s|^)(")(")(?=\\s|$)'
captures:
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
name: "string.quoted.double.roff",
begin: '(?<=(?<=[^\\\\]|^)\\s|^)"(?!")'
end: '(?<!")"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
patterns: [include: "#string-escapes"]
}]
# Escape sequences to match inside double-quoted strings
"string-escapes":
patterns: [
{match: '""', name: "constant.character.escape.quote.double.roff"}
{include: "#escapes"}
]
# Highlighting for macro arguments that don't match anything else
"generic-parameter":
name: "variable.parameter.roff"
match: "[^\\s\\\\]+"
# List of arguments passed to a request or macro
"param-group":
name: "function-call.arguments.roff"
begin: "\\G|^"
end: "\\Z|$"
patterns: [include: "#params"]
# Bracket-delimited long-name (GNU)
"long-name":
patterns: [{
name: "variable.parameter.other.roff"
begin: "\\G\\s*"
end: "(?=\\]|\\s)"
patterns: [include: "#escapes"]
}
{include: "#escapes"}
{include: "#string"}
{include: "#number"}]
# Group of strings delimited with an arbitrary character
"3-part-title":
name: "string.3-part.other.roff"
match: '\\G[ \t]*(.)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)'
captures:
1: name: "punctuation.definition.string.begin.roff"
2: name: "entity.string.left.roff", patterns: [include: "#escapes"]
3: name: "punctuation.definition.string.begin.roff"
4: name: "entity.string.centre.roff", patterns: [include: "#escapes"]
5: name: "punctuation.definition.string.end.roff"
6: name: "entity.string.right.roff", patterns: [include: "#escapes"]
7: name: "punctuation.definition.string.end.roff"
# Requests
requests:
patterns:[{
# GNU extensions
name: "meta.function.request.$2.gnu.roff"
begin: "(?x) ^([.'])[ \t]*
(aln|als|asciify|backtrace|blm|boxa|box|brp|cflags|chop|close|composite|color
|cp|devicem|device|do|ecs|ecr|evc|fam|fchar|fcolor|fschar|fspecial|ftr|fzoom
|gcolor|hcode|hla|hlm|hpfa|hpfcode|hpf|hym|hys|itc|kern|length|linetabs|lsm
|mso|nop|nroff|opena|open|output|pev|pnr|psbb|pso|ptr|pvs|rchar|rfschar|rj
|rnn|schar|shc|shift|sizes|special|spreadwarn|sty|substring|tkf|tm1|tmc|trf
|trin|trnt|troff|unformat|vpt|warnscale|warn|writec|writem|write)
(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
},{
# .class: Assign a name to a range of characters (GNU)
name: "meta.function.request.assign-class.gnu.roff"
begin: "^([.'])[ \t]*(class)[ \t]+(\\S+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff"}
patterns: [{
match: "[^\\s\\\\]+(-)[^\\s\\\\]+"
captures:
0: name: "string.unquoted.character-range.roff"
1: name: "punctuation.separator.dash.roff"
}, include: "#params"]
},{
# .char: Define character or glyph (GNU)
name: "meta.function.request.$2.gnu.roff"
begin: "^([.'])[ \t]*(char)[ \t]*(\\S+)?[ \t]*(.*)(?=$|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
patterns: [include: "$self"]
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "variable.parameter.roff"}
4: {patterns: [include: "#param-group"]}
},{
# .defcolor: Define colour (GNU)
name: "meta.function.request.define-colour.gnu.roff"
begin: "^([.'])[ \t]*(defcolor)(?=\\s)[ \t]*((?:[^\\s\\\\]|\\\\(?![\"#]).)*)[ \t]*(rgb|cmyk?|gr[ae]y)?"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "string.other.colour-name.roff", patterns: [include: "#escapes"]}
4: {name: "constant.language.colour-scheme.roff"}
patterns: [{
# Hexadecimal colour
name: "constant.other.colour.hex.roff"
match: "(\#{1,2})[A-Fa-f0-9]+"
captures: 1: name: "punctuation.definition.colour.roff"
}, include: "#params"]
},{
# Requests for controlling program flow (GNU)
begin: "^([.'])[ \t]*(break|continue|return|while)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
patterns: [include: "#param-group"]
beginCaptures:
0: {name: "meta.function.request.control.gnu.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
},{
# .tm/.ab: Print remainder of line to STDERR
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(ab|tm)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#escapes-copymode"}]
contentName: "string.unquoted.roff"
},{
# Generic requests without formatting
name: "meta.function.request.$2.roff"
begin: "(?x) ^([.'])[ \t]*
(ab|ad|af|bd|bp|br|c2|cc|ce|cf|ch|cs|da|di|dt|ec|em|eo|ev
|ex|fc|fi|fl|fp|ft|hc|hw|hy|in|it|lc|lg|lf|ll|ls|lt|mc|mk
|na|ne|nf|nh|nm|nn|ns|nx|os|pc|pi|pl|pm|pn|po|ps|rd|rm|rn
|rr|rs|rt|so|sp|ss|sv|sy|ta|tc|ti|tm|tr|uf|vs|wh)
(?=\\s|\\d+\\s*$|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
}
{ include: "#conditionals" }
{ include: "#definition" }
{ include: "#ignore" }
{ include: "#underlines" }
{
# Register assignment
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(nr)[ \t]*(?:(%|ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)|(c\\.)|(\\${2}|\\.[$aAbcdfFhHijklLnopRTstuvVwxyz])|(\\.[CgmMOPUxyY])|(\\S+))?[ \t]*(.*)$"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "constant.language.predefined.register.roff"}
4: {name: "constant.language.predefined.register.gnu.roff"}
5: {name: "invalid.illegal.readonly.register.roff"}
6: {name: "invalid.illegal.readonly.register.gnu.roff"}
7: {name: "variable.parameter.roff", patterns: [include: "#escapes"]}
8: {patterns: [{include: "#arithmetic"}, {include: "#param-group"}]}
},{
# String definition
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*([ad]s1?)[ \t]+(((?:[^\\s\\\\]|\\\\(?!\").)+))?"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "storage.type.var.roff"
3: name: "variable.parameter.roff"
4: name: "entity.name.roff", patterns: [include: "#escapes"]
contentName: "string.unquoted.roff"
patterns: [include: "#escapes"]
},{
# Three-part title
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(tl)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
contentName: "function-call.arguments.roff"
patterns: [
{include: "#3-part-title"}
{include: "#params"}
]
}]
# Conditional input
conditionals:
patterns: [{
# Conditional: If
begin: """(?x)^
([.']) [ \t]* # 1: punctuation.definition.request.roff
(ie|if) [ \t]* # 2: keyword.control.roff
(!)? # 3: keyword.operator.logical
(?:
# One-character built-in comparison name
([notev]) # 4: constant.language.builtin-comparison.$4.roff
|
# GNU extensions
([cdFmrS]) # 5: constant.language.builtin-comparison.$5.gnu.roff
# Name being validated
[ \t]*
((?:[^ \\t\\\\]|\\\\(?!["#]).)+) # 6: Include “#escapes”
|
# Arithmetic
( # 7: meta.equation.roff
# Starts with a bracket
(\\() # 8: punctuation.definition.begin.roff
(.*?) # 9: Include “#arithmetic”
(\\)) # 10: punctuation.definition.end.roff
# Anything else affixed to it
( # 11: Include “#arithmetic”
(?:
[^\\s\\(] | # Operators/numbers
\\(.*?\\) # More brackets
)*
)
|
# Doesn’t start with a bracket
(?:
# Starts with a long-form string/register
(\\|?\\\\+[n*]\\(\\S{2}) # 12: Include “#escapes”
|
# Starts with a digit or backslash
(?=\\d|\\\\)
)
([^\\s\\(]*) # 13: Sandwiched mathematical junk
(?: # Possible embedded brackets
(\\() # 14: punctuation.definition.begin.roff
(.*?) # 15: Include “#arithmetic”
(\\)) # 16: punctuation.definition.end.roff
)?
(?: # Possible trailing digits/operators
[^\\s\\(]*?
\\d+
)?
# Ends with a...
(?<=
# Digit
\\d |
# Unit suffix
(?<=[\\d.])
[A-Za-z] |
# Closing bracket
[\\)\\]] |
# String/register: Long-form
\\\\[n*]
\\(
\\S{2} |
# String/register: Short-form
\\\\[n*]\\S
)
)
|
# String/variable comparison
([^\\d\\s\\\\]) # 17: punctuation.definition.string.begin.roff
( # 18: variable.parameter.operand.left.roff
(.*?) # 19: Include “#escapes”
)
(\\17) # 20: punctuation.definition.string.roff
( # 21: variable.parameter.operand.right.roff
(.*?) # 22: Include “#escapes”
)
(\\17) # 23: punctuation.definition.string.end.roff
|
# Anything not recognised
(\\S) # 24: meta.operand.single.roff
)?
(.*) # 25: Include “#conditional-innards”
"""
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {name: "keyword.operator.logical"}
4: {name: "constant.language.builtin-comparison.$4.roff"}
5: {name: "constant.language.builtin-comparison.$5.gnu.roff"}
6: {patterns: [include: "#escapes"]}
7: {name: "meta.equation.roff"}
8: {name: "punctuation.definition.begin.roff"}
9: {patterns: [{include: "#arithmetic"}]}
10: {name: "punctuation.definition.end.roff"}
11: {patterns: [{include: "#arithmetic"}]}
12: {patterns: [{include: "#escapes"}]}
13: {patterns: [{include: "#arithmetic"}]}
14: {name: "punctuation.definition.begin.roff"}
15: {patterns: [{include: "#arithmetic"}]}
16: {name: "punctuation.definition.end.roff"}
17: {name: "punctuation.definition.string.begin.roff"}
18: {name: "variable.parameter.operand.left.roff"}
19: {patterns: [{include: "#escapes"}]}
20: {name: "punctuation.definition.string.roff"}
21: {name: "variable.parameter.operand.right.roff"}
22: {patterns: [{include: "#escapes"}]}
23: {name: "punctuation.definition.string.end.roff"}
24: {name: "meta.operand.single.roff"}
25: {patterns: [{include: "#conditional-innards"}]}
},{
# Conditional: Else
begin: "^([.'])[ \t]*(el)\\s*(.*)"
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {patterns: [{include: "#conditional-innards"}]}
}]
"conditional-innards":
patterns: [{
begin: "^\\s*(\\\\\\{(?:\\\\(?=\\n))?)?\\s*(.*)"
end: "$"
beginCaptures:
1: {name: "punctuation.section.conditional.begin.roff"}
2: {patterns: [{include: "$self"}]}
}]
# Basic arithmetic sequences
arithmetic:
patterns: [
{include: "#escapes"},
{
name: "meta.brackets.roff"
match: "(\\()(.*?)(\\))"
captures:
1: {name: "punctuation.arithmetic.begin.roff"}
2: {patterns: [{include: "#arithmetic"}]}
3: {name: "punctuation.arithmetic.end.roff"}
}
{include: "#number"}
{match: "<\\?", name: "keyword.operator.minimum.gnu.roff"}
{match: ">\\?", name: "keyword.operator.maximum.gnu.roff"}
{match: "[-/+*%]", name: "keyword.operator.arithmetic.roff"}
{match: ":|&|[<=>]=?", name: "keyword.operator.logical.roff"}
{match: "\\|", name: "keyword.operator.absolute.roff"}
{
# Change default scaling indicator (GNU)
name: "meta.scaling-indicator.gnu.roff"
match: "(?<=^|\\()([cfimnPpsuvz])(;)"
captures:
1: name: "keyword.other.unit.roff"
2: name: "punctuation.separator.semicolon.roff"
}
]
# Macro definitions
definition:
patterns: [{
# No terminator specified
name: "meta.function.definition.request.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+?)?\\s*(\\\\[\"#].*)?$"
end: "^(?:[ \t]*\\x5C{2})?\\.[ \t]*\\."
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {patterns: [include: "#escapes"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
0: {name: "punctuation.definition.request.roff"}
patterns: [include: "$self"]
},{
# Terminator included
name: "meta.function.definition.request.with-terminator.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+)\\s*(\"[^\"]+\"?|\\S+?(?=\\s|\\\\[\"#]))?(.*)$"
end: "^(\\.)[ \t]*((\\6)(?=$|\\s|\\\\(?:$|\")))"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {name: "keyword.control.terminator.roff", patterns: [include: "#string"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.terminator.roff"}
3: {patterns: [{include: "#string"}]}
patterns: [{include: "$self"}]
}]
# Ignored content
ignore:
patterns: [{
# Terminator specified
contentName: "comment.block.ignored-input.with-terminator.roff"
begin: "^([.'])[ \t]*(ig)[ \t]+(?!\\\\[\"#])((\"[^\"]+\")|\\S+?(?=\\s|\\\\[\"#]))(.*)$"
end: "^([.'])[ \t]*(\\3)(?=\\s|$|\\\\)"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: name: "keyword.control.terminator.roff"
4: patterns: [include: "#string"]
5: patterns: [include: "#params"]
endCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "keyword.control.terminator.roff", patterns: [include: "#string"]
},{
# No terminator given
contentName: "comment.block.ignored-input.roff"
begin: "^([.'])[ \t]*(ig)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*\\.(?=\\s|\\\\[\"#])"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#params"]
endCaptures:
0: name: "punctuation.definition.request.roff"
}]
# Underlined passages
underlines:
patterns: [{
# .ul/.cu 0: Empty request/noop
name: "meta.request.$2.roff"
match: "^([.'])[ \t]*(ul|cu)\\s*(0+)(?:(?!\\\\\")[\\D])*(?=\\s|$)(.*)$"
captures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [{include: "#params"}]}
}, {
# Underline following line
name: "meta.request.$2.roff"
begin: "^([.'])[ \t]*(ul|cu)(?=\\s|$|\\\\)(.*?)$\\n"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [{include: "#params"}]}
patterns: [{
# Ignore control-lines
begin: "^(?=[.']|\\\\!)(.*)$\\n"
end: "^"
beginCaptures:
1: {patterns: [{include: "$self"}]}
}, {
name: "markup.underline.roff"
begin: "^(?![.'])"
end: "(?<!\\\\)$"
}]
}]
# Escape sequences
escapes:
patterns: [
{include: "#escapes-copymode"}
{include: "#escapes-full"}
]
# Register interpolation
"register-expansion":
patterns: [{
# \n[xx] - Contents of number register "XX" (GNU)
name: "constant.character.escape.function.expand-register.gnu.roff"
begin: "(\\|)?(((?:(?<=\\|)\\\\*?)?\\\\)n([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \nX, \n(XX - Contents of number register "X" or "XX"
name: "constant.character.escape.function.expand-register.roff"
match: """(?x)
# 1: keyword.operator.absolute.roff
(\\|)?
# 2: entity.name.roff
(
# 3: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
([-+])? # 4: keyword.operator.arithmetic.roff
(\\() # 5: punctuation.definition.brace.roff
)
# Name of register
(?:
# 6: constant.language.predefined.register.roff
(ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)
|
# 7: constant.language.predefined.register.gnu.roff
(c\\.)
|
# 8: constant.language.predefined.register.readonly.roff
(\\${2} | \\.[$aAbcdfFhHijklLnopRTstuvVwxyz])
|
# 9: constant.language.predefined.register.readonly.gnu.roff
(\\.[CgmMOPUxyY])
|
# 10: variable.parameter.roff
(\\S{2})
)
|
# 11: keyword.operator.absolute.roff
(\\|)?
# 12: entity.name.roff
(
# 13: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
)
# 14: keyword.operator.arithmetic.roff
([-+])?
# Name of register
(?:
(%) | # 15: constant.language.predefined.register.roff
(\\S) # 16: variable.parameter.roff
)
"""
captures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.definition.brace.roff"}
6: {name: "constant.language.predefined.register.roff"}
7: {name: "constant.language.predefined.register.gnu.roff"}
8: {name: "constant.language.predefined.register.readonly.roff"}
9: {name: "constant.language.predefined.register.readonly.gnu.roff"}
10: {name: "variable.parameter.roff"}
11: {name: "keyword.operator.absolute.roff"}
12: {name: "entity.name.roff"}
13: {name: "punctuation.definition.escape.roff"}
14: {name: "keyword.operator.arithmetic.roff"}
15: {name: "constant.language.predefined.register.roff"}
16: {name: "variable.parameter.roff"}
}]
# Limited range of escape sequences permitted in copy-mode
"escapes-copymode":
patterns: [{
# Backslashed escape sequences: \t -> \\t
match: "(\\\\+?)(?=\\1\\S)"
name: "punctuation.definition.concealed.escape.backslash.roff"
},{
# Comments
name: "comment.line.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\")"
end: "$"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Newline-devouring comment (GNU)
name: "comment.line.number-sign.gnu.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\#).*$\\n?"
end: "^"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Empty control lines
name: "comment.empty.roff"
match: "^(\\.|'+)[ \t]*$"
captures:
1: {name: "punctuation.definition.comment.roff"}
},{
# Concealed newline
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^(?:[.'])?"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}
# Basic sequences
{include: "#register-expansion"}
{match: "(\\\\)\\1", name: "constant.character.escape.backslash.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)t", name: "constant.character.escape.tab.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)a", name: "constant.character.escape.leader-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\.", name: "constant.character.escape.dot.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \*[name].macro - Adhoc matching to improve tbl's "\*[3trans]" hack (GNU)
begin: "^(\\\\\\*\\[[^\\]]+\\])\\s*(\\.\\w+.*)"
end: "$"
beginCaptures:
1: patterns: [include: "#escapes"]
2: patterns: [include: "#conditional-innards"]
},{
# \*[xx args…] - Interpolate string "xx" with optional arguments (GNU)
name: "constant.character.escape.function.interpolate-string.gnu.roff"
begin: "((\\\\)\\*(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "function-call.arguments.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \*x, \*(xx - Interpolate string "x" or "xx"
name: "constant.character.escape.function.interpolate-string.roff"
match: "((\\\\)\\*(\\())(\\S{2})|((\\\\)\\*)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \$N - Interpolate argument number N (valid range: 1-9)
name: "constant.character.escape.function.interpolate-argument.roff"
match: "((\\\\)\\$\\d)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \m[X] - Alternate syntax for setting drawing/background colour (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
begin: "((\\\\)[Mm](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \mX, \m(XX - Set drawing or background colour to "X" (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
match: "((\\\\)[Mm](\\())(\\S{2})|((\\\\)[Mm])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \s[±n], \s±[n] - Set/adjust point-size (GNU)
name: "constant.character.escape.function.point-size.gnu.roff"
begin: "((\\\\)s([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "keyword.operator.arithmetic.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# "Parametric" escape sequences supported in Groff (GNU)
name: "constant.character.escape.function.check-identifier.gnu.roff"
begin: "((\\\\)(?!s[-+]?\\d)[ABRsZ])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# \ON - Suppress troff output with signal "N" (GNU)
name: "constant.character.escape.internal.gnu.roff"
match: "((\\\\)O([0-4]))"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
},{
# \O5[xyz] - Write file "xyz" to STDERR; grohtml-specific (GNU)
name: "constant.character.escape.internal.stderr-write-file.gnu.roff"
begin: "((\\\\)O(5)(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "string.unquoted.filename.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \V[x] - Alternate syntax for interpolating environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
begin: "((\\\\)[VY](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \Vx, \V(xx - Interpolate contents of environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
match: "((\\\\)[VY](\\())(\\S{2})|((\\\\)[VY])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \?code\? - Embed a chunk of code in diversion (GNU)
match: "((\\\\)(\\?))(.*)((\\\\)(\\?))"
captures:
1: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.script.roff"}
4: {name: "string.interpolated.roff", patterns: [include: "$self"]}
5: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "punctuation.definition.script.roff"}
},{
# \$*, \$@, \$^ - Argument concatenation for macros/strings (GNU)
name: "constant.character.escape.function.concatenated-arguments.gnu.roff"
match: "((\\\\)\\$[*@^])"
captures:
1: {name: "variable.language.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \$(nn - Expand n-th argument passed to macro or string (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
match: "((\\\\)\\$(\\())(\\S{2})"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \$[nnn] - Alternate syntax for expanding n-th macro/string argument (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
begin: "((\\\\)\\$(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
}]
# Every other escape sequence
"escapes-full":
patterns: [
# Basic sequences
{match: "(\\\\)e", name: "constant.character.escape.current-escape-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)´", name: "constant.character.escape.acute-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)`", name: "constant.character.escape.grave-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)-", name: "constant.character.escape.minus.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\) ", name: "constant.character.escape.space.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)0", name: "constant.character.escape.space.digit-width.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\|", name: "constant.character.escape.space.one-sixth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\^", name: "constant.character.escape.space.one-twelfth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)&", name: "constant.character.escape.zero-width-marker.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)%", name: "constant.character.escape.hyphenation-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)c", name: "constant.character.escape.connect.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)d", name: "constant.character.escape.downwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)p", name: "constant.character.escape.spread-line.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)r", name: "constant.character.escape.reverse.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)u", name: "constant.character.escape.upwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \(aa - Character named "aa"
name: "constant.character.escape.function.named-char.roff"
match: "(\\\\)(\\()(\\S{2})"
captures:
1: {name: "punctuation.definition.brace.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \[aa] - Character named "aa" (GNU)
name: "constant.character.escape.function.named-char.gnu.roff"
begin: "(\\\\)(\\[)"
end: "(\\S*?)(\\])|(?<!\\\\)(?=$)"
patterns: [
{include: "#params"}
{match: '(?:[^\\s\\]\\\\]|\\\\(?!["#]).)+', name: "variable.parameter.roff"}
]
beginCaptures:
1: {name: "punctuation.definition.escape.roff"}
2: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {patterns: [include: "#params"]}
2: {name: "punctuation.section.end.bracket.square.roff"}
},{
# Conditional input: Begin
name: "meta.function.begin.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\{(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.begin.roff"}
},{
# Conditional input: End
name: "meta.function.end.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\}(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.end.roff"}
},{
# Parametric/function-like escape sequences
name: "constant.character.escape.function.roff"
begin: "((\\\\)[bCDhHSlLovwxXN])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# Transparent throughput
name: "meta.throughput.roff"
begin: "(\\\\)!"
end: "(?<!\\\\)$"
beginCaptures:
0: {name: "constant.character.escape.transparent-line.roff"}
1: {name: "punctuation.definition.escape.roff"}
patterns: [{include: "#escapes-copymode"}]
},{
# Font: Roman/regular
name: "constant.character.escape.font.roff"
match: "(\\\\)f[RP1]"
captures:
0: {name: "entity.name.roff"}
1: {name: "punctuation.definition.escape.roff"}
}, {
# Font: Italics (typically rendered by nroff as underlined text)
begin: "((\\\\)f(?:[I2]|(\\()CI|(\\[)\\s*(?:[I2]|CI)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
4: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# Font: Bold
begin: "((\\\\)f(?:[B3]|(\\()CB|(\\[)\\s*(?:[B3]|CB)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# Font: Bold and italic
begin: "((\\\\)f(?:4|(\\()BI|(\\[)\\s*BI\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-italic-word"}
]
},{
# Font: Constant-width/monospaced
begin: "((\\\\)f(?:(\\()C[WR]|(\\[)\\s*C[WR]\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# \f[XX] - Change to font named "XX" (GNU)
name: "constant.character.escape.function.font.gnu.roff"
begin: "((\\\\)[Ff](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \fX, \f(XX, \fN - Change to font named "X" or "XX", or position N
name: "constant.character.escape.function.font.roff"
match: "((\\\\)[Ff](\\())(\\S{2})|((\\\\)[Ff])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \gx, \g(xx - Format of number register "x" or "xx"
name: "constant.character.escape.function.format-register.roff"
match: "((\\\\)g(\\())(\\S{2})|((\\\\)g)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \kX - Mark horizontal input place in register "X"
name: "constant.character.escape.function.mark-input.roff"
match: "((\\\\)k)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \sN, \s±N - Point-size change function; also \s(NN, \s±(NN
name: "constant.character.escape.function.point-size.roff"
match: "((\\\\)s[-+]?(\\()?)(\\d+)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \zC - Print "C" with zero width (without spacing)
name: "constant.character.escape.function.zero-width-print.roff"
match: "((\\\\)z)([^\\s\\\\])"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \Z - Any character not listed above
name: "constant.character.escape.misc.roff"
match: "(\\\\)\\S"
captures:
1: name: "punctuation.definition.escape.roff"
}]
# Macros
macros:
patterns: [
{include: "#man"}
{include: "#mdoc"}
{include: "#ms"}
{include: "#mm"}
{include: "#me"}
{include: "#www"}
# Generic macro highlighting
name: "meta.function.macro.roff"
begin: "^([.'])[ \t]*((?:[^\\s\\\\]|\\\\(?![#\"]).)+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
]
# Document macros
mdoc:
patterns: [{
# .Bf [ -emphasis | Em ]: Begin emphasised text
name: "meta.function.begin-emphasis.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-emphasis|Em)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Bf [ -literal | Li ]: Begin literal text
name: "meta.function.begin-literal.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-literal|Li)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Bf [ -symbolic | Sy ]: Begin symbolic text
name: "meta.function.begin-symbolic.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-symbolic|Sy)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Rs/.Re: Bibliographic block
begin: "^([.'])\\s*(Rs)(?=\\s)(.*)$"
end: "^([.'])\\s*(Re)(?=\\s)"
patterns: [include: "#refer"]
contentName: "meta.citation.mdoc.roff"
beginCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "entity.function.name.mdoc.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.mdoc.macro.roff"
2: name: "entity.function.name.mdoc.roff"
},{
# .Bd/.Ed: Ad-hoc rules to highlight embedded source code
begin: "^([.'])\\s*(Bd)\\s+(-literal)(?=\\s|$)(.*)"
end: "^([.'])\\s*(Ed)(?=\\s|$)"
beginCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#mdoc-args"]
4: patterns: [include: "#mdoc-unparsed"]
endCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [{
# HTML
name: "meta.html-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?HTML:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
name: "text.embedded.html.basic"
match: ".+"
captures:
0: patterns: [include: "text.html.basic"]
}]
},{
# JavaScript
name: "meta.js-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?JavaScript:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
match: ".+"
captures:
0: patterns: [include: "source.js"]
}]
},{
# CSS
name: "meta.css-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?CSS:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [include: "source.css"]
}, include: "#main"]
},{
# Unparsed macros: passing callable macros as arguments won't invoke them
name: "meta.function.$2.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(%[ABCDIJNOPQRTUV]|B[dfklt]|br|D[bdt]|E[dfklx]|F[do]|Hf|In|L[bp]|Nd|Os|Pp|R[esv]|Sm|sp|Ud)(?=\\s)"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [include: "#mdoc-unparsed"]
},{
# Parsed macros: will execute callable mdoc macros
name: "meta.function.$2.parsed.macro.mdoc.roff"
begin: """(?x)^([.'])\\s*
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|D1|Dc
|Dl|Do|Dq|Dv|Dx|Ec|Em|En|Eo|Eq|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic
|It|Li|Lk|Me|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc|Pf|Po|Pq|Qc
|Ql|Qo|Qq|Rd|Sc|Sh|So|Sq|Ss|St|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
(?=\\s)"""
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-callables"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
}]
# Mdoc macros that're executed as arguments by "parsed" macros
"mdoc-callables":
patterns: [{
# .Em: Emphasised text (Italic)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Em|Ar)\\G|(?<=\\s)(Em|Ar)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Sy: Symbolic text (Bold)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Sy|Fl|Cm)\\G|(?<=\\s)(Sy|Fl|Cm)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Li: Literal text (Monospaced)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Li)\\G|(?<=\\s)(Li)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Lk/.Mt: Hyperlink or mailto
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Lk|Mt)\\G|(?<=\\s)(Lk|Mt)(?=\\s)"
end: "$|(?=\\\\\")|(\\S+?)(?=$|\\s|\\\\\")"
beginCaptures:
1: name: "entity.function.name.roff"
endCaptures:
0: name: "markup.underline.link.hyperlink.mdoc.roff"
1: patterns: [include: "#escapes"]
},{
# Embedded macro name inside argument list
name: "meta.function.$1.callable.macro.mdoc.roff"
match: """(?x) (?<=[ \t])
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|En
|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc
|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)(?=\\s)"""
captures:
1: name: "entity.function.name.roff"
}]
# Arguments passed to mdoc macros
"mdoc-args":
patterns: [
{include: "#escapes"}
{include: "#string"}
{
# Document revision date
name: "string.quoted.other.date.roff"
begin: "\\$(?=Mdocdate)"
end: "\\$"
beginCaptures: 0: name: "punctuation.section.begin.date.roff"
endCaptures: 0: name: "punctuation.section.end.date.roff"
},{
# "Delimiters" (in mdoc's terms)
name: "punctuation.delimiter.mdoc.macro.roff"
match: "(?<=\\s)[(\\[.,:|;)\\]?!](?=\\s|$)"
},{
# Option flags used by some macros
name: "constant.language.option.mdoc.macro.roff"
match: """(?x)
(?<=\\s) (-)
(alpha|beta|bullet|centered|column|compact|dash|devel|diag|emphasis|enum|file|filled|hang
|hyphen|inset|item|literal|nested|nosplit|ohang|ragged|split|std|symbolic|tag|type|unfilled
|width|words|offset(?:\\s+(?:left|center|indent|indent-two|right))?)(?=\\s)"""
captures: 1: name: "punctuation.definition.dash.roff"
}]
# Arguments passed to "unparsed" mdoc macros
"mdoc-unparsed":
patterns: [
{include: "#mdoc-delimiters"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
# Manuscript macros
ms:
patterns: [{
name: "meta.function.${2:/downcase}.ms.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AB|AE|AI|AU|B1|B2|BT|BX|DA|DE|DS|EN|EQ|FE|FS|IP|KE|KF|KS|LG
|LP|MC|ND|NH|NL|P1|PE|PP|PS|PT|PX|QP|RP|SH|SM|TA|TC|TE|TL|TS|XA|XE
|XP|XS)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*([EO][FH])(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
},{
# Deprecated macros
name: "meta.deprecated.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*((De|Ds))(?=\\s)"
end: "(?<!\\\\)$|(?=\\s*\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [
{include: "#escapes"}
{include: "#string"}
]
},{
# Monospaced/constant-width text
name: "meta.function.cw.ms.macro.roff"
begin: "^([.'])[ \t]*(CW)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{
# Unquoted string
name: "markup.raw.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.raw.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.raw.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.raw.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
},{
# Underlined text
name: "meta.function.ul.ms.macro.roff"
begin: "^([.'])[ \t]*(UL)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
}]
# Memorandum macros
mm:
patterns: [{
name: "meta.function.${2:/downcase}.mm.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AE|AF|AL|APP|APPSK|AS|AST|AT|AU|AV|AVL|B1|B2|BE|BL|BS|BVL
|COVER|COVEND|DE|DF|DL|DS|EC|EF|EH|EN|EOP|EPIC|EQ|EX|FC|FD|FE|FG
|FS|GETHN|GETPN|GETR|GETST|H|HC|HM|HU|HX|HY|HZ|IA|IE|INITI|INITR
|IND|INDP|ISODATE|LB|LC|LE|LI|LT|LO|MC|ML|MT|MOVE|MULB|MULN|MULE
|nP|NCOL|NS|ND|OF|OH|OP|PGFORM|PGNH|PIC|PE|PF|PH|PS|PX?|RD|RF|RL
|RP|RS|S|SA|SETR|SG|SK|SM|SP|TA?B|TC|TE|TL|TM|TP|TS|TX|TY|VERBON
|VERBOFF|VL|VM|WA|WE|WC|\\)E)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
}]
# Paper-formatting macros
me:
patterns: [{
# Assorted macros without special highlighting or pattern-matching
name: "meta.function.${3:/downcase}.me.macro.roff"
begin: "(?x) ^([.'])[ \t]*
((?:[()][cdfqxz]|\\+\\+|\\+c)|
(1c|2c|EN|EQ|GE|GS|PE|PS|TE|TH|TS|ba|bc|bu|bx|hx
|hl|ip|lp|np|pd|pp|r|re|sk|sm|sz|tp|uh|xp)(?=\\s))"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
3: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .(l: List
begin: "^([.'])[ \t]*(\\(l)(?=\\s)"
end: "^([.'])[ \t]*(\\)l)(?=\\s)"
contentName: "markup.list.unnumbered.roff"
patterns: [include: "$self"]
beginCaptures:
0: {name: "meta.function.list.begin.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
endCaptures:
0: {name: "meta.function.list.end.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
},{
# .b: Bold
begin: "^([.'])[ \t]*(b)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-first"]
},{
# .i: Italic
begin: "^([.'])[ \t]*(i)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#italic-first"]
},{
# .bi: Bold/Italic
begin: "^([.'])[ \t]*(bi)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-italic-first"]
},{
# .u: Underline
begin: "^([.'])[ \t]*(u)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.underline-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# .sh: Section heading
name: "markup.heading.section.function.me.macro.roff"
begin: "^([.'])[ \t]*(sh)[ \t]+((?!\")\\S+)\\b[ \t]*(?!$|\\n|\\\\\")"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff", patterns: [include: "#params"]}
patterns: [include: "#bold-first"]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.me.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*(of|oh|he|eh|fo|ef)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
}]
# Webpage macros
www:
patterns: [{
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(ALN|BCL|BGIMG|DC|DLE|DLS|HEAD|HR|HTM?L|HX|JOBNAME
|LI|LINKSTYLE|LK|LNE|LNS|MPIMG|NHR|P?IMG|TAG)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# Macros that take URIs as their first argument
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "^([.'])[ \t]*(URL|FTP|MTO)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# Code blocks
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(CDS)(?=\\s|\\\\[\"#])\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(CDE)(?=\\s|\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Headings
name: "markup.heading.$3.www.macro.roff"
contentName: "string.unquoted.heading.roff"
begin: "^([.'])[ \t]*(HnS)(?=\\s)(?:\\s*(\\d+))?(?:\\s*(\\\\[#\"].*)$)?"
end: "^([.'])[ \t]*(HnE)(?=\\s)(.*)$"
beginCaptures:
0: {name: "meta.function.${2:/downcase}.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# Ordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(OLS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(OLE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Unordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(ULS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(ULE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
}]
# Manual-page macros
man:
patterns: [{
# Various macros that don't need special highlighting
name: "meta.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*(RE|RS|SM|BT|PT)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# Various deprecated macros
name: "meta.deprecated.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*((AT|DT|PD|UC))(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .TH: Title
name: "markup.heading.title.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(TH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SH: Section heading
name: "markup.heading.section.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SS: Subsection
name: "markup.heading.subsection.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SS)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EX: Example code
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(EX)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(EE)(?=\\s|\\\\[#\"])"
patterns: [{ include: "$self" }]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .LP/.PP/.P: Paragraph
name: "meta.function.paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(LP|PP?)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .IP: Indented paragraph
name: "meta.function.indented-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(IP)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# .TP: Titled paragraph
begin: "^([.'])[ \t]*(TP)(?=\\s|\\\\[\"#])(.*)?$\\n?"
end: "^(.*)(?<!\\\\)$"
patterns: [
match: ".+"
captures: 0: patterns: [include: "$self"]
]
beginCaptures:
0: {name: "meta.function.titled-paragraph.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#param-group"]}
endCaptures:
1: {patterns: [include: "$self"]}
},{
# .TQ: Header continuation for .TP (GNU extension)
name: "markup.list.unnumbered.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(TQ)[ \t]*(\\\\[#\"].*)?$"
end: "^(?=[.'][ \t]*TP(?:\\s|\\\\[#\"]))"
beginCaptures:
0: {name: "meta.function.header-continuation.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# .HP: Hanging paragraph (deprecated)
name: "meta.deprecated.function.hanging-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*((HP))(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .MT/.ME: Hyperlink (GNU extension)
name: "meta.function.mailto.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(MT)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(ME)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .UR/.UE: URL (GNU extension)
name: "meta.function.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(UR)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(UE)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .SY: Command synopsis (GNU extension)
name: "meta.command-synopsis.roff"
begin: "^([.'])[ \t]*(SY)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(YS)(?=\\s|\\\\[\"#])"
beginCaptures:
0: {name: "meta.function.begin.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
0: {name: "meta.function.end.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [include: "#bold-first", {
# .OP: Option description (GNU extension)
name: "meta.function.option-description.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(OP)(?=\\s)"
end: "(?<!\\\\)(?=\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [{
name: "function-call.arguments.roff"
begin: "\\G"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}, include: "#escapes"]
},{include: "$self"}]
},{
# .B/.SB: Bold
begin: "^([.'])[ \t]*(S?B)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.bold.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.bold.roff"}
2: {patterns: [{include: "#escapes"}]}
},{
# .I: Italic
begin: "^([.'])[ \t]*(I)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.italic.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.italic.roff"}
2: {patterns: [{include: "#escapes"}]}
}, include: "#alternating-fonts"]
# Repeating/combined-font macros
"alternating-fonts":
patterns: [{
# .BI: Bold + Italic
begin: "^([.'])[ \t]*(BI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
},{
# .BR: Bold + Roman
begin: "^([.'])[ \t]*(BR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-roman-after-bold"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .IB: Italic + Bold
begin: "^([.'])[ \t]*(IB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-bold-after-italic"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .IR: Italic + Roman
begin: "^([.'])[ \t]*(IR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-roman-after-italic"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .RB: Roman + Bold
begin: "^([.'])[ \t]*(RB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-bold-after-roman"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .RI: Roman + Italic
begin: "^([.'])[ \t]*(RI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-italic-after-roman"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}]
"bridge-escapes":
patterns: [{
name: "constant.character.escape.newline.roff"
begin: "[ \t]+(\\\\)$\\n?"
end: "^"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
},{
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^[ \t]*"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}]
"odd-bold":
patterns: [{
name: "markup.bold.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.bold.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.bold.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-italic":
patterns: [{
name: "markup.italic.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.italic.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.italic.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-roman":
patterns: [{
name: "markup.plain.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.plain.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.plain.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"even-bold":
patterns: [
name: "markup.bold.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-italic":
patterns: [
name: "markup.italic.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-roman":
patterns: [
name: "markup.plain.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-bold-after-italic":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-bold-after-roman":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-bold":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-roman":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-bold":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-italic":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
# Embolden first argument only
"bold-first":
patterns: [{
# Unquoted string
name: "markup.bold.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Italicise first argument only
"italic-first":
patterns: [{
# Unquoted string
name: "markup.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden and italicise first argument only
"bold-italic-first":
patterns: [{
# Unquoted string
name: "markup.bold.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden a word
"bold-word":
name: "markup.bold.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Italicise a word
"italic-word":
match: "\\S+?(?=\\\\|$|\\s)"
name: "markup.italic.roff"
# Embolden and italicise a word
"bold-italic-word":
name: "markup.bold.italic.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Render a word as raw/verbatim text
"monospace-word":
name: "markup.raw.monospaced.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Underline first argument only
"underline-first":
patterns: [{
# Unquoted string
contentName: "markup.underline.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "string.quoted.double.empty.roff"
match: '(")(")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.underline.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.underline.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Preprocessors for preparing Troff documents
preprocessors:
patterns: [{
# .TS/.TE: Tbl
begin: "^([.'])[ \t]*(TS)(?=\\s|\\\\[\"#])(.*)"
end: "^([.'])[ \t]*(TE)(?=\\s|\\\\[\"#])"
contentName: "markup.other.table.preprocessor.tbl.roff"
patterns: [include: "#tbl"]
beginCaptures:
0: {name: "meta.function.begin.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EQ/.EN: Eqn
begin: "^([.'])[ \t]*(EQ)(?=\\s|\\\\[\"#])[ \t]*([LIC]\\b)?\\s*([^\\\\\"]+|\\\\[^\"])*(\\\\\".*)?$"
end: "^([.'])[ \t]*(EN)(?=\\s|\\\\[\"#])"
contentName: "markup.other.math.preprocessor.eqn.roff"
patterns: [include: "#eqn"]
beginCaptures:
0: {name: "meta.function.begin.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.language.alignment-mode.eqn.roff"}
4: {name: "string.unquoted.equation-label.eqn.roff"}
5: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .[/.]: Refer
begin: "^([.'])[ \t]*(\\[)(.*?)\\s*(\\\\[\"#].*)?$"
end: "^([.'])[ \t]*(\\])(.*?)(?=\\s|$|\\\\\")"
contentName: "meta.citation.roff"
patterns: [{
# First line: Flags + Keywords
begin: "\\G"
end: "$|(?=\\\\[#\"])"
patterns: [{
name: "constant.character.flags.refer.gnu.roff"
match: "^[#\\[\\]]+"
}, include: "#params"]
}, include: "#refer"]
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.begin.roff"}
3: {name: "string.unquoted.opening-text.refer.roff", patterns: [include: "#escapes"]}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.end.roff"}
3: {name: "string.unquoted.closing-text.refer.roff", patterns: [include: "#escapes"]}
},{
# .GS/.GE: Gremlin pictures
begin: "^([.'])[ \t]*(GS)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(GE)(?=\\s|\\\\[\"#])"
beginCaptures:
0: name: "meta.function.begin.gremlin.macro.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: {name: "meta.function.end.gremlin.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
# Gremlin keywords
name: "keyword.operator.gremlin"
match: """(?x)
\\b((?:sun)?gremlinfile|ARC|BEZIER|BOTCENT|BOTLEFT|BOTRIGHT
|BSPLINE|CENTCENT|CENTLEFT|CENTRIGHT|CURVE|POLYGON|TOPCENT
|TOPLEFT|TOPRIGHT|VECTOR)\\b"""
{include: "#params"}
]
},{
# Perl (GNU)
begin: "^([.'])[ \t]*(Perl)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(Perl)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.perl.gnu.roff"
patterns: [include: "source.perl"]
beginCaptures:
0: name: "meta.function.begin.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
},{
# LilyPond (GNU)
begin: "^([.'])[ \t]*(lilypond)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(lilypond)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.lilypond.gnu.roff"
beginCaptures:
0: name: "meta.function.begin.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
patterns: [
{include: "source.AtLilyPond"}
{include: "source.lilypond"}
]
},{
# Pinyin (GNU)
begin: "^([.'])[ \t]*(pinyin)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(pinyin)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "meta.pinyin.gnu.roff"
patterns: [include: "#main"]
beginCaptures:
0: name: "meta.function.begin.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
}
{include: "source.pic#tags"}
{include: "source.ideal#tags"}]
# Equation preprocessor
eqn:
patterns: [{
# Greek letters
name: "constant.language.greek-letter.eqn.roff"
match: """(?x)\\b
(DELTA|GAMMA|LAMBDA|OMEGA|PHI|PI|PSI|SIGMA|THETA|UPSILON|XI|alpha|beta|chi
|delta|epsilon|eta|gamma|iota|kappa|lambda|mu|nu|omega|omicron|phi|pi|psi
|rho|sigma|tau|theta|upsilon|xi|zeta)\\b"""
},{
# Math symbols
name: "constant.character.math-symbol.eqn.roff"
match: """(?x)\\b
(sum|int|prod|union|inter|inf|partial|half|prime|approx|nothing|cdot
|times|del|grad|[><=!]=|\\+-|->|<-|<<|>>|\\.{3}|,\\.,)\\b"""
},{
# Punctuation
name: "punctuation.definition.eqn.roff"
match: "[~,^{}]"
},{
# Eqn keywords
name: "keyword.language.eqn.roff"
match: """(?x)\\b
(above|back|bar|bold|ccol|col|cpile|define|delim|dot|dotdot|down|dyad|fat|font|from
|fwd|gfont|gsize|hat|italic|lcol|left|lineup|lpile|mark|matrix|ndefine|over|pile
|rcol|right|roman|rpile|size|sqrt|sub|sup|tdefine|tilde|to|under|up|vec)\\b"""
},{
# GNU Eqn: Keywords
name: "keyword.language.eqn.gnu.roff"
match: """(?x)\\b
(accent|big|chartype|smallover|type|vcenter|uaccent|split|nosplit
|opprime|special|sdefine|include|ifdef|undef|g[rb]font|space)\\b"""
},{
# GNU Eqn: Character names
name: "constant.language.eqn.gnu.roff"
match: """(?x)\\b
(Alpha|Beta|Chi|Delta|Epsilon|Eta|Gamma|Iota|Kappa|Lambda|Mu|Nu
|Omega|Omicron|Phi|Pi|Psi|Rho|Sigma|Tau|Theta|Upsilon|Xi|Zeta
|ldots|dollar)\\b"""
},{
# GNU Eqn: Set MathML variables
name: "meta.set-variable.eqn.gnu.roff"
match: """(?x)\\b(set)[ \t]+
(accent_width|axis_height|baseline_sep|big_op_spacing[1-5]|body_depth|body_height|column_sep
|default_rule_thickness|delimiter_factor|delimiter_shortfall|denom[12]|draw_lines|fat_offset
|matrix_side_sep|medium_space|minimum_size|nroff|null_delimiter_space|num[12]|over_hang
|script_space|shift_down|su[bp]_drop|sub[12]|sup[1-3]|thick_space|thin_space|x_height)\\b"""
captures:
1: name: "storage.type.var.eqn.roff"
2: name: "variable.other.mathml.eqn.roff"
}, include: "#string"]
# Table preprocessor
tbl:
patterns: [{
# Options/Formats
name: "meta.function-call.arguments.tbl.roff"
begin: "\\G|^((\\.)T&)[ \t]*$"
end: "(\\.)$\\n?|^(?=[.'][ \t]*TE(?=\\s))"
beginCaptures:
1: {name: "entity.function.name.roff"}
2: {name: "punctuation.definition.macro.roff"}
endCaptures:
1: patterns: [include: "#params"]
2: name: "punctuation.terminator.section.tbl.roff"
patterns: [{
# Not preprocessor source; abandon ship
begin: "^(?=\\.)"
end: "^(?=[.'][ \t]*TE(?=\\s|\\\\[\"#]))"
patterns: [include: "$self"]},{
# Global options
match: "^(.+)(;)$"
captures:
1: patterns: [
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{match: "\\b(center|centre|expand|box|allbox|doublebox)\\b", name: "constant.language.$1.tbl.roff"}
{match: "\\b((tab|linesize|delim)(\\()([^\\)\\s]*)(\\)))"
captures:
1: name: "constant.language.$2.tbl.roff"
3: name: "punctuation.definition.arguments.begin.tbl.roff"
4: patterns: [include: "#params"]
5: name: "punctuation.definition.arguments.end.tbl.roff"}]
2: name: "punctuation.terminator.line.tbl.roff"}
# Field specifiers
{match: "[ABCEFILNPRSTUVWZabcefilnprstuvwz^]", name: "constant.language.key-letter.tbl.roff"}
{match: "[|_=]", name: "punctuation.keyword.tbl.roff"}
{match: "[-+]?\\d+", name: "constant.numeric.tbl.roff"}
{match: "\\.", name: "punctuation.delimiter.period.full-stop.tbl.roff"}
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{include: "#params"}
]
},{
# Horizontal line indicators
name: "punctuation.keyword.tbl.roff"
match: "^\\s*([=_]|\\\\_)\\s*$"
},{
# Column-filling repeated character sequence
name: "constant.character.escape.repeat.tbl.roff"
match: "(?<!\\\\)((\\\\)R)(.)"
captures:
1: {name: "keyword.operator.tbl.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.unquoted.tbl.roff"}
},{
# Vertically-spanned item indicator
name: "constant.character.escape.vertical-span.tbl.roff"
match: "(\\\\)\\^"
captures:
0: {name: "keyword.operator.tbl.roff"}
1: {name: "punctuation.definition.escape.roff"}
},{
# Multiline cell content
name: "meta.multiline-cell.tbl.roff"
contentName: "string.unquoted.tbl.roff"
begin: "T(\\{)"
end: "^T(\\})|^(?=[.'][ \t]*TE\\b)"
patterns: [include: "$self"]
beginCaptures:
0: name: "keyword.operator.section.begin.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
endCaptures:
0: name: "keyword.operator.section.end.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
}, include: "$self"]
# Bibliographic references
refer:
patterns: [{
# Comment
name: "comment.line.refer.roff"
begin: "#"
end: "$"
beginCaptures:
0: name: "punctuation.definition.comment.refer.roff"
},{
# Names of each author, concatenated with the string specified by `join-authors`
name: "variable.other.readonly.author-names.refer.roff"
match: "@"
},{
# %KEY Value
name: "meta.structure.dictionary.refer.roff"
contentName: "meta.structure.dictionary.value.refer.roff"
begin: "^([.'])?\\s*(%)([A-Z])(?=\\s)"
end: "(?<!\\\\)$"
patterns: [{
name: "string.unquoted.refer.roff"
begin: "\\G"
end: "(?<!\\\\)$"
patterns: [{
# Make sure "special" characters don't trigger refer patterns
name: "meta.symbol.refer.roff"
match: "[-+'\"<>\\].*\\[~!&?:]"
}, include: "#refer"]
}, include: "#escapes"]
beginCaptures:
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "punctuation.definition.percentage-sign.refer.roff"
3: name: "variable.other.readonly.key-letter.refer.roff"
},{
# Literal/single-quoted string
name: "string.quoted.single.refer.roff"
begin: "'"
end: "'"
beginCaptures: 0: name: "punctuation.definition.string.begin.roff"
endCaptures: 0: name: "punctuation.definition.string.end.roff"
},{
# Formatted/placeholder value
name: "variable.other.readonly.formatted.refer.roff"
match: "(%+)[\\daiA-Z]"
captures:
1: name: "punctuation.definition.percentage-sign.refer.roff"
},{
# Label expressions
name: "keyword.operator.label-expression.refer.roff"
match: """(?x)
(?<=\\S)(?:\\*|[-+]\\d+|(\\.)(?:[-+]?y|[lucran]))(?=\\s|$) |
(?<=\\S)[~!&?:](?=\\S)"""
captures:
1: name: "punctuation.separator.period.full-stop.refer.roff"
},{
# Angle brackets
begin: "<"
end: ">|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
endCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
patterns: [include: "#refer"]
},{
# Round brackets
begin: "\\("
end: "\\)|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.round.refer.roff"
endCaptures: 0: name: "punctuation.bracket.round.refer.roff"
patterns: [include: "#refer"]
},{
# Negatable commands
name: "keyword.operator.negatable.refer.roff"
match: """(?x)\\b
(?:no-)?
(?:abbreviate|abbreviate-label-ranges|accumulate|annotate|compatible|date-as-label
|default-database|discard|et-al|label-in-reference|label-in-text|move-punctuation
|reverse|search-ignore|search-truncate|short-label|sort|sort-adjacent-labels)\\b"""
captures:
0: name: "entity.function.name.refer.roff"
},{
# Non-negatable commands
name: "keyword.operator.refer.roff"
match: "\\b(articles|bibliography|capitalize|join-authors|label|separate-label-second-parts)\\b"
captures:
0: name: "entity.function.name.refer.roff"
},{
# Commands that take filenames as arguments
begin: "^\\s*\\b(database|include)\\b"
end: "(?<!\\\\)$"
beginCaptures:
0: name: "keyword.operator.refer.roff"
1: name: "entity.function.name.refer.roff"
patterns: [
{include: "#escapes"}
# Add underlines to filenames for themes supporting them
name: "string.unquoted.filename.refer.roff"
match: "((?:[^\\\\\\s]|\\\\(?!\").)+)"
captures:
0: name: "markup.link.underline.refer.roff"
1: patterns: [include: "#escapes"]
]
}
{include: "#string"}
{include: "#escapes"}]
| true | name: "PI:NAME:<NAME>END_PI"
scopeName: "text.roff"
fileTypes: [
"1", "1b", "1c", "1has", "1in", "1m", "1s", "1t", "1x",
"2",
"3", "3avl", "3bsm", "3c", "3in", "3m", "3qt", "3x",
"4",
"5",
"6",
"7", "7d", "7fs", "7i", "7ipp", "7m", "7p",
"8",
"9", "9e", "9f", "9p", "9s",
"groff",
"man",
"mandoc",
"mdoc",
"me",
"mmn", "mmt",
"ms",
"mom",
"n",
"nroff",
"roff", "rof",
"t",
"tmac", "tmac-u", "tmac.in",
"tr",
"troff"
]
firstLineMatch: """(?x)
# Manual page with .TH macro on first line
^\\.TH[ \t]+(?:\\S+)
|
# Preprocessor line
# See: https://www.gnu.org/software/groff/manual/html_node/Preprocessors-in-man-pages.html
^'\\\\\"\\x20[tre]+(?=\\s|$)
|
# “Aliased” manual page
^\\.so[ \t]+man(\\w+)/.+\\.\\1(?=\\s|$)
|
# Modeline
(?i:
# Emacs
-\\*-(?:\\s*(?=[^:;\\s]+\\s*-\\*-)|(?:.*?[;\\s]|(?<=-\\*-))mode\\s*:\\s*)
[gnt]?roff
(?=[\\s;]|(?<![-*])-\\*-).*?-\\*-
|
# Vim
(?:(?:\\s|^)vi(?:m[<=>]?\\d+|m)?|\\sex)(?=:(?=\\s*set?\\s[^\\n:]+:)|:(?!\\s* set?\\s))(?:(?:\\s|\\s*:\\s*)\\w*(?:\\s*=(?:[^\\n\\\\\\s]|\\\\.)*)?)*[\\s:](?:filetype|ft|syntax)\\s*=
[gnt]?roff
(?=\\s|:|$)
)
"""
limitLineLength: no
patterns: [{ include: "#main" }]
repository:
# Common patterns
main:
patterns: [
{include: "#preprocessors"}
{include: "#escapes"}
{include: "#requests"}
{include: "#macros"}
]
# Control line parameters
params:
patterns: [
{include: "#escapes"}
{include: "#string"}
{include: "#number"}
{include: "#generic-parameter"}
]
# Numeric literal
number:
name: "constant.numeric.roff"
match: "(?!\\d+[cfimnPpsuvz]\\w)(\\|)?(?:(?<!\\w)[-+])?(?:\\d+(?:\\.\\d*)?|\\.\\d+|(?<=[-+])\\.)([cfimnPpsuvz])?"
captures:
1: name: "keyword.operator.absolute.roff"
2: name: "keyword.other.unit.roff"
# "Double-quoted string"
string:
patterns: [{
name: "string.quoted.double.empty.roff",
match: '(?<=(?<=[^\\\\]|^)\\s|^)(")(")(?=\\s|$)'
captures:
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
name: "string.quoted.double.roff",
begin: '(?<=(?<=[^\\\\]|^)\\s|^)"(?!")'
end: '(?<!")"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
patterns: [include: "#string-escapes"]
}]
# Escape sequences to match inside double-quoted strings
"string-escapes":
patterns: [
{match: '""', name: "constant.character.escape.quote.double.roff"}
{include: "#escapes"}
]
# Highlighting for macro arguments that don't match anything else
"generic-parameter":
name: "variable.parameter.roff"
match: "[^\\s\\\\]+"
# List of arguments passed to a request or macro
"param-group":
name: "function-call.arguments.roff"
begin: "\\G|^"
end: "\\Z|$"
patterns: [include: "#params"]
# Bracket-delimited long-name (GNU)
"long-name":
patterns: [{
name: "variable.parameter.other.roff"
begin: "\\G\\s*"
end: "(?=\\]|\\s)"
patterns: [include: "#escapes"]
}
{include: "#escapes"}
{include: "#string"}
{include: "#number"}]
# Group of strings delimited with an arbitrary character
"3-part-title":
name: "string.3-part.other.roff"
match: '\\G[ \t]*(.)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)((?:(?!\\1).)*)(\\1)'
captures:
1: name: "punctuation.definition.string.begin.roff"
2: name: "entity.string.left.roff", patterns: [include: "#escapes"]
3: name: "punctuation.definition.string.begin.roff"
4: name: "entity.string.centre.roff", patterns: [include: "#escapes"]
5: name: "punctuation.definition.string.end.roff"
6: name: "entity.string.right.roff", patterns: [include: "#escapes"]
7: name: "punctuation.definition.string.end.roff"
# Requests
requests:
patterns:[{
# GNU extensions
name: "meta.function.request.$2.gnu.roff"
begin: "(?x) ^([.'])[ \t]*
(aln|als|asciify|backtrace|blm|boxa|box|brp|cflags|chop|close|composite|color
|cp|devicem|device|do|ecs|ecr|evc|fam|fchar|fcolor|fschar|fspecial|ftr|fzoom
|gcolor|hcode|hla|hlm|hpfa|hpfcode|hpf|hym|hys|itc|kern|length|linetabs|lsm
|mso|nop|nroff|opena|open|output|pev|pnr|psbb|pso|ptr|pvs|rchar|rfschar|rj
|rnn|schar|shc|shift|sizes|special|spreadwarn|sty|substring|tkf|tm1|tmc|trf
|trin|trnt|troff|unformat|vpt|warnscale|warn|writec|writem|write)
(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
},{
# .class: Assign a name to a range of characters (GNU)
name: "meta.function.request.assign-class.gnu.roff"
begin: "^([.'])[ \t]*(class)[ \t]+(\\S+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff"}
patterns: [{
match: "[^\\s\\\\]+(-)[^\\s\\\\]+"
captures:
0: name: "string.unquoted.character-range.roff"
1: name: "punctuation.separator.dash.roff"
}, include: "#params"]
},{
# .char: Define character or glyph (GNU)
name: "meta.function.request.$2.gnu.roff"
begin: "^([.'])[ \t]*(char)[ \t]*(\\S+)?[ \t]*(.*)(?=$|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
patterns: [include: "$self"]
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "variable.parameter.roff"}
4: {patterns: [include: "#param-group"]}
},{
# .defcolor: Define colour (GNU)
name: "meta.function.request.define-colour.gnu.roff"
begin: "^([.'])[ \t]*(defcolor)(?=\\s)[ \t]*((?:[^\\s\\\\]|\\\\(?![\"#]).)*)[ \t]*(rgb|cmyk?|gr[ae]y)?"
end: "(?<!\\\\)(?=$)|(?=\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "string.other.colour-name.roff", patterns: [include: "#escapes"]}
4: {name: "constant.language.colour-scheme.roff"}
patterns: [{
# Hexadecimal colour
name: "constant.other.colour.hex.roff"
match: "(\#{1,2})[A-Fa-f0-9]+"
captures: 1: name: "punctuation.definition.colour.roff"
}, include: "#params"]
},{
# Requests for controlling program flow (GNU)
begin: "^([.'])[ \t]*(break|continue|return|while)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
patterns: [include: "#param-group"]
beginCaptures:
0: {name: "meta.function.request.control.gnu.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
},{
# .tm/.ab: Print remainder of line to STDERR
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(ab|tm)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#escapes-copymode"}]
contentName: "string.unquoted.roff"
},{
# Generic requests without formatting
name: "meta.function.request.$2.roff"
begin: "(?x) ^([.'])[ \t]*
(ab|ad|af|bd|bp|br|c2|cc|ce|cf|ch|cs|da|di|dt|ec|em|eo|ev
|ex|fc|fi|fl|fp|ft|hc|hw|hy|in|it|lc|lg|lf|ll|ls|lt|mc|mk
|na|ne|nf|nh|nm|nn|ns|nx|os|pc|pi|pl|pm|pn|po|ps|rd|rm|rn
|rr|rs|rt|so|sp|ss|sv|sy|ta|tc|ti|tm|tr|uf|vs|wh)
(?=\\s|\\d+\\s*$|\\\\[\"#])"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#param-group"}]
}
{ include: "#conditionals" }
{ include: "#definition" }
{ include: "#ignore" }
{ include: "#underlines" }
{
# Register assignment
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(nr)[ \t]*(?:(%|ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)|(c\\.)|(\\${2}|\\.[$aAbcdfFhHijklLnopRTstuvVwxyz])|(\\.[CgmMOPUxyY])|(\\S+))?[ \t]*(.*)$"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "storage.type.var.roff"}
3: {name: "constant.language.predefined.register.roff"}
4: {name: "constant.language.predefined.register.gnu.roff"}
5: {name: "invalid.illegal.readonly.register.roff"}
6: {name: "invalid.illegal.readonly.register.gnu.roff"}
7: {name: "variable.parameter.roff", patterns: [include: "#escapes"]}
8: {patterns: [{include: "#arithmetic"}, {include: "#param-group"}]}
},{
# String definition
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*([ad]s1?)[ \t]+(((?:[^\\s\\\\]|\\\\(?!\").)+))?"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "storage.type.var.roff"
3: name: "variable.parameter.roff"
4: name: "entity.name.roff", patterns: [include: "#escapes"]
contentName: "string.unquoted.roff"
patterns: [include: "#escapes"]
},{
# Three-part title
name: "meta.function.request.$2.roff"
begin: "^([.'])[ \t]*(tl)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "entity.function.name.roff"}
contentName: "function-call.arguments.roff"
patterns: [
{include: "#3-part-title"}
{include: "#params"}
]
}]
# Conditional input
conditionals:
patterns: [{
# Conditional: If
begin: """(?x)^
([.']) [ \t]* # 1: punctuation.definition.request.roff
(ie|if) [ \t]* # 2: keyword.control.roff
(!)? # 3: keyword.operator.logical
(?:
# One-character built-in comparison name
([notev]) # 4: constant.language.builtin-comparison.$4.roff
|
# GNU extensions
([cdFmrS]) # 5: constant.language.builtin-comparison.$5.gnu.roff
# Name being validated
[ \t]*
((?:[^ \\t\\\\]|\\\\(?!["#]).)+) # 6: Include “#escapes”
|
# Arithmetic
( # 7: meta.equation.roff
# Starts with a bracket
(\\() # 8: punctuation.definition.begin.roff
(.*?) # 9: Include “#arithmetic”
(\\)) # 10: punctuation.definition.end.roff
# Anything else affixed to it
( # 11: Include “#arithmetic”
(?:
[^\\s\\(] | # Operators/numbers
\\(.*?\\) # More brackets
)*
)
|
# Doesn’t start with a bracket
(?:
# Starts with a long-form string/register
(\\|?\\\\+[n*]\\(\\S{2}) # 12: Include “#escapes”
|
# Starts with a digit or backslash
(?=\\d|\\\\)
)
([^\\s\\(]*) # 13: Sandwiched mathematical junk
(?: # Possible embedded brackets
(\\() # 14: punctuation.definition.begin.roff
(.*?) # 15: Include “#arithmetic”
(\\)) # 16: punctuation.definition.end.roff
)?
(?: # Possible trailing digits/operators
[^\\s\\(]*?
\\d+
)?
# Ends with a...
(?<=
# Digit
\\d |
# Unit suffix
(?<=[\\d.])
[A-Za-z] |
# Closing bracket
[\\)\\]] |
# String/register: Long-form
\\\\[n*]
\\(
\\S{2} |
# String/register: Short-form
\\\\[n*]\\S
)
)
|
# String/variable comparison
([^\\d\\s\\\\]) # 17: punctuation.definition.string.begin.roff
( # 18: variable.parameter.operand.left.roff
(.*?) # 19: Include “#escapes”
)
(\\17) # 20: punctuation.definition.string.roff
( # 21: variable.parameter.operand.right.roff
(.*?) # 22: Include “#escapes”
)
(\\17) # 23: punctuation.definition.string.end.roff
|
# Anything not recognised
(\\S) # 24: meta.operand.single.roff
)?
(.*) # 25: Include “#conditional-innards”
"""
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {name: "keyword.operator.logical"}
4: {name: "constant.language.builtin-comparison.$4.roff"}
5: {name: "constant.language.builtin-comparison.$5.gnu.roff"}
6: {patterns: [include: "#escapes"]}
7: {name: "meta.equation.roff"}
8: {name: "punctuation.definition.begin.roff"}
9: {patterns: [{include: "#arithmetic"}]}
10: {name: "punctuation.definition.end.roff"}
11: {patterns: [{include: "#arithmetic"}]}
12: {patterns: [{include: "#escapes"}]}
13: {patterns: [{include: "#arithmetic"}]}
14: {name: "punctuation.definition.begin.roff"}
15: {patterns: [{include: "#arithmetic"}]}
16: {name: "punctuation.definition.end.roff"}
17: {name: "punctuation.definition.string.begin.roff"}
18: {name: "variable.parameter.operand.left.roff"}
19: {patterns: [{include: "#escapes"}]}
20: {name: "punctuation.definition.string.roff"}
21: {name: "variable.parameter.operand.right.roff"}
22: {patterns: [{include: "#escapes"}]}
23: {name: "punctuation.definition.string.end.roff"}
24: {name: "meta.operand.single.roff"}
25: {patterns: [{include: "#conditional-innards"}]}
},{
# Conditional: Else
begin: "^([.'])[ \t]*(el)\\s*(.*)"
end: "$"
beginCaptures:
0: {name: "meta.function.request.$2.roff"}
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.roff"}
3: {patterns: [{include: "#conditional-innards"}]}
}]
"conditional-innards":
patterns: [{
begin: "^\\s*(\\\\\\{(?:\\\\(?=\\n))?)?\\s*(.*)"
end: "$"
beginCaptures:
1: {name: "punctuation.section.conditional.begin.roff"}
2: {patterns: [{include: "$self"}]}
}]
# Basic arithmetic sequences
arithmetic:
patterns: [
{include: "#escapes"},
{
name: "meta.brackets.roff"
match: "(\\()(.*?)(\\))"
captures:
1: {name: "punctuation.arithmetic.begin.roff"}
2: {patterns: [{include: "#arithmetic"}]}
3: {name: "punctuation.arithmetic.end.roff"}
}
{include: "#number"}
{match: "<\\?", name: "keyword.operator.minimum.gnu.roff"}
{match: ">\\?", name: "keyword.operator.maximum.gnu.roff"}
{match: "[-/+*%]", name: "keyword.operator.arithmetic.roff"}
{match: ":|&|[<=>]=?", name: "keyword.operator.logical.roff"}
{match: "\\|", name: "keyword.operator.absolute.roff"}
{
# Change default scaling indicator (GNU)
name: "meta.scaling-indicator.gnu.roff"
match: "(?<=^|\\()([cfimnPpsuvz])(;)"
captures:
1: name: "keyword.other.unit.roff"
2: name: "punctuation.separator.semicolon.roff"
}
]
# Macro definitions
definition:
patterns: [{
# No terminator specified
name: "meta.function.definition.request.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+?)?\\s*(\\\\[\"#].*)?$"
end: "^(?:[ \t]*\\x5C{2})?\\.[ \t]*\\."
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {patterns: [include: "#escapes"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
0: {name: "punctuation.definition.request.roff"}
patterns: [include: "$self"]
},{
# Terminator included
name: "meta.function.definition.request.with-terminator.$2.roff"
begin: "^([.'])[ \t]*((dei?1?)|(ami?1?))\\s+(\\S+)\\s*(\"[^\"]+\"?|\\S+?(?=\\s|\\\\[\"#]))?(.*)$"
end: "^(\\.)[ \t]*((\\6)(?=$|\\s|\\\\(?:$|\")))"
beginCaptures:
1: {name: "punctuation.definition.request.roff"}
3: {name: "storage.type.function.roff"}
4: {name: "entity.name.function.roff"}
5: {name: "variable.parameter.roff"}
6: {name: "keyword.control.terminator.roff", patterns: [include: "#string"]}
7: {patterns: [include: "#param-group"]}
endCaptures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "keyword.control.terminator.roff"}
3: {patterns: [{include: "#string"}]}
patterns: [{include: "$self"}]
}]
# Ignored content
ignore:
patterns: [{
# Terminator specified
contentName: "comment.block.ignored-input.with-terminator.roff"
begin: "^([.'])[ \t]*(ig)[ \t]+(?!\\\\[\"#])((\"[^\"]+\")|\\S+?(?=\\s|\\\\[\"#]))(.*)$"
end: "^([.'])[ \t]*(\\3)(?=\\s|$|\\\\)"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: name: "keyword.control.terminator.roff"
4: patterns: [include: "#string"]
5: patterns: [include: "#params"]
endCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "keyword.control.terminator.roff", patterns: [include: "#string"]
},{
# No terminator given
contentName: "comment.block.ignored-input.roff"
begin: "^([.'])[ \t]*(ig)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*\\.(?=\\s|\\\\[\"#])"
patterns: [include: "#register-expansion"]
beginCaptures:
1: name: "punctuation.definition.request.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#params"]
endCaptures:
0: name: "punctuation.definition.request.roff"
}]
# Underlined passages
underlines:
patterns: [{
# .ul/.cu 0: Empty request/noop
name: "meta.request.$2.roff"
match: "^([.'])[ \t]*(ul|cu)\\s*(0+)(?:(?!\\\\\")[\\D])*(?=\\s|$)(.*)$"
captures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [{include: "#params"}]}
}, {
# Underline following line
name: "meta.request.$2.roff"
begin: "^([.'])[ \t]*(ul|cu)(?=\\s|$|\\\\)(.*?)$\\n"
end: "(?<!\\\\)$"
beginCaptures:
1: {name: "punctuation.definition.function.request.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [{include: "#params"}]}
patterns: [{
# Ignore control-lines
begin: "^(?=[.']|\\\\!)(.*)$\\n"
end: "^"
beginCaptures:
1: {patterns: [{include: "$self"}]}
}, {
name: "markup.underline.roff"
begin: "^(?![.'])"
end: "(?<!\\\\)$"
}]
}]
# Escape sequences
escapes:
patterns: [
{include: "#escapes-copymode"}
{include: "#escapes-full"}
]
# Register interpolation
"register-expansion":
patterns: [{
# \n[xx] - Contents of number register "XX" (GNU)
name: "constant.character.escape.function.expand-register.gnu.roff"
begin: "(\\|)?(((?:(?<=\\|)\\\\*?)?\\\\)n([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \nX, \n(XX - Contents of number register "X" or "XX"
name: "constant.character.escape.function.expand-register.roff"
match: """(?x)
# 1: keyword.operator.absolute.roff
(\\|)?
# 2: entity.name.roff
(
# 3: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
([-+])? # 4: keyword.operator.arithmetic.roff
(\\() # 5: punctuation.definition.brace.roff
)
# Name of register
(?:
# 6: constant.language.predefined.register.roff
(ct|dl|dn|dw|dy|ln|mo|nl|sb|st|yr)
|
# 7: constant.language.predefined.register.gnu.roff
(c\\.)
|
# 8: constant.language.predefined.register.readonly.roff
(\\${2} | \\.[$aAbcdfFhHijklLnopRTstuvVwxyz])
|
# 9: constant.language.predefined.register.readonly.gnu.roff
(\\.[CgmMOPUxyY])
|
# 10: variable.parameter.roff
(\\S{2})
)
|
# 11: keyword.operator.absolute.roff
(\\|)?
# 12: entity.name.roff
(
# 13: punctuation.definition.escape.roff
(
(?:(?<=\\|)\\\\*?)?
\\\\
)
n
)
# 14: keyword.operator.arithmetic.roff
([-+])?
# Name of register
(?:
(%) | # 15: constant.language.predefined.register.roff
(\\S) # 16: variable.parameter.roff
)
"""
captures:
1: {name: "keyword.operator.absolute.roff"}
2: {name: "entity.name.roff"}
3: {name: "punctuation.definition.escape.roff"}
4: {name: "keyword.operator.arithmetic.roff"}
5: {name: "punctuation.definition.brace.roff"}
6: {name: "constant.language.predefined.register.roff"}
7: {name: "constant.language.predefined.register.gnu.roff"}
8: {name: "constant.language.predefined.register.readonly.roff"}
9: {name: "constant.language.predefined.register.readonly.gnu.roff"}
10: {name: "variable.parameter.roff"}
11: {name: "keyword.operator.absolute.roff"}
12: {name: "entity.name.roff"}
13: {name: "punctuation.definition.escape.roff"}
14: {name: "keyword.operator.arithmetic.roff"}
15: {name: "constant.language.predefined.register.roff"}
16: {name: "variable.parameter.roff"}
}]
# Limited range of escape sequences permitted in copy-mode
"escapes-copymode":
patterns: [{
# Backslashed escape sequences: \t -> \\t
match: "(\\\\+?)(?=\\1\\S)"
name: "punctuation.definition.concealed.escape.backslash.roff"
},{
# Comments
name: "comment.line.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\")"
end: "$"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Newline-devouring comment (GNU)
name: "comment.line.number-sign.gnu.roff"
begin: "(?:^(\\.|'+)\\s*)?(\\\\\#).*$\\n?"
end: "^"
beginCaptures:
1: {name: "punctuation.definition.comment.roff"}
2: {name: "punctuation.definition.comment.roff"}
},{
# Empty control lines
name: "comment.empty.roff"
match: "^(\\.|'+)[ \t]*$"
captures:
1: {name: "punctuation.definition.comment.roff"}
},{
# Concealed newline
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^(?:[.'])?"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}
# Basic sequences
{include: "#register-expansion"}
{match: "(\\\\)\\1", name: "constant.character.escape.backslash.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)t", name: "constant.character.escape.tab.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)a", name: "constant.character.escape.leader-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\.", name: "constant.character.escape.dot.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \*[name].macro - Adhoc matching to improve tbl's "\*[3trans]" hack (GNU)
begin: "^(\\\\\\*\\[[^\\]]+\\])\\s*(\\.\\w+.*)"
end: "$"
beginCaptures:
1: patterns: [include: "#escapes"]
2: patterns: [include: "#conditional-innards"]
},{
# \*[xx args…] - Interpolate string "xx" with optional arguments (GNU)
name: "constant.character.escape.function.interpolate-string.gnu.roff"
begin: "((\\\\)\\*(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "function-call.arguments.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \*x, \*(xx - Interpolate string "x" or "xx"
name: "constant.character.escape.function.interpolate-string.roff"
match: "((\\\\)\\*(\\())(\\S{2})|((\\\\)\\*)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \$N - Interpolate argument number N (valid range: 1-9)
name: "constant.character.escape.function.interpolate-argument.roff"
match: "((\\\\)\\$\\d)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \m[X] - Alternate syntax for setting drawing/background colour (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
begin: "((\\\\)[Mm](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \mX, \m(XX - Set drawing or background colour to "X" (GNU)
name: "constant.character.escape.function.set-colour.gnu.roff"
match: "((\\\\)[Mm](\\())(\\S{2})|((\\\\)[Mm])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \s[±n], \s±[n] - Set/adjust point-size (GNU)
name: "constant.character.escape.function.point-size.gnu.roff"
begin: "((\\\\)s([-+])?(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#params"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "keyword.operator.arithmetic.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# "Parametric" escape sequences supported in Groff (GNU)
name: "constant.character.escape.function.check-identifier.gnu.roff"
begin: "((\\\\)(?!s[-+]?\\d)[ABRsZ])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# \ON - Suppress troff output with signal "N" (GNU)
name: "constant.character.escape.internal.gnu.roff"
match: "((\\\\)O([0-4]))"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
},{
# \O5[xyz] - Write file "xyz" to STDERR; grohtml-specific (GNU)
name: "constant.character.escape.internal.stderr-write-file.gnu.roff"
begin: "((\\\\)O(5)(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "string.unquoted.filename.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "constant.numeric.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \V[x] - Alternate syntax for interpolating environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
begin: "((\\\\)[VY](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \Vx, \V(xx - Interpolate contents of environment variable (GNU)
name: "constant.character.escape.function.interpolate-variable.gnu.roff"
match: "((\\\\)[VY](\\())(\\S{2})|((\\\\)[VY])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \?code\? - Embed a chunk of code in diversion (GNU)
match: "((\\\\)(\\?))(.*)((\\\\)(\\?))"
captures:
1: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.script.roff"}
4: {name: "string.interpolated.roff", patterns: [include: "$self"]}
5: {name: "constant.character.escape.embed-diversion.start.gnu.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "punctuation.definition.script.roff"}
},{
# \$*, \$@, \$^ - Argument concatenation for macros/strings (GNU)
name: "constant.character.escape.function.concatenated-arguments.gnu.roff"
match: "((\\\\)\\$[*@^])"
captures:
1: {name: "variable.language.roff"}
2: {name: "punctuation.definition.escape.roff"}
},{
# \$(nn - Expand n-th argument passed to macro or string (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
match: "((\\\\)\\$(\\())(\\S{2})"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \$[nnn] - Alternate syntax for expanding n-th macro/string argument (GNU)
name: "constant.character.escape.function.interpolate-argument.gnu.roff"
begin: "((\\\\)\\$(\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#long-name"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
}]
# Every other escape sequence
"escapes-full":
patterns: [
# Basic sequences
{match: "(\\\\)e", name: "constant.character.escape.current-escape-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)´", name: "constant.character.escape.acute-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)`", name: "constant.character.escape.grave-accent.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)-", name: "constant.character.escape.minus.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\) ", name: "constant.character.escape.space.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)0", name: "constant.character.escape.space.digit-width.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\|", name: "constant.character.escape.space.one-sixth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)\\^", name: "constant.character.escape.space.one-twelfth-em.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)&", name: "constant.character.escape.zero-width-marker.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)%", name: "constant.character.escape.hyphenation-char.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)c", name: "constant.character.escape.connect.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)d", name: "constant.character.escape.downwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)p", name: "constant.character.escape.spread-line.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)r", name: "constant.character.escape.reverse.roff", captures: 1: name: "punctuation.definition.escape.roff"}
{match: "(\\\\)u", name: "constant.character.escape.upwards.roff", captures: 1: name: "punctuation.definition.escape.roff"}, {
# \(aa - Character named "aa"
name: "constant.character.escape.function.named-char.roff"
match: "(\\\\)(\\()(\\S{2})"
captures:
1: {name: "punctuation.definition.brace.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \[aa] - Character named "aa" (GNU)
name: "constant.character.escape.function.named-char.gnu.roff"
begin: "(\\\\)(\\[)"
end: "(\\S*?)(\\])|(?<!\\\\)(?=$)"
patterns: [
{include: "#params"}
{match: '(?:[^\\s\\]\\\\]|\\\\(?!["#]).)+', name: "variable.parameter.roff"}
]
beginCaptures:
1: {name: "punctuation.definition.escape.roff"}
2: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {patterns: [include: "#params"]}
2: {name: "punctuation.section.end.bracket.square.roff"}
},{
# Conditional input: Begin
name: "meta.function.begin.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\{(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.begin.roff"}
},{
# Conditional input: End
name: "meta.function.end.roff"
match: "(?:^(\\.|'+)[ \t]*)?(\\\\\\}(?:\\\\(?=\\n))?)"
captures:
1: {name: "punctuation.definition.request.roff"}
2: {name: "punctuation.section.conditional.end.roff"}
},{
# Parametric/function-like escape sequences
name: "constant.character.escape.function.roff"
begin: "((\\\\)[bCDhHSlLovwxXN])((.))"
end: "(\\4)|(?<!\\\\)(?=$)"
contentName: "string.other.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.function.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.other.roff"}
4: {name: "punctuation.definition.begin.roff"}
endCaptures:
0: {name: "string.other.roff"}
1: {name: "punctuation.definition.end.roff"}
},{
# Transparent throughput
name: "meta.throughput.roff"
begin: "(\\\\)!"
end: "(?<!\\\\)$"
beginCaptures:
0: {name: "constant.character.escape.transparent-line.roff"}
1: {name: "punctuation.definition.escape.roff"}
patterns: [{include: "#escapes-copymode"}]
},{
# Font: Roman/regular
name: "constant.character.escape.font.roff"
match: "(\\\\)f[RP1]"
captures:
0: {name: "entity.name.roff"}
1: {name: "punctuation.definition.escape.roff"}
}, {
# Font: Italics (typically rendered by nroff as underlined text)
begin: "((\\\\)f(?:[I2]|(\\()CI|(\\[)\\s*(?:[I2]|CI)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
4: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# Font: Bold
begin: "((\\\\)f(?:[B3]|(\\()CB|(\\[)\\s*(?:[B3]|CB)\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# Font: Bold and italic
begin: "((\\\\)f(?:4|(\\()BI|(\\[)\\s*BI\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#bold-italic-word"}
]
},{
# Font: Constant-width/monospaced
begin: "((\\\\)f(?:(\\()C[WR]|(\\[)\\s*C[WR]\\s*(\\])))"
end: "(?=\\\\f[\\[A-Za-z0-9])|^(?=\\.(?:SH|SS|P|[HILPT]P)\\b)"
beginCaptures:
0: {name: "constant.character.escape.font.roff"}
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "punctuation.section.begin.bracket.square.roff"}
5: {name: "punctuation.section.end.bracket.square.roff"}
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# \f[XX] - Change to font named "XX" (GNU)
name: "constant.character.escape.function.font.gnu.roff"
begin: "((\\\\)[Ff](\\[))"
end: "(\\])|(?<!\\\\)(?=$)"
contentName: "variable.parameter.roff"
patterns: [include: "#escapes"]
beginCaptures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.section.begin.bracket.square.roff"}
endCaptures:
1: {name: "punctuation.section.end.bracket.square.roff"}
},{
# \fX, \f(XX, \fN - Change to font named "X" or "XX", or position N
name: "constant.character.escape.function.font.roff"
match: "((\\\\)[Ff](\\())(\\S{2})|((\\\\)[Ff])(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \gx, \g(xx - Format of number register "x" or "xx"
name: "constant.character.escape.function.format-register.roff"
match: "((\\\\)g(\\())(\\S{2})|((\\\\)g)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
5: {name: "entity.name.roff"}
6: {name: "punctuation.definition.escape.roff"}
7: {name: "variable.parameter.roff"}
},{
# \kX - Mark horizontal input place in register "X"
name: "constant.character.escape.function.mark-input.roff"
match: "((\\\\)k)(\\S)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \sN, \s±N - Point-size change function; also \s(NN, \s±(NN
name: "constant.character.escape.function.point-size.roff"
match: "((\\\\)s[-+]?(\\()?)(\\d+)"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "punctuation.definition.brace.roff"}
4: {name: "variable.parameter.roff"}
},{
# \zC - Print "C" with zero width (without spacing)
name: "constant.character.escape.function.zero-width-print.roff"
match: "((\\\\)z)([^\\s\\\\])"
captures:
1: {name: "entity.name.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "variable.parameter.roff"}
},{
# \Z - Any character not listed above
name: "constant.character.escape.misc.roff"
match: "(\\\\)\\S"
captures:
1: name: "punctuation.definition.escape.roff"
}]
# Macros
macros:
patterns: [
{include: "#man"}
{include: "#mdoc"}
{include: "#ms"}
{include: "#mm"}
{include: "#me"}
{include: "#www"}
# Generic macro highlighting
name: "meta.function.macro.roff"
begin: "^([.'])[ \t]*((?:[^\\s\\\\]|\\\\(?![#\"]).)+)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
]
# Document macros
mdoc:
patterns: [{
# .Bf [ -emphasis | Em ]: Begin emphasised text
name: "meta.function.begin-emphasis.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-emphasis|Em)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Bf [ -literal | Li ]: Begin literal text
name: "meta.function.begin-literal.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-literal|Li)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Bf [ -symbolic | Sy ]: Begin symbolic text
name: "meta.function.begin-symbolic.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(Bf)[ \t]+(-symbolic|Sy)(?=\\s)(.*)"
end: "^(?=[.']\\s*[BE]f\\s)"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.option.mdoc.macro.roff"
4: patterns: [include: "#escapes"]
patterns: [
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Rs/.Re: Bibliographic block
begin: "^([.'])\\s*(Rs)(?=\\s)(.*)$"
end: "^([.'])\\s*(Re)(?=\\s)"
patterns: [include: "#refer"]
contentName: "meta.citation.mdoc.roff"
beginCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "entity.function.name.mdoc.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.mdoc.macro.roff"
2: name: "entity.function.name.mdoc.roff"
},{
# .Bd/.Ed: Ad-hoc rules to highlight embedded source code
begin: "^([.'])\\s*(Bd)\\s+(-literal)(?=\\s|$)(.*)"
end: "^([.'])\\s*(Ed)(?=\\s|$)"
beginCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#mdoc-args"]
4: patterns: [include: "#mdoc-unparsed"]
endCaptures:
0: name: "meta.function.$2.unparsed.macro.mdoc.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [{
# HTML
name: "meta.html-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?HTML:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
name: "text.embedded.html.basic"
match: ".+"
captures:
0: patterns: [include: "text.html.basic"]
}]
},{
# JavaScript
name: "meta.js-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?JavaScript:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [{
match: ".+"
captures:
0: patterns: [include: "source.js"]
}]
},{
# CSS
name: "meta.css-snippet.mdoc.roff"
begin: "^(?:\\S*.*?\\s+)?CSS:\\s*$\\n?"
end: "^(?!\\t|\\s*$)"
beginCaptures:
0: patterns: [include: "#main"]
patterns: [include: "source.css"]
}, include: "#main"]
},{
# Unparsed macros: passing callable macros as arguments won't invoke them
name: "meta.function.$2.unparsed.macro.mdoc.roff"
begin: "^([.'])\\s*(%[ABCDIJNOPQRTUV]|B[dfklt]|br|D[bdt]|E[dfklx]|F[do]|Hf|In|L[bp]|Nd|Os|Pp|R[esv]|Sm|sp|Ud)(?=\\s)"
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [include: "#mdoc-unparsed"]
},{
# Parsed macros: will execute callable mdoc macros
name: "meta.function.$2.parsed.macro.mdoc.roff"
begin: """(?x)^([.'])\\s*
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|D1|Dc
|Dl|Do|Dq|Dv|Dx|Ec|Em|En|Eo|Eq|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic
|It|Li|Lk|Me|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc|Pf|Po|Pq|Qc
|Ql|Qo|Qq|Rd|Sc|Sh|So|Sq|Ss|St|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
(?=\\s)"""
end: "(?<!\\\\)$"
beginCaptures:
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-callables"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
}]
# Mdoc macros that're executed as arguments by "parsed" macros
"mdoc-callables":
patterns: [{
# .Em: Emphasised text (Italic)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Em|Ar)\\G|(?<=\\s)(Em|Ar)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#italic-word"}
]
},{
# .Sy: Symbolic text (Bold)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Sy|Fl|Cm)\\G|(?<=\\s)(Sy|Fl|Cm)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[\\[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#bold-word"}
]
},{
# .Li: Literal text (Monospaced)
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Li)\\G|(?<=\\s)(Li)(?=\\s)"
end: """(?x)
(?<!\\\\)$ |
(?=
\\s+
(?:Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|Em
|En|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa
|Pc|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Sy|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)
\\s |
\\\\" |
\\\\f[A-Za-z0-9]
)"""
beginCaptures:
1: name: "entity.function.name.roff"
patterns: [
{include: "#mdoc-args"}
{include: "$self"}
{include: "#monospace-word"}
]
},{
# .Lk/.Mt: Hyperlink or mailto
name: "meta.function.$1.callable.macro.mdoc.roff"
begin: "(?<=Lk|Mt)\\G|(?<=\\s)(Lk|Mt)(?=\\s)"
end: "$|(?=\\\\\")|(\\S+?)(?=$|\\s|\\\\\")"
beginCaptures:
1: name: "entity.function.name.roff"
endCaptures:
0: name: "markup.underline.link.hyperlink.mdoc.roff"
1: patterns: [include: "#escapes"]
},{
# Embedded macro name inside argument list
name: "meta.function.$1.callable.macro.mdoc.roff"
match: """(?x) (?<=[ \t])
(Ac|Ad|An|Ao|Ap|Aq|Ar|At|Bc|Bo|Bq|Brc|Bro|Brq|Bsx|Bx|Cd|Cm|Dc|Do|Dq|Dv|Dx|Ec|En
|Eo|Er|Es|Ev|Fa|Fc|Fl|Fn|Fr|Ft|Fx|Ic|Li|Lk|Ms|Mt|Nm|No|Ns|Nx|Oc|Oo|Op|Ot|Ox|Pa|Pc
|Pf|Po|Pq|Qc|Ql|Qo|Qq|Sc|So|Sq|Sx|Ta|Tn|Ux|Va|Vt|Xc|Xo|Xr)(?=\\s)"""
captures:
1: name: "entity.function.name.roff"
}]
# Arguments passed to mdoc macros
"mdoc-args":
patterns: [
{include: "#escapes"}
{include: "#string"}
{
# Document revision date
name: "string.quoted.other.date.roff"
begin: "\\$(?=Mdocdate)"
end: "\\$"
beginCaptures: 0: name: "punctuation.section.begin.date.roff"
endCaptures: 0: name: "punctuation.section.end.date.roff"
},{
# "Delimiters" (in mdoc's terms)
name: "punctuation.delimiter.mdoc.macro.roff"
match: "(?<=\\s)[(\\[.,:|;)\\]?!](?=\\s|$)"
},{
# Option flags used by some macros
name: "constant.language.option.mdoc.macro.roff"
match: """(?x)
(?<=\\s) (-)
(alpha|beta|bullet|centered|column|compact|dash|devel|diag|emphasis|enum|file|filled|hang
|hyphen|inset|item|literal|nested|nosplit|ohang|ragged|split|std|symbolic|tag|type|unfilled
|width|words|offset(?:\\s+(?:left|center|indent|indent-two|right))?)(?=\\s)"""
captures: 1: name: "punctuation.definition.dash.roff"
}]
# Arguments passed to "unparsed" mdoc macros
"mdoc-unparsed":
patterns: [
{include: "#mdoc-delimiters"}
{include: "#mdoc-args"}
{include: "#generic-parameter"}
]
# Manuscript macros
ms:
patterns: [{
name: "meta.function.${2:/downcase}.ms.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AB|AE|AI|AU|B1|B2|BT|BX|DA|DE|DS|EN|EQ|FE|FS|IP|KE|KF|KS|LG
|LP|MC|ND|NH|NL|P1|PE|PP|PS|PT|PX|QP|RP|SH|SM|TA|TC|TE|TL|TS|XA|XE
|XP|XS)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*([EO][FH])(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
},{
# Deprecated macros
name: "meta.deprecated.function.${2:/downcase}.ms.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*((De|Ds))(?=\\s)"
end: "(?<!\\\\)$|(?=\\s*\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [
{include: "#escapes"}
{include: "#string"}
]
},{
# Monospaced/constant-width text
name: "meta.function.cw.ms.macro.roff"
begin: "^([.'])[ \t]*(CW)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{
# Unquoted string
name: "markup.raw.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.raw.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.raw.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.raw.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
},{
# Underlined text
name: "meta.function.ul.ms.macro.roff"
begin: "^([.'])[ \t]*(UL)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
}]
# Memorandum macros
mm:
patterns: [{
name: "meta.function.${2:/downcase}.mm.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(1C|2C|AE|AF|AL|APP|APPSK|AS|AST|AT|AU|AV|AVL|B1|B2|BE|BL|BS|BVL
|COVER|COVEND|DE|DF|DL|DS|EC|EF|EH|EN|EOP|EPIC|EQ|EX|FC|FD|FE|FG
|FS|GETHN|GETPN|GETR|GETST|H|HC|HM|HU|HX|HY|HZ|IA|IE|INITI|INITR
|IND|INDP|ISODATE|LB|LC|LE|LI|LT|LO|MC|ML|MT|MOVE|MULB|MULN|MULE
|nP|NCOL|NS|ND|OF|OH|OP|PGFORM|PGNH|PIC|PE|PF|PH|PS|PX?|RD|RF|RL
|RP|RS|S|SA|SETR|SG|SK|SM|SP|TA?B|TC|TE|TL|TM|TP|TS|TX|TY|VERBON
|VERBOFF|VL|VM|WA|WE|WC|\\)E)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [{include: "#params"}]
}]
# Paper-formatting macros
me:
patterns: [{
# Assorted macros without special highlighting or pattern-matching
name: "meta.function.${3:/downcase}.me.macro.roff"
begin: "(?x) ^([.'])[ \t]*
((?:[()][cdfqxz]|\\+\\+|\\+c)|
(1c|2c|EN|EQ|GE|GS|PE|PS|TE|TH|TS|ba|bc|bu|bx|hx
|hl|ip|lp|np|pd|pp|r|re|sk|sm|sz|tp|uh|xp)(?=\\s))"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
3: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .(l: List
begin: "^([.'])[ \t]*(\\(l)(?=\\s)"
end: "^([.'])[ \t]*(\\)l)(?=\\s)"
contentName: "markup.list.unnumbered.roff"
patterns: [include: "$self"]
beginCaptures:
0: {name: "meta.function.list.begin.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
endCaptures:
0: {name: "meta.function.list.end.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
},{
# .b: Bold
begin: "^([.'])[ \t]*(b)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-first"]
},{
# .i: Italic
begin: "^([.'])[ \t]*(i)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#italic-first"]
},{
# .bi: Bold/Italic
begin: "^([.'])[ \t]*(bi)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.bold-italic-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#bold-italic-first"]
},{
# .u: Underline
begin: "^([.'])[ \t]*(u)(?=\\s)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
contentName: "function-call.arguments.roff"
beginCaptures:
0: {name: "meta.function.underline-text.me.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# .sh: Section heading
name: "markup.heading.section.function.me.macro.roff"
begin: "^([.'])[ \t]*(sh)[ \t]+((?!\")\\S+)\\b[ \t]*(?!$|\\n|\\\\\")"
end: "(?<![^\\\\]\\\\|^\\\\)(?=$|\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "variable.parameter.roff", patterns: [include: "#params"]}
patterns: [include: "#bold-first"]
},{
# Headers and footers
name: "meta.function.${2:/downcase}.me.macro.roff"
contentName: "function-call.arguments.roff"
begin: "^([.'])[ \t]*(of|oh|he|eh|fo|ef)(?=\\s)"
end: "(?<!\\\\)(?=\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [
{include: "#3-part-title"}
{include: "#escapes"}
{include: "#string"}
]
}]
# Webpage macros
www:
patterns: [{
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "(?x) ^([.'])[ \t]*
(ALN|BCL|BGIMG|DC|DLE|DLS|HEAD|HR|HTM?L|HX|JOBNAME
|LI|LINKSTYLE|LK|LNE|LNS|MPIMG|NHR|P?IMG|TAG)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# Macros that take URIs as their first argument
name: "meta.function.${2:/downcase}.www.macro.roff"
begin: "^([.'])[ \t]*(URL|FTP|MTO)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#underline-first"]
},{
# Code blocks
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(CDS)(?=\\s|\\\\[\"#])\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(CDE)(?=\\s|\\\\[\"#])"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Headings
name: "markup.heading.$3.www.macro.roff"
contentName: "string.unquoted.heading.roff"
begin: "^([.'])[ \t]*(HnS)(?=\\s)(?:\\s*(\\d+))?(?:\\s*(\\\\[#\"].*)$)?"
end: "^([.'])[ \t]*(HnE)(?=\\s)(.*)$"
beginCaptures:
0: {name: "meta.function.${2:/downcase}.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.numeric.roff"}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# Ordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(OLS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(OLE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
},{
# Unordered lists
name: "meta.function.${2:/downcase}.www.macro.roff"
contentName: "markup.list.ordered.roff"
begin: "^([.'])[ \t]*(ULS)(?=\\s)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(ULE)(?=\\s)"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "$self"]
}]
# Manual-page macros
man:
patterns: [{
# Various macros that don't need special highlighting
name: "meta.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*(RE|RS|SM|BT|PT)(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# Various deprecated macros
name: "meta.deprecated.function.${2:/downcase}.man.macro.roff"
begin: "^([.'])[ \t]*((AT|DT|PD|UC))(?=\\s)"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .TH: Title
name: "markup.heading.title.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(TH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SH: Section heading
name: "markup.heading.section.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SH)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .SS: Subsection
name: "markup.heading.subsection.function.man.macro.roff"
patterns: [include: "#param-group"]
begin: "^([.'])[ \t]*(SS)(?=\\s)"
end: "(?<!\\\\)$|(?=\\\\\")"
patterns: [include: "#escapes"]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EX: Example code
contentName: "markup.raw.roff"
begin: "^([.'])[ \t]*(EX)\\s*(\\\\[#\"].*)?$"
end: "^([.'])[ \t]*(EE)(?=\\s|\\\\[#\"])"
patterns: [{ include: "$self" }]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .LP/.PP/.P: Paragraph
name: "meta.function.paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(LP|PP?)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#params"]
},{
# .IP: Indented paragraph
name: "meta.function.indented-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*(IP)(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
patterns: [include: "#param-group"]
},{
# .TP: Titled paragraph
begin: "^([.'])[ \t]*(TP)(?=\\s|\\\\[\"#])(.*)?$\\n?"
end: "^(.*)(?<!\\\\)$"
patterns: [
match: ".+"
captures: 0: patterns: [include: "$self"]
]
beginCaptures:
0: {name: "meta.function.titled-paragraph.man.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#param-group"]}
endCaptures:
1: {patterns: [include: "$self"]}
},{
# .TQ: Header continuation for .TP (GNU extension)
name: "markup.list.unnumbered.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(TQ)[ \t]*(\\\\[#\"].*)?$"
end: "^(?=[.'][ \t]*TP(?:\\s|\\\\[#\"]))"
beginCaptures:
0: {name: "meta.function.header-continuation.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#escapes"]}
patterns: [include: "$self"]
},{
# .HP: Hanging paragraph (deprecated)
name: "meta.deprecated.function.hanging-paragraph.man.macro.roff"
begin: "^([.'])[ \t]*((HP))(?=\\s|\\\\[\"#])"
end: "(?<!\\\\)(?=$)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "invalid.deprecated.roff"}
patterns: [include: "#param-group"]
},{
# .MT/.ME: Hyperlink (GNU extension)
name: "meta.function.mailto.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(MT)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(ME)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .UR/.UE: URL (GNU extension)
name: "meta.function.hyperlink.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(UR)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(UE)(?=\\s|\\\\[\"#])(.*)\\s*(\\\\[\"#].*)?$"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
3: {patterns: [include: "#param-group"]}
4: {patterns: [include: "#escapes"]}
patterns: [include: "#underline-first"]
},{
# .SY: Command synopsis (GNU extension)
name: "meta.command-synopsis.roff"
begin: "^([.'])[ \t]*(SY)(?=\\s|\\\\[\"#])"
end: "^([.'])[ \t]*(YS)(?=\\s|\\\\[\"#])"
beginCaptures:
0: {name: "meta.function.begin.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
endCaptures:
0: {name: "meta.function.end.synopsis.man.macro.gnu.roff"}
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [include: "#bold-first", {
# .OP: Option description (GNU extension)
name: "meta.function.option-description.man.macro.gnu.roff"
begin: "^([.'])[ \t]*(OP)(?=\\s)"
end: "(?<!\\\\)(?=\\n)|(?=\\\\\")"
beginCaptures:
1: {name: "punctuation.definition.macro.gnu.roff"}
2: {name: "entity.function.name.gnu.roff"}
patterns: [{
name: "function-call.arguments.roff"
begin: "\\G"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}, include: "#escapes"]
},{include: "$self"}]
},{
# .B/.SB: Bold
begin: "^([.'])[ \t]*(S?B)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.bold.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.bold.roff"}
2: {patterns: [{include: "#escapes"}]}
},{
# .I: Italic
begin: "^([.'])[ \t]*(I)(\\s*\\\\[#\"].*$)?(?=$|[ \t]+|\\\\)"
end: "^(?=[.'])|(?=\\\\\")|(?!\\\\#)((\\S+[ \t]*)(?<![^\\\\]\\\\)\n)"
patterns: [include: "$self", {match: "\\S+", name: "markup.italic.roff"}]
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
3: {patterns: [{include: "#escapes-copymode"}]}
endCaptures:
1: {name: "markup.italic.roff"}
2: {patterns: [{include: "#escapes"}]}
}, include: "#alternating-fonts"]
# Repeating/combined-font macros
"alternating-fonts":
patterns: [{
# .BI: Bold + Italic
begin: "^([.'])[ \t]*(BI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-italic-after-bold"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
},{
# .BR: Bold + Roman
begin: "^([.'])[ \t]*(BR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-bold"}
{include: "#even-roman-after-bold"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .IB: Italic + Bold
begin: "^([.'])[ \t]*(IB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-bold-after-italic"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .IR: Italic + Roman
begin: "^([.'])[ \t]*(IR)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-italic"}
{include: "#even-roman-after-italic"}
{include: "#even-roman"}
{include: "#bridge-escapes"}
]
},{
# .RB: Roman + Bold
begin: "^([.'])[ \t]*(RB)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-bold-after-roman"}
{include: "#even-bold"}
{include: "#bridge-escapes"}
]
},{
# .RI: Roman + Italic
begin: "^([.'])[ \t]*(RI)(?=\\s)"
end: '(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures:
0: {name: "meta.function.man.macro.roff"}
1: {name: "punctuation.definition.function.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
{include: "#odd-roman"}
{include: "#even-italic-after-roman"}
{include: "#even-italic"}
{include: "#bridge-escapes"}
]
}]
"bridge-escapes":
patterns: [{
name: "constant.character.escape.newline.roff"
begin: "[ \t]+(\\\\)$\\n?"
end: "^"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
},{
name: "constant.character.escape.newline.roff"
begin: "(\\\\)$\\n?"
end: "^[ \t]*"
beginCaptures:
1: name: "punctuation.definition.escape.roff"
}]
"odd-bold":
patterns: [{
name: "markup.bold.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.bold.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.bold.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-italic":
patterns: [{
name: "markup.italic.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.italic.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.italic.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"odd-roman":
patterns: [{
name: "markup.plain.roff"
begin: '[ \t]+(")'
end: '(")[ \t]*|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures: 1: name: "punctuation.definition.string.end.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
},{
name: "markup.plain.roff"
begin: '[ \t]+(\\\\$\\n?)'
end: '(?<!^)[ \t]+|(?=\\\\")|(?<!\\\\)(?=\\n|$)'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes", {
begin: "^[ \t]+"
end: "(?=\\S)|(?<!\\\\)(?:$|\\n)"
}]
},{
name: "markup.plain.roff"
begin: '[ \t]+(?!")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '[ \t]+|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
}]
"even-bold":
patterns: [
name: "markup.bold.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-italic":
patterns: [
name: "markup.italic.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-roman":
patterns: [
name: "markup.plain.roff"
begin: '(?<=^|\\s|")(?!"|\\\\")((?:[^\\s"\\\\]|\\\\(?!").)+)'
end: '(?=[ \t])|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)|(?=\\\\")'
beginCaptures: 1: patterns: [include: "#escapes"]
patterns: [include: "#escapes"]
]
"even-bold-after-italic":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-bold-after-roman":
patterns: [{
contentName: "markup.bold.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.bold.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.bold.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-bold":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-italic-after-roman":
patterns: [{
contentName: "markup.italic.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.italic.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.italic.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.plain.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-bold":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.bold.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
"even-roman-after-italic":
patterns: [{
contentName: "markup.plain.roff"
begin: '(")'
end: '(("))([^"\\s]+[ \t]*)?|(?=\\\\")|(?<![^\\\\]\\\\|^\\\\)(?=\\n|$)'
beginCaptures:
0: name: "markup.plain.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
1: name: "markup.plain.roff"
2: name: "punctuation.definition.string.end.roff"
3: name: "markup.italic.roff"
patterns: [{
match: '((?:[^"\\\\]|""|\\\\(?!").)+)(?!$)'
captures: 1: patterns: [include: "#string-escapes"]
}, include: "#string-escapes"]
}]
# Embolden first argument only
"bold-first":
patterns: [{
# Unquoted string
name: "markup.bold.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Italicise first argument only
"italic-first":
patterns: [{
# Unquoted string
name: "markup.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden and italicise first argument only
"bold-italic-first":
patterns: [{
# Unquoted string
name: "markup.bold.italic.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "markup.bold.italic.roff"
match: '(")(")'
captures:
0: {name: "string.quoted.double.empty.roff"}
1: {name: "punctuation.definition.string.begin.roff"}
2: {name: "punctuation.definition.string.end.roff"}
},{
# Quoted string
name: "markup.bold.italic.roff"
contentName: "string.quoted.double.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)(?:$|\\n)|(?=\\\\\")'
beginCaptures:
0: name: "string.quoted.double.roff"
1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.bold.italic.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Embolden a word
"bold-word":
name: "markup.bold.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Italicise a word
"italic-word":
match: "\\S+?(?=\\\\|$|\\s)"
name: "markup.italic.roff"
# Embolden and italicise a word
"bold-italic-word":
name: "markup.bold.italic.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Render a word as raw/verbatim text
"monospace-word":
name: "markup.raw.monospaced.roff"
match: "\\S+?(?=\\\\|$|\\s)"
# Underline first argument only
"underline-first":
patterns: [{
# Unquoted string
contentName: "markup.underline.roff"
begin: "\\G[ \t]*(?!\")(?=(?:[^\\s\\\\]|\\\\(?!\").)+)"
end: "(?<![^\\\\]\\\\|^\\\\)(?=\\s|$)|(?=\\\\\")"
patterns: [include: "#escapes"]
},{
# Null argument
name: "string.quoted.double.empty.roff"
match: '(")(")'
beginCaptures: {0: {name: "punctuation.definition.string.begin.roff"}}
endCaptures: {0: {name: "punctuation.definition.string.end.roff"}}
},{
# Quoted string
name: "string.quoted.double.roff"
contentName: "markup.underline.roff"
begin: '\\G[ \t]*(")'
end: '((?:"")*)"(?!")|(?<!\\\\)$|(?=\\\\\")'
beginCaptures: 1: name: "punctuation.definition.string.begin.roff"
endCaptures:
0: name: "punctuation.definition.string.end.roff"
1: name: "markup.underline.roff", patterns: [include: "#string-escapes"]
patterns: [include: "#string-escapes"]
}
{include: "#escapes"}
{include: "#string"}]
# Preprocessors for preparing Troff documents
preprocessors:
patterns: [{
# .TS/.TE: Tbl
begin: "^([.'])[ \t]*(TS)(?=\\s|\\\\[\"#])(.*)"
end: "^([.'])[ \t]*(TE)(?=\\s|\\\\[\"#])"
contentName: "markup.other.table.preprocessor.tbl.roff"
patterns: [include: "#tbl"]
beginCaptures:
0: {name: "meta.function.begin.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.table.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .EQ/.EN: Eqn
begin: "^([.'])[ \t]*(EQ)(?=\\s|\\\\[\"#])[ \t]*([LIC]\\b)?\\s*([^\\\\\"]+|\\\\[^\"])*(\\\\\".*)?$"
end: "^([.'])[ \t]*(EN)(?=\\s|\\\\[\"#])"
contentName: "markup.other.math.preprocessor.eqn.roff"
patterns: [include: "#eqn"]
beginCaptures:
0: {name: "meta.function.begin.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.function.name.roff"}
3: {name: "constant.language.alignment-mode.eqn.roff"}
4: {name: "string.unquoted.equation-label.eqn.roff"}
5: {patterns: [include: "#escapes"]}
endCaptures:
0: {name: "meta.function.end.math.section.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
},{
# .[/.]: Refer
begin: "^([.'])[ \t]*(\\[)(.*?)\\s*(\\\\[\"#].*)?$"
end: "^([.'])[ \t]*(\\])(.*?)(?=\\s|$|\\\\\")"
contentName: "meta.citation.roff"
patterns: [{
# First line: Flags + Keywords
begin: "\\G"
end: "$|(?=\\\\[#\"])"
patterns: [{
name: "constant.character.flags.refer.gnu.roff"
match: "^[#\\[\\]]+"
}, include: "#params"]
}, include: "#refer"]
beginCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.begin.roff"}
3: {name: "string.unquoted.opening-text.refer.roff", patterns: [include: "#escapes"]}
4: {patterns: [include: "#escapes"]}
endCaptures:
1: {name: "punctuation.definition.macro.roff"}
2: {name: "punctuation.section.function.end.roff"}
3: {name: "string.unquoted.closing-text.refer.roff", patterns: [include: "#escapes"]}
},{
# .GS/.GE: Gremlin pictures
begin: "^([.'])[ \t]*(GS)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(GE)(?=\\s|\\\\[\"#])"
beginCaptures:
0: name: "meta.function.begin.gremlin.macro.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: patterns: [include: "#escapes"]
endCaptures:
0: {name: "meta.function.end.gremlin.macro.roff"}
1: {name: "punctuation.definition.macro.roff"}
2: {name: "entity.name.function.roff"}
patterns: [
# Gremlin keywords
name: "keyword.operator.gremlin"
match: """(?x)
\\b((?:sun)?gremlinfile|ARC|BEZIER|BOTCENT|BOTLEFT|BOTRIGHT
|BSPLINE|CENTCENT|CENTLEFT|CENTRIGHT|CURVE|POLYGON|TOPCENT
|TOPLEFT|TOPRIGHT|VECTOR)\\b"""
{include: "#params"}
]
},{
# Perl (GNU)
begin: "^([.'])[ \t]*(Perl)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(Perl)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.perl.gnu.roff"
patterns: [include: "source.perl"]
beginCaptures:
0: name: "meta.function.begin.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.perl.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
},{
# LilyPond (GNU)
begin: "^([.'])[ \t]*(lilypond)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(lilypond)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "source.embedded.lilypond.gnu.roff"
beginCaptures:
0: name: "meta.function.begin.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.lilypond.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
patterns: [
{include: "source.AtLilyPond"}
{include: "source.lilypond"}
]
},{
# Pinyin (GNU)
begin: "^([.'])[ \t]*(pinyin)[ \t]+(begin|start)(?=\\s|\\\\[\"#])(.*)$"
end: "^([.'])[ \t]*(pinyin)[ \t]+(end|stop)(?=\\s|\\\\[\"#])"
contentName: "meta.pinyin.gnu.roff"
patterns: [include: "#main"]
beginCaptures:
0: name: "meta.function.begin.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
4: patterns: [include: "#escapes"]
endCaptures:
0: name: "meta.function.end.pinyin.macro.gnu.roff"
1: name: "punctuation.definition.macro.roff"
2: name: "entity.function.name.roff"
3: name: "constant.language.embedding-control.roff"
}
{include: "source.pic#tags"}
{include: "source.ideal#tags"}]
# Equation preprocessor
eqn:
patterns: [{
# Greek letters
name: "constant.language.greek-letter.eqn.roff"
match: """(?x)\\b
(DELTA|GAMMA|LAMBDA|OMEGA|PHI|PI|PSI|SIGMA|THETA|UPSILON|XI|alpha|beta|chi
|delta|epsilon|eta|gamma|iota|kappa|lambda|mu|nu|omega|omicron|phi|pi|psi
|rho|sigma|tau|theta|upsilon|xi|zeta)\\b"""
},{
# Math symbols
name: "constant.character.math-symbol.eqn.roff"
match: """(?x)\\b
(sum|int|prod|union|inter|inf|partial|half|prime|approx|nothing|cdot
|times|del|grad|[><=!]=|\\+-|->|<-|<<|>>|\\.{3}|,\\.,)\\b"""
},{
# Punctuation
name: "punctuation.definition.eqn.roff"
match: "[~,^{}]"
},{
# Eqn keywords
name: "keyword.language.eqn.roff"
match: """(?x)\\b
(above|back|bar|bold|ccol|col|cpile|define|delim|dot|dotdot|down|dyad|fat|font|from
|fwd|gfont|gsize|hat|italic|lcol|left|lineup|lpile|mark|matrix|ndefine|over|pile
|rcol|right|roman|rpile|size|sqrt|sub|sup|tdefine|tilde|to|under|up|vec)\\b"""
},{
# GNU Eqn: Keywords
name: "keyword.language.eqn.gnu.roff"
match: """(?x)\\b
(accent|big|chartype|smallover|type|vcenter|uaccent|split|nosplit
|opprime|special|sdefine|include|ifdef|undef|g[rb]font|space)\\b"""
},{
# GNU Eqn: Character names
name: "constant.language.eqn.gnu.roff"
match: """(?x)\\b
(Alpha|Beta|Chi|Delta|Epsilon|Eta|Gamma|Iota|Kappa|Lambda|Mu|Nu
|Omega|Omicron|Phi|Pi|Psi|Rho|Sigma|Tau|Theta|Upsilon|Xi|Zeta
|ldots|dollar)\\b"""
},{
# GNU Eqn: Set MathML variables
name: "meta.set-variable.eqn.gnu.roff"
match: """(?x)\\b(set)[ \t]+
(accent_width|axis_height|baseline_sep|big_op_spacing[1-5]|body_depth|body_height|column_sep
|default_rule_thickness|delimiter_factor|delimiter_shortfall|denom[12]|draw_lines|fat_offset
|matrix_side_sep|medium_space|minimum_size|nroff|null_delimiter_space|num[12]|over_hang
|script_space|shift_down|su[bp]_drop|sub[12]|sup[1-3]|thick_space|thin_space|x_height)\\b"""
captures:
1: name: "storage.type.var.eqn.roff"
2: name: "variable.other.mathml.eqn.roff"
}, include: "#string"]
# Table preprocessor
tbl:
patterns: [{
# Options/Formats
name: "meta.function-call.arguments.tbl.roff"
begin: "\\G|^((\\.)T&)[ \t]*$"
end: "(\\.)$\\n?|^(?=[.'][ \t]*TE(?=\\s))"
beginCaptures:
1: {name: "entity.function.name.roff"}
2: {name: "punctuation.definition.macro.roff"}
endCaptures:
1: patterns: [include: "#params"]
2: name: "punctuation.terminator.section.tbl.roff"
patterns: [{
# Not preprocessor source; abandon ship
begin: "^(?=\\.)"
end: "^(?=[.'][ \t]*TE(?=\\s|\\\\[\"#]))"
patterns: [include: "$self"]},{
# Global options
match: "^(.+)(;)$"
captures:
1: patterns: [
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{match: "\\b(center|centre|expand|box|allbox|doublebox)\\b", name: "constant.language.$1.tbl.roff"}
{match: "\\b((tab|linesize|delim)(\\()([^\\)\\s]*)(\\)))"
captures:
1: name: "constant.language.$2.tbl.roff"
3: name: "punctuation.definition.arguments.begin.tbl.roff"
4: patterns: [include: "#params"]
5: name: "punctuation.definition.arguments.end.tbl.roff"}]
2: name: "punctuation.terminator.line.tbl.roff"}
# Field specifiers
{match: "[ABCEFILNPRSTUVWZabcefilnprstuvwz^]", name: "constant.language.key-letter.tbl.roff"}
{match: "[|_=]", name: "punctuation.keyword.tbl.roff"}
{match: "[-+]?\\d+", name: "constant.numeric.tbl.roff"}
{match: "\\.", name: "punctuation.delimiter.period.full-stop.tbl.roff"}
{match: ",", name: "punctuation.separator.comma.tbl.roff"}
{include: "#params"}
]
},{
# Horizontal line indicators
name: "punctuation.keyword.tbl.roff"
match: "^\\s*([=_]|\\\\_)\\s*$"
},{
# Column-filling repeated character sequence
name: "constant.character.escape.repeat.tbl.roff"
match: "(?<!\\\\)((\\\\)R)(.)"
captures:
1: {name: "keyword.operator.tbl.roff"}
2: {name: "punctuation.definition.escape.roff"}
3: {name: "string.unquoted.tbl.roff"}
},{
# Vertically-spanned item indicator
name: "constant.character.escape.vertical-span.tbl.roff"
match: "(\\\\)\\^"
captures:
0: {name: "keyword.operator.tbl.roff"}
1: {name: "punctuation.definition.escape.roff"}
},{
# Multiline cell content
name: "meta.multiline-cell.tbl.roff"
contentName: "string.unquoted.tbl.roff"
begin: "T(\\{)"
end: "^T(\\})|^(?=[.'][ \t]*TE\\b)"
patterns: [include: "$self"]
beginCaptures:
0: name: "keyword.operator.section.begin.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
endCaptures:
0: name: "keyword.operator.section.end.tbl.roff"
1: name: "punctuation.embedded.tbl.roff"
}, include: "$self"]
# Bibliographic references
refer:
patterns: [{
# Comment
name: "comment.line.refer.roff"
begin: "#"
end: "$"
beginCaptures:
0: name: "punctuation.definition.comment.refer.roff"
},{
# Names of each author, concatenated with the string specified by `join-authors`
name: "variable.other.readonly.author-names.refer.roff"
match: "@"
},{
# %KEY Value
name: "meta.structure.dictionary.refer.roff"
contentName: "meta.structure.dictionary.value.refer.roff"
begin: "^([.'])?\\s*(%)([A-Z])(?=\\s)"
end: "(?<!\\\\)$"
patterns: [{
name: "string.unquoted.refer.roff"
begin: "\\G"
end: "(?<!\\\\)$"
patterns: [{
# Make sure "special" characters don't trigger refer patterns
name: "meta.symbol.refer.roff"
match: "[-+'\"<>\\].*\\[~!&?:]"
}, include: "#refer"]
}, include: "#escapes"]
beginCaptures:
1: name: "punctuation.definition.macro.mdoc.roff"
2: name: "punctuation.definition.percentage-sign.refer.roff"
3: name: "variable.other.readonly.key-letter.refer.roff"
},{
# Literal/single-quoted string
name: "string.quoted.single.refer.roff"
begin: "'"
end: "'"
beginCaptures: 0: name: "punctuation.definition.string.begin.roff"
endCaptures: 0: name: "punctuation.definition.string.end.roff"
},{
# Formatted/placeholder value
name: "variable.other.readonly.formatted.refer.roff"
match: "(%+)[\\daiA-Z]"
captures:
1: name: "punctuation.definition.percentage-sign.refer.roff"
},{
# Label expressions
name: "keyword.operator.label-expression.refer.roff"
match: """(?x)
(?<=\\S)(?:\\*|[-+]\\d+|(\\.)(?:[-+]?y|[lucran]))(?=\\s|$) |
(?<=\\S)[~!&?:](?=\\S)"""
captures:
1: name: "punctuation.separator.period.full-stop.refer.roff"
},{
# Angle brackets
begin: "<"
end: ">|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
endCaptures: 0: name: "punctuation.bracket.angle.refer.roff"
patterns: [include: "#refer"]
},{
# Round brackets
begin: "\\("
end: "\\)|^(?=\\.\\])"
beginCaptures: 0: name: "punctuation.bracket.round.refer.roff"
endCaptures: 0: name: "punctuation.bracket.round.refer.roff"
patterns: [include: "#refer"]
},{
# Negatable commands
name: "keyword.operator.negatable.refer.roff"
match: """(?x)\\b
(?:no-)?
(?:abbreviate|abbreviate-label-ranges|accumulate|annotate|compatible|date-as-label
|default-database|discard|et-al|label-in-reference|label-in-text|move-punctuation
|reverse|search-ignore|search-truncate|short-label|sort|sort-adjacent-labels)\\b"""
captures:
0: name: "entity.function.name.refer.roff"
},{
# Non-negatable commands
name: "keyword.operator.refer.roff"
match: "\\b(articles|bibliography|capitalize|join-authors|label|separate-label-second-parts)\\b"
captures:
0: name: "entity.function.name.refer.roff"
},{
# Commands that take filenames as arguments
begin: "^\\s*\\b(database|include)\\b"
end: "(?<!\\\\)$"
beginCaptures:
0: name: "keyword.operator.refer.roff"
1: name: "entity.function.name.refer.roff"
patterns: [
{include: "#escapes"}
# Add underlines to filenames for themes supporting them
name: "string.unquoted.filename.refer.roff"
match: "((?:[^\\\\\\s]|\\\\(?!\").)+)"
captures:
0: name: "markup.link.underline.refer.roff"
1: patterns: [include: "#escapes"]
]
}
{include: "#string"}
{include: "#escapes"}]
|
[
{
"context": "n\n\n @token = (String.fromCharCode(48 + code + (if code > 9 then 7 else 0) + (if code >",
"end": 525,
"score": 0.8197256326675415,
"start": 524,
"tag": "KEY",
"value": "8"
}
] | vendor/assets/javascripts/seapig-router.coffee | MirnaShalaby/scheduler-server | 2 | class @SeapigRouter
constructor: (seapig_client, options={})->
@seapig_client = seapig_client
@session_id = undefined
@mountpoint = (options.mountpoint or "/")
@default_state = (options.default or {})
@debug = options.debug
@expose = (options.expose or [])
@cast = (options.cast or (state)-> state)
@onsessionopen = options.onsessionopen
@token = (String.fromCharCode(48 + code + (if code > 9 then 7 else 0) + (if code > 35 then 6 else 0)) for code in (Math.floor(Math.random()*62) for i in [0..11])).join("")
console.log('ROUTER: Generated token: ', @token) if @debug
@state = undefined
@state_id = 1
@state_raw = { session_id: undefined, state_id: 0, state_parent: undefined, state_committed: true }
@state_valid = false
commit_scheduled_at = null
commit_timer = null
remote_state = null
priv = {}
@private = priv if options.expose_privates
session_data = @seapig_client.master('SeapigRouter::Session::'+@token+'::Data', object: { token: @token, session: @session_id, states: {}})
session_data.bump()
session_data_saved = @seapig_client.slave('SeapigRouter::Session::'+@token+'::Saved')
session_data_saved.onchange =>
return if not session_data_saved.valid
for state_id in _.keys(session_data.object.states)
delete session_data.object.states[state_id] if parseInt(state_id) < session_data_saved.object.max_state_id
if not @session_id?
@session_id = session_data_saved.object.session_id
@state.session_id = @state_raw.session_id = @session_id if @state? and not @state_raw.session_id?
console.log('ROUTER: Session opened', @session_id) if @debug
@onsessionopen(@session_id) if @onsessionopen?
console.log('ROUTER: Session saved up till:', session_data_saved.object.max_state_id) if @debug
location_update(false) if @state_valid
document.addEventListener("click", (event) =>
return true if not (event.button == 0)
href = (event.target.getAttribute("href") or "")
console.log('ROUTER: A-element clicked, changing location to:', href) if @debug
return true if not (href[0] == '?')
@navigate(href)
event.preventDefault()
false)
window.onpopstate = (event) =>
previous_state = @state_raw
@state_raw = JSON.parse(JSON.stringify(event.state))
@state_raw.session_id = @session_id if not @state_raw.session_id?
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
console.log('ROUTER: History navigation triggered. Going to:', event.state) if @debug
location_update(false)
@onchange(@state_raw, previous_state) if @onchange?
state_permanent = (state)=>
_.omit(state, (value, key)-> key.indexOf("_") == 0 or key == "session_id" or key == "state_id" or key == "state_parent" or key == "state_committed")
state_diff_generate = priv.state_diff_generate = (state1, state2)=>
element_diff = (diff, address, object1, object2)->
same_type = ((typeof object1 == typeof object2) and (Array.isArray(object1) == Array.isArray(object2)))
if (not object2?) or (object1? and not same_type)
diff.push ['-'+address, '-']
object1 = undefined
if Array.isArray(object2)
array_diff(diff, address+"~", object1 or [], object2)
else if typeof object2 == 'object'
object_diff(diff, address+".", object1 or {}, object2)
else if object2?
diff.push [address, object2] if object1 != object2
object_diff = (diff, address, object1, object2)->
for key in _.uniq(_.union(_.keys(object1), _.keys(object2)))
element_diff(diff, address+key, object1[key], object2[key])
diff
array_diff = (diff, address, array1, array2)->
j = 0
for element1, i in array1
if _.isEqual(element1, array2[j])
j++
else
k = j
k++ while (not _.isEqual(element1,array2[k])) and (k < array2.length)
if k == array2.length
if typeof element1 == 'object'
diff.push ["-"+address+j+"~", "-"]
else
diff.push ["-"+address+"~", element1]
else
while j < k
element_diff(diff, address+j+"~", undefined, array2[j++])
j++
while j < array2.length
element_diff(diff, address+"~", undefined, array2[j++])
object_diff([], "", state1, state2)
state_diff_apply = priv.state_diff_apply = (state, diff)=>
for entry in diff
address = entry[0]
value = entry[1]
add = (address[0] != '-')
address = address[1..-1] if address[0] == '-'
obj = state
spl = address.split('.')
for subobj,i in spl
if i < (spl.length-1)
if subobj[subobj.length-1] == '~'
if subobj.split("~")[1].length > 0
obj[parseInt(subobj.split("~")[1])] = {} if not obj[parseInt(subobj.split("~")[1])]
obj = obj[parseInt(subobj.split("~")[1])]
else
obj[subobj.split("~")[0]] = [new_obj = {}]
obj = new_obj
else
obj[subobj] = {} if not obj[subobj]?
obj = obj[subobj]
address = spl[spl.length-1]
hash = (address[address.length-1] != '~')
index = undefined
index = parseInt(address.split('~')[1]) if (not hash) and address.split("~")[1].length > 0
address = address.split("~")[0]
if add
if hash
obj[address] = value
else
if index?
(obj[address] ||= []).splice(index,0,value)
else
(obj[address] ||= []).push(value)
else
if hash
delete obj[address]
else
if index?
obj[address].splice(index,1)
else
obj[address].splice(_.indexOf(obj[address], value),1)
state
url_to_state_description = (pathname, search)=>
# URL FORMAT:
# /VERSION/SESSION_ID/STATE_ID/[EXPOSED_DIFF/][-/BUFFER_DIFF][?CHANGE_DIFF]
# VERSION - format code
# SESSION_ID
# STATE_ID - id of latest state saved on server
# EXPOSED DIFF - "pretty" part of the url, exposing selected state components for end user manipulation.
# BUFFER_DIFF - temporary section, holding the difference between STATE_ID state and current state. vanishes after current state gets saved on server.
# CHANGE_DIFF - temporary section, holding state change intended by <A> link (e.g. href="?view=users&user=10"). vanishes immediately and gets transeferred to BUFFER_DIFF.
state_description = { session_id: null, state_id: null, buffer: [], exposed: [], change: [] }
spl = pathname.split(@mountpoint)
spl.shift()
spl = (decodeURIComponent(part) for part in spl.join(@mountpoint).split('/'))
version = spl.shift()
if version == 'a'
state_description.session_id = spl.shift()
state_description.session_id = undefined if state_description.session_id == '_'
state_description.state_id = spl.shift()
if state_description.state_id?
while spl.length > 0
key = spl.shift()
break if key == '-'
component = _.find @expose, (component)-> component[1]
next if not component
state_description.exposed.push([component[0],spl.shift()])
while spl.length > 0
state_description.buffer.push([spl.shift(),spl.shift()])
else
state_description.session_id = @session_id
state_description.state_id = 0
state_description.buffer = state_diff_generate(state_permanent(@state_raw), state_permanent(@default_state))
if search.length > 1
for pair in search.split('?')[1].split('&')
decoded_pair = (decodeURIComponent(part) for part in pair.split('=',2))
state_description.change.push(decoded_pair)
console.log('ROUTER: Parsed location', state_description) if @debug
state_description
state_description_to_url = (state_description)=>
console.log('ROUTER: Calculating url for state description:', state_description) if @debug
url = @mountpoint+'a/'+(state_description.session_id or '_')+'/'+state_description.state_id
url += "/"+(encodeURIComponent(component) for component in _.flatten(state_description.exposed)).join("/") if state_description.exposed.length > 0
url += "/-/"+(encodeURIComponent(component) for component in _.flatten(state_description.buffer)).join("/") if state_description.buffer.length > 0
console.log('ROUTER: Calculated url:', url) if @debug
url
state_set_from_state_description = (state_description, defer, replace)=>
state_commit = (replace) =>
console.log("ROUTER: Committing state:",@state_raw) if @debug
@state_raw.state_committed = true
session_data.object.states[@state_raw.state_id] = state_permanent(@state_raw)
session_data.bump()
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
location_update(replace)
commit_needed_at = Date.now() + defer
if not @state_raw.state_committed
last_committed_state = @state_raw.state_parent
else
last_committed_state = @state_raw
console.log("ROUTER: Changing state. Commit deferred by", defer, "to be done at", commit_needed_at, " State before mutation:",last_committed_state) if @debug
previous_state = @state_raw
new_state = JSON.parse(JSON.stringify(state_permanent(@state_raw)))
new_state = state_diff_apply(new_state, state_description.buffer)
new_state = state_diff_apply(new_state, state_description.exposed)
new_state = state_diff_apply(new_state, state_description.change)
_.extend(new_state, _.pick(previous_state, (value,key)-> key.indexOf("_") == 0))
if state_diff_generate(state_permanent(last_committed_state), state_permanent(new_state)).length > 0
new_state.state_committed = false
if previous_state.state_committed
new_state.session_id = @session_id
new_state.state_id = @state_id++
new_state.state_parent = previous_state
else
new_state.session_id = previous_state.session_id
new_state.state_id = previous_state.state_id
new_state.state_parent = previous_state.state_parent
else
new_state.session_id = last_committed_state.session_id
new_state.state_id = last_committed_state.state_id
new_state.state_parent = last_committed_state.state_parent
new_state.state_committed = last_committed_state.state_committed
@filter(new_state, previous_state) if @filter?
@state_raw = new_state
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
@state_valid = true
if @state_raw.state_committed
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
else
if commit_needed_at <= Date.now()
state_commit(replace)
else
location_update(false)
if (not commit_scheduled_at) or (commit_needed_at < commit_scheduled_at)
console.log("ROUTER: Deferring commit by:", defer, "till", commit_needed_at) if @debug
@state_raw.state_committed = false
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = commit_needed_at
commit_timer = setTimeout((()=> state_commit(replace)), commit_scheduled_at - Date.now())
@onchange(@state_raw,previous_state) if @onchange?
state_get_as_state_description = (state)=>
last_committed_state = state
while last_committed_state.state_parent and ((not last_committed_state.session_id) or last_committed_state.session_id == @session_id) and ((session_data_saved.object.max_state_id or 0 ) < last_committed_state.state_id)
last_committed_state = last_committed_state.state_parent
console.log('ROUTER: Last shareable state:', last_committed_state) if @debug
buffer = state_diff_generate(state_permanent(last_committed_state), state_permanent(state))
exposed = ([component[1], pair[1]] for pair in state_diff_generate({}, state) when component = _.find @expose, (component)-> component[0] == pair[0])
buffer = (pair for pair in buffer when not _.find @expose, (component)-> component[0] == pair[0])
{ session_id: last_committed_state.session_id, state_id: last_committed_state.state_id, exposed: exposed, buffer: buffer, change: [] }
location_update = (new_history_entry)=>
url = state_description_to_url(state_get_as_state_description(@state_raw))
console.log("ROUTER: Updating location: state:", @state_raw, ' url:', url) if @debug
if new_history_entry
window.history.pushState(@state_raw,null,url)
else
window.history.replaceState(@state_raw,null,url)
@navigate = (search, options = {})->
pathname = window.location.pathname
console.log('ROUTER: Navigating to: pathname:', pathname, ' search:', search) if @debug
state_description = url_to_state_description(pathname, search)
console.log('ROUTER: New state description:', state_description) if @debug
if remote_state?
remote_state.unlink()
remote_state = null
if state_description.session_id == @session_id or state_description.state_id == "0"
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
else
@state_valid = false
remote_state = @seapig_client.slave('SeapigRouter::Session::'+state_description.session_id+'::State::'+state_description.state_id)
remote_state.onchange ()=>
return if not remote_state.valid
console.log("ROUTER: Received remote state", remote_state.object) if @debug
@state_raw = JSON.parse(JSON.stringify(remote_state.object))
@state_raw.state_committed = true
@state_raw.session_id = state_description.session_id
@state_raw.state_id = state_description.state_id
@state_raw.state_parent = undefined
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
remote_state.unlink()
remote_state = null
@volatile = (data...)->
if data.length == 1 and typeof data[0] == 'object'
for key, value of data[0]
@state["_"+key] = value
_.extend(@state_raw, _.pick(@state, (value,key)-> key.indexOf("_") == 0))
window.history.replaceState(@state_raw,null,window.location)
else
_.object(([key, @state["_"+key]] for key in data))
| 56661 | class @SeapigRouter
constructor: (seapig_client, options={})->
@seapig_client = seapig_client
@session_id = undefined
@mountpoint = (options.mountpoint or "/")
@default_state = (options.default or {})
@debug = options.debug
@expose = (options.expose or [])
@cast = (options.cast or (state)-> state)
@onsessionopen = options.onsessionopen
@token = (String.fromCharCode(4<KEY> + code + (if code > 9 then 7 else 0) + (if code > 35 then 6 else 0)) for code in (Math.floor(Math.random()*62) for i in [0..11])).join("")
console.log('ROUTER: Generated token: ', @token) if @debug
@state = undefined
@state_id = 1
@state_raw = { session_id: undefined, state_id: 0, state_parent: undefined, state_committed: true }
@state_valid = false
commit_scheduled_at = null
commit_timer = null
remote_state = null
priv = {}
@private = priv if options.expose_privates
session_data = @seapig_client.master('SeapigRouter::Session::'+@token+'::Data', object: { token: @token, session: @session_id, states: {}})
session_data.bump()
session_data_saved = @seapig_client.slave('SeapigRouter::Session::'+@token+'::Saved')
session_data_saved.onchange =>
return if not session_data_saved.valid
for state_id in _.keys(session_data.object.states)
delete session_data.object.states[state_id] if parseInt(state_id) < session_data_saved.object.max_state_id
if not @session_id?
@session_id = session_data_saved.object.session_id
@state.session_id = @state_raw.session_id = @session_id if @state? and not @state_raw.session_id?
console.log('ROUTER: Session opened', @session_id) if @debug
@onsessionopen(@session_id) if @onsessionopen?
console.log('ROUTER: Session saved up till:', session_data_saved.object.max_state_id) if @debug
location_update(false) if @state_valid
document.addEventListener("click", (event) =>
return true if not (event.button == 0)
href = (event.target.getAttribute("href") or "")
console.log('ROUTER: A-element clicked, changing location to:', href) if @debug
return true if not (href[0] == '?')
@navigate(href)
event.preventDefault()
false)
window.onpopstate = (event) =>
previous_state = @state_raw
@state_raw = JSON.parse(JSON.stringify(event.state))
@state_raw.session_id = @session_id if not @state_raw.session_id?
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
console.log('ROUTER: History navigation triggered. Going to:', event.state) if @debug
location_update(false)
@onchange(@state_raw, previous_state) if @onchange?
state_permanent = (state)=>
_.omit(state, (value, key)-> key.indexOf("_") == 0 or key == "session_id" or key == "state_id" or key == "state_parent" or key == "state_committed")
state_diff_generate = priv.state_diff_generate = (state1, state2)=>
element_diff = (diff, address, object1, object2)->
same_type = ((typeof object1 == typeof object2) and (Array.isArray(object1) == Array.isArray(object2)))
if (not object2?) or (object1? and not same_type)
diff.push ['-'+address, '-']
object1 = undefined
if Array.isArray(object2)
array_diff(diff, address+"~", object1 or [], object2)
else if typeof object2 == 'object'
object_diff(diff, address+".", object1 or {}, object2)
else if object2?
diff.push [address, object2] if object1 != object2
object_diff = (diff, address, object1, object2)->
for key in _.uniq(_.union(_.keys(object1), _.keys(object2)))
element_diff(diff, address+key, object1[key], object2[key])
diff
array_diff = (diff, address, array1, array2)->
j = 0
for element1, i in array1
if _.isEqual(element1, array2[j])
j++
else
k = j
k++ while (not _.isEqual(element1,array2[k])) and (k < array2.length)
if k == array2.length
if typeof element1 == 'object'
diff.push ["-"+address+j+"~", "-"]
else
diff.push ["-"+address+"~", element1]
else
while j < k
element_diff(diff, address+j+"~", undefined, array2[j++])
j++
while j < array2.length
element_diff(diff, address+"~", undefined, array2[j++])
object_diff([], "", state1, state2)
state_diff_apply = priv.state_diff_apply = (state, diff)=>
for entry in diff
address = entry[0]
value = entry[1]
add = (address[0] != '-')
address = address[1..-1] if address[0] == '-'
obj = state
spl = address.split('.')
for subobj,i in spl
if i < (spl.length-1)
if subobj[subobj.length-1] == '~'
if subobj.split("~")[1].length > 0
obj[parseInt(subobj.split("~")[1])] = {} if not obj[parseInt(subobj.split("~")[1])]
obj = obj[parseInt(subobj.split("~")[1])]
else
obj[subobj.split("~")[0]] = [new_obj = {}]
obj = new_obj
else
obj[subobj] = {} if not obj[subobj]?
obj = obj[subobj]
address = spl[spl.length-1]
hash = (address[address.length-1] != '~')
index = undefined
index = parseInt(address.split('~')[1]) if (not hash) and address.split("~")[1].length > 0
address = address.split("~")[0]
if add
if hash
obj[address] = value
else
if index?
(obj[address] ||= []).splice(index,0,value)
else
(obj[address] ||= []).push(value)
else
if hash
delete obj[address]
else
if index?
obj[address].splice(index,1)
else
obj[address].splice(_.indexOf(obj[address], value),1)
state
url_to_state_description = (pathname, search)=>
# URL FORMAT:
# /VERSION/SESSION_ID/STATE_ID/[EXPOSED_DIFF/][-/BUFFER_DIFF][?CHANGE_DIFF]
# VERSION - format code
# SESSION_ID
# STATE_ID - id of latest state saved on server
# EXPOSED DIFF - "pretty" part of the url, exposing selected state components for end user manipulation.
# BUFFER_DIFF - temporary section, holding the difference between STATE_ID state and current state. vanishes after current state gets saved on server.
# CHANGE_DIFF - temporary section, holding state change intended by <A> link (e.g. href="?view=users&user=10"). vanishes immediately and gets transeferred to BUFFER_DIFF.
state_description = { session_id: null, state_id: null, buffer: [], exposed: [], change: [] }
spl = pathname.split(@mountpoint)
spl.shift()
spl = (decodeURIComponent(part) for part in spl.join(@mountpoint).split('/'))
version = spl.shift()
if version == 'a'
state_description.session_id = spl.shift()
state_description.session_id = undefined if state_description.session_id == '_'
state_description.state_id = spl.shift()
if state_description.state_id?
while spl.length > 0
key = spl.shift()
break if key == '-'
component = _.find @expose, (component)-> component[1]
next if not component
state_description.exposed.push([component[0],spl.shift()])
while spl.length > 0
state_description.buffer.push([spl.shift(),spl.shift()])
else
state_description.session_id = @session_id
state_description.state_id = 0
state_description.buffer = state_diff_generate(state_permanent(@state_raw), state_permanent(@default_state))
if search.length > 1
for pair in search.split('?')[1].split('&')
decoded_pair = (decodeURIComponent(part) for part in pair.split('=',2))
state_description.change.push(decoded_pair)
console.log('ROUTER: Parsed location', state_description) if @debug
state_description
state_description_to_url = (state_description)=>
console.log('ROUTER: Calculating url for state description:', state_description) if @debug
url = @mountpoint+'a/'+(state_description.session_id or '_')+'/'+state_description.state_id
url += "/"+(encodeURIComponent(component) for component in _.flatten(state_description.exposed)).join("/") if state_description.exposed.length > 0
url += "/-/"+(encodeURIComponent(component) for component in _.flatten(state_description.buffer)).join("/") if state_description.buffer.length > 0
console.log('ROUTER: Calculated url:', url) if @debug
url
state_set_from_state_description = (state_description, defer, replace)=>
state_commit = (replace) =>
console.log("ROUTER: Committing state:",@state_raw) if @debug
@state_raw.state_committed = true
session_data.object.states[@state_raw.state_id] = state_permanent(@state_raw)
session_data.bump()
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
location_update(replace)
commit_needed_at = Date.now() + defer
if not @state_raw.state_committed
last_committed_state = @state_raw.state_parent
else
last_committed_state = @state_raw
console.log("ROUTER: Changing state. Commit deferred by", defer, "to be done at", commit_needed_at, " State before mutation:",last_committed_state) if @debug
previous_state = @state_raw
new_state = JSON.parse(JSON.stringify(state_permanent(@state_raw)))
new_state = state_diff_apply(new_state, state_description.buffer)
new_state = state_diff_apply(new_state, state_description.exposed)
new_state = state_diff_apply(new_state, state_description.change)
_.extend(new_state, _.pick(previous_state, (value,key)-> key.indexOf("_") == 0))
if state_diff_generate(state_permanent(last_committed_state), state_permanent(new_state)).length > 0
new_state.state_committed = false
if previous_state.state_committed
new_state.session_id = @session_id
new_state.state_id = @state_id++
new_state.state_parent = previous_state
else
new_state.session_id = previous_state.session_id
new_state.state_id = previous_state.state_id
new_state.state_parent = previous_state.state_parent
else
new_state.session_id = last_committed_state.session_id
new_state.state_id = last_committed_state.state_id
new_state.state_parent = last_committed_state.state_parent
new_state.state_committed = last_committed_state.state_committed
@filter(new_state, previous_state) if @filter?
@state_raw = new_state
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
@state_valid = true
if @state_raw.state_committed
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
else
if commit_needed_at <= Date.now()
state_commit(replace)
else
location_update(false)
if (not commit_scheduled_at) or (commit_needed_at < commit_scheduled_at)
console.log("ROUTER: Deferring commit by:", defer, "till", commit_needed_at) if @debug
@state_raw.state_committed = false
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = commit_needed_at
commit_timer = setTimeout((()=> state_commit(replace)), commit_scheduled_at - Date.now())
@onchange(@state_raw,previous_state) if @onchange?
state_get_as_state_description = (state)=>
last_committed_state = state
while last_committed_state.state_parent and ((not last_committed_state.session_id) or last_committed_state.session_id == @session_id) and ((session_data_saved.object.max_state_id or 0 ) < last_committed_state.state_id)
last_committed_state = last_committed_state.state_parent
console.log('ROUTER: Last shareable state:', last_committed_state) if @debug
buffer = state_diff_generate(state_permanent(last_committed_state), state_permanent(state))
exposed = ([component[1], pair[1]] for pair in state_diff_generate({}, state) when component = _.find @expose, (component)-> component[0] == pair[0])
buffer = (pair for pair in buffer when not _.find @expose, (component)-> component[0] == pair[0])
{ session_id: last_committed_state.session_id, state_id: last_committed_state.state_id, exposed: exposed, buffer: buffer, change: [] }
location_update = (new_history_entry)=>
url = state_description_to_url(state_get_as_state_description(@state_raw))
console.log("ROUTER: Updating location: state:", @state_raw, ' url:', url) if @debug
if new_history_entry
window.history.pushState(@state_raw,null,url)
else
window.history.replaceState(@state_raw,null,url)
@navigate = (search, options = {})->
pathname = window.location.pathname
console.log('ROUTER: Navigating to: pathname:', pathname, ' search:', search) if @debug
state_description = url_to_state_description(pathname, search)
console.log('ROUTER: New state description:', state_description) if @debug
if remote_state?
remote_state.unlink()
remote_state = null
if state_description.session_id == @session_id or state_description.state_id == "0"
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
else
@state_valid = false
remote_state = @seapig_client.slave('SeapigRouter::Session::'+state_description.session_id+'::State::'+state_description.state_id)
remote_state.onchange ()=>
return if not remote_state.valid
console.log("ROUTER: Received remote state", remote_state.object) if @debug
@state_raw = JSON.parse(JSON.stringify(remote_state.object))
@state_raw.state_committed = true
@state_raw.session_id = state_description.session_id
@state_raw.state_id = state_description.state_id
@state_raw.state_parent = undefined
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
remote_state.unlink()
remote_state = null
@volatile = (data...)->
if data.length == 1 and typeof data[0] == 'object'
for key, value of data[0]
@state["_"+key] = value
_.extend(@state_raw, _.pick(@state, (value,key)-> key.indexOf("_") == 0))
window.history.replaceState(@state_raw,null,window.location)
else
_.object(([key, @state["_"+key]] for key in data))
| true | class @SeapigRouter
constructor: (seapig_client, options={})->
@seapig_client = seapig_client
@session_id = undefined
@mountpoint = (options.mountpoint or "/")
@default_state = (options.default or {})
@debug = options.debug
@expose = (options.expose or [])
@cast = (options.cast or (state)-> state)
@onsessionopen = options.onsessionopen
@token = (String.fromCharCode(4PI:KEY:<KEY>END_PI + code + (if code > 9 then 7 else 0) + (if code > 35 then 6 else 0)) for code in (Math.floor(Math.random()*62) for i in [0..11])).join("")
console.log('ROUTER: Generated token: ', @token) if @debug
@state = undefined
@state_id = 1
@state_raw = { session_id: undefined, state_id: 0, state_parent: undefined, state_committed: true }
@state_valid = false
commit_scheduled_at = null
commit_timer = null
remote_state = null
priv = {}
@private = priv if options.expose_privates
session_data = @seapig_client.master('SeapigRouter::Session::'+@token+'::Data', object: { token: @token, session: @session_id, states: {}})
session_data.bump()
session_data_saved = @seapig_client.slave('SeapigRouter::Session::'+@token+'::Saved')
session_data_saved.onchange =>
return if not session_data_saved.valid
for state_id in _.keys(session_data.object.states)
delete session_data.object.states[state_id] if parseInt(state_id) < session_data_saved.object.max_state_id
if not @session_id?
@session_id = session_data_saved.object.session_id
@state.session_id = @state_raw.session_id = @session_id if @state? and not @state_raw.session_id?
console.log('ROUTER: Session opened', @session_id) if @debug
@onsessionopen(@session_id) if @onsessionopen?
console.log('ROUTER: Session saved up till:', session_data_saved.object.max_state_id) if @debug
location_update(false) if @state_valid
document.addEventListener("click", (event) =>
return true if not (event.button == 0)
href = (event.target.getAttribute("href") or "")
console.log('ROUTER: A-element clicked, changing location to:', href) if @debug
return true if not (href[0] == '?')
@navigate(href)
event.preventDefault()
false)
window.onpopstate = (event) =>
previous_state = @state_raw
@state_raw = JSON.parse(JSON.stringify(event.state))
@state_raw.session_id = @session_id if not @state_raw.session_id?
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
console.log('ROUTER: History navigation triggered. Going to:', event.state) if @debug
location_update(false)
@onchange(@state_raw, previous_state) if @onchange?
state_permanent = (state)=>
_.omit(state, (value, key)-> key.indexOf("_") == 0 or key == "session_id" or key == "state_id" or key == "state_parent" or key == "state_committed")
state_diff_generate = priv.state_diff_generate = (state1, state2)=>
element_diff = (diff, address, object1, object2)->
same_type = ((typeof object1 == typeof object2) and (Array.isArray(object1) == Array.isArray(object2)))
if (not object2?) or (object1? and not same_type)
diff.push ['-'+address, '-']
object1 = undefined
if Array.isArray(object2)
array_diff(diff, address+"~", object1 or [], object2)
else if typeof object2 == 'object'
object_diff(diff, address+".", object1 or {}, object2)
else if object2?
diff.push [address, object2] if object1 != object2
object_diff = (diff, address, object1, object2)->
for key in _.uniq(_.union(_.keys(object1), _.keys(object2)))
element_diff(diff, address+key, object1[key], object2[key])
diff
array_diff = (diff, address, array1, array2)->
j = 0
for element1, i in array1
if _.isEqual(element1, array2[j])
j++
else
k = j
k++ while (not _.isEqual(element1,array2[k])) and (k < array2.length)
if k == array2.length
if typeof element1 == 'object'
diff.push ["-"+address+j+"~", "-"]
else
diff.push ["-"+address+"~", element1]
else
while j < k
element_diff(diff, address+j+"~", undefined, array2[j++])
j++
while j < array2.length
element_diff(diff, address+"~", undefined, array2[j++])
object_diff([], "", state1, state2)
state_diff_apply = priv.state_diff_apply = (state, diff)=>
for entry in diff
address = entry[0]
value = entry[1]
add = (address[0] != '-')
address = address[1..-1] if address[0] == '-'
obj = state
spl = address.split('.')
for subobj,i in spl
if i < (spl.length-1)
if subobj[subobj.length-1] == '~'
if subobj.split("~")[1].length > 0
obj[parseInt(subobj.split("~")[1])] = {} if not obj[parseInt(subobj.split("~")[1])]
obj = obj[parseInt(subobj.split("~")[1])]
else
obj[subobj.split("~")[0]] = [new_obj = {}]
obj = new_obj
else
obj[subobj] = {} if not obj[subobj]?
obj = obj[subobj]
address = spl[spl.length-1]
hash = (address[address.length-1] != '~')
index = undefined
index = parseInt(address.split('~')[1]) if (not hash) and address.split("~")[1].length > 0
address = address.split("~")[0]
if add
if hash
obj[address] = value
else
if index?
(obj[address] ||= []).splice(index,0,value)
else
(obj[address] ||= []).push(value)
else
if hash
delete obj[address]
else
if index?
obj[address].splice(index,1)
else
obj[address].splice(_.indexOf(obj[address], value),1)
state
url_to_state_description = (pathname, search)=>
# URL FORMAT:
# /VERSION/SESSION_ID/STATE_ID/[EXPOSED_DIFF/][-/BUFFER_DIFF][?CHANGE_DIFF]
# VERSION - format code
# SESSION_ID
# STATE_ID - id of latest state saved on server
# EXPOSED DIFF - "pretty" part of the url, exposing selected state components for end user manipulation.
# BUFFER_DIFF - temporary section, holding the difference between STATE_ID state and current state. vanishes after current state gets saved on server.
# CHANGE_DIFF - temporary section, holding state change intended by <A> link (e.g. href="?view=users&user=10"). vanishes immediately and gets transeferred to BUFFER_DIFF.
state_description = { session_id: null, state_id: null, buffer: [], exposed: [], change: [] }
spl = pathname.split(@mountpoint)
spl.shift()
spl = (decodeURIComponent(part) for part in spl.join(@mountpoint).split('/'))
version = spl.shift()
if version == 'a'
state_description.session_id = spl.shift()
state_description.session_id = undefined if state_description.session_id == '_'
state_description.state_id = spl.shift()
if state_description.state_id?
while spl.length > 0
key = spl.shift()
break if key == '-'
component = _.find @expose, (component)-> component[1]
next if not component
state_description.exposed.push([component[0],spl.shift()])
while spl.length > 0
state_description.buffer.push([spl.shift(),spl.shift()])
else
state_description.session_id = @session_id
state_description.state_id = 0
state_description.buffer = state_diff_generate(state_permanent(@state_raw), state_permanent(@default_state))
if search.length > 1
for pair in search.split('?')[1].split('&')
decoded_pair = (decodeURIComponent(part) for part in pair.split('=',2))
state_description.change.push(decoded_pair)
console.log('ROUTER: Parsed location', state_description) if @debug
state_description
state_description_to_url = (state_description)=>
console.log('ROUTER: Calculating url for state description:', state_description) if @debug
url = @mountpoint+'a/'+(state_description.session_id or '_')+'/'+state_description.state_id
url += "/"+(encodeURIComponent(component) for component in _.flatten(state_description.exposed)).join("/") if state_description.exposed.length > 0
url += "/-/"+(encodeURIComponent(component) for component in _.flatten(state_description.buffer)).join("/") if state_description.buffer.length > 0
console.log('ROUTER: Calculated url:', url) if @debug
url
state_set_from_state_description = (state_description, defer, replace)=>
state_commit = (replace) =>
console.log("ROUTER: Committing state:",@state_raw) if @debug
@state_raw.state_committed = true
session_data.object.states[@state_raw.state_id] = state_permanent(@state_raw)
session_data.bump()
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
location_update(replace)
commit_needed_at = Date.now() + defer
if not @state_raw.state_committed
last_committed_state = @state_raw.state_parent
else
last_committed_state = @state_raw
console.log("ROUTER: Changing state. Commit deferred by", defer, "to be done at", commit_needed_at, " State before mutation:",last_committed_state) if @debug
previous_state = @state_raw
new_state = JSON.parse(JSON.stringify(state_permanent(@state_raw)))
new_state = state_diff_apply(new_state, state_description.buffer)
new_state = state_diff_apply(new_state, state_description.exposed)
new_state = state_diff_apply(new_state, state_description.change)
_.extend(new_state, _.pick(previous_state, (value,key)-> key.indexOf("_") == 0))
if state_diff_generate(state_permanent(last_committed_state), state_permanent(new_state)).length > 0
new_state.state_committed = false
if previous_state.state_committed
new_state.session_id = @session_id
new_state.state_id = @state_id++
new_state.state_parent = previous_state
else
new_state.session_id = previous_state.session_id
new_state.state_id = previous_state.state_id
new_state.state_parent = previous_state.state_parent
else
new_state.session_id = last_committed_state.session_id
new_state.state_id = last_committed_state.state_id
new_state.state_parent = last_committed_state.state_parent
new_state.state_committed = last_committed_state.state_committed
@filter(new_state, previous_state) if @filter?
@state_raw = new_state
@state = @cast(JSON.parse(JSON.stringify(@state_raw)))
@state_valid = true
if @state_raw.state_committed
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = null
commit_timer = null
else
if commit_needed_at <= Date.now()
state_commit(replace)
else
location_update(false)
if (not commit_scheduled_at) or (commit_needed_at < commit_scheduled_at)
console.log("ROUTER: Deferring commit by:", defer, "till", commit_needed_at) if @debug
@state_raw.state_committed = false
clearTimeout(commit_timer) if commit_timer
commit_scheduled_at = commit_needed_at
commit_timer = setTimeout((()=> state_commit(replace)), commit_scheduled_at - Date.now())
@onchange(@state_raw,previous_state) if @onchange?
state_get_as_state_description = (state)=>
last_committed_state = state
while last_committed_state.state_parent and ((not last_committed_state.session_id) or last_committed_state.session_id == @session_id) and ((session_data_saved.object.max_state_id or 0 ) < last_committed_state.state_id)
last_committed_state = last_committed_state.state_parent
console.log('ROUTER: Last shareable state:', last_committed_state) if @debug
buffer = state_diff_generate(state_permanent(last_committed_state), state_permanent(state))
exposed = ([component[1], pair[1]] for pair in state_diff_generate({}, state) when component = _.find @expose, (component)-> component[0] == pair[0])
buffer = (pair for pair in buffer when not _.find @expose, (component)-> component[0] == pair[0])
{ session_id: last_committed_state.session_id, state_id: last_committed_state.state_id, exposed: exposed, buffer: buffer, change: [] }
location_update = (new_history_entry)=>
url = state_description_to_url(state_get_as_state_description(@state_raw))
console.log("ROUTER: Updating location: state:", @state_raw, ' url:', url) if @debug
if new_history_entry
window.history.pushState(@state_raw,null,url)
else
window.history.replaceState(@state_raw,null,url)
@navigate = (search, options = {})->
pathname = window.location.pathname
console.log('ROUTER: Navigating to: pathname:', pathname, ' search:', search) if @debug
state_description = url_to_state_description(pathname, search)
console.log('ROUTER: New state description:', state_description) if @debug
if remote_state?
remote_state.unlink()
remote_state = null
if state_description.session_id == @session_id or state_description.state_id == "0"
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
else
@state_valid = false
remote_state = @seapig_client.slave('SeapigRouter::Session::'+state_description.session_id+'::State::'+state_description.state_id)
remote_state.onchange ()=>
return if not remote_state.valid
console.log("ROUTER: Received remote state", remote_state.object) if @debug
@state_raw = JSON.parse(JSON.stringify(remote_state.object))
@state_raw.state_committed = true
@state_raw.session_id = state_description.session_id
@state_raw.state_id = state_description.state_id
@state_raw.state_parent = undefined
state_set_from_state_description(state_description, (options.defer or 0), !options.replace)
remote_state.unlink()
remote_state = null
@volatile = (data...)->
if data.length == 1 and typeof data[0] == 'object'
for key, value of data[0]
@state["_"+key] = value
_.extend(@state_raw, _.pick(@state, (value,key)-> key.indexOf("_") == 0))
window.history.replaceState(@state_raw,null,window.location)
else
_.object(([key, @state["_"+key]] for key in data))
|
[
{
"context": ": this.req.session.user.id ).set\n password: inputs.password\n resetToken: ''\n resetExpires: null",
"end": 527,
"score": 0.9976928234100342,
"start": 512,
"tag": "PASSWORD",
"value": "inputs.password"
}
] | api/controllers/auth/set-password.coffee | nkofl/sails-1.0-template | 0 | module.exports =
friendlyName: 'Set new password'
description: 'Set a new password after recovery'
inputs:
password:
description: 'unencrypted password'
type: 'string'
required: true
exits:
success:
description: 'Your password has been updated.'
redirect:
description: 'Your password has been updated'
responseType: 'redirect'
fn: (inputs, exits) ->
try
updatedUser = await User.update( id: this.req.session.user.id ).set
password: inputs.password
resetToken: ''
resetExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Password updated'
exits.redirect '/'
catch err
if this.req.wantsJSON || this.req.isSocket
exits.error err
else
await sails.helpers.flash this.req, 'Password update failed', 3000, 'error'
exits.redirect '/' | 149783 | module.exports =
friendlyName: 'Set new password'
description: 'Set a new password after recovery'
inputs:
password:
description: 'unencrypted password'
type: 'string'
required: true
exits:
success:
description: 'Your password has been updated.'
redirect:
description: 'Your password has been updated'
responseType: 'redirect'
fn: (inputs, exits) ->
try
updatedUser = await User.update( id: this.req.session.user.id ).set
password: <PASSWORD>
resetToken: ''
resetExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Password updated'
exits.redirect '/'
catch err
if this.req.wantsJSON || this.req.isSocket
exits.error err
else
await sails.helpers.flash this.req, 'Password update failed', 3000, 'error'
exits.redirect '/' | true | module.exports =
friendlyName: 'Set new password'
description: 'Set a new password after recovery'
inputs:
password:
description: 'unencrypted password'
type: 'string'
required: true
exits:
success:
description: 'Your password has been updated.'
redirect:
description: 'Your password has been updated'
responseType: 'redirect'
fn: (inputs, exits) ->
try
updatedUser = await User.update( id: this.req.session.user.id ).set
password: PI:PASSWORD:<PASSWORD>END_PI
resetToken: ''
resetExpires: null
.fetch()
if updatedUser? && updatedUser.length > 0
this.req.session.user = updatedUser[0]
if this.req.wantsJSON || this.req.isSocket
exits.success()
else
await sails.helpers.flash this.req, 'Password updated'
exits.redirect '/'
catch err
if this.req.wantsJSON || this.req.isSocket
exits.error err
else
await sails.helpers.flash this.req, 'Password update failed', 3000, 'error'
exits.redirect '/' |
[
{
"context": "ubKey, used for pairing.\nAttestation =\n String: \"04c370d4013107a98dfef01d6db5bb3419deb9299535f0be47f05939a78b314a3c29b51fcaa9b3d46fa382c995456af50cd57fb017c0ce05e4a31864a79b8fbfd6\"\n\nAttestation.Bytes = parseInt(hex, 16) for hex i",
"end": 667,
"score": 0.9970107078552246,
"start... | app/src/dongle/dongle.coffee | doged/ledger-wallet-doged-chrome | 1 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmware =
V1_4_11: 0x0001040b0146
V1_4_12: 0x0001040c0146
V1_4_13: 0x0001040d0146
V1_0_0B: 0x20010000010f
# Ledger OS pubKey, used for pairing.
Attestation =
String: "04c370d4013107a98dfef01d6db5bb3419deb9299535f0be47f05939a78b314a3c29b51fcaa9b3d46fa382c995456af50cd57fb017c0ce05e4a31864a79b8fbfd6"
Attestation.Bytes = parseInt(hex, 16) for hex in Attestation.String.match(/\w\w/g)
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
Firmware: Firmware
Attestation: Attestation
BitIdRootPath: BitIdRootPath
###
Signals :
@emit connected
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
# @property
device_id: undefined
# @property [String]
state: States.UNDEFINED
# @property [Integer]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @property [BtChip]
_btchip: undefined
# @property [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs = []
# @private @property [String] pin used to unlock dongle.
_pin = undefined
constructor: (@device_id, card) ->
super
@_btchip = new BTChip(card)
@_recoverFirmwareVersion().then( =>
return @_recoverOperationMode().q()
).then( =>
# Set dongle state on failure.
return @getPublicAddress("0'/0/0").q()
).then( =>
# @todo Se connecter directement à la carte sans redemander le PIN
console.warn("Dongle is already unlock ! Case not handle => Pin Code Required.")
@_setState(States.LOCKED)
).done()
# Called when
disconnect: () -> @_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> @firmwareVersion.byteAt(1) + "." + @firmwareVersion.byteAt(2) + "." + @firmwareVersion.byteAt(3)
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @firmwareVersion
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [CompletionClosure]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, callback=undefined) ->
completion = new CompletionClosure(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
completion.success([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
@getRawFirmwareVersion(isInBootLoaderMode, yes).thenForward(completion)
else
if sw is 0x9000
completion.success([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
completion.success([0, (1 << 16) + (4 << 8) + (3)])
else
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, "Failed to get version"))
.fail (error) ->
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, error))
.done()
completion.readonly()
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Boolean]
isFirmwareUpdateAvailable: () -> @getFirmwareUpdater().isFirmwareUpdateAvailable(this)
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [CompletionClosure]
isCertified: (callback=undefined) ->
completion = new CompletionClosure(callback)
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
completion.success()
else
completion.failure()
.fail (err) =>
error = new ledger.StandardError(Errors.SignatureError, err)
completion.failure(error)
.done()
completion.readonly()
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getState: (callback=undefined) ->
completion = new CompletionClosure(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => completion.success(state)
else
completion.success(@state)
completion.readonly()
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [CompletionClosure]
unlockWithPinCode: (pin, callback=undefined) ->
throw new ledger.StandardError(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
completion = new CompletionClosure(callback)
_pin = pin
@_btchip.verifyPin_async(new ByteString(_pin, ASCII))
.then =>
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"01"+"01", HEX), [0x9000])
.then =>
if @firmwareVersion >= ledger.dongle.Firmware.V1_4_13
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"00"+"01", HEX), [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
completion.success()
.fail (err) =>
error = new ledger.StandardError(Errors.NotSupportedDongle, err)
completion.failure(error)
.done()
.fail (err) =>
error = new ledger.StandardError(Error.WrongPinCode, err)
if err.match(/6faa|63c0/)
@_setState(States.BLANK)
error.code = Error.DongleLocked
else
@_setState(States.ERROR)
if data.match(/63c\d/)
error.retryCount = parseInt(err.substr(-1))
completion.failure(error)
.done()
completion.readonly()
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [CompletionClosure]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [Object] options
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [CompletionClosure]
###
setup: (pin, options={}, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[options, callback] = [callback, options] if ! callback && typeof options == 'function'
[restoreSeed, keyMap] = [options.restoreSeed, options.keyMap]
completion = new CompletionClosure(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 32
e('Invalid seed :', restoreSeed)
return completion.failure().readonly()
l("Setup in progress ... please wait")
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
BTChip.VERSION_DOGECOIN_MAINNET,
BTChip.VERSION_DOGECOIN_P2SH_MAINNET,
new ByteString(pin, ASCII),
undefined,
keyMap || BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( ->
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
completion.success()
).fail( (err) =>
error = new ledger.StandardError(Errors.UnknowError, err)
completion.failure(error)
).done()
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED
completion = new CompletionClosure(callback)
@_btchip.getWalletPublicKey_async(path)
.then (result) =>
ledger.wallet.HDWallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> completion.success(result)
.fail (err) =>
if err.indexOf("6982") >= 0 # Pin required
@_setState(States.LOCKED)
else if err.indexOf("6985") >= 0 # Error ?
@_setState(States.BLANK)
else if err.indexOf("6faa") >= 0
@_setState(States.ERROR)
else
error = new ledger.StandardError(Errors.UnknowError, err)
_.defer -> completion.failure(error)
.done()
completion.readonly()
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [CompletionClosure]
signMessage: (message, path, callback=undefined) ->
completion = new CompletionClosure(callback)
@getPublicAddress(path)
.then( (address) =>
message = new ByteString(message, ASCII)
return @_btchip.signMessagePrepare_async(path, message)
).then( =>
return @_btchip.signMessageSign_async(new ByteString(_pin, ASCII))
).then( (sig) =>
signedMessage = @_convertMessageSignature(address.publicKey, message, sig.signature)
completion.success(signedMessage)
).fail( (error) ->
completion.failure(error)
).done()
completion.readonly()
###
@overload getBitIdAddress(subpath=undefined, callback=undefined)
@param [Integer, String] subpath
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload getBitIdAddress(callback)
@param [Function] callback
@return [CompletionClosure]
###
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
###
@overload signMessageWithBitId(derivationPath, message, callback=undefined)
@param [String] message
@param [String] message
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload signMessageWithBitId(derivationPath, message, subpath=undefined, callback=undefined)
@param [String] message
@param [String] message
@param [Integer, String] subpath Optional argument
@param [Function] callback Optional argument
@return [CompletionClosure]
@see signMessage && getBitIdAddress
###
signMessageWithBitId: (derivationPath, message, subpath=undefined, callback=undefined) ->
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@signMessage(derivationPath, message, path, callback)
# @param [Function] callback Optional argument
# @return [CompletionClosure]
randomBitIdAddress: (callback=undefined) ->
i = sjcl.random.randomWords(1) & 0xffff
@getBitIdAddress(i, callback)
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}") unless pubKey.match(/^[0-9A-Fa-f]{130}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then( (d) -> completion.success(d.toString()) )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid challenge resp : #{resp}") unless resp.match(/^[0-9A-Fa-f]{32}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then( () -> completion.success() )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
completion = new CompletionClosure(callback)
return completion.success(@_xpubs[path]).readonly() if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
completion.success(xpub)
completion.readonly()
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Integer] amount
@param [Integer] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && lockTime.toByteString(),
sighashType && sighashType.toByteString(),
authorization && new ByteString(authorization, HEX),
resumeData
).then (result) ->
switch typeof result
when 'object'
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
when 'string'
result = result.toString(HEX)
return result
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX))
_sendApdu: (cla, ins, p1, p2, opt1, opt2, opt3, wrapScript) -> @_btchip.card.sendApdu_async(cla, ins, p1, p2, opt1, opt2, opt3, wrapScript)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
@_btchip.getFirmwareVersion_async().then( (result) =>
firmwareVersion = result['firmwareVersion']
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 7)
l "Using old BIP32 derivation"
@_btchip.setDeprecatedBIP32Derivation()
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 8)
l "Using old setup keymap encoding"
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(result['compressedPublicKeys'])
@firmwareVersion = firmwareVersion
).fail( (error) =>
e("Firmware version not supported :", error)
)
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [@state, newState]
# Legacy
@emit 'connected' if newState == States.LOCKED && oldState == States.UNDEFINED
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_convertMessageSignature: (pubKey, message, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
| 133151 |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmware =
V1_4_11: 0x0001040b0146
V1_4_12: 0x0001040c0146
V1_4_13: 0x0001040d0146
V1_0_0B: 0x20010000010f
# Ledger OS pubKey, used for pairing.
Attestation =
String: "<KEY>"
Attestation.Bytes = parseInt(hex, 16) for hex in Attestation.String.match(/\w\w/g)
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
Firmware: Firmware
Attestation: Attestation
BitIdRootPath: BitIdRootPath
###
Signals :
@emit connected
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
# @property
device_id: undefined
# @property [String]
state: States.UNDEFINED
# @property [Integer]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @property [BtChip]
_btchip: undefined
# @property [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs = []
# @private @property [String] pin used to unlock dongle.
_pin = undefined
constructor: (@device_id, card) ->
super
@_btchip = new BTChip(card)
@_recoverFirmwareVersion().then( =>
return @_recoverOperationMode().q()
).then( =>
# Set dongle state on failure.
return @getPublicAddress("0'/0/0").q()
).then( =>
# @todo Se connecter directement à la carte sans redemander le PIN
console.warn("Dongle is already unlock ! Case not handle => Pin Code Required.")
@_setState(States.LOCKED)
).done()
# Called when
disconnect: () -> @_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> @firmwareVersion.byteAt(1) + "." + @firmwareVersion.byteAt(2) + "." + @firmwareVersion.byteAt(3)
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @firmwareVersion
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [CompletionClosure]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, callback=undefined) ->
completion = new CompletionClosure(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
completion.success([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
@getRawFirmwareVersion(isInBootLoaderMode, yes).thenForward(completion)
else
if sw is 0x9000
completion.success([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
completion.success([0, (1 << 16) + (4 << 8) + (3)])
else
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, "Failed to get version"))
.fail (error) ->
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, error))
.done()
completion.readonly()
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Boolean]
isFirmwareUpdateAvailable: () -> @getFirmwareUpdater().isFirmwareUpdateAvailable(this)
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [CompletionClosure]
isCertified: (callback=undefined) ->
completion = new CompletionClosure(callback)
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
completion.success()
else
completion.failure()
.fail (err) =>
error = new ledger.StandardError(Errors.SignatureError, err)
completion.failure(error)
.done()
completion.readonly()
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getState: (callback=undefined) ->
completion = new CompletionClosure(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => completion.success(state)
else
completion.success(@state)
completion.readonly()
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [CompletionClosure]
unlockWithPinCode: (pin, callback=undefined) ->
throw new ledger.StandardError(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
completion = new CompletionClosure(callback)
_pin = pin
@_btchip.verifyPin_async(new ByteString(_pin, ASCII))
.then =>
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"01"+"01", HEX), [0x9000])
.then =>
if @firmwareVersion >= ledger.dongle.Firmware.V1_4_13
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"00"+"01", HEX), [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
completion.success()
.fail (err) =>
error = new ledger.StandardError(Errors.NotSupportedDongle, err)
completion.failure(error)
.done()
.fail (err) =>
error = new ledger.StandardError(Error.WrongPinCode, err)
if err.match(/6faa|63c0/)
@_setState(States.BLANK)
error.code = Error.DongleLocked
else
@_setState(States.ERROR)
if data.match(/63c\d/)
error.retryCount = parseInt(err.substr(-1))
completion.failure(error)
.done()
completion.readonly()
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [CompletionClosure]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [Object] options
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [CompletionClosure]
###
setup: (pin, options={}, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[options, callback] = [callback, options] if ! callback && typeof options == 'function'
[restoreSeed, keyMap] = [options.restoreSeed, options.keyMap]
completion = new CompletionClosure(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 32
e('Invalid seed :', restoreSeed)
return completion.failure().readonly()
l("Setup in progress ... please wait")
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
BTChip.VERSION_DOGECOIN_MAINNET,
BTChip.VERSION_DOGECOIN_P2SH_MAINNET,
new ByteString(pin, ASCII),
undefined,
keyMap || BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( ->
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
completion.success()
).fail( (err) =>
error = new ledger.StandardError(Errors.UnknowError, err)
completion.failure(error)
).done()
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED
completion = new CompletionClosure(callback)
@_btchip.getWalletPublicKey_async(path)
.then (result) =>
ledger.wallet.HDWallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> completion.success(result)
.fail (err) =>
if err.indexOf("6982") >= 0 # Pin required
@_setState(States.LOCKED)
else if err.indexOf("6985") >= 0 # Error ?
@_setState(States.BLANK)
else if err.indexOf("6faa") >= 0
@_setState(States.ERROR)
else
error = new ledger.StandardError(Errors.UnknowError, err)
_.defer -> completion.failure(error)
.done()
completion.readonly()
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [CompletionClosure]
signMessage: (message, path, callback=undefined) ->
completion = new CompletionClosure(callback)
@getPublicAddress(path)
.then( (address) =>
message = new ByteString(message, ASCII)
return @_btchip.signMessagePrepare_async(path, message)
).then( =>
return @_btchip.signMessageSign_async(new ByteString(_pin, ASCII))
).then( (sig) =>
signedMessage = @_convertMessageSignature(address.publicKey, message, sig.signature)
completion.success(signedMessage)
).fail( (error) ->
completion.failure(error)
).done()
completion.readonly()
###
@overload getBitIdAddress(subpath=undefined, callback=undefined)
@param [Integer, String] subpath
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload getBitIdAddress(callback)
@param [Function] callback
@return [CompletionClosure]
###
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
###
@overload signMessageWithBitId(derivationPath, message, callback=undefined)
@param [String] message
@param [String] message
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload signMessageWithBitId(derivationPath, message, subpath=undefined, callback=undefined)
@param [String] message
@param [String] message
@param [Integer, String] subpath Optional argument
@param [Function] callback Optional argument
@return [CompletionClosure]
@see signMessage && getBitIdAddress
###
signMessageWithBitId: (derivationPath, message, subpath=undefined, callback=undefined) ->
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@signMessage(derivationPath, message, path, callback)
# @param [Function] callback Optional argument
# @return [CompletionClosure]
randomBitIdAddress: (callback=undefined) ->
i = sjcl.random.randomWords(1) & 0xffff
@getBitIdAddress(i, callback)
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}") unless pubKey.match(/^[0-9A-Fa-f]{130}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then( (d) -> completion.success(d.toString()) )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid challenge resp : #{resp}") unless resp.match(/^[0-9A-Fa-f]{32}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then( () -> completion.success() )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
completion = new CompletionClosure(callback)
return completion.success(@_xpubs[path]).readonly() if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
completion.success(xpub)
completion.readonly()
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Integer] amount
@param [Integer] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && lockTime.toByteString(),
sighashType && sighashType.toByteString(),
authorization && new ByteString(authorization, HEX),
resumeData
).then (result) ->
switch typeof result
when 'object'
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
when 'string'
result = result.toString(HEX)
return result
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX))
_sendApdu: (cla, ins, p1, p2, opt1, opt2, opt3, wrapScript) -> @_btchip.card.sendApdu_async(cla, ins, p1, p2, opt1, opt2, opt3, wrapScript)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
@_btchip.getFirmwareVersion_async().then( (result) =>
firmwareVersion = result['firmwareVersion']
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 7)
l "Using old BIP32 derivation"
@_btchip.setDeprecatedBIP32Derivation()
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 8)
l "Using old setup keymap encoding"
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(result['compressedPublicKeys'])
@firmwareVersion = firmwareVersion
).fail( (error) =>
e("Firmware version not supported :", error)
)
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [@state, newState]
# Legacy
@emit 'connected' if newState == States.LOCKED && oldState == States.UNDEFINED
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_convertMessageSignature: (pubKey, message, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
| true |
States =
# Dongle juste created, not initialized.
UNDEFINED: undefined
# PIN required.
LOCKED: 'locked'
# PIN has been verified.
UNLOCKED: 'unlocked'
# No seed present, dongle must be setup.
BLANK: 'blank'
# Dongle has been unplugged.
DISCONNECTED: 'disconnected'
# An error appended, user must unplug/replug dongle.
ERROR: 'error'
Firmware =
V1_4_11: 0x0001040b0146
V1_4_12: 0x0001040c0146
V1_4_13: 0x0001040d0146
V1_0_0B: 0x20010000010f
# Ledger OS pubKey, used for pairing.
Attestation =
String: "PI:KEY:<KEY>END_PI"
Attestation.Bytes = parseInt(hex, 16) for hex in Attestation.String.match(/\w\w/g)
# This path do not need a verified PIN to sign messages.
BitIdRootPath = "0'/0/0xb11e"
Errors = @ledger.errors
# Populate dongle namespace.
@ledger.dongle ?= {}
_.extend @ledger.dongle,
States: States
Firmware: Firmware
Attestation: Attestation
BitIdRootPath: BitIdRootPath
###
Signals :
@emit connected
@emit state:changed(States)
@emit state:locked
@emit state:unlocked
@emit state:blank
@emit state:disconnected
@emit state:error(args...)
###
class @ledger.dongle.Dongle extends EventEmitter
# @property
device_id: undefined
# @property [String]
state: States.UNDEFINED
# @property [Integer]
firmwareVersion: undefined
# @property [Integer]
operationMode: undefined
# @property [BtChip]
_btchip: undefined
# @property [Array<ledger.wallet.ExtendedPublicKey>]
_xpubs = []
# @private @property [String] pin used to unlock dongle.
_pin = undefined
constructor: (@device_id, card) ->
super
@_btchip = new BTChip(card)
@_recoverFirmwareVersion().then( =>
return @_recoverOperationMode().q()
).then( =>
# Set dongle state on failure.
return @getPublicAddress("0'/0/0").q()
).then( =>
# @todo Se connecter directement à la carte sans redemander le PIN
console.warn("Dongle is already unlock ! Case not handle => Pin Code Required.")
@_setState(States.LOCKED)
).done()
# Called when
disconnect: () -> @_setState(States.DISCONNECTED)
# @return [String] Firmware version, 1.0.0 for example.
getStringFirmwareVersion: -> @firmwareVersion.byteAt(1) + "." + @firmwareVersion.byteAt(2) + "." + @firmwareVersion.byteAt(3)
# @return [Integer] Firmware version, 0x20010000010f for example.
getIntFirmwareVersion: -> @firmwareVersion
###
Gets the raw version {ByteString} of the dongle.
@param [Boolean] isInBootLoaderMode Must be true if the current dongle is in bootloader mode.
@param [Boolean] forceBl Force the call in BootLoader mode
@param [Function] callback Called once the version is retrieved. The callback must be prototyped like size `(version, error) ->`
@return [CompletionClosure]
###
getRawFirmwareVersion: (isInBootLoaderMode, forceBl=no, callback=undefined) ->
completion = new CompletionClosure(callback)
apdu = new ByteString((if !isInBootLoaderMode and !forceBl then "E0C4000000" else "F001000000"), HEX)
@_sendApdu(apdu).then (result) =>
sw = @_btchip.card.SW
if !isInBootLoaderMode and !forceBl
if sw is 0x9000
completion.success([result.byteAt(1), (result.byteAt(2) << 16) + (result.byteAt(3) << 8) + result.byteAt(4)])
else
# Not initialized now - Retry
@getRawFirmwareVersion(isInBootLoaderMode, yes).thenForward(completion)
else
if sw is 0x9000
completion.success([0, (result.byteAt(5) << 16) + (result.byteAt(6) << 8) + result.byteAt(7)])
else if !isInBootLoaderMode and (sw is 0x6d00 or sw is 0x6e00)
# Unexpected - let's say it's 1.4.3
completion.success([0, (1 << 16) + (4 << 8) + (3)])
else
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, "Failed to get version"))
.fail (error) ->
completion.failure(new ledger.StandardError(ledger.errors.UnknowError, error))
.done()
completion.readonly()
# @return [ledger.fup.FirmwareUpdater]
getFirmwareUpdater: () -> ledger.fup.FirmwareUpdater.instance
# @return [Boolean]
isFirmwareUpdateAvailable: () -> @getFirmwareUpdater().isFirmwareUpdateAvailable(this)
# Verify that dongle firmware is "official".
# @param [Function] callback Optional argument
# @return [CompletionClosure]
isCertified: (callback=undefined) ->
completion = new CompletionClosure(callback)
randomValues = new Uint32Array(2)
crypto.getRandomValues(randomValues)
random = _.str.lpad(randomValues[0].toString(16), 8, '0') + _.str.lpad(randomValues[1].toString(16), 8, '0')
# 24.2. GET DEVICE ATTESTATION
@_sendApdu(new ByteString("E0"+"C2"+"00"+"00"+"08"+random, HEX), [0x9000])
.then (result) =>
attestation = result.toString(HEX)
dataToSign = attestation.substring(16,32) + random
dataSig = attestation.substring(32)
dataSigBytes = (parseInt(n,16) for n in dataSig.match(/\w\w/g))
sha = new JSUCrypt.hash.SHA256()
domain = JSUCrypt.ECFp.getEcDomainByName("secp256k1")
affinePoint = new JSUCrypt.ECFp.AffinePoint(Attestation.xPoint, Attestation.yPoint)
pubkey = new JSUCrypt.key.EcFpPublicKey(256, domain, affinePoint)
ecsig = new JSUCrypt.signature.ECDSA(sha)
ecsig.init(pubkey, JSUCrypt.signature.MODE_VERIFY)
if ecsig.verify(dataToSign, dataSigBytes)
completion.success()
else
completion.failure()
.fail (err) =>
error = new ledger.StandardError(Errors.SignatureError, err)
completion.failure(error)
.done()
completion.readonly()
# Return asynchronosly state. Wait until a state is set.
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getState: (callback=undefined) ->
completion = new CompletionClosure(callback)
if @state is States.UNDEFINED
@once 'state:changed', (e, state) => completion.success(state)
else
completion.success(@state)
completion.readonly()
# @param [String] pin ASCII encoded
# @param [Function] callback Optional argument
# @return [CompletionClosure]
unlockWithPinCode: (pin, callback=undefined) ->
throw new ledger.StandardError(Errors.DongleAlreadyUnlock) if @state isnt States.LOCKED
completion = new CompletionClosure(callback)
_pin = pin
@_btchip.verifyPin_async(new ByteString(_pin, ASCII))
.then =>
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"01"+"01", HEX), [0x9000])
.then =>
if @firmwareVersion >= ledger.dongle.Firmware.V1_4_13
# 19.7. SET OPERATION MODE
@_sendApdu(new ByteString("E0"+"26"+"01"+"00"+"01", HEX), [0x9000]).fail(=> e('Unlock FAIL', arguments)).done()
@_setState(States.UNLOCKED)
completion.success()
.fail (err) =>
error = new ledger.StandardError(Errors.NotSupportedDongle, err)
completion.failure(error)
.done()
.fail (err) =>
error = new ledger.StandardError(Error.WrongPinCode, err)
if err.match(/6faa|63c0/)
@_setState(States.BLANK)
error.code = Error.DongleLocked
else
@_setState(States.ERROR)
if data.match(/63c\d/)
error.retryCount = parseInt(err.substr(-1))
completion.failure(error)
.done()
completion.readonly()
###
@overload setup(pin, callback)
@param [String] pin
@param [Function] callback
@return [CompletionClosure]
@overload setup(pin, options={}, callback=undefined)
@param [String] pin
@param [Object] options
@options options [String] restoreSeed
@options options [ByteString] keyMap
@param [Function] callback
@return [CompletionClosure]
###
setup: (pin, options={}, callback=undefined) ->
Errors.throw(Errors.DongleNotBlank) if @state isnt States.BLANK
[options, callback] = [callback, options] if ! callback && typeof options == 'function'
[restoreSeed, keyMap] = [options.restoreSeed, options.keyMap]
completion = new CompletionClosure(callback)
# Validate seed
if restoreSeed?
bytesSeed = new ByteString(restoreSeed, HEX)
if bytesSeed.length != 32
e('Invalid seed :', restoreSeed)
return completion.failure().readonly()
l("Setup in progress ... please wait")
@_btchip.setupNew_async(
BTChip.MODE_WALLET,
BTChip.FEATURE_DETERMINISTIC_SIGNATURE | BTChip.FEATURE_NO_2FA_P2SH,
BTChip.VERSION_DOGECOIN_MAINNET,
BTChip.VERSION_DOGECOIN_P2SH_MAINNET,
new ByteString(pin, ASCII),
undefined,
keyMap || BTChip.QWERTY_KEYMAP_NEW,
restoreSeed?,
bytesSeed
).then( ->
if restoreSeed?
msg = "Seed restored, please reopen the extension"
else
msg = "Plug the dongle into a secure host to read the generated seed, then reopen the extension"
console.warn(msg)
@_setState(States.ERROR, msg)
completion.success()
).fail( (err) =>
error = new ledger.StandardError(Errors.UnknowError, err)
completion.failure(error)
).done()
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure]
getPublicAddress: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked, 'Cannot get a public while the key is not unlocked') if @state isnt States.UNLOCKED
completion = new CompletionClosure(callback)
@_btchip.getWalletPublicKey_async(path)
.then (result) =>
ledger.wallet.HDWallet.instance?.cache?.set [[path, result.bitcoinAddress.value]]
_.defer -> completion.success(result)
.fail (err) =>
if err.indexOf("6982") >= 0 # Pin required
@_setState(States.LOCKED)
else if err.indexOf("6985") >= 0 # Error ?
@_setState(States.BLANK)
else if err.indexOf("6faa") >= 0
@_setState(States.ERROR)
else
error = new ledger.StandardError(Errors.UnknowError, err)
_.defer -> completion.failure(error)
.done()
completion.readonly()
# @param [String] message
# @param [String] path Optional argument
# @param [Function] callback Optional argument
# @return [CompletionClosure]
signMessage: (message, path, callback=undefined) ->
completion = new CompletionClosure(callback)
@getPublicAddress(path)
.then( (address) =>
message = new ByteString(message, ASCII)
return @_btchip.signMessagePrepare_async(path, message)
).then( =>
return @_btchip.signMessageSign_async(new ByteString(_pin, ASCII))
).then( (sig) =>
signedMessage = @_convertMessageSignature(address.publicKey, message, sig.signature)
completion.success(signedMessage)
).fail( (error) ->
completion.failure(error)
).done()
completion.readonly()
###
@overload getBitIdAddress(subpath=undefined, callback=undefined)
@param [Integer, String] subpath
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload getBitIdAddress(callback)
@param [Function] callback
@return [CompletionClosure]
###
getBitIdAddress: (subpath=undefined, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state isnt States.UNLOCKED
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@getPublicAddress(path, callback)
###
@overload signMessageWithBitId(derivationPath, message, callback=undefined)
@param [String] message
@param [String] message
@param [Function] callback Optional argument
@return [CompletionClosure]
@overload signMessageWithBitId(derivationPath, message, subpath=undefined, callback=undefined)
@param [String] message
@param [String] message
@param [Integer, String] subpath Optional argument
@param [Function] callback Optional argument
@return [CompletionClosure]
@see signMessage && getBitIdAddress
###
signMessageWithBitId: (derivationPath, message, subpath=undefined, callback=undefined) ->
[subpath, callback] = [callback, subpath] if ! callback && typeof subpath == 'function'
path = ledger.dongle.BitIdRootPath
path += "/#{subpath}" if subpath?
@signMessage(derivationPath, message, path, callback)
# @param [Function] callback Optional argument
# @return [CompletionClosure]
randomBitIdAddress: (callback=undefined) ->
i = sjcl.random.randomWords(1) & 0xffff
@getBitIdAddress(i, callback)
# @param [String] pubKey public key, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve with a 32 bytes length pairing blob hex encoded.
initiateSecureScreen: (pubKey, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid pubKey : #{pubKey}") unless pubKey.match(/^[0-9A-Fa-f]{130}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"01"+"00"+"41"+pubKey, HEX), [0x9000])
.then( (d) -> completion.success(d.toString()) )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] resp challenge response, hex encoded.
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
confirmSecureScreen: (resp, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
Errors.throw(Errors.InvalidArgument, "Invalid challenge resp : #{resp}") unless resp.match(/^[0-9A-Fa-f]{32}$/)
completion = new CompletionClosure(callback)
# 19.3. SETUP SECURE SCREEN
@_sendApdu(new ByteString("E0"+"12"+"02"+"00"+"10"+resp, HEX), [0x9000])
.then( () -> completion.success() )
.fail( (error) -> completion.failure(error) )
completion.readonly()
# @param [String] path
# @param [Function] callback Optional argument
# @return [CompletionClosure] Resolve if pairing is successful.
getExtendedPublicKey: (path, callback=undefined) ->
Errors.throw(Errors.DongleLocked) if @state != States.UNLOCKED
completion = new CompletionClosure(callback)
return completion.success(@_xpubs[path]).readonly() if @_xpubs[path]?
xpub = new ledger.wallet.ExtendedPublicKey(@, path)
xpub.initialize () =>
@_xpubs[path] = xpub
completion.success(xpub)
completion.readonly()
###
@param [Array<Object>] inputs
@param [Array] associatedKeysets
@param changePath
@param [String] recipientAddress
@param [Integer] amount
@param [Integer] fee
@param [Integer] lockTime
@param [Integer] sighashType
@param [String] authorization hex encoded
@param [Object] resumeData
@return [Q.Promise] Resolve with resumeData
###
createPaymentTransaction: (inputs, associatedKeysets, changePath, recipientAddress, amount, fees, lockTime, sighashType, authorization, resumeData) ->
resumeData = _.clone(resumeData)
resumeData.scriptData = new ByteString(resumeData.scriptData, HEX)
resumeData.trustedInputs = (new ByteString(trustedInput, HEX) for trustedInput in resumeData.trustedInputs)
resumeData.publicKeys = (new ByteString(publicKey, HEX) for publicKey in resumeData.publicKeys)
@_btchip.createPaymentTransaction_async(
inputs, associatedKeysets, changePath,
new ByteString(recipientAddress, ASCII),
amount.toByteString(),
fees.toByteString(),
lockTime && lockTime.toByteString(),
sighashType && sighashType.toByteString(),
authorization && new ByteString(authorization, HEX),
resumeData
).then (result) ->
switch typeof result
when 'object'
result.scriptData = result.scriptData.toString(HEX)
result.trustedInputs = (trustedInput.toString(HEX) for trustedInput in result.trustedInputs)
result.publicKeys = (publicKey.toString(HEX) for publicKey in result.publicKeys)
result.authorizationPaired = result.authorizationPaired.toString(HEX) if result.authorizationPaired?
result.authorizationReference = result.authorizationReference.toString(HEX) if result.authorizationReference?
when 'string'
result = result.toString(HEX)
return result
###
@param [String] input hex encoded
@return [Object]
[Array<Byte>] version length is 4
[Array<Object>] inputs
[Array<Byte>] prevout length is 36
[Array<Byte>] script var length
[Array<Byte>] sequence length is 4
[Array<Object>] outputs
[Array<Byte>] amount length is 4
[Array<Byte>] script var length
[Array<Byte>] locktime length is 4
###
splitTransaction: (input) ->
@_btchip.splitTransaction(new ByteString(input.raw, HEX))
_sendApdu: (cla, ins, p1, p2, opt1, opt2, opt3, wrapScript) -> @_btchip.card.sendApdu_async(cla, ins, p1, p2, opt1, opt2, opt3, wrapScript)
# @return [Q.Promise] Must be done
_recoverFirmwareVersion: ->
@_btchip.getFirmwareVersion_async().then( (result) =>
firmwareVersion = result['firmwareVersion']
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 7)
l "Using old BIP32 derivation"
@_btchip.setDeprecatedBIP32Derivation()
if (firmwareVersion.byteAt(1) == 0x01) && (firmwareVersion.byteAt(2) == 0x04) && (firmwareVersion.byteAt(3) < 8)
l "Using old setup keymap encoding"
@_btchip.setDeprecatedSetupKeymap()
@_btchip.setCompressedPublicKeys(result['compressedPublicKeys'])
@firmwareVersion = firmwareVersion
).fail( (error) =>
e("Firmware version not supported :", error)
)
# @return [Q.Promise] Must be done
_recoverOperationMode: ->
@_btchip.getOperationMode_async().then (mode) =>
@operationMode = mode
_setState: (newState, args...) ->
[@state, oldState] = [@state, newState]
# Legacy
@emit 'connected' if newState == States.LOCKED && oldState == States.UNDEFINED
@emit "state:#{@state}", @state, args...
@emit 'state:changed', @state
_convertMessageSignature: (pubKey, message, signature) ->
bitcoin = new BitcoinExternal()
hash = bitcoin.getSignedMessageHash(message)
pubKey = bitcoin.compressPublicKey(pubKey)
for i in [0...4]
recoveredKey = bitcoin.recoverPublicKey(signature, hash, i)
recoveredKey = bitcoin.compressPublicKey(recoveredKey)
if recoveredKey.equals(pubKey)
splitSignature = bitcoin.splitAsn1Signature(signature)
sig = new ByteString(Convert.toHexByte(i + 27 + 4), HEX).concat(splitSignature[0]).concat(splitSignature[1])
break
throw "Recovery failed" if ! sig?
return @_convertBase64(sig)
_convertBase64: (data) ->
codes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
output = ""
leven = 3 * (Math.floor(data.length / 3))
offset = 0
for i in [0...leven] when i % 3 == 0
output += codes.charAt((data.byteAt(offset) >> 2) & 0x3f)
output += codes.charAt((((data.byteAt(offset) & 3) << 4) + (data.byteAt(offset + 1) >> 4)) & 0x3f)
output += codes.charAt((((data.byteAt(offset + 1) & 0x0f) << 2) + (data.byteAt(offset + 2) >> 6)) & 0x3f)
output += codes.charAt(data.byteAt(offset + 2) & 0x3f)
offset += 3
if i < data.length
a = data.byteAt(offset)
b = if (i + 1) < data.length then data.byteAt(offset + 1) else 0
output += codes.charAt((a >> 2) & 0x3f)
output += codes.charAt((((a & 3) << 4) + (b >> 4)) & 0x3f)
output += if (i + 1) < data.length then codes.charAt((((b & 0x0f) << 2)) & 0x3f) else '='
output += '='
return output
|
[
{
"context": "ain'\n\n index: (params) ->\n @set 'firstName', 'Bruce'\n @set 'lastName', 'Wayne'\n\n @accessor 'fullN",
"end": 176,
"score": 0.9996806979179382,
"start": 171,
"tag": "NAME",
"value": "Bruce"
},
{
"context": " @set 'firstName', 'Bruce'\n @set 'lastName', 'W... | lib/templates/batman/main_controller.coffee | nickjs/batman-rails | 1 | class <%= js_application_name %>.MainController extends <%= js_application_name %>.ApplicationController
routingKey: 'main'
index: (params) ->
@set 'firstName', 'Bruce'
@set 'lastName', 'Wayne'
@accessor 'fullName', ->
"#{@get('firstName')} #{@get('lastName')}"
| 2756 | class <%= js_application_name %>.MainController extends <%= js_application_name %>.ApplicationController
routingKey: 'main'
index: (params) ->
@set 'firstName', '<NAME>'
@set 'lastName', '<NAME>'
@accessor 'fullName', ->
"#{@get('firstName')} #{@get('lastName')}"
| true | class <%= js_application_name %>.MainController extends <%= js_application_name %>.ApplicationController
routingKey: 'main'
index: (params) ->
@set 'firstName', 'PI:NAME:<NAME>END_PI'
@set 'lastName', 'PI:NAME:<NAME>END_PI'
@accessor 'fullName', ->
"#{@get('firstName')} #{@get('lastName')}"
|
[
{
"context": "elta(0, [\n new InsertOp(\"Hello\", {authorId: 'Timon'})\n new InsertOp(\"World\", {authorId: 'Pumba'",
"end": 1006,
"score": 0.8716175556182861,
"start": 1001,
"tag": "USERNAME",
"value": "Timon"
},
{
"context": "'Timon'})\n new InsertOp(\"World\", {auth... | tests/split.coffee | tandem/tandem-core | 2 | # Copyright (c) 2012, Salesforce.com, Inc. 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 Salesforce.com nor the names of
# its contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
expect = require('chai').expect
Tandem = require('../index')
Delta = Tandem.Delta
InsertOp = Tandem.InsertOp
RetainOp = Tandem.RetainOp
describe('delta', ->
describe('split', ->
delta = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
it('split without op splitting', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(5)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 1', ->
expectedLeft = new Delta(0, [
new InsertOp("Hell", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("o", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(4)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 2', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("W", {authorId: 'Pumba'})
])
expectedRight = new Delta(0, [
new InsertOp("orld", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(6)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at 0', ->
expectedLeft = new Delta(0, [])
expectedRight = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(0)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at boundary', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
expectedRight = new Delta(0, [])
[leftDelta, rightDelta] = delta.split(10)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
)
)
| 183116 | # Copyright (c) 2012, Salesforce.com, Inc. 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 Salesforce.com nor the names of
# its contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
expect = require('chai').expect
Tandem = require('../index')
Delta = Tandem.Delta
InsertOp = Tandem.InsertOp
RetainOp = Tandem.RetainOp
describe('delta', ->
describe('split', ->
delta = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
it('split without op splitting', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(5)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 1', ->
expectedLeft = new Delta(0, [
new InsertOp("Hell", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("o", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(4)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 2', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: '<NAME>'})
new InsertOp("W", {authorId: '<NAME>umba'})
])
expectedRight = new Delta(0, [
new InsertOp("orld", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(6)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at 0', ->
expectedLeft = new Delta(0, [])
expectedRight = new Delta(0, [
new InsertOp("Hello", {authorId: '<NAME>'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(0)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at boundary', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: '<NAME>'})
new InsertOp("World", {authorId: '<NAME>umba'})
])
expectedRight = new Delta(0, [])
[leftDelta, rightDelta] = delta.split(10)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
)
)
| true | # Copyright (c) 2012, Salesforce.com, Inc. 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 Salesforce.com nor the names of
# its contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
expect = require('chai').expect
Tandem = require('../index')
Delta = Tandem.Delta
InsertOp = Tandem.InsertOp
RetainOp = Tandem.RetainOp
describe('delta', ->
describe('split', ->
delta = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
it('split without op splitting', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(5)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 1', ->
expectedLeft = new Delta(0, [
new InsertOp("Hell", {authorId: 'Timon'})
])
expectedRight = new Delta(0, [
new InsertOp("o", {authorId: 'Timon'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(4)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split with op splitting 2', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'PI:NAME:<NAME>END_PI'})
new InsertOp("W", {authorId: 'PI:NAME:<NAME>END_PIumba'})
])
expectedRight = new Delta(0, [
new InsertOp("orld", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(6)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at 0', ->
expectedLeft = new Delta(0, [])
expectedRight = new Delta(0, [
new InsertOp("Hello", {authorId: 'PI:NAME:<NAME>END_PI'})
new InsertOp("World", {authorId: 'Pumba'})
])
[leftDelta, rightDelta] = delta.split(0)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
it('split at boundary', ->
expectedLeft = new Delta(0, [
new InsertOp("Hello", {authorId: 'PI:NAME:<NAME>END_PI'})
new InsertOp("World", {authorId: 'PI:NAME:<NAME>END_PIumba'})
])
expectedRight = new Delta(0, [])
[leftDelta, rightDelta] = delta.split(10)
expect(leftDelta).to.deep.equal(expectedLeft)
expect(rightDelta).to.deep.equal(expectedRight)
)
)
)
|
[
{
"context": "\n bhec:\n name: \"BHEC\"\n requestKey: \"bhec\"\n showCRef: true\n troubleStatusKey: \"bh",
"end": 2303,
"score": 0.923973798751831,
"start": 2300,
"tag": "KEY",
"value": "hec"
},
{
"context": " ucaas:\n name: \"UCaaS\"\n requestKey: \... | ClientApp/app/scripts/services/services/service_constant.coffee | nttcom/apigw-sample-app | 1 | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceConstant
# @description
# # serviceConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceConstant',
uno:
name: "UNO"
requestKey: "uno"
showVpnGroupId: true
excludes: [
"Arcstar Universal One モバイル"
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-mobile":
name: "UNOモバイル"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"global-m2m":
name: "GlobalM2M"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-virtual":
name: "UNO Virtual"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
cloudn:
name: "Cloudn"
requestKey: "cloudn"
bhec:
name: "BHEC"
requestKey: "bhec"
showCRef: true
troubleStatusKey: "bhec"
ucaas:
name: "UCaaS"
requestKey: "ucaas"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "ucaas"
"sip-trunking":
name: "SIP Trunking"
requestKey: "sip-trunking"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "ucaas"
"050plusbiz":
name: "050 plus for Biz"
requestKey: "050plusbiz"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"ip-voice":
name: "IP Voice"
requestKey: "ip-voice"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"smart-pbx":
name: "Smart PBX"
requestKey: "smart-pbx"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
accs:
name: "Contact Center"
requestKey: "accs"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
bizmail:
name: "Bizメール"
requestKey: "bizmail"
"bdp-e":
name: "Bizデスクトップ"
requestKey: "bdp-e"
orderTypeKey: "bdp-e"
orderStatusKey: "bdp-e"
troubleStatusKey: "bdp-e"
mss:
name: "WideAngle"
requestKey: "mss"
orderTypeKey: "bdp-e"
orderStatusKey: "mss"
troubleStatusKey: "bdp-e"
gmone:
name: "GMOne"
requestKey: "gmone"
| 111027 | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceConstant
# @description
# # serviceConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceConstant',
uno:
name: "UNO"
requestKey: "uno"
showVpnGroupId: true
excludes: [
"Arcstar Universal One モバイル"
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-mobile":
name: "UNOモバイル"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"global-m2m":
name: "GlobalM2M"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-virtual":
name: "UNO Virtual"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
cloudn:
name: "Cloudn"
requestKey: "cloudn"
bhec:
name: "BHEC"
requestKey: "b<KEY>"
showCRef: true
troubleStatusKey: "bhec"
ucaas:
name: "UCaaS"
requestKey: "uc<KEY>"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "uc<KEY>as"
"sip-trunking":
name: "SIP Trunking"
requestKey: "<KEY>"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "ucaas"
"050plusbiz":
name: "050 plus for Biz"
requestKey: "<KEY>"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"ip-voice":
name: "IP Voice"
requestKey: "ip-voice"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"smart-pbx":
name: "Smart PBX"
requestKey: "smart-<KEY>"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
accs:
name: "Contact Center"
requestKey: "accs"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
bizmail:
name: "Bizメール"
requestKey: "bizmail"
"bdp-e":
name: "Bizデスクトップ"
requestKey: "bd<KEY>"
orderTypeKey: "bdp-<KEY>"
orderStatusKey: "bdp-e"
troubleStatusKey: "bdp-<KEY>"
mss:
name: "<NAME>"
requestKey: "<KEY>"
orderTypeKey: "<KEY>"
orderStatusKey: "<KEY>"
troubleStatusKey: "<KEY>"
gmone:
name: "<NAME>"
requestKey: "<KEY>"
| true | ###
Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You 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.
###
'use strict'
###*
# @ngdoc service
# @name nttcomApiGatewayWebappApp.serviceConstant
# @description
# # serviceConstant
# Constant in the nttcomApiGatewayWebappApp.
###
angular.module 'nttcomApiGatewayWebappApp'
.constant 'serviceConstant',
uno:
name: "UNO"
requestKey: "uno"
showVpnGroupId: true
excludes: [
"Arcstar Universal One モバイル"
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-mobile":
name: "UNOモバイル"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"global-m2m":
name: "GlobalM2M"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One モバイル グローバルM2M"
"Global M2M"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
"uno-virtual":
name: "UNO Virtual"
requestKey: "uno"
showVpnGroupId: true
includes: [
"Arcstar Universal One Virtual"
]
orderTypeKey: "uno"
orderStatusKey: "uno"
troubleStatusKey: "uno"
cloudn:
name: "Cloudn"
requestKey: "cloudn"
bhec:
name: "BHEC"
requestKey: "bPI:KEY:<KEY>END_PI"
showCRef: true
troubleStatusKey: "bhec"
ucaas:
name: "UCaaS"
requestKey: "ucPI:KEY:<KEY>END_PI"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "ucPI:KEY:<KEY>END_PIas"
"sip-trunking":
name: "SIP Trunking"
requestKey: "PI:KEY:<KEY>END_PI"
orderTypeKey: "ucaas"
orderStatusKey: "ucaas"
troubleStatusKey: "ucaas"
"050plusbiz":
name: "050 plus for Biz"
requestKey: "PI:KEY:<KEY>END_PI"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"ip-voice":
name: "IP Voice"
requestKey: "ip-voice"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
"smart-pbx":
name: "Smart PBX"
requestKey: "smart-PI:KEY:<KEY>END_PI"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
accs:
name: "Contact Center"
requestKey: "accs"
orderTypeKey: "voice"
orderStatusKey: "voice"
troubleStatusKey: "voice"
bizmail:
name: "Bizメール"
requestKey: "bizmail"
"bdp-e":
name: "Bizデスクトップ"
requestKey: "bdPI:KEY:<KEY>END_PI"
orderTypeKey: "bdp-PI:KEY:<KEY>END_PI"
orderStatusKey: "bdp-e"
troubleStatusKey: "bdp-PI:KEY:<KEY>END_PI"
mss:
name: "PI:NAME:<NAME>END_PI"
requestKey: "PI:KEY:<KEY>END_PI"
orderTypeKey: "PI:KEY:<KEY>END_PI"
orderStatusKey: "PI:KEY:<KEY>END_PI"
troubleStatusKey: "PI:KEY:<KEY>END_PI"
gmone:
name: "PI:NAME:<NAME>END_PI"
requestKey: "PI:KEY:<KEY>END_PI"
|
[
{
"context": "####################################\n#\n#Created by Markus on 26/10/2015.\n#\n################################",
"end": 76,
"score": 0.998380720615387,
"start": 70,
"tag": "NAME",
"value": "Markus"
}
] | server/3_database/document.coffee | agottschalk10/worklearn | 0 | #######################################################
#
#Created by Markus on 26/10/2015.
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document)->
document["created"] = new Date()
document["modified"] = new Date()
document["loaded"] = true
if not ("owner_id" of document)
document["owner_id"] = Meteor.userId()
if not ("visible_to" of document)
document["visible_to"] = "owner"
if not ("group" of document)
document["group"] = ""
id = collection.insert document
return id
#######################################################
@find_documents_paged_unprotected = (collection, filter, mod, parameter) ->
parameter.size = if parameter.size > 100 then 100 else parameter.size
if parameter.query
filter["$text"] =
$search: parameter.query
if not mod.fields
mod.fields = {}
mod.fields.score = {$meta: "textScore"}
mod.limit = parameter.size
mod.skip = parameter.size*parameter.page
if parameter.query
mod.sort =
score:
$meta: "textScore"
crs = collection.find filter, mod
return crs
###############################################
@find_document = (collection, item_id, owner = true) ->
check item_id, String
user = Meteor.user()
if not user
throw new Meteor.Error("Not permitted.")
item = collection.findOne item_id
if not item
throw new Meteor.Error("Not permitted.")
if owner
if item.owner_id != user._id
throw new Meteor.Error("Not permitted.")
return item
#######################################################
@filter_visible_documents = (user_id, restrict={}) ->
filter = []
roles = ["all"]
if restrict.owner_id
if not user_id
msg = "user_id undefined! If restrict variable contains owner_id user_id must be defined."
throw new Meteor.Error msg
if restrict.owner_id == user_id
owner = true
if user_id
# find all user roles
roles.push "anonymous"
user = Meteor.users.findOne user_id
roles.push user.roles ...
if owner
roles.push 'owner'
# adding a filter for all elements our current role allows us to see
filter =
visible_to:
$in: roles
for k,v of restrict
filter[k] = v
if not owner
filter["deleted"] =
$ne:
true
if owner
filter["owner_id"] = user_id
return filter
#######################################################
@action_permitted = (permission, action) ->
if permission[action]!=true
return false
return true
#######################################################
@is_owner = (collection, id, user_id) ->
if not collection
throw new Meteor.Error('Collection not found:' + collection)
item = collection.findOne(id)
if not item
throw new Meteor.Error('Not permitted.')
if not item.owner_id
return false
if item.owner_id == user_id
return true
return false
#######################################################
@deny_action = (action, collection, item_id, field) ->
if not collection
throw new Meteor.Error "Collection undefined."
if not field
throw new Meteor.Error "Field undefined."
if not item_id
throw new Meteor.Error "Item_id undefined."
check item_id, String
check action, String
check field, String
roles = ['all']
user = Meteor.user()
if user
roles.push user.roles ...
roles.push 'anonymous'
if is_owner collection, item_id, user._id
roles.push 'owner'
filter =
role:
$in: roles
field: field
collection_name: collection._name
permissions = Permissions.find(filter)
if permissions.count() == 0
throw new Meteor.Error action + ' not permitted: ' + field
for permission in permissions.fetch()
if action_permitted permission, action
return false
throw new Meteor.Error action + ' not permitted: ' + field
| 119125 | #######################################################
#
#Created by <NAME> on 26/10/2015.
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document)->
document["created"] = new Date()
document["modified"] = new Date()
document["loaded"] = true
if not ("owner_id" of document)
document["owner_id"] = Meteor.userId()
if not ("visible_to" of document)
document["visible_to"] = "owner"
if not ("group" of document)
document["group"] = ""
id = collection.insert document
return id
#######################################################
@find_documents_paged_unprotected = (collection, filter, mod, parameter) ->
parameter.size = if parameter.size > 100 then 100 else parameter.size
if parameter.query
filter["$text"] =
$search: parameter.query
if not mod.fields
mod.fields = {}
mod.fields.score = {$meta: "textScore"}
mod.limit = parameter.size
mod.skip = parameter.size*parameter.page
if parameter.query
mod.sort =
score:
$meta: "textScore"
crs = collection.find filter, mod
return crs
###############################################
@find_document = (collection, item_id, owner = true) ->
check item_id, String
user = Meteor.user()
if not user
throw new Meteor.Error("Not permitted.")
item = collection.findOne item_id
if not item
throw new Meteor.Error("Not permitted.")
if owner
if item.owner_id != user._id
throw new Meteor.Error("Not permitted.")
return item
#######################################################
@filter_visible_documents = (user_id, restrict={}) ->
filter = []
roles = ["all"]
if restrict.owner_id
if not user_id
msg = "user_id undefined! If restrict variable contains owner_id user_id must be defined."
throw new Meteor.Error msg
if restrict.owner_id == user_id
owner = true
if user_id
# find all user roles
roles.push "anonymous"
user = Meteor.users.findOne user_id
roles.push user.roles ...
if owner
roles.push 'owner'
# adding a filter for all elements our current role allows us to see
filter =
visible_to:
$in: roles
for k,v of restrict
filter[k] = v
if not owner
filter["deleted"] =
$ne:
true
if owner
filter["owner_id"] = user_id
return filter
#######################################################
@action_permitted = (permission, action) ->
if permission[action]!=true
return false
return true
#######################################################
@is_owner = (collection, id, user_id) ->
if not collection
throw new Meteor.Error('Collection not found:' + collection)
item = collection.findOne(id)
if not item
throw new Meteor.Error('Not permitted.')
if not item.owner_id
return false
if item.owner_id == user_id
return true
return false
#######################################################
@deny_action = (action, collection, item_id, field) ->
if not collection
throw new Meteor.Error "Collection undefined."
if not field
throw new Meteor.Error "Field undefined."
if not item_id
throw new Meteor.Error "Item_id undefined."
check item_id, String
check action, String
check field, String
roles = ['all']
user = Meteor.user()
if user
roles.push user.roles ...
roles.push 'anonymous'
if is_owner collection, item_id, user._id
roles.push 'owner'
filter =
role:
$in: roles
field: field
collection_name: collection._name
permissions = Permissions.find(filter)
if permissions.count() == 0
throw new Meteor.Error action + ' not permitted: ' + field
for permission in permissions.fetch()
if action_permitted permission, action
return false
throw new Meteor.Error action + ' not permitted: ' + field
| true | #######################################################
#
#Created by PI:NAME:<NAME>END_PI on 26/10/2015.
#
#######################################################
#######################################################
@store_document_unprotected = (collection, document)->
document["created"] = new Date()
document["modified"] = new Date()
document["loaded"] = true
if not ("owner_id" of document)
document["owner_id"] = Meteor.userId()
if not ("visible_to" of document)
document["visible_to"] = "owner"
if not ("group" of document)
document["group"] = ""
id = collection.insert document
return id
#######################################################
@find_documents_paged_unprotected = (collection, filter, mod, parameter) ->
parameter.size = if parameter.size > 100 then 100 else parameter.size
if parameter.query
filter["$text"] =
$search: parameter.query
if not mod.fields
mod.fields = {}
mod.fields.score = {$meta: "textScore"}
mod.limit = parameter.size
mod.skip = parameter.size*parameter.page
if parameter.query
mod.sort =
score:
$meta: "textScore"
crs = collection.find filter, mod
return crs
###############################################
@find_document = (collection, item_id, owner = true) ->
check item_id, String
user = Meteor.user()
if not user
throw new Meteor.Error("Not permitted.")
item = collection.findOne item_id
if not item
throw new Meteor.Error("Not permitted.")
if owner
if item.owner_id != user._id
throw new Meteor.Error("Not permitted.")
return item
#######################################################
@filter_visible_documents = (user_id, restrict={}) ->
filter = []
roles = ["all"]
if restrict.owner_id
if not user_id
msg = "user_id undefined! If restrict variable contains owner_id user_id must be defined."
throw new Meteor.Error msg
if restrict.owner_id == user_id
owner = true
if user_id
# find all user roles
roles.push "anonymous"
user = Meteor.users.findOne user_id
roles.push user.roles ...
if owner
roles.push 'owner'
# adding a filter for all elements our current role allows us to see
filter =
visible_to:
$in: roles
for k,v of restrict
filter[k] = v
if not owner
filter["deleted"] =
$ne:
true
if owner
filter["owner_id"] = user_id
return filter
#######################################################
@action_permitted = (permission, action) ->
if permission[action]!=true
return false
return true
#######################################################
@is_owner = (collection, id, user_id) ->
if not collection
throw new Meteor.Error('Collection not found:' + collection)
item = collection.findOne(id)
if not item
throw new Meteor.Error('Not permitted.')
if not item.owner_id
return false
if item.owner_id == user_id
return true
return false
#######################################################
@deny_action = (action, collection, item_id, field) ->
if not collection
throw new Meteor.Error "Collection undefined."
if not field
throw new Meteor.Error "Field undefined."
if not item_id
throw new Meteor.Error "Item_id undefined."
check item_id, String
check action, String
check field, String
roles = ['all']
user = Meteor.user()
if user
roles.push user.roles ...
roles.push 'anonymous'
if is_owner collection, item_id, user._id
roles.push 'owner'
filter =
role:
$in: roles
field: field
collection_name: collection._name
permissions = Permissions.find(filter)
if permissions.count() == 0
throw new Meteor.Error action + ' not permitted: ' + field
for permission in permissions.fetch()
if action_permitted permission, action
return false
throw new Meteor.Error action + ' not permitted: ' + field
|
[
{
"context": "{me} = require 'lib/auth'\n\ngplusClientID = \"800329290710-j9sivplv2gpcdgkrsis9rff3o",
"end": 32,
"score": 0.553384006023407,
"start": 28,
"tag": "KEY",
"value": "plus"
},
{
"context": "{me} = require 'lib/auth'\n\ngplusClientID = \"800329290710-j9sivplv2gpcdgkrsis9rff... | app/lib/Router.coffee | cochee/codecombat | 0 | {me} = require 'lib/auth'
gplusClientID = "800329290710-j9sivplv2gpcdgkrsis9rff3o417mlfa.apps.googleusercontent.com"
module.exports = class CocoRouter extends Backbone.Router
subscribe: ->
Backbone.Mediator.subscribe 'gapi-loaded', @onGPlusAPILoaded, @
Backbone.Mediator.subscribe 'router:navigate', @onNavigate, @
routes:
# every abnormal view gets listed here
'': 'home'
'preview': 'home'
'beta': 'home'
# editor views tend to have the same general structure
'editor/:model(/:slug_or_id)(/:subview)': 'editorModelView'
# db and file urls call the server directly
'db/*path': 'routeToServer'
'file/*path': 'routeToServer'
# most go through here
'*name': 'general'
home: -> @openRoute('home')
general: (name) ->
@openRoute(name)
editorModelView: (modelName, slugOrId, subview) ->
modulePrefix = "views/editor/#{modelName}/"
suffix = subview or (if slugOrId then 'edit' else 'home')
ViewClass = @tryToLoadModule(modulePrefix + suffix)
unless ViewClass
#console.log('could not hack it', modulePrefix + suffix)
args = (a for a in arguments when a)
args.splice(0, 0, 'editor')
return @openRoute(args.join('/'))
view = new ViewClass({}, slugOrId)
view.render()
if view then @openView(view) else @showNotFound()
cache: {}
openRoute: (route) ->
route = route.split('?')[0]
route = route.split('#')[0]
view = @getViewFromCache(route)
@openView(view)
openView: (view) ->
@closeCurrentView()
$('#page-container').empty().append view.el
window.currentView = view
@activateTab()
@renderLoginButtons()
window.scrollTo(0, view.scrollY) if view.scrollY?
view.afterInsert()
view.didReappear() if view.fromCache
onGPlusAPILoaded: =>
@renderLoginButtons()
renderLoginButtons: ->
$('.share-buttons, .partner-badges').addClass('fade-in').delay(10000).removeClass('fade-in', 5000)
setTimeout(FB.XFBML.parse, 10) if FB? # Handles FB login and Like
twttr?.widgets?.load()
return unless gapi?.plusone?
gapi.plusone.go() # Handles +1 button
for gplusButton in $('.gplus-login-button')
params = {
callback:"signinCallback",
clientid:gplusClientID,
cookiepolicy:"single_host_origin",
scope:"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
size:"medium",
}
if gapi.signin
gapi.signin.render(gplusButton, params)
else
console.warn "Didn't have gapi.signin to render G+ login button. (DoNotTrackMe extension?)"
getViewFromCache: (route) ->
if route of @cache
@cache[route].fromCache = true
return @cache[route]
view = @getView(route)
@cache[route] = view unless view and view.cache is false
return view
getView: (route, suffix='_view') ->
# iteratively breaks down the url pieces looking for the view
# passing the broken off pieces as args. This way views like "resource/14394893"
# will get passed to the resource view with arg '14394893'
pieces = _.string.words(route, '/')
split = Math.max(1, pieces.length-1)
while split > -1
sub_route = _.string.join('/', pieces[0..split]...)
path = "views/#{sub_route}#{suffix}"
ViewClass = @tryToLoadModule(path)
break if ViewClass
split -= 1
return @showNotFound() if not ViewClass
args = pieces[split+1..]
view = new ViewClass({}, args...) # options, then any path fragment args
view.render()
tryToLoadModule: (path) ->
try
return require(path)
catch error
if error.toString().search('Cannot find module "' + path + '" from') is -1
throw error
showNotFound: ->
NotFoundView = require('views/not_found')
view = new NotFoundView()
view.render()
closeCurrentView: ->
window.currentModal?.hide()
return unless window.currentView?
if window.currentView.cache
window.currentView.scrollY = window.scrollY
window.currentView.willDisappear()
else
window.currentView.destroy()
activateTab: ->
base = _.string.words(document.location.pathname[1..], '/')[0]
$("ul.nav li.#{base}").addClass('active')
initialize: ->
@cache = {}
# http://nerds.airbnb.com/how-to-add-google-analytics-page-tracking-to-57536
@bind 'route', @_trackPageView
_trackPageView: ->
window.tracker?.trackPageView()
onNavigate: (e) ->
manualView = e.view or e.viewClass
@navigate e.route, {trigger:not manualView}
return unless manualView
if e.viewClass
args = e.viewArgs or []
view = new e.viewClass(args...)
view.render()
@openView view
else
@openView e.view
routeToServer: (e) ->
window.location.href = window.location.href
| 41991 | {me} = require 'lib/auth'
g<KEY>ClientID = "<KEY>"
module.exports = class CocoRouter extends Backbone.Router
subscribe: ->
Backbone.Mediator.subscribe 'gapi-loaded', @onGPlusAPILoaded, @
Backbone.Mediator.subscribe 'router:navigate', @onNavigate, @
routes:
# every abnormal view gets listed here
'': 'home'
'preview': 'home'
'beta': 'home'
# editor views tend to have the same general structure
'editor/:model(/:slug_or_id)(/:subview)': 'editorModelView'
# db and file urls call the server directly
'db/*path': 'routeToServer'
'file/*path': 'routeToServer'
# most go through here
'*name': 'general'
home: -> @openRoute('home')
general: (name) ->
@openRoute(name)
editorModelView: (modelName, slugOrId, subview) ->
modulePrefix = "views/editor/#{modelName}/"
suffix = subview or (if slugOrId then 'edit' else 'home')
ViewClass = @tryToLoadModule(modulePrefix + suffix)
unless ViewClass
#console.log('could not hack it', modulePrefix + suffix)
args = (a for a in arguments when a)
args.splice(0, 0, 'editor')
return @openRoute(args.join('/'))
view = new ViewClass({}, slugOrId)
view.render()
if view then @openView(view) else @showNotFound()
cache: {}
openRoute: (route) ->
route = route.split('?')[0]
route = route.split('#')[0]
view = @getViewFromCache(route)
@openView(view)
openView: (view) ->
@closeCurrentView()
$('#page-container').empty().append view.el
window.currentView = view
@activateTab()
@renderLoginButtons()
window.scrollTo(0, view.scrollY) if view.scrollY?
view.afterInsert()
view.didReappear() if view.fromCache
onGPlusAPILoaded: =>
@renderLoginButtons()
renderLoginButtons: ->
$('.share-buttons, .partner-badges').addClass('fade-in').delay(10000).removeClass('fade-in', 5000)
setTimeout(FB.XFBML.parse, 10) if FB? # Handles FB login and Like
twttr?.widgets?.load()
return unless gapi?.plusone?
gapi.plusone.go() # Handles +1 button
for gplusButton in $('.gplus-login-button')
params = {
callback:"signinCallback",
clientid:gplusClientID,
cookiepolicy:"single_host_origin",
scope:"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
size:"medium",
}
if gapi.signin
gapi.signin.render(gplusButton, params)
else
console.warn "Didn't have gapi.signin to render G+ login button. (DoNotTrackMe extension?)"
getViewFromCache: (route) ->
if route of @cache
@cache[route].fromCache = true
return @cache[route]
view = @getView(route)
@cache[route] = view unless view and view.cache is false
return view
getView: (route, suffix='_view') ->
# iteratively breaks down the url pieces looking for the view
# passing the broken off pieces as args. This way views like "resource/14394893"
# will get passed to the resource view with arg '14394893'
pieces = _.string.words(route, '/')
split = Math.max(1, pieces.length-1)
while split > -1
sub_route = _.string.join('/', pieces[0..split]...)
path = "views/#{sub_route}#{suffix}"
ViewClass = @tryToLoadModule(path)
break if ViewClass
split -= 1
return @showNotFound() if not ViewClass
args = pieces[split+1..]
view = new ViewClass({}, args...) # options, then any path fragment args
view.render()
tryToLoadModule: (path) ->
try
return require(path)
catch error
if error.toString().search('Cannot find module "' + path + '" from') is -1
throw error
showNotFound: ->
NotFoundView = require('views/not_found')
view = new NotFoundView()
view.render()
closeCurrentView: ->
window.currentModal?.hide()
return unless window.currentView?
if window.currentView.cache
window.currentView.scrollY = window.scrollY
window.currentView.willDisappear()
else
window.currentView.destroy()
activateTab: ->
base = _.string.words(document.location.pathname[1..], '/')[0]
$("ul.nav li.#{base}").addClass('active')
initialize: ->
@cache = {}
# http://nerds.airbnb.com/how-to-add-google-analytics-page-tracking-to-57536
@bind 'route', @_trackPageView
_trackPageView: ->
window.tracker?.trackPageView()
onNavigate: (e) ->
manualView = e.view or e.viewClass
@navigate e.route, {trigger:not manualView}
return unless manualView
if e.viewClass
args = e.viewArgs or []
view = new e.viewClass(args...)
view.render()
@openView view
else
@openView e.view
routeToServer: (e) ->
window.location.href = window.location.href
| true | {me} = require 'lib/auth'
gPI:KEY:<KEY>END_PIClientID = "PI:KEY:<KEY>END_PI"
module.exports = class CocoRouter extends Backbone.Router
subscribe: ->
Backbone.Mediator.subscribe 'gapi-loaded', @onGPlusAPILoaded, @
Backbone.Mediator.subscribe 'router:navigate', @onNavigate, @
routes:
# every abnormal view gets listed here
'': 'home'
'preview': 'home'
'beta': 'home'
# editor views tend to have the same general structure
'editor/:model(/:slug_or_id)(/:subview)': 'editorModelView'
# db and file urls call the server directly
'db/*path': 'routeToServer'
'file/*path': 'routeToServer'
# most go through here
'*name': 'general'
home: -> @openRoute('home')
general: (name) ->
@openRoute(name)
editorModelView: (modelName, slugOrId, subview) ->
modulePrefix = "views/editor/#{modelName}/"
suffix = subview or (if slugOrId then 'edit' else 'home')
ViewClass = @tryToLoadModule(modulePrefix + suffix)
unless ViewClass
#console.log('could not hack it', modulePrefix + suffix)
args = (a for a in arguments when a)
args.splice(0, 0, 'editor')
return @openRoute(args.join('/'))
view = new ViewClass({}, slugOrId)
view.render()
if view then @openView(view) else @showNotFound()
cache: {}
openRoute: (route) ->
route = route.split('?')[0]
route = route.split('#')[0]
view = @getViewFromCache(route)
@openView(view)
openView: (view) ->
@closeCurrentView()
$('#page-container').empty().append view.el
window.currentView = view
@activateTab()
@renderLoginButtons()
window.scrollTo(0, view.scrollY) if view.scrollY?
view.afterInsert()
view.didReappear() if view.fromCache
onGPlusAPILoaded: =>
@renderLoginButtons()
renderLoginButtons: ->
$('.share-buttons, .partner-badges').addClass('fade-in').delay(10000).removeClass('fade-in', 5000)
setTimeout(FB.XFBML.parse, 10) if FB? # Handles FB login and Like
twttr?.widgets?.load()
return unless gapi?.plusone?
gapi.plusone.go() # Handles +1 button
for gplusButton in $('.gplus-login-button')
params = {
callback:"signinCallback",
clientid:gplusClientID,
cookiepolicy:"single_host_origin",
scope:"https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email",
size:"medium",
}
if gapi.signin
gapi.signin.render(gplusButton, params)
else
console.warn "Didn't have gapi.signin to render G+ login button. (DoNotTrackMe extension?)"
getViewFromCache: (route) ->
if route of @cache
@cache[route].fromCache = true
return @cache[route]
view = @getView(route)
@cache[route] = view unless view and view.cache is false
return view
getView: (route, suffix='_view') ->
# iteratively breaks down the url pieces looking for the view
# passing the broken off pieces as args. This way views like "resource/14394893"
# will get passed to the resource view with arg '14394893'
pieces = _.string.words(route, '/')
split = Math.max(1, pieces.length-1)
while split > -1
sub_route = _.string.join('/', pieces[0..split]...)
path = "views/#{sub_route}#{suffix}"
ViewClass = @tryToLoadModule(path)
break if ViewClass
split -= 1
return @showNotFound() if not ViewClass
args = pieces[split+1..]
view = new ViewClass({}, args...) # options, then any path fragment args
view.render()
tryToLoadModule: (path) ->
try
return require(path)
catch error
if error.toString().search('Cannot find module "' + path + '" from') is -1
throw error
showNotFound: ->
NotFoundView = require('views/not_found')
view = new NotFoundView()
view.render()
closeCurrentView: ->
window.currentModal?.hide()
return unless window.currentView?
if window.currentView.cache
window.currentView.scrollY = window.scrollY
window.currentView.willDisappear()
else
window.currentView.destroy()
activateTab: ->
base = _.string.words(document.location.pathname[1..], '/')[0]
$("ul.nav li.#{base}").addClass('active')
initialize: ->
@cache = {}
# http://nerds.airbnb.com/how-to-add-google-analytics-page-tracking-to-57536
@bind 'route', @_trackPageView
_trackPageView: ->
window.tracker?.trackPageView()
onNavigate: (e) ->
manualView = e.view or e.viewClass
@navigate e.route, {trigger:not manualView}
return unless manualView
if e.viewClass
args = e.viewArgs or []
view = new e.viewClass(args...)
view.render()
@openView view
else
@openView e.view
routeToServer: (e) ->
window.location.href = window.location.href
|
[
{
"context": "\"card_sets.bloodborn_set_name_short\"),\n\tdevName: \"bloodborn\",\n\tenabled: false\n\torbGoldCost: 300\n\tisUnlocka",
"end": 841,
"score": 0.8107479810714722,
"start": 835,
"tag": "USERNAME",
"value": "bloodb"
},
{
"context": "Set.Unity,\n\tname: \"Gauntlet Specials\... | app/sdk/cards/cardSetFactory.coffee | willroberts/duelyst | 5 |
CardSet = require './cardSetLookup'
i18next = require 'i18next'
class CardSetFactory
@setMap: {}
@cardSetForIdentifier: (identifier) ->
return CardSetFactory.setMap[identifier]
@cardSetForDevName: (devName) ->
for cardSetId,cardSetData of CardSetFactory.setMap
if cardSetData.devName == devName
return cardSetData
return null
# generate sets once in a map
smap = CardSetFactory.setMap
# core
smap[CardSet.Core] =
id: CardSet.Core,
title: i18next.t("card_sets.core_set_name"),
name: i18next.t("card_sets.core_set_name_short"),
devName: "core",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/core-set"
# bloodborn
smap[CardSet.Bloodborn] =
id: CardSet.Bloodborn,
title: i18next.t("card_sets.bloodborn_set_name"),
name: i18next.t("card_sets.bloodborn_set_name_short"),
devName: "bloodborn",
enabled: false
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
fullSetSpiritCost: 15000
orbSpiritRefund: 300
cardSetUrl: "https://cards.duelyst.com/rise-of-the-bloodborn"
# unity
smap[CardSet.Unity] =
id: CardSet.Unity,
title: i18next.t("card_sets.ancient_bonds_set_name"),
name: i18next.t("card_sets.ancient_bonds_set_name_short"),
devName: "unity",
enabled: true
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
fullSetSpiritCost: 15000
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# gauntlet specials
smap[CardSet.GauntletSpecial] =
id: CardSet.Unity,
name: "Gauntlet Specials",
devName: "gauntlet_special",
title: "Gauntlet Specials",
enabled: true
# first watch
smap[CardSet.FirstWatch] =
id: CardSet.FirstWatch,
name: i18next.t("card_sets.firstwatch_set_name_short"),
devName: "firstwatch",
title: i18next.t("card_sets.firstwatch_set_name"),
enabled: true,
orbGoldCost: 100,
cardSetUrl: "https://cards.duelyst.com/unearthed-prophecy"
# wartech
smap[CardSet.Wartech] =
id: CardSet.Wartech,
name: "Immortal",
devName: "wartech",
title: "Immortal Vanguard",
orbGoldCost: 100,
enabled: true,
isPreRelease: false, # allows users seeing orbs and receiving them, but disables purchasing for gold and opening them
cardSetUrl: "https://cards.duelyst.com/immortal-vanguard"
# shimzar
smap[CardSet.Shimzar] =
id: CardSet.Shimzar,
title: i18next.t("card_sets.shimzar_set_name"),
name: i18next.t("card_sets.shimzar_set_name_short"),
devName: "shimzar",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/denizens-of-shimzar"
smap[CardSet.CombinedUnlockables] =
id: CardSet.CombinedUnlockables,
title: i18next.t("card_sets.combined_unlockables_set_name"),
name: i18next.t("card_sets.combined_unlockables_set_name_short"),
devName: "combined_unlockables",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# coreshatter
smap[CardSet.Coreshatter] =
id: CardSet.Coreshatter,
name: "Mythron",
devName: "coreshatter",
title: "Trials of Mythron",
orbGoldCost: 100,
enabled: true
cardSetUrl: "https://cards.duelyst.com/trials-of-mythron"
module.exports = CardSetFactory
| 159795 |
CardSet = require './cardSetLookup'
i18next = require 'i18next'
class CardSetFactory
@setMap: {}
@cardSetForIdentifier: (identifier) ->
return CardSetFactory.setMap[identifier]
@cardSetForDevName: (devName) ->
for cardSetId,cardSetData of CardSetFactory.setMap
if cardSetData.devName == devName
return cardSetData
return null
# generate sets once in a map
smap = CardSetFactory.setMap
# core
smap[CardSet.Core] =
id: CardSet.Core,
title: i18next.t("card_sets.core_set_name"),
name: i18next.t("card_sets.core_set_name_short"),
devName: "core",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/core-set"
# bloodborn
smap[CardSet.Bloodborn] =
id: CardSet.Bloodborn,
title: i18next.t("card_sets.bloodborn_set_name"),
name: i18next.t("card_sets.bloodborn_set_name_short"),
devName: "bloodborn",
enabled: false
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
fullSetSpiritCost: 15000
orbSpiritRefund: 300
cardSetUrl: "https://cards.duelyst.com/rise-of-the-bloodborn"
# unity
smap[CardSet.Unity] =
id: CardSet.Unity,
title: i18next.t("card_sets.ancient_bonds_set_name"),
name: i18next.t("card_sets.ancient_bonds_set_name_short"),
devName: "unity",
enabled: true
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
fullSetSpiritCost: 15000
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# gauntlet specials
smap[CardSet.GauntletSpecial] =
id: CardSet.Unity,
name: "Gauntlet Specials",
devName: "gauntlet_special",
title: "Gauntlet Specials",
enabled: true
# first watch
smap[CardSet.FirstWatch] =
id: CardSet.FirstWatch,
name: i18next.t("card_sets.firstwatch_set_name_short"),
devName: "firstwatch",
title: i18next.t("card_sets.firstwatch_set_name"),
enabled: true,
orbGoldCost: 100,
cardSetUrl: "https://cards.duelyst.com/unearthed-prophecy"
# wartech
smap[CardSet.Wartech] =
id: CardSet.Wartech,
name: "<NAME>",
devName: "wartech",
title: "Immortal Vanguard",
orbGoldCost: 100,
enabled: true,
isPreRelease: false, # allows users seeing orbs and receiving them, but disables purchasing for gold and opening them
cardSetUrl: "https://cards.duelyst.com/immortal-vanguard"
# shimzar
smap[CardSet.Shimzar] =
id: CardSet.Shimzar,
title: i18next.t("card_sets.shimzar_set_name"),
name: i18next.t("card_sets.shimzar_set_name_short"),
devName: "<NAME>",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/denizens-of-shimzar"
smap[CardSet.CombinedUnlockables] =
id: CardSet.CombinedUnlockables,
title: i18next.t("card_sets.combined_unlockables_set_name"),
name: i18next.t("card_sets.combined_unlockables_set_name_short"),
devName: "combined_unlockables",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# coreshatter
smap[CardSet.Coreshatter] =
id: CardSet.Coreshatter,
name: "<NAME>",
devName: "<NAME>",
title: "Trials of Mythron",
orbGoldCost: 100,
enabled: true
cardSetUrl: "https://cards.duelyst.com/trials-of-mythron"
module.exports = CardSetFactory
| true |
CardSet = require './cardSetLookup'
i18next = require 'i18next'
class CardSetFactory
@setMap: {}
@cardSetForIdentifier: (identifier) ->
return CardSetFactory.setMap[identifier]
@cardSetForDevName: (devName) ->
for cardSetId,cardSetData of CardSetFactory.setMap
if cardSetData.devName == devName
return cardSetData
return null
# generate sets once in a map
smap = CardSetFactory.setMap
# core
smap[CardSet.Core] =
id: CardSet.Core,
title: i18next.t("card_sets.core_set_name"),
name: i18next.t("card_sets.core_set_name_short"),
devName: "core",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/core-set"
# bloodborn
smap[CardSet.Bloodborn] =
id: CardSet.Bloodborn,
title: i18next.t("card_sets.bloodborn_set_name"),
name: i18next.t("card_sets.bloodborn_set_name_short"),
devName: "bloodborn",
enabled: false
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
fullSetSpiritCost: 15000
orbSpiritRefund: 300
cardSetUrl: "https://cards.duelyst.com/rise-of-the-bloodborn"
# unity
smap[CardSet.Unity] =
id: CardSet.Unity,
title: i18next.t("card_sets.ancient_bonds_set_name"),
name: i18next.t("card_sets.ancient_bonds_set_name_short"),
devName: "unity",
enabled: true
orbGoldCost: 300
isUnlockableThroughOrbs: true
numOrbsToCompleteSet: 13
fullSetSpiritCost: 15000
orbGoldRefund: 300 # If a player buys a complete set this is what they get back per orb already purchased
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# gauntlet specials
smap[CardSet.GauntletSpecial] =
id: CardSet.Unity,
name: "Gauntlet Specials",
devName: "gauntlet_special",
title: "Gauntlet Specials",
enabled: true
# first watch
smap[CardSet.FirstWatch] =
id: CardSet.FirstWatch,
name: i18next.t("card_sets.firstwatch_set_name_short"),
devName: "firstwatch",
title: i18next.t("card_sets.firstwatch_set_name"),
enabled: true,
orbGoldCost: 100,
cardSetUrl: "https://cards.duelyst.com/unearthed-prophecy"
# wartech
smap[CardSet.Wartech] =
id: CardSet.Wartech,
name: "PI:NAME:<NAME>END_PI",
devName: "wartech",
title: "Immortal Vanguard",
orbGoldCost: 100,
enabled: true,
isPreRelease: false, # allows users seeing orbs and receiving them, but disables purchasing for gold and opening them
cardSetUrl: "https://cards.duelyst.com/immortal-vanguard"
# shimzar
smap[CardSet.Shimzar] =
id: CardSet.Shimzar,
title: i18next.t("card_sets.shimzar_set_name"),
name: i18next.t("card_sets.shimzar_set_name_short"),
devName: "PI:NAME:<NAME>END_PI",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/denizens-of-shimzar"
smap[CardSet.CombinedUnlockables] =
id: CardSet.CombinedUnlockables,
title: i18next.t("card_sets.combined_unlockables_set_name"),
name: i18next.t("card_sets.combined_unlockables_set_name_short"),
devName: "combined_unlockables",
enabled: true
orbGoldCost: 100
cardSetUrl: "https://cards.duelyst.com/ancient-bonds"
# coreshatter
smap[CardSet.Coreshatter] =
id: CardSet.Coreshatter,
name: "PI:NAME:<NAME>END_PI",
devName: "PI:NAME:<NAME>END_PI",
title: "Trials of Mythron",
orbGoldCost: 100,
enabled: true
cardSetUrl: "https://cards.duelyst.com/trials-of-mythron"
module.exports = CardSetFactory
|
[
{
"context": "# name: clp.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: 沈",
"end": 30,
"score": 0.9998958706855774,
"start": 27,
"tag": "NAME",
"value": "沈维忠"
},
{
"context": "# name: clp.js\n#\n# author: 沈维忠 ( Shen Weizhong / Tony Stark )\n#\n# Last Update: ... | dev/splited_tasks_for_gulp/clp.coffee | gitter-badger/is-object-brace | 0 | # name: clp.js
#
# author: 沈维忠 ( Shen Weizhong / Tony Stark )
#
# Last Update: 沈维忠 ( Shen Weizhong / Tony Stark )
'use strict'
cfg = require '../config.json'
gulp = require 'gulp'
$ = require('gulp-load-plugins')()
parse_args = require 'minimist'
__args = parse_args process.argv.slice(2),
'boolean': cfg.clp
module.exports = __args
| 102960 | # name: clp.js
#
# author: <NAME> ( <NAME> / <NAME> )
#
# Last Update: <NAME> ( <NAME> / <NAME> )
'use strict'
cfg = require '../config.json'
gulp = require 'gulp'
$ = require('gulp-load-plugins')()
parse_args = require 'minimist'
__args = parse_args process.argv.slice(2),
'boolean': cfg.clp
module.exports = __args
| true | # name: clp.js
#
# author: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI )
#
# Last Update: PI:NAME:<NAME>END_PI ( PI:NAME:<NAME>END_PI / PI:NAME:<NAME>END_PI )
'use strict'
cfg = require '../config.json'
gulp = require 'gulp'
$ = require('gulp-load-plugins')()
parse_args = require 'minimist'
__args = parse_args process.argv.slice(2),
'boolean': cfg.clp
module.exports = __args
|
[
{
"context": "EOUT: 'timeout'\n @USER: 'user'\n @PASSWORD: 'password'\n @DATABASE: 'domain'\n @TABLE: 'resource'\n ",
"end": 247,
"score": 0.9994081258773804,
"start": 239,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "abase\n user: user\n ... | src/MySQL.coffee | rodolforios/MySQLConnector | 0 | 'use strict'
mysql = require 'mysql2'
rules = require 'rules'
exceptions = require 'exception'
class MySQLConnector
@HOST: 'host'
@PORT: 'port'
@POOL_SIZE: 'poolSize'
@TIMEOUT: 'timeout'
@USER: 'user'
@PASSWORD: 'password'
@DATABASE: 'domain'
@TABLE: 'resource'
@DEFAULT_TIMEOUT: 10000
instance = null
# constructor: (params, container) ->
# return instance if instance?
# @init params, container
# instance = @
constructor: (params, container) ->
@rules = container?.Rules || rules
@Exceptions = container?.Exceptions || exceptions
@_checkArg params, 'params'
@mysql = container?.mysql || mysql
host = params[MySQLConnector.HOST] || null
port = params[MySQLConnector.PORT] || 3306
poolSize = params[MySQLConnector.POOL_SIZE] || null
timeout = params[MySQLConnector.TIMEOUT] || MySQLConnector.DEFAULT_TIMEOUT
user = params[MySQLConnector.USER] || null
password = params[MySQLConnector.PASSWORD] || ''
@database = params[MySQLConnector.DATABASE] || null
@table = params[MySQLConnector.TABLE] || null
@_checkArg host, MySQLConnector.HOST
@_checkArg user, MySQLConnector.USER
@_checkArg poolSize, MySQLConnector.POOL_SIZE
@_checkArg @database, MySQLConnector.DATABASE
poolParams =
host: host
port: port
database: @database
user: user
password: password
connectionLimit: poolSize
acquireTimeout: timeout
waitForConnections: 0
@pool = @mysql.createPool poolParams
readById: (id, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
@_execute "SELECT * FROM #{@table} WHERE id = ?", [id], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback new @Exceptions.Error @Exceptions.NOT_FOUND
read: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
create: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} SET #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
# multi data in one insert command
multiCreate: (listData, callback) ->
return callback 'Invalid data' if !@rules.isUseful(listData)
isExtractFields = true
fields = ''
values = []
queryValues = ''
listData.map (data) ->
queryValues += '('
for key, value of data
# Extrai os fields apenas na primeira vez
fields += "#{key}," if isExtractFields
values.push value
queryValues += '?,'
isExtractFields = false
# Remove última vírgula da quantidade de fields
queryValues = queryValues.substr 0,queryValues.length-1
queryValues += '),'
# Remove última vírgula da quantidade de rows
queryValues = queryValues.substr 0,queryValues.length-1
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} (#{fields}) VALUES #{queryValues}", values, (err, row) ->
return callback err if err?
return callback null, row
bulkCreate: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
update:(id, data, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push id
@_execute "UPDATE #{@table} SET #{fields} WHERE id=?", values, (err, row) ->
return callback err if err?
return callback null, row
updateByField:(field, field_value, data, callback) ->
return callback 'Invalid field' if !@rules.isUseful(field)
return callback 'Invalid field_value' if !@rules.isUseful(field_value) or @rules.isZero field_value
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push field_value
query = "UPDATE #{@table} SET #{fields} WHERE #{field}=?"
@_execute "UPDATE #{@table} SET #{fields} WHERE #{field}=?", values, (err, row) ->
return callback err if err?
return callback null, row
query: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
_checkArg: (arg, name) ->
if !@rules.isUseful arg
throw new @Exceptions.Fatal @Exceptions.INVALID_ARGUMENT, "Parameter #{name} is invalid"
_execute: (query, params, callback) ->
@pool.getConnection (err, connection) =>
if err?
return callback "Database connection failed. Error: #{err}" if err?
@_selectDatabase "#{@database}", connection, (err) ->
if err?
connection.release()
return callback 'Error selecting database' if err?
connection.query query, params, (err, row) ->
connection.release()
callback err, row
_selectDatabase: (databaseName, connection, callback) ->
connection.query "USE #{databaseName}", [], callback
changeTable: (tableName) ->
@table = tableName
readJoin: (orderIdentifier, params, callback) ->
orderSearch = null
fieldSearch = null
if orderIdentifier?.data?.id?
orderSearch = orderIdentifier.data.id
fieldSearch = 'id'
else if orderIdentifier?.data?.reference?
orderSearch = orderIdentifier.data.reference
fieldSearch = 'reference'
return callback 'Invalid id' if !@rules.isUseful(orderIdentifier) or @rules.isZero orderIdentifier
joinTable = params?.table || null
condition = params?.condition || null
fields = params?.fields || null
if !@rules.isUseful(joinTable) or !@rules.isUseful(condition) or !@rules.isUseful(fields)
return callback 'Invalid join parameters'
if params?.orderBy
orderBy = "ORDER BY #{params.orderBy}"
if params?.limit
limit = "LIMIT #{params.limit}"
selectFields = ''
for key in fields
selectFields += "#{key},"
selectFields = selectFields.substring(0, selectFields.length-1)
query = "SELECT #{selectFields} FROM #{@table} JOIN #{joinTable} ON #{condition} WHERE #{@table}.#{fieldSearch} = ? #{orderBy} #{limit}"
@_execute query, [orderSearch], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback 'NOT_FOUND'
delete: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "DELETE FROM #{@table} WHERE #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
start_transaction: (callback) ->
@_execute "START TRANSACTION", [], (err, row) ->
return callback err if err?
return callback null, row
commit: (callback) ->
@_execute "COMMIT", [], (err, row) ->
return callback err if err?
return callback null, row
rollback: (callback) ->
@_execute "ROLLBACK", [], (err, row) ->
return callback err if err?
return callback null, row
callProcedure: (name, data, callback) ->
fields = ''
for key, value of data
fields += "#{value},"
fields = fields.substr 0,fields.length-1
query = "CALL #{name} (#{fields})"
@_execute query, [], (error, success) ->
return callback error if error?
callback null, success
close: ->
@pool.end()
# createMany
# readMany
# update
# updateMany
# deleteMany
module.exports = MySQLConnector | 225215 | 'use strict'
mysql = require 'mysql2'
rules = require 'rules'
exceptions = require 'exception'
class MySQLConnector
@HOST: 'host'
@PORT: 'port'
@POOL_SIZE: 'poolSize'
@TIMEOUT: 'timeout'
@USER: 'user'
@PASSWORD: '<PASSWORD>'
@DATABASE: 'domain'
@TABLE: 'resource'
@DEFAULT_TIMEOUT: 10000
instance = null
# constructor: (params, container) ->
# return instance if instance?
# @init params, container
# instance = @
constructor: (params, container) ->
@rules = container?.Rules || rules
@Exceptions = container?.Exceptions || exceptions
@_checkArg params, 'params'
@mysql = container?.mysql || mysql
host = params[MySQLConnector.HOST] || null
port = params[MySQLConnector.PORT] || 3306
poolSize = params[MySQLConnector.POOL_SIZE] || null
timeout = params[MySQLConnector.TIMEOUT] || MySQLConnector.DEFAULT_TIMEOUT
user = params[MySQLConnector.USER] || null
password = params[MySQLConnector.PASSWORD] || ''
@database = params[MySQLConnector.DATABASE] || null
@table = params[MySQLConnector.TABLE] || null
@_checkArg host, MySQLConnector.HOST
@_checkArg user, MySQLConnector.USER
@_checkArg poolSize, MySQLConnector.POOL_SIZE
@_checkArg @database, MySQLConnector.DATABASE
poolParams =
host: host
port: port
database: @database
user: user
password: <PASSWORD>
connectionLimit: poolSize
acquireTimeout: timeout
waitForConnections: 0
@pool = @mysql.createPool poolParams
readById: (id, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
@_execute "SELECT * FROM #{@table} WHERE id = ?", [id], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback new @Exceptions.Error @Exceptions.NOT_FOUND
read: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
create: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} SET #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
# multi data in one insert command
multiCreate: (listData, callback) ->
return callback 'Invalid data' if !@rules.isUseful(listData)
isExtractFields = true
fields = ''
values = []
queryValues = ''
listData.map (data) ->
queryValues += '('
for key, value of data
# Extrai os fields apenas na primeira vez
fields += "#{key}," if isExtractFields
values.push value
queryValues += '?,'
isExtractFields = false
# Remove última vírgula da quantidade de fields
queryValues = queryValues.substr 0,queryValues.length-1
queryValues += '),'
# Remove última vírgula da quantidade de rows
queryValues = queryValues.substr 0,queryValues.length-1
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} (#{fields}) VALUES #{queryValues}", values, (err, row) ->
return callback err if err?
return callback null, row
bulkCreate: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
update:(id, data, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push id
@_execute "UPDATE #{@table} SET #{fields} WHERE id=?", values, (err, row) ->
return callback err if err?
return callback null, row
updateByField:(field, field_value, data, callback) ->
return callback 'Invalid field' if !@rules.isUseful(field)
return callback 'Invalid field_value' if !@rules.isUseful(field_value) or @rules.isZero field_value
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push field_value
query = "UPDATE #{@table} SET #{fields} WHERE #{field}=?"
@_execute "UPDATE #{@table} SET #{fields} WHERE #{field}=?", values, (err, row) ->
return callback err if err?
return callback null, row
query: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
_checkArg: (arg, name) ->
if !@rules.isUseful arg
throw new @Exceptions.Fatal @Exceptions.INVALID_ARGUMENT, "Parameter #{name} is invalid"
_execute: (query, params, callback) ->
@pool.getConnection (err, connection) =>
if err?
return callback "Database connection failed. Error: #{err}" if err?
@_selectDatabase "#{@database}", connection, (err) ->
if err?
connection.release()
return callback 'Error selecting database' if err?
connection.query query, params, (err, row) ->
connection.release()
callback err, row
_selectDatabase: (databaseName, connection, callback) ->
connection.query "USE #{databaseName}", [], callback
changeTable: (tableName) ->
@table = tableName
readJoin: (orderIdentifier, params, callback) ->
orderSearch = null
fieldSearch = null
if orderIdentifier?.data?.id?
orderSearch = orderIdentifier.data.id
fieldSearch = 'id'
else if orderIdentifier?.data?.reference?
orderSearch = orderIdentifier.data.reference
fieldSearch = 'reference'
return callback 'Invalid id' if !@rules.isUseful(orderIdentifier) or @rules.isZero orderIdentifier
joinTable = params?.table || null
condition = params?.condition || null
fields = params?.fields || null
if !@rules.isUseful(joinTable) or !@rules.isUseful(condition) or !@rules.isUseful(fields)
return callback 'Invalid join parameters'
if params?.orderBy
orderBy = "ORDER BY #{params.orderBy}"
if params?.limit
limit = "LIMIT #{params.limit}"
selectFields = ''
for key in fields
selectFields += "#{key},"
selectFields = selectFields.substring(0, selectFields.length-1)
query = "SELECT #{selectFields} FROM #{@table} JOIN #{joinTable} ON #{condition} WHERE #{@table}.#{fieldSearch} = ? #{orderBy} #{limit}"
@_execute query, [orderSearch], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback 'NOT_FOUND'
delete: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "DELETE FROM #{@table} WHERE #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
start_transaction: (callback) ->
@_execute "START TRANSACTION", [], (err, row) ->
return callback err if err?
return callback null, row
commit: (callback) ->
@_execute "COMMIT", [], (err, row) ->
return callback err if err?
return callback null, row
rollback: (callback) ->
@_execute "ROLLBACK", [], (err, row) ->
return callback err if err?
return callback null, row
callProcedure: (name, data, callback) ->
fields = ''
for key, value of data
fields += "#{value},"
fields = fields.substr 0,fields.length-1
query = "CALL #{name} (#{fields})"
@_execute query, [], (error, success) ->
return callback error if error?
callback null, success
close: ->
@pool.end()
# createMany
# readMany
# update
# updateMany
# deleteMany
module.exports = MySQLConnector | true | 'use strict'
mysql = require 'mysql2'
rules = require 'rules'
exceptions = require 'exception'
class MySQLConnector
@HOST: 'host'
@PORT: 'port'
@POOL_SIZE: 'poolSize'
@TIMEOUT: 'timeout'
@USER: 'user'
@PASSWORD: 'PI:PASSWORD:<PASSWORD>END_PI'
@DATABASE: 'domain'
@TABLE: 'resource'
@DEFAULT_TIMEOUT: 10000
instance = null
# constructor: (params, container) ->
# return instance if instance?
# @init params, container
# instance = @
constructor: (params, container) ->
@rules = container?.Rules || rules
@Exceptions = container?.Exceptions || exceptions
@_checkArg params, 'params'
@mysql = container?.mysql || mysql
host = params[MySQLConnector.HOST] || null
port = params[MySQLConnector.PORT] || 3306
poolSize = params[MySQLConnector.POOL_SIZE] || null
timeout = params[MySQLConnector.TIMEOUT] || MySQLConnector.DEFAULT_TIMEOUT
user = params[MySQLConnector.USER] || null
password = params[MySQLConnector.PASSWORD] || ''
@database = params[MySQLConnector.DATABASE] || null
@table = params[MySQLConnector.TABLE] || null
@_checkArg host, MySQLConnector.HOST
@_checkArg user, MySQLConnector.USER
@_checkArg poolSize, MySQLConnector.POOL_SIZE
@_checkArg @database, MySQLConnector.DATABASE
poolParams =
host: host
port: port
database: @database
user: user
password: PI:PASSWORD:<PASSWORD>END_PI
connectionLimit: poolSize
acquireTimeout: timeout
waitForConnections: 0
@pool = @mysql.createPool poolParams
readById: (id, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
@_execute "SELECT * FROM #{@table} WHERE id = ?", [id], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback new @Exceptions.Error @Exceptions.NOT_FOUND
read: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
create: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} SET #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
# multi data in one insert command
multiCreate: (listData, callback) ->
return callback 'Invalid data' if !@rules.isUseful(listData)
isExtractFields = true
fields = ''
values = []
queryValues = ''
listData.map (data) ->
queryValues += '('
for key, value of data
# Extrai os fields apenas na primeira vez
fields += "#{key}," if isExtractFields
values.push value
queryValues += '?,'
isExtractFields = false
# Remove última vírgula da quantidade de fields
queryValues = queryValues.substr 0,queryValues.length-1
queryValues += '),'
# Remove última vírgula da quantidade de rows
queryValues = queryValues.substr 0,queryValues.length-1
fields = fields.substr 0,fields.length-1
@_execute "INSERT INTO #{@table} (#{fields}) VALUES #{queryValues}", values, (err, row) ->
return callback err if err?
return callback null, row
bulkCreate: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
update:(id, data, callback) ->
return callback 'Invalid id' if !@rules.isUseful(id) or @rules.isZero id
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push id
@_execute "UPDATE #{@table} SET #{fields} WHERE id=?", values, (err, row) ->
return callback err if err?
return callback null, row
updateByField:(field, field_value, data, callback) ->
return callback 'Invalid field' if !@rules.isUseful(field)
return callback 'Invalid field_value' if !@rules.isUseful(field_value) or @rules.isZero field_value
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
values.push field_value
query = "UPDATE #{@table} SET #{fields} WHERE #{field}=?"
@_execute "UPDATE #{@table} SET #{fields} WHERE #{field}=?", values, (err, row) ->
return callback err if err?
return callback null, row
query: (query, callback) ->
@_execute query, [], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback()
_checkArg: (arg, name) ->
if !@rules.isUseful arg
throw new @Exceptions.Fatal @Exceptions.INVALID_ARGUMENT, "Parameter #{name} is invalid"
_execute: (query, params, callback) ->
@pool.getConnection (err, connection) =>
if err?
return callback "Database connection failed. Error: #{err}" if err?
@_selectDatabase "#{@database}", connection, (err) ->
if err?
connection.release()
return callback 'Error selecting database' if err?
connection.query query, params, (err, row) ->
connection.release()
callback err, row
_selectDatabase: (databaseName, connection, callback) ->
connection.query "USE #{databaseName}", [], callback
changeTable: (tableName) ->
@table = tableName
readJoin: (orderIdentifier, params, callback) ->
orderSearch = null
fieldSearch = null
if orderIdentifier?.data?.id?
orderSearch = orderIdentifier.data.id
fieldSearch = 'id'
else if orderIdentifier?.data?.reference?
orderSearch = orderIdentifier.data.reference
fieldSearch = 'reference'
return callback 'Invalid id' if !@rules.isUseful(orderIdentifier) or @rules.isZero orderIdentifier
joinTable = params?.table || null
condition = params?.condition || null
fields = params?.fields || null
if !@rules.isUseful(joinTable) or !@rules.isUseful(condition) or !@rules.isUseful(fields)
return callback 'Invalid join parameters'
if params?.orderBy
orderBy = "ORDER BY #{params.orderBy}"
if params?.limit
limit = "LIMIT #{params.limit}"
selectFields = ''
for key in fields
selectFields += "#{key},"
selectFields = selectFields.substring(0, selectFields.length-1)
query = "SELECT #{selectFields} FROM #{@table} JOIN #{joinTable} ON #{condition} WHERE #{@table}.#{fieldSearch} = ? #{orderBy} #{limit}"
@_execute query, [orderSearch], (err, row) =>
return callback err if err?
return callback null, row if @rules.isUseful(row)
return callback 'NOT_FOUND'
delete: (data, callback) ->
return callback 'Invalid data' if !@rules.isUseful(data)
fields = ''
values = []
for key, value of data
fields += "#{key}=?,"
values.push value
fields = fields.substr 0,fields.length-1
@_execute "DELETE FROM #{@table} WHERE #{fields}", values, (err, row) ->
return callback err if err?
return callback null, row
start_transaction: (callback) ->
@_execute "START TRANSACTION", [], (err, row) ->
return callback err if err?
return callback null, row
commit: (callback) ->
@_execute "COMMIT", [], (err, row) ->
return callback err if err?
return callback null, row
rollback: (callback) ->
@_execute "ROLLBACK", [], (err, row) ->
return callback err if err?
return callback null, row
callProcedure: (name, data, callback) ->
fields = ''
for key, value of data
fields += "#{value},"
fields = fields.substr 0,fields.length-1
query = "CALL #{name} (#{fields})"
@_execute query, [], (error, success) ->
return callback error if error?
callback null, success
close: ->
@pool.end()
# createMany
# readMany
# update
# updateMany
# deleteMany
module.exports = MySQLConnector |
[
{
"context": "or.create 245, 126, 0\n\n\n colloquialName: ->\n \"Drawings Maker\"\n\n representativeIcon: ->\n new PaintBuc",
"end": 290,
"score": 0.7527223825454712,
"start": 282,
"tag": "NAME",
"value": "Drawings"
},
{
"context": "245, 126, 0\n\n\n colloquialName: ->\n ... | src/apps/ReconfigurablePaintWdgt.coffee | intensifier/Fizzygum | 110 | class ReconfigurablePaintWdgt extends StretchableEditableWdgt
mainCanvas: nil
overlayCanvas: nil
pencilToolButton: nil
brushToolButton: nil
toothpasteToolButton: nil
eraserToolButton: nil
highlightedToolIconColor: Color.create 245, 126, 0
colloquialName: ->
"Drawings Maker"
representativeIcon: ->
new PaintBucketIconWdgt
isToolPressed: (buttonToCheckIfPressed) ->
whichButtonIsSelected = @toolsPanel.whichButtonSelected()
if whichButtonIsSelected?
if whichButtonIsSelected == buttonToCheckIfPressed.parent
return true
else
return false
return false
# normally a button injects new code only when
# is pressed, BUT here we make it so we inject new
# code also if the tool is selected, without it to
# be re-pressed. In order to do that, we
# simply listen to a notification of new code being
# available from a button, we check if it's selected
# and in that case we tell the button to actually
# inject the code.
newCodeToInjectFromButton: (whichButtonHasNewCode) ->
if @isToolPressed whichButtonHasNewCode
whichButtonHasNewCode.injectCodeIntoTarget()
createNewStretchablePanel: ->
# mainCanvas
@stretchableWidgetContainer = new StretchableWidgetContainerWdgt new StretchableCanvasWdgt
@stretchableWidgetContainer.disableDrops()
@add @stretchableWidgetContainer
@mainCanvas = @stretchableWidgetContainer.contents
# overlayCanvas
@overlayCanvas = new CanvasGlassTopWdgt
@overlayCanvas.underlyingCanvasMorph = @mainCanvas
@overlayCanvas.disableDrops()
@mainCanvas.add @overlayCanvas
# if you clear the overlay to perfectly
# transparent, then we need to set this flag
# otherwise the pointer won't be reported
# as moving inside the canvas.
# If you give the overlay canvas even the smallest
# tint then you don't need this flag.
@overlayCanvas.noticesTransparentClick = true
@overlayCanvas.injectProperty "mouseLeave", """
# don't leave any trace behind then the pointer
# moves out.
(pos) ->
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
@changed()
"""
createToolsPanel: ->
@toolsPanel = new RadioButtonsHolderMorph
@add @toolsPanel
pencilButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph
pencilButtonOff.alpha = 0.1
pencilButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
# give it a little bit of a tint so
# you can see the canvas when you take it
# apart from the paint tool.
#context.fillStyle = (Color.create 0,255,0,0.5).toString()
#context.fillRect 0, 0, @width(), @height()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.BLACK.toString()
contextMain.rect(-2,-2,4,4)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.RED.toString()
context.rect(-2,-2,4,4)
context.stroke()
@changed()
"""
pencilButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph @highlightedToolIconColor
pencilButtonOn.alpha = 0.1
pencilButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@pencilToolButton = new ToggleButtonMorph pencilButtonOff, pencilButtonOn
brushToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph
brushToolButtonOff.alpha = 0.1
brushToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
brushToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph @highlightedToolIconColor
brushToolButtonOn.alpha = 0.1
brushToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@brushToolButton = new ToggleButtonMorph brushToolButtonOff, brushToolButtonOn
toothpasteToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph
toothpasteToolButtonOff.alpha = 0.1
toothpasteToolButtonOff.sourceCodeToBeInjected = """
# Toothpaste graphics
# original implementation by Ward Cunningham, from Tektronix Smalltalk
# implementation of Smalltalk 80
# on the Magnolia (1980-1983) and the Tek 4404 (1984)
# "Draw spheres ala Ken Knowlton, Computer Graphics, v15 n4 p352."
paintBrush = (contextMain) ->
contextMain.save()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
contextMain.restore()
# you'd be tempted to initialise the queue
# on mouseDown but it would be a bad idea
# because the mouse could come "already-pressed"
# from outside the canvas
initialiseQueueIfNeeded = ->
if !@queue?
@queue = [0..24].map -> nil
mouseUpLeft = ->
if world.hand.isThisPointerDraggingSomething() then return
if @queue?
# draining the queue
contextMain = @underlyingCanvasMorph.getContextForPainting()
until @queue.length == 0
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
delete @queue
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
@initialiseQueueIfNeeded()
@queue.push pos
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.save()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
#@paintBrush contextMain
contextMain.beginPath()
contextMain.arc 0,0,9,0,2*Math.PI
contextMain.fill()
contextMain.restore()
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
toothpasteToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph @highlightedToolIconColor
toothpasteToolButtonOn.alpha = 0.1
toothpasteToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@toothpasteToolButton = new ToggleButtonMorph toothpasteToolButtonOff, toothpasteToolButtonOn
eraserToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph
eraserToolButtonOff.alpha = 0.1
eraserToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.WHITE.toString()
contextMain.rect(-5,-5,10,10)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
eraserToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph @highlightedToolIconColor
eraserToolButtonOn.alpha = 0.1
eraserToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@eraserToolButton = new ToggleButtonMorph eraserToolButtonOff, eraserToolButtonOn
# pencilAnnotation
new EditableMarkMorph @pencilToolButton, pencilButtonOff, "editInjectableSource"
# brushAnnotation
new EditableMarkMorph @brushToolButton, brushToolButtonOff, "editInjectableSource"
# toothpasteAnnotation
new EditableMarkMorph @toothpasteToolButton, toothpasteToolButtonOff, "editInjectableSource"
# eraserAnnotation
new EditableMarkMorph @eraserToolButton, eraserToolButtonOff, "editInjectableSource"
@toolsPanel.add @pencilToolButton
@toolsPanel.add @brushToolButton
@toolsPanel.add @toothpasteToolButton
@toolsPanel.add @eraserToolButton
@pencilToolButton.toggle()
@invalidateLayout()
reLayout: ->
# here we are disabling all the broken
# rectangles. The reason is that all the
# submorphs of the inspector are within the
# bounds of the parent Widget. This means that
# if only the parent morph breaks its rectangle
# then everything is OK.
# Also note that if you attach something else to its
# boundary in a way that sticks out, that's still
# going to be painted and moved OK.
world.disableTrackChanges()
# label
labelLeft = @left() + @externalPadding
labelRight = @right() - @externalPadding
labelBottom = @top() + @externalPadding
# tools -------------------------------
if @toolsPanel? and @toolsPanel.parent == @
toolButtonSize = new Point 93, 55
else
toolButtonSize = new Point 0, 0
if @toolsPanel? and @toolsPanel.parent == @
@toolsPanel.fullRawMoveTo new Point @left() + @externalPadding, labelBottom
@toolsPanel.rawSetExtent new Point 2 * @internalPadding + toolButtonSize.width(), @height() - 2 * @externalPadding
if @pencilToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, labelBottom + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@pencilToolButton.doLayout buttonBounds
if @brushToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @pencilToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@brushToolButton.doLayout buttonBounds
if @toothpasteToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @brushToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@toothpasteToolButton.doLayout buttonBounds
if @eraserToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @toothpasteToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@eraserToolButton.doLayout buttonBounds
# stretchableWidgetContainer --------------------------
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerWidth = @width() - @toolsPanel.width() - 2*@externalPadding - @internalPadding
else
stretchableWidgetContainerWidth = @width() - 2*@externalPadding
stretchableWidgetContainerHeight = @height() - 2 * @externalPadding
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerLeft = @toolsPanel.right() + @internalPadding
else
stretchableWidgetContainerLeft = @left() + @externalPadding
if @stretchableWidgetContainer.parent == @
@stretchableWidgetContainer.fullRawMoveTo new Point stretchableWidgetContainerLeft, labelBottom
@stretchableWidgetContainer.setExtent new Point stretchableWidgetContainerWidth, stretchableWidgetContainerHeight
world.maybeEnableTrackChanges()
if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism
world.alignIDsOfNextMorphsInSystemTests()
@markLayoutAsFixed()
| 196689 | class ReconfigurablePaintWdgt extends StretchableEditableWdgt
mainCanvas: nil
overlayCanvas: nil
pencilToolButton: nil
brushToolButton: nil
toothpasteToolButton: nil
eraserToolButton: nil
highlightedToolIconColor: Color.create 245, 126, 0
colloquialName: ->
"<NAME> M<NAME>"
representativeIcon: ->
new PaintBucketIconWdgt
isToolPressed: (buttonToCheckIfPressed) ->
whichButtonIsSelected = @toolsPanel.whichButtonSelected()
if whichButtonIsSelected?
if whichButtonIsSelected == buttonToCheckIfPressed.parent
return true
else
return false
return false
# normally a button injects new code only when
# is pressed, BUT here we make it so we inject new
# code also if the tool is selected, without it to
# be re-pressed. In order to do that, we
# simply listen to a notification of new code being
# available from a button, we check if it's selected
# and in that case we tell the button to actually
# inject the code.
newCodeToInjectFromButton: (whichButtonHasNewCode) ->
if @isToolPressed whichButtonHasNewCode
whichButtonHasNewCode.injectCodeIntoTarget()
createNewStretchablePanel: ->
# mainCanvas
@stretchableWidgetContainer = new StretchableWidgetContainerWdgt new StretchableCanvasWdgt
@stretchableWidgetContainer.disableDrops()
@add @stretchableWidgetContainer
@mainCanvas = @stretchableWidgetContainer.contents
# overlayCanvas
@overlayCanvas = new CanvasGlassTopWdgt
@overlayCanvas.underlyingCanvasMorph = @mainCanvas
@overlayCanvas.disableDrops()
@mainCanvas.add @overlayCanvas
# if you clear the overlay to perfectly
# transparent, then we need to set this flag
# otherwise the pointer won't be reported
# as moving inside the canvas.
# If you give the overlay canvas even the smallest
# tint then you don't need this flag.
@overlayCanvas.noticesTransparentClick = true
@overlayCanvas.injectProperty "mouseLeave", """
# don't leave any trace behind then the pointer
# moves out.
(pos) ->
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
@changed()
"""
createToolsPanel: ->
@toolsPanel = new RadioButtonsHolderMorph
@add @toolsPanel
pencilButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph
pencilButtonOff.alpha = 0.1
pencilButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
# give it a little bit of a tint so
# you can see the canvas when you take it
# apart from the paint tool.
#context.fillStyle = (Color.create 0,255,0,0.5).toString()
#context.fillRect 0, 0, @width(), @height()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.BLACK.toString()
contextMain.rect(-2,-2,4,4)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.RED.toString()
context.rect(-2,-2,4,4)
context.stroke()
@changed()
"""
pencilButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph @highlightedToolIconColor
pencilButtonOn.alpha = 0.1
pencilButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@pencilToolButton = new ToggleButtonMorph pencilButtonOff, pencilButtonOn
brushToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph
brushToolButtonOff.alpha = 0.1
brushToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
brushToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph @highlightedToolIconColor
brushToolButtonOn.alpha = 0.1
brushToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@brushToolButton = new ToggleButtonMorph brushToolButtonOff, brushToolButtonOn
toothpasteToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph
toothpasteToolButtonOff.alpha = 0.1
toothpasteToolButtonOff.sourceCodeToBeInjected = """
# Toothpaste graphics
# original implementation by <NAME>, from Tektronix Smalltalk
# implementation of Smalltalk 80
# on the Magnolia (1980-1983) and the Tek 4404 (1984)
# "Draw spheres ala <NAME>, Computer Graphics, v15 n4 p352."
paintBrush = (contextMain) ->
contextMain.save()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
contextMain.restore()
# you'd be tempted to initialise the queue
# on mouseDown but it would be a bad idea
# because the mouse could come "already-pressed"
# from outside the canvas
initialiseQueueIfNeeded = ->
if !@queue?
@queue = [0..24].map -> nil
mouseUpLeft = ->
if world.hand.isThisPointerDraggingSomething() then return
if @queue?
# draining the queue
contextMain = @underlyingCanvasMorph.getContextForPainting()
until @queue.length == 0
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
delete @queue
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
@initialiseQueueIfNeeded()
@queue.push pos
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.save()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
#@paintBrush contextMain
contextMain.beginPath()
contextMain.arc 0,0,9,0,2*Math.PI
contextMain.fill()
contextMain.restore()
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
toothpasteToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph @highlightedToolIconColor
toothpasteToolButtonOn.alpha = 0.1
toothpasteToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@toothpasteToolButton = new ToggleButtonMorph toothpasteToolButtonOff, toothpasteToolButtonOn
eraserToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph
eraserToolButtonOff.alpha = 0.1
eraserToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.WHITE.toString()
contextMain.rect(-5,-5,10,10)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
eraserToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph @highlightedToolIconColor
eraserToolButtonOn.alpha = 0.1
eraserToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@eraserToolButton = new ToggleButtonMorph eraserToolButtonOff, eraserToolButtonOn
# pencilAnnotation
new EditableMarkMorph @pencilToolButton, pencilButtonOff, "editInjectableSource"
# brushAnnotation
new EditableMarkMorph @brushToolButton, brushToolButtonOff, "editInjectableSource"
# toothpasteAnnotation
new EditableMarkMorph @toothpasteToolButton, toothpasteToolButtonOff, "editInjectableSource"
# eraserAnnotation
new EditableMarkMorph @eraserToolButton, eraserToolButtonOff, "editInjectableSource"
@toolsPanel.add @pencilToolButton
@toolsPanel.add @brushToolButton
@toolsPanel.add @toothpasteToolButton
@toolsPanel.add @eraserToolButton
@pencilToolButton.toggle()
@invalidateLayout()
reLayout: ->
# here we are disabling all the broken
# rectangles. The reason is that all the
# submorphs of the inspector are within the
# bounds of the parent Widget. This means that
# if only the parent morph breaks its rectangle
# then everything is OK.
# Also note that if you attach something else to its
# boundary in a way that sticks out, that's still
# going to be painted and moved OK.
world.disableTrackChanges()
# label
labelLeft = @left() + @externalPadding
labelRight = @right() - @externalPadding
labelBottom = @top() + @externalPadding
# tools -------------------------------
if @toolsPanel? and @toolsPanel.parent == @
toolButtonSize = new Point 93, 55
else
toolButtonSize = new Point 0, 0
if @toolsPanel? and @toolsPanel.parent == @
@toolsPanel.fullRawMoveTo new Point @left() + @externalPadding, labelBottom
@toolsPanel.rawSetExtent new Point 2 * @internalPadding + toolButtonSize.width(), @height() - 2 * @externalPadding
if @pencilToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, labelBottom + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@pencilToolButton.doLayout buttonBounds
if @brushToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @pencilToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@brushToolButton.doLayout buttonBounds
if @toothpasteToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @brushToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@toothpasteToolButton.doLayout buttonBounds
if @eraserToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @toothpasteToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@eraserToolButton.doLayout buttonBounds
# stretchableWidgetContainer --------------------------
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerWidth = @width() - @toolsPanel.width() - 2*@externalPadding - @internalPadding
else
stretchableWidgetContainerWidth = @width() - 2*@externalPadding
stretchableWidgetContainerHeight = @height() - 2 * @externalPadding
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerLeft = @toolsPanel.right() + @internalPadding
else
stretchableWidgetContainerLeft = @left() + @externalPadding
if @stretchableWidgetContainer.parent == @
@stretchableWidgetContainer.fullRawMoveTo new Point stretchableWidgetContainerLeft, labelBottom
@stretchableWidgetContainer.setExtent new Point stretchableWidgetContainerWidth, stretchableWidgetContainerHeight
world.maybeEnableTrackChanges()
if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism
world.alignIDsOfNextMorphsInSystemTests()
@markLayoutAsFixed()
| true | class ReconfigurablePaintWdgt extends StretchableEditableWdgt
mainCanvas: nil
overlayCanvas: nil
pencilToolButton: nil
brushToolButton: nil
toothpasteToolButton: nil
eraserToolButton: nil
highlightedToolIconColor: Color.create 245, 126, 0
colloquialName: ->
"PI:NAME:<NAME>END_PI MPI:NAME:<NAME>END_PI"
representativeIcon: ->
new PaintBucketIconWdgt
isToolPressed: (buttonToCheckIfPressed) ->
whichButtonIsSelected = @toolsPanel.whichButtonSelected()
if whichButtonIsSelected?
if whichButtonIsSelected == buttonToCheckIfPressed.parent
return true
else
return false
return false
# normally a button injects new code only when
# is pressed, BUT here we make it so we inject new
# code also if the tool is selected, without it to
# be re-pressed. In order to do that, we
# simply listen to a notification of new code being
# available from a button, we check if it's selected
# and in that case we tell the button to actually
# inject the code.
newCodeToInjectFromButton: (whichButtonHasNewCode) ->
if @isToolPressed whichButtonHasNewCode
whichButtonHasNewCode.injectCodeIntoTarget()
createNewStretchablePanel: ->
# mainCanvas
@stretchableWidgetContainer = new StretchableWidgetContainerWdgt new StretchableCanvasWdgt
@stretchableWidgetContainer.disableDrops()
@add @stretchableWidgetContainer
@mainCanvas = @stretchableWidgetContainer.contents
# overlayCanvas
@overlayCanvas = new CanvasGlassTopWdgt
@overlayCanvas.underlyingCanvasMorph = @mainCanvas
@overlayCanvas.disableDrops()
@mainCanvas.add @overlayCanvas
# if you clear the overlay to perfectly
# transparent, then we need to set this flag
# otherwise the pointer won't be reported
# as moving inside the canvas.
# If you give the overlay canvas even the smallest
# tint then you don't need this flag.
@overlayCanvas.noticesTransparentClick = true
@overlayCanvas.injectProperty "mouseLeave", """
# don't leave any trace behind then the pointer
# moves out.
(pos) ->
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
@changed()
"""
createToolsPanel: ->
@toolsPanel = new RadioButtonsHolderMorph
@add @toolsPanel
pencilButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph
pencilButtonOff.alpha = 0.1
pencilButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
# give it a little bit of a tint so
# you can see the canvas when you take it
# apart from the paint tool.
#context.fillStyle = (Color.create 0,255,0,0.5).toString()
#context.fillRect 0, 0, @width(), @height()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.BLACK.toString()
contextMain.rect(-2,-2,4,4)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.RED.toString()
context.rect(-2,-2,4,4)
context.stroke()
@changed()
"""
pencilButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new Pencil2IconMorph @highlightedToolIconColor
pencilButtonOn.alpha = 0.1
pencilButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@pencilToolButton = new ToggleButtonMorph pencilButtonOff, pencilButtonOn
brushToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph
brushToolButtonOff.alpha = 0.1
brushToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
brushToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new BrushIconMorph @highlightedToolIconColor
brushToolButtonOn.alpha = 0.1
brushToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@brushToolButton = new ToggleButtonMorph brushToolButtonOff, brushToolButtonOn
toothpasteToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph
toothpasteToolButtonOff.alpha = 0.1
toothpasteToolButtonOff.sourceCodeToBeInjected = """
# Toothpaste graphics
# original implementation by PI:NAME:<NAME>END_PI, from Tektronix Smalltalk
# implementation of Smalltalk 80
# on the Magnolia (1980-1983) and the Tek 4404 (1984)
# "Draw spheres ala PI:NAME:<NAME>END_PI, Computer Graphics, v15 n4 p352."
paintBrush = (contextMain) ->
contextMain.save()
# the brush is 16 x 16, so center it
contextMain.translate -8, -8
# for convenience, the brush has been
# drawn first using 6x6 squares, so now
# scale those back
contextMain.scale 1/6, 1/6
contextMain.beginPath()
contextMain.rect 48, 0, 6, 6
contextMain.rect 36, 6, 6, 6
contextMain.rect 54, 6, 6, 6
contextMain.rect 66, 6, 6, 6
contextMain.rect 30, 12, 12, 6
contextMain.rect 48, 12, 6, 6
contextMain.rect 72, 12, 6, 6
contextMain.rect 12, 18, 36, 6
contextMain.rect 60, 18, 6, 6
contextMain.rect 78, 18, 6, 6
contextMain.rect 24, 24, 42, 6
contextMain.rect 72, 24, 6, 6
contextMain.rect 90, 24, 6, 6
contextMain.rect 18, 30, 42, 6
contextMain.rect 66, 30, 6, 6
contextMain.rect 18, 36, 36, 6
contextMain.rect 6, 36, 6, 6
contextMain.rect 60, 36, 12, 6
contextMain.rect 78, 36, 6, 6
contextMain.rect 90, 36, 6, 6
contextMain.rect 24, 42, 36, 6
contextMain.rect 66, 42, 12, 6
contextMain.rect 6, 48, 6, 6
contextMain.rect 18, 48, 6, 6
contextMain.rect 30, 48, 12, 6
contextMain.rect 54, 48, 6, 6
contextMain.rect 78, 48, 6, 6
contextMain.rect 36, 54, 6, 12
contextMain.rect 48, 54, 6, 6
contextMain.rect 60, 54, 12, 6
contextMain.rect 90, 54, 6, 6
contextMain.rect 6, 60, 6, 6
contextMain.rect 18, 60, 12, 6
contextMain.rect 54, 60, 6, 12
contextMain.rect 78, 60, 6, 6
contextMain.rect 0, 66, 6, 6
contextMain.rect 42, 66, 6, 12
contextMain.rect 66, 66, 6, 6
contextMain.rect 18, 72, 6, 6
contextMain.rect 30, 72, 6, 6
contextMain.rect 60, 78, 6, 6
contextMain.rect 78, 78, 6, 6
contextMain.rect 12, 84, 6, 6
contextMain.rect 36, 84, 6, 6
contextMain.rect 54, 84, 6, 6
contextMain.rect 42, 90, 6, 6
contextMain.rect 18, 6, 6, 6
contextMain.rect 6, 24, 6, 6
contextMain.rect 0, 42, 6, 6
contextMain.fill()
contextMain.restore()
# you'd be tempted to initialise the queue
# on mouseDown but it would be a bad idea
# because the mouse could come "already-pressed"
# from outside the canvas
initialiseQueueIfNeeded = ->
if !@queue?
@queue = [0..24].map -> nil
mouseUpLeft = ->
if world.hand.isThisPointerDraggingSomething() then return
if @queue?
# draining the queue
contextMain = @underlyingCanvasMorph.getContextForPainting()
until @queue.length == 0
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
delete @queue
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
@initialiseQueueIfNeeded()
@queue.push pos
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.save()
contextMain.translate pos.x, pos.y
contextMain.fillStyle = Color.BLACK.toString()
#@paintBrush contextMain
contextMain.beginPath()
contextMain.arc 0,0,9,0,2*Math.PI
contextMain.fill()
contextMain.restore()
previousPos = @queue[0]
@queue.shift()
if previousPos?
contextMain.save()
contextMain.translate previousPos.x, previousPos.y
contextMain.fillStyle = Color.WHITE.toString()
@paintBrush contextMain
contextMain.restore()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
toothpasteToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new ToothpasteIconMorph @highlightedToolIconColor
toothpasteToolButtonOn.alpha = 0.1
toothpasteToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@toothpasteToolButton = new ToggleButtonMorph toothpasteToolButtonOff, toothpasteToolButtonOn
eraserToolButtonOff = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph
eraserToolButtonOff.alpha = 0.1
eraserToolButtonOff.sourceCodeToBeInjected = """
mouseMove = (pos, mouseButton) ->
if world.hand.isThisPointerDraggingSomething() then return
context = @backBufferContext
context.setTransform 1, 0, 0, 1, 0, 0
context.clearRect 0, 0, @width() * ceilPixelRatio, @height() * ceilPixelRatio
context.useLogicalPixelsUntilRestore()
context.translate -@bounds.origin.x, -@bounds.origin.y
context.translate pos.x, pos.y
context.beginPath()
context.lineWidth="2"
if mouseButton == 'left'
context.fillStyle = Color.RED.toString()
contextMain = @underlyingCanvasMorph.getContextForPainting()
contextMain.translate pos.x, pos.y
contextMain.beginPath()
contextMain.lineWidth="2"
contextMain.fillStyle = Color.WHITE.toString()
contextMain.rect(-5,-5,10,10)
contextMain.fill()
@underlyingCanvasMorph.changed()
else
context.strokeStyle=Color.GREEN.toString()
context.rect(-5,-5,10,10)
context.stroke()
@changed()
"""
eraserToolButtonOn = new CodeInjectingSimpleRectangularButtonMorph @, @overlayCanvas, new EraserIconMorph @highlightedToolIconColor
eraserToolButtonOn.alpha = 0.1
eraserToolButtonOn.sourceCodeToBeInjected = "mouseMove = -> return"
@eraserToolButton = new ToggleButtonMorph eraserToolButtonOff, eraserToolButtonOn
# pencilAnnotation
new EditableMarkMorph @pencilToolButton, pencilButtonOff, "editInjectableSource"
# brushAnnotation
new EditableMarkMorph @brushToolButton, brushToolButtonOff, "editInjectableSource"
# toothpasteAnnotation
new EditableMarkMorph @toothpasteToolButton, toothpasteToolButtonOff, "editInjectableSource"
# eraserAnnotation
new EditableMarkMorph @eraserToolButton, eraserToolButtonOff, "editInjectableSource"
@toolsPanel.add @pencilToolButton
@toolsPanel.add @brushToolButton
@toolsPanel.add @toothpasteToolButton
@toolsPanel.add @eraserToolButton
@pencilToolButton.toggle()
@invalidateLayout()
reLayout: ->
# here we are disabling all the broken
# rectangles. The reason is that all the
# submorphs of the inspector are within the
# bounds of the parent Widget. This means that
# if only the parent morph breaks its rectangle
# then everything is OK.
# Also note that if you attach something else to its
# boundary in a way that sticks out, that's still
# going to be painted and moved OK.
world.disableTrackChanges()
# label
labelLeft = @left() + @externalPadding
labelRight = @right() - @externalPadding
labelBottom = @top() + @externalPadding
# tools -------------------------------
if @toolsPanel? and @toolsPanel.parent == @
toolButtonSize = new Point 93, 55
else
toolButtonSize = new Point 0, 0
if @toolsPanel? and @toolsPanel.parent == @
@toolsPanel.fullRawMoveTo new Point @left() + @externalPadding, labelBottom
@toolsPanel.rawSetExtent new Point 2 * @internalPadding + toolButtonSize.width(), @height() - 2 * @externalPadding
if @pencilToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, labelBottom + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@pencilToolButton.doLayout buttonBounds
if @brushToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @pencilToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@brushToolButton.doLayout buttonBounds
if @toothpasteToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @brushToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@toothpasteToolButton.doLayout buttonBounds
if @eraserToolButton.parent == @toolsPanel
buttonBounds = new Rectangle new Point @toolsPanel.left() + @internalPadding, @toothpasteToolButton.bottom() + @internalPadding
buttonBounds = buttonBounds.setBoundsWidthAndHeight toolButtonSize
@eraserToolButton.doLayout buttonBounds
# stretchableWidgetContainer --------------------------
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerWidth = @width() - @toolsPanel.width() - 2*@externalPadding - @internalPadding
else
stretchableWidgetContainerWidth = @width() - 2*@externalPadding
stretchableWidgetContainerHeight = @height() - 2 * @externalPadding
if @toolsPanel? and @toolsPanel.parent == @
stretchableWidgetContainerLeft = @toolsPanel.right() + @internalPadding
else
stretchableWidgetContainerLeft = @left() + @externalPadding
if @stretchableWidgetContainer.parent == @
@stretchableWidgetContainer.fullRawMoveTo new Point stretchableWidgetContainerLeft, labelBottom
@stretchableWidgetContainer.setExtent new Point stretchableWidgetContainerWidth, stretchableWidgetContainerHeight
world.maybeEnableTrackChanges()
if Automator? and Automator.state != Automator.IDLE and Automator.alignmentOfMorphIDsMechanism
world.alignIDsOfNextMorphsInSystemTests()
@markLayoutAsFixed()
|
[
{
"context": "ctedProduct =\n id: 'xyz'\n key: 'key123'\n productType:\n typeId: 'prod",
"end": 4130,
"score": 0.9986766576766968,
"start": 4124,
"tag": "KEY",
"value": "key123"
},
{
"context": " id: '123'\n name:\n en: ... | src/spec/mapping.spec.coffee | easybi-vv/sphere-node-product-csv-sync-1 | 0 | _ = require 'underscore'
CONS = require '../lib/constants'
{Header, Mapping, Validator} = require '../lib/main'
Categories = require '../lib/categories'
# API Types
Types = require '../lib/types'
Categories = require '../lib/categories'
CustomerGroups = require '../lib/customergroups'
Taxes = require '../lib/taxes'
Channels = require '../lib/channels'
describe 'Mapping', ->
beforeEach ->
options = {
types : new Types(),
customerGroups : new CustomerGroups(),
categories : new Categories(),
taxes : new Taxes(),
channels : new Channels(),
}
@validator = new Validator(options)
@map = new Mapping(options)
describe '#constructor', ->
it 'should initialize', ->
expect(-> new Mapping()).toBeDefined()
expect(@map).toBeDefined()
describe '#isValidValue', ->
it 'should return false for undefined and null', ->
expect(@map.isValidValue(undefined)).toBe false
expect(@map.isValidValue(null)).toBe false
it 'should return false for empty string', ->
expect(@map.isValidValue('')).toBe false
expect(@map.isValidValue("")).toBe false
it 'should return true for strings with length > 0', ->
expect(@map.isValidValue("foo")).toBe true
describe '#ensureValidSlug', ->
it 'should accept unique slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
it 'should enhance duplicate slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
expect(@map.ensureValidSlug 'foo').toMatch /foo\d{5}/
it 'should fail for undefined or null', ->
expect(@map.ensureValidSlug undefined, 99).toBeUndefined()
expect(@map.errors[0]).toBe "[row 99:slug] Can't generate valid slug out of 'undefined'!"
expect(@map.ensureValidSlug null, 3).toBeUndefined()
expect(@map.errors[1]).toBe "[row 3:slug] Can't generate valid slug out of 'null'!"
it 'should fail for too short slug', ->
expect(@map.ensureValidSlug '1', 7).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:slug] Can't generate valid slug out of '1'!"
describe '#mapLocalizedAttrib', ->
it 'should create mapping for language attributes', (done) ->
csv =
"""
foo,name.de,bar,name.it
x,Hallo,y,ciao
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
values = @map.mapLocalizedAttrib parsed.data[0], CONS.HEADER_NAME, @validator.header.toLanguageIndex()
expect(_.size values).toBe 2
expect(values['de']).toBe 'Hallo'
expect(values['it']).toBe 'ciao'
done()
.catch done.fail
it 'should fallback to non localized column', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
aaa,,bbb
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a1', {})
expect(_.size values).toBe 1
expect(values['en']).toBe 'hi'
values = @map.mapLocalizedAttrib(parsed.data[1], 'a1', {})
expect(values).toBeUndefined()
done()
.catch done.fail
it 'should return undefined if header can not be found', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a2', {})
expect(values).toBeUndefined()
done()
.catch done.fail
describe '#mapBaseProduct', ->
it 'should map base product', (done) ->
csv =
"""
productType,id,name,variantId,key
foo,xyz,myProduct,1,key123
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
key: 'key123'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'myProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map base product with categories', (done) ->
csv =
"""
productType,id,name,variantId,categories
foo,xyz,myProduct,1,ext-123
"""
pt =
id: '123'
cts = [
id: '234'
name:
en: 'mockName'
slug:
en: 'mockSlug'
externalId: 'ext-123'
]
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@categories = new Categories
@categories.buildMaps cts
@map.categories = @categories
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'myProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: [
typeId: 'category'
id: '234'
]
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en,searchKeywords.fr-FR
product-type,1,xyz,myProduct,myproduct,some;new;search;keywords,bruxelle;liege;brugge,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'myProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
searchKeywords: {"en":[{"text":"some"},{"text":"new"},{"text":"search"},{"text":"keywords"}],"fr-FR":[{"text":"bruxelle"},{"text":"liege"},{"text":"brugge"}]}
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map empty search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en
product-type,1,xyz,myProduct,myproduct,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'myProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapVariant', ->
it 'should give feedback on bad variant id', ->
@map.header = new Header [ 'variantId' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'foo' ], 3, null, 7
expect(variant).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:variantId] The number 'foo' isn't valid!"
it 'should map variant with one attribute', ->
productType =
attributes: [
{ name: 'a2', type: { name: 'text' } }
]
@map.header = new Header [ 'a0', 'a1', 'a2', 'sku', 'variantId', 'variantKey' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'v0', 'v1', 'v2', 'mySKU', '9', 'vKey123' ], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
key: 'vKey123'
prices: []
attributes: [
name: 'a2'
value: 'v2'
]
images: []
expect(variant).toEqual expectedVariant
it 'should map conflicting attribute names', ->
productType =
name: 'prodType'
attributes: [
{
name: "description"
type: {
name: "ltext"
}
}
{
name: "productType"
type: {
name: "ltext"
}
}
{
name: "createdAt"
type: {
name: "number"
}
}
{
name: "slug"
type: {
name: "text"
}
}
{
name: "name"
type: {
name: "ltext"
}
}
]
@map.header = new Header [
'productType', 'sku', 'name.en','name.de','slug.en','slug.de','attribute.description.en',
'attribute.description.de','attribute.productType.en','attribute.productType.de',
'attribute.createdAt','attribute.slug','attribute.name.en','attribute.name.de'
]
@map.header.toIndex()
variant = @map.mapVariant [
'testConflict','mySKU','testNameEn','testNameDe','slugEn','slugDe','abcdEn','abcdDe','ptEn','ptDe','1234','slugTextAttr','nameAttrEn','nameAttrDe'
], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
prices: []
attributes: [
{ name: 'description', value: { en: 'abcdEn', de: 'abcdDe' } },
{ name: 'productType', value: { en: 'ptEn', de: 'ptDe' } },
{ name: 'createdAt', value: 1234 },
{ name: 'slug', value: 'slugTextAttr' },
{ name: 'name', value: { en: 'nameAttrEn', de: 'nameAttrDe' } }
]
images: []
expect(variant).toEqual expectedVariant
it 'should take over SameForAll contrainted attribute from master row', ->
@map.header = new Header [ 'aSame', 'variantId' ]
@map.header.toIndex()
productType =
attributes: [
{ name: 'aSame', type: { name: 'text' }, attributeConstraint: 'SameForAll' }
]
product =
masterVariant:
attributes: [
{ name: 'aSame', value: 'sameValue' }
]
variant = @map.mapVariant [ 'whatever', '11' ], 11, productType, 99, product
expectedVariant =
id: 11
prices: []
attributes: [
name: 'aSame'
value: 'sameValue'
]
images: []
expect(variant).toEqual expectedVariant
describe '#mapAttribute', ->
it 'should map simple text attribute', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ 'some text', 'blabla' ], productTypeAttribute
expectedAttribute =
name: 'foo'
value: 'some text'
expect(attribute).toEqual expectedAttribute
it 'should map ltext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'bar'
type:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'bar.en', 'bar.es' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'hi', 'hola' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'bar'
value:
en: 'hi'
es: 'hola'
expect(attribute).toEqual expectedAttribute
it 'should map set of lext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'baz'
type:
name: 'set'
elementType:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'baz.en', 'baz.de' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'foo1;foo2', 'barA;barB;barC' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'baz'
value: [
{"en": "foo1", "de": "barA"},
{"en": "foo2", "de": "barB"},
{"de": "barC"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of money attributes', ->
productType =
id: 'myType'
attributes: [
name: 'money-rules'
type:
name: 'set'
elementType:
name: 'money'
]
@map.header = new Header [ 'money-rules' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'EUR 200;USD 100' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'money-rules'
value: [
{"centAmount": 200, "currencyCode": "EUR"},
{"centAmount": 100, "currencyCode": "USD"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of number attributes', ->
productType =
id: 'myType'
attributes: [
name: 'numbers'
type:
name: 'set'
elementType:
name: 'number'
]
@map.header = new Header [ 'numbers' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '1;0;-1' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'numbers'
value: [ 1, 0, -1 ]
expect(attribute).toEqual expectedAttribute
it 'should map set of boolean attributes', ->
productType =
id: 'myType'
attributes: [
name: 'booleanAttr'
type:
name: 'set'
elementType:
name: 'boolean'
]
@map.header = new Header [ 'booleanAttr' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'true;false;1;0' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'booleanAttr'
value: [ true, false, true, false ]
expect(attribute).toEqual expectedAttribute
it 'should validate attribute value (undefined)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ undefined, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty object)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ {}, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty string)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ '', 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
describe '#mapPrices', ->
it 'should map single simple price', ->
prices = @map.mapPrices 'EUR 999'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 999
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when number part is not a number', ->
prices = @map.mapPrices 'EUR 9.99', 7
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:prices] Can not parse price 'EUR 9.99'!"
it 'should give feedback when when currency and amount isnt proper separated', ->
prices = @map.mapPrices 'EUR1', 8
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 8:prices] Can not parse price 'EUR1'!"
it 'should map price with country', ->
prices = @map.mapPrices 'CH-EUR 700'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 700
currencyCode: 'EUR'
country: 'CH'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when there are problems in parsing the country info ', ->
prices = @map.mapPrices 'CH-DE-EUR 700', 99
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 99:prices] Can not parse price 'CH-DE-EUR 700'!"
it 'should map price with customer group', ->
@map.customerGroups =
name2id:
'my Group 7': 'group123'
prices = @map.mapPrices 'GBP 0 my Group 7'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 0
currencyCode: 'GBP'
customerGroup:
typeId: 'customer-group'
id: 'group123'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom', ->
prices = @map.mapPrices 'EUR 234$2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
value:
centAmount: 234
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validUntil', ->
prices = @map.mapPrices 'EUR 1123~2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validUntil: '2001-09-11T14:00:00.000Z'
value:
centAmount: 1123
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom and validUntil', ->
prices = @map.mapPrices 'EUR 6352$2001-09-11T14:00:00.000Z~2015-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
validUntil: '2015-09-11T14:00:00.000Z'
value:
centAmount: 6352
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback that customer group does not exist', ->
prices = @map.mapPrices 'YEN 777 unknownGroup', 5
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 5:prices] Can not find customer group 'unknownGroup'!"
it 'should map price with channel', ->
@map.channels =
key2id:
retailerA: 'channelId123'
prices = @map.mapPrices 'YEN 19999#retailerA;USD 1 #retailerA', 1234
expect(prices.length).toBe 2
expect(@map.errors.length).toBe 0
expectedPrice =
value:
centAmount: 19999
currencyCode: 'YEN'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 1
currencyCode: 'USD'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[1]).toEqual expectedPrice
it 'should give feedback that channel with key does not exist', ->
prices = @map.mapPrices 'YEN 777 #nonExistingChannelKey', 42
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 42:prices] Can not find channel with key 'nonExistingChannelKey'!"
it 'should map price with customer group and channel', ->
@map.customerGroups =
name2id:
b2bCustomer: 'group_123'
@map.channels =
key2id:
'ware House-42': 'dwh_987'
prices = @map.mapPrices 'DE-EUR 100 b2bCustomer#ware House-42'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
country: 'DE'
channel:
typeId: 'channel'
id: 'dwh_987'
customerGroup:
typeId: 'customer-group'
id: 'group_123'
expect(prices[0]).toEqual expectedPrice
it 'should map multiple prices', ->
prices = @map.mapPrices 'EUR 100;UK-USD 200;YEN -999'
expect(prices.length).toBe 3
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 200
currencyCode: 'USD'
country: 'UK'
expect(prices[1]).toEqual expectedPrice
expectedPrice =
value:
centAmount: -999
currencyCode: 'YEN'
expect(prices[2]).toEqual expectedPrice
describe '#mapNumber', ->
it 'should map integer', ->
expect(@map.mapNumber('0')).toBe 0
it 'should map negative integer', ->
expect(@map.mapNumber('-100')).toBe -100
it 'should map float', ->
expect(@map.mapNumber('0.99')).toBe 0.99
it 'should map negative float', ->
expect(@map.mapNumber('-13.3333')).toBe -13.3333
it 'should fail when input is not a valid number', ->
number = @map.mapNumber '-10e5', 'myAttrib', 4
expect(number).toBeUndefined()
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The number '-10e5' isn't valid!"
describe '#mapInteger', ->
it 'should map integer', ->
expect(@map.mapInteger('11')).toBe 11
it 'should not map floats', ->
number = @map.mapInteger '-0.1', 'foo', 7
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:foo] The number '-0.1' isn't valid!"
describe '#mapBoolean', ->
it 'should map true', ->
expect(@map.mapBoolean('true')).toBe true
it 'should map true represented as a number', ->
expect(@map.mapBoolean('1')).toBe true
it 'should map false represented as a number', ->
expect(@map.mapBoolean('0')).toBe false
it 'should not map invalid number as a boolean', ->
expect(@map.mapBoolean('12345', 'myAttrib', '4')).toBe undefined
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The value '12345' isn't a valid boolean!"
it 'should map case insensitive', ->
expect(@map.mapBoolean('false')).toBe false
expect(@map.mapBoolean('False')).toBe false
expect(@map.mapBoolean('False')).toBe false
it 'should map the empty string', ->
expect(@map.mapBoolean('')).toBeUndefined()
it 'should map undefined', ->
expect(@map.mapBoolean()).toBeUndefined()
describe '#mapReference', ->
it 'should map a single reference', ->
attribute =
type:
referenceTypeId: 'product'
expect(@map.mapReference('123-456', attribute.type)).toEqual { id: '123-456', typeId: 'product' }
it 'should map set of references', ->
productType =
id: 'myType'
attributes: [
name: 'refAttrName'
type:
name: 'set'
elementType:
name: 'reference'
referenceTypeId: 'product'
]
@map.header = new Header [ 'refAttrName' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '123;456' ], productType.attributes[0], languageHeader2Index
expect(attribute).toEqual({
name: 'refAttrName'
value: [
{
id: '123',
typeId: 'product'
},
{
id: '456',
typeId: 'product'
}
]
})
describe '#mapProduct', ->
it 'should map a product', (done) ->
productType =
id: 'myType'
attributes: []
csv =
"""
productType,name,variantId,sku
foo,myProduct,1,x
,,2,y
,,3,z
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], productType
expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
categoryOrderHints: {}
variants: [
{ id: 2, sku: 'y', prices: [], attributes: [], images: [] }
{ id: 3, sku: 'z', prices: [], attributes: [], images: [] }
]
expect(data.product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapCategoryOrderHints', ->
beforeEach ->
@exampleCategory =
id: 'categoryId'
name:
en: 'myCoolCategory',
slug:
en: 'slug-123'
externalId: 'myExternalId'
# mock the categories
@map.categories.buildMaps([
@exampleCategory
])
@productType =
id: 'myType'
attributes: []
@expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
categoryOrderHints: {
categoryId: '0.9'
}
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
variants: []
it 'should should map the categoryOrderHints using a category id', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.id}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category name', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.name.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category slug', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.slug.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category externalId', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.externalId}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
| 190004 | _ = require 'underscore'
CONS = require '../lib/constants'
{Header, Mapping, Validator} = require '../lib/main'
Categories = require '../lib/categories'
# API Types
Types = require '../lib/types'
Categories = require '../lib/categories'
CustomerGroups = require '../lib/customergroups'
Taxes = require '../lib/taxes'
Channels = require '../lib/channels'
describe 'Mapping', ->
beforeEach ->
options = {
types : new Types(),
customerGroups : new CustomerGroups(),
categories : new Categories(),
taxes : new Taxes(),
channels : new Channels(),
}
@validator = new Validator(options)
@map = new Mapping(options)
describe '#constructor', ->
it 'should initialize', ->
expect(-> new Mapping()).toBeDefined()
expect(@map).toBeDefined()
describe '#isValidValue', ->
it 'should return false for undefined and null', ->
expect(@map.isValidValue(undefined)).toBe false
expect(@map.isValidValue(null)).toBe false
it 'should return false for empty string', ->
expect(@map.isValidValue('')).toBe false
expect(@map.isValidValue("")).toBe false
it 'should return true for strings with length > 0', ->
expect(@map.isValidValue("foo")).toBe true
describe '#ensureValidSlug', ->
it 'should accept unique slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
it 'should enhance duplicate slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
expect(@map.ensureValidSlug 'foo').toMatch /foo\d{5}/
it 'should fail for undefined or null', ->
expect(@map.ensureValidSlug undefined, 99).toBeUndefined()
expect(@map.errors[0]).toBe "[row 99:slug] Can't generate valid slug out of 'undefined'!"
expect(@map.ensureValidSlug null, 3).toBeUndefined()
expect(@map.errors[1]).toBe "[row 3:slug] Can't generate valid slug out of 'null'!"
it 'should fail for too short slug', ->
expect(@map.ensureValidSlug '1', 7).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:slug] Can't generate valid slug out of '1'!"
describe '#mapLocalizedAttrib', ->
it 'should create mapping for language attributes', (done) ->
csv =
"""
foo,name.de,bar,name.it
x,Hallo,y,ciao
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
values = @map.mapLocalizedAttrib parsed.data[0], CONS.HEADER_NAME, @validator.header.toLanguageIndex()
expect(_.size values).toBe 2
expect(values['de']).toBe 'Hallo'
expect(values['it']).toBe 'ciao'
done()
.catch done.fail
it 'should fallback to non localized column', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
aaa,,bbb
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a1', {})
expect(_.size values).toBe 1
expect(values['en']).toBe 'hi'
values = @map.mapLocalizedAttrib(parsed.data[1], 'a1', {})
expect(values).toBeUndefined()
done()
.catch done.fail
it 'should return undefined if header can not be found', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a2', {})
expect(values).toBeUndefined()
done()
.catch done.fail
describe '#mapBaseProduct', ->
it 'should map base product', (done) ->
csv =
"""
productType,id,name,variantId,key
foo,xyz,myProduct,1,key123
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
key: '<KEY>'
productType:
typeId: 'product-type'
id: '123'
name:
en: '<NAME>Product'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map base product with categories', (done) ->
csv =
"""
productType,id,name,variantId,categories
foo,xyz,myProduct,1,ext-123
"""
pt =
id: '123'
cts = [
id: '234'
name:
en: 'mockName'
slug:
en: 'mockSlug'
externalId: 'ext-123'
]
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@categories = new Categories
@categories.buildMaps cts
@map.categories = @categories
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: '<NAME>'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: [
typeId: 'category'
id: '234'
]
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en,searchKeywords.fr-FR
product-type,1,xyz,myProduct,myproduct,some;new;search;keywords,bruxelle;liege;brugge,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: '<NAME>Product'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
searchKeywords: {"en":[{"text":"some"},{"text":"new"},{"text":"search"},{"text":"keywords"}],"fr-FR":[{"text":"bruxelle"},{"text":"liege"},{"text":"brugge"}]}
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map empty search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en
product-type,1,xyz,myProduct,myproduct,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: '<NAME>'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapVariant', ->
it 'should give feedback on bad variant id', ->
@map.header = new Header [ 'variantId' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'foo' ], 3, null, 7
expect(variant).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:variantId] The number 'foo' isn't valid!"
it 'should map variant with one attribute', ->
productType =
attributes: [
{ name: 'a2', type: { name: 'text' } }
]
@map.header = new Header [ 'a0', 'a1', 'a2', 'sku', 'variantId', 'variantKey' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'v0', 'v1', 'v2', 'mySKU', '9', 'vKey123' ], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
key: '<KEY>'
prices: []
attributes: [
name: 'a2'
value: 'v2'
]
images: []
expect(variant).toEqual expectedVariant
it 'should map conflicting attribute names', ->
productType =
name: 'prodType'
attributes: [
{
name: "description"
type: {
name: "ltext"
}
}
{
name: "productType"
type: {
name: "ltext"
}
}
{
name: "createdAt"
type: {
name: "number"
}
}
{
name: "slug"
type: {
name: "text"
}
}
{
name: "name"
type: {
name: "ltext"
}
}
]
@map.header = new Header [
'productType', 'sku', 'name.en','name.de','slug.en','slug.de','attribute.description.en',
'attribute.description.de','attribute.productType.en','attribute.productType.de',
'attribute.createdAt','attribute.slug','attribute.name.en','attribute.name.de'
]
@map.header.toIndex()
variant = @map.mapVariant [
'testConflict','mySKU','testNameEn','testNameDe','slugEn','slugDe','abcdEn','abcdDe','ptEn','ptDe','1234','slugTextAttr','nameAttrEn','nameAttrDe'
], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
prices: []
attributes: [
{ name: 'description', value: { en: 'abcdEn', de: 'abcdDe' } },
{ name: 'productType', value: { en: 'ptEn', de: 'ptDe' } },
{ name: 'createdAt', value: 1234 },
{ name: 'slug', value: 'slugTextAttr' },
{ name: 'name', value: { en: 'nameAttrEn', de: 'nameAttrDe' } }
]
images: []
expect(variant).toEqual expectedVariant
it 'should take over SameForAll contrainted attribute from master row', ->
@map.header = new Header [ 'aSame', 'variantId' ]
@map.header.toIndex()
productType =
attributes: [
{ name: 'aSame', type: { name: 'text' }, attributeConstraint: 'SameForAll' }
]
product =
masterVariant:
attributes: [
{ name: 'aSame', value: 'sameValue' }
]
variant = @map.mapVariant [ 'whatever', '11' ], 11, productType, 99, product
expectedVariant =
id: 11
prices: []
attributes: [
name: 'aSame'
value: 'sameValue'
]
images: []
expect(variant).toEqual expectedVariant
describe '#mapAttribute', ->
it 'should map simple text attribute', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ 'some text', 'blabla' ], productTypeAttribute
expectedAttribute =
name: 'foo'
value: 'some text'
expect(attribute).toEqual expectedAttribute
it 'should map ltext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'bar'
type:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'bar.en', 'bar.es' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'hi', 'hola' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'bar'
value:
en: 'hi'
es: 'hola'
expect(attribute).toEqual expectedAttribute
it 'should map set of lext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'baz'
type:
name: 'set'
elementType:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'baz.en', 'baz.de' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'foo1;foo2', 'barA;barB;barC' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'baz'
value: [
{"en": "foo1", "de": "barA"},
{"en": "foo2", "de": "barB"},
{"de": "barC"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of money attributes', ->
productType =
id: 'myType'
attributes: [
name: 'money-rules'
type:
name: 'set'
elementType:
name: 'money'
]
@map.header = new Header [ 'money-rules' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'EUR 200;USD 100' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'money-rules'
value: [
{"centAmount": 200, "currencyCode": "EUR"},
{"centAmount": 100, "currencyCode": "USD"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of number attributes', ->
productType =
id: 'myType'
attributes: [
name: 'numbers'
type:
name: 'set'
elementType:
name: 'number'
]
@map.header = new Header [ 'numbers' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '1;0;-1' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'numbers'
value: [ 1, 0, -1 ]
expect(attribute).toEqual expectedAttribute
it 'should map set of boolean attributes', ->
productType =
id: 'myType'
attributes: [
name: 'booleanAttr'
type:
name: 'set'
elementType:
name: 'boolean'
]
@map.header = new Header [ 'booleanAttr' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'true;false;1;0' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'booleanAttr'
value: [ true, false, true, false ]
expect(attribute).toEqual expectedAttribute
it 'should validate attribute value (undefined)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ undefined, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty object)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ {}, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty string)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ '', 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
describe '#mapPrices', ->
it 'should map single simple price', ->
prices = @map.mapPrices 'EUR 999'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 999
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when number part is not a number', ->
prices = @map.mapPrices 'EUR 9.99', 7
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:prices] Can not parse price 'EUR 9.99'!"
it 'should give feedback when when currency and amount isnt proper separated', ->
prices = @map.mapPrices 'EUR1', 8
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 8:prices] Can not parse price 'EUR1'!"
it 'should map price with country', ->
prices = @map.mapPrices 'CH-EUR 700'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 700
currencyCode: 'EUR'
country: 'CH'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when there are problems in parsing the country info ', ->
prices = @map.mapPrices 'CH-DE-EUR 700', 99
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 99:prices] Can not parse price 'CH-DE-EUR 700'!"
it 'should map price with customer group', ->
@map.customerGroups =
name2id:
'my Group 7': 'group123'
prices = @map.mapPrices 'GBP 0 my Group 7'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 0
currencyCode: 'GBP'
customerGroup:
typeId: 'customer-group'
id: 'group123'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom', ->
prices = @map.mapPrices 'EUR 234$2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
value:
centAmount: 234
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validUntil', ->
prices = @map.mapPrices 'EUR 1123~2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validUntil: '2001-09-11T14:00:00.000Z'
value:
centAmount: 1123
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom and validUntil', ->
prices = @map.mapPrices 'EUR 6352$2001-09-11T14:00:00.000Z~2015-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
validUntil: '2015-09-11T14:00:00.000Z'
value:
centAmount: 6352
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback that customer group does not exist', ->
prices = @map.mapPrices 'YEN 777 unknownGroup', 5
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 5:prices] Can not find customer group 'unknownGroup'!"
it 'should map price with channel', ->
@map.channels =
key2id:
retailerA: 'channelId<KEY>23'
prices = @map.mapPrices 'YEN 19999#retailerA;USD 1 #retailerA', 1234
expect(prices.length).toBe 2
expect(@map.errors.length).toBe 0
expectedPrice =
value:
centAmount: 19999
currencyCode: 'YEN'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 1
currencyCode: 'USD'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[1]).toEqual expectedPrice
it 'should give feedback that channel with key does not exist', ->
prices = @map.mapPrices 'YEN 777 #nonExistingChannelKey', 42
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 42:prices] Can not find channel with key 'nonExistingChannelKey'!"
it 'should map price with customer group and channel', ->
@map.customerGroups =
name2id:
b2bCustomer: 'group_123'
@map.channels =
key2id:
'<KEY>': '<KEY>'
prices = @map.mapPrices 'DE-EUR 100 b2bCustomer#ware House-42'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
country: 'DE'
channel:
typeId: 'channel'
id: 'dwh_987'
customerGroup:
typeId: 'customer-group'
id: 'group_123'
expect(prices[0]).toEqual expectedPrice
it 'should map multiple prices', ->
prices = @map.mapPrices 'EUR 100;UK-USD 200;YEN -999'
expect(prices.length).toBe 3
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 200
currencyCode: 'USD'
country: 'UK'
expect(prices[1]).toEqual expectedPrice
expectedPrice =
value:
centAmount: -999
currencyCode: '<NAME>'
expect(prices[2]).toEqual expectedPrice
describe '#mapNumber', ->
it 'should map integer', ->
expect(@map.mapNumber('0')).toBe 0
it 'should map negative integer', ->
expect(@map.mapNumber('-100')).toBe -100
it 'should map float', ->
expect(@map.mapNumber('0.99')).toBe 0.99
it 'should map negative float', ->
expect(@map.mapNumber('-13.3333')).toBe -13.3333
it 'should fail when input is not a valid number', ->
number = @map.mapNumber '-10e5', 'myAttrib', 4
expect(number).toBeUndefined()
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The number '-10e5' isn't valid!"
describe '#mapInteger', ->
it 'should map integer', ->
expect(@map.mapInteger('11')).toBe 11
it 'should not map floats', ->
number = @map.mapInteger '-0.1', 'foo', 7
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:foo] The number '-0.1' isn't valid!"
describe '#mapBoolean', ->
it 'should map true', ->
expect(@map.mapBoolean('true')).toBe true
it 'should map true represented as a number', ->
expect(@map.mapBoolean('1')).toBe true
it 'should map false represented as a number', ->
expect(@map.mapBoolean('0')).toBe false
it 'should not map invalid number as a boolean', ->
expect(@map.mapBoolean('12345', 'myAttrib', '4')).toBe undefined
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The value '12345' isn't a valid boolean!"
it 'should map case insensitive', ->
expect(@map.mapBoolean('false')).toBe false
expect(@map.mapBoolean('False')).toBe false
expect(@map.mapBoolean('False')).toBe false
it 'should map the empty string', ->
expect(@map.mapBoolean('')).toBeUndefined()
it 'should map undefined', ->
expect(@map.mapBoolean()).toBeUndefined()
describe '#mapReference', ->
it 'should map a single reference', ->
attribute =
type:
referenceTypeId: 'product'
expect(@map.mapReference('123-456', attribute.type)).toEqual { id: '123-456', typeId: 'product' }
it 'should map set of references', ->
productType =
id: 'myType'
attributes: [
name: 'refAttrName'
type:
name: 'set'
elementType:
name: 'reference'
referenceTypeId: 'product'
]
@map.header = new Header [ 'refAttrName' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '123;456' ], productType.attributes[0], languageHeader2Index
expect(attribute).toEqual({
name: 'refAttrName'
value: [
{
id: '123',
typeId: 'product'
},
{
id: '456',
typeId: 'product'
}
]
})
describe '#mapProduct', ->
it 'should map a product', (done) ->
productType =
id: 'myType'
attributes: []
csv =
"""
productType,name,variantId,sku
foo,myProduct,1,x
,,2,y
,,3,z
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], productType
expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
categoryOrderHints: {}
variants: [
{ id: 2, sku: 'y', prices: [], attributes: [], images: [] }
{ id: 3, sku: 'z', prices: [], attributes: [], images: [] }
]
expect(data.product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapCategoryOrderHints', ->
beforeEach ->
@exampleCategory =
id: 'categoryId'
name:
en: 'myCoolCategory',
slug:
en: 'slug-123'
externalId: 'myExternalId'
# mock the categories
@map.categories.buildMaps([
@exampleCategory
])
@productType =
id: 'myType'
attributes: []
@expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
categoryOrderHints: {
categoryId: '0.9'
}
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
variants: []
it 'should should map the categoryOrderHints using a category id', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.id}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category name', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.name.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category slug', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.slug.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category externalId', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.externalId}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
| true | _ = require 'underscore'
CONS = require '../lib/constants'
{Header, Mapping, Validator} = require '../lib/main'
Categories = require '../lib/categories'
# API Types
Types = require '../lib/types'
Categories = require '../lib/categories'
CustomerGroups = require '../lib/customergroups'
Taxes = require '../lib/taxes'
Channels = require '../lib/channels'
describe 'Mapping', ->
beforeEach ->
options = {
types : new Types(),
customerGroups : new CustomerGroups(),
categories : new Categories(),
taxes : new Taxes(),
channels : new Channels(),
}
@validator = new Validator(options)
@map = new Mapping(options)
describe '#constructor', ->
it 'should initialize', ->
expect(-> new Mapping()).toBeDefined()
expect(@map).toBeDefined()
describe '#isValidValue', ->
it 'should return false for undefined and null', ->
expect(@map.isValidValue(undefined)).toBe false
expect(@map.isValidValue(null)).toBe false
it 'should return false for empty string', ->
expect(@map.isValidValue('')).toBe false
expect(@map.isValidValue("")).toBe false
it 'should return true for strings with length > 0', ->
expect(@map.isValidValue("foo")).toBe true
describe '#ensureValidSlug', ->
it 'should accept unique slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
it 'should enhance duplicate slug', ->
expect(@map.ensureValidSlug 'foo').toBe 'foo'
expect(@map.ensureValidSlug 'foo').toMatch /foo\d{5}/
it 'should fail for undefined or null', ->
expect(@map.ensureValidSlug undefined, 99).toBeUndefined()
expect(@map.errors[0]).toBe "[row 99:slug] Can't generate valid slug out of 'undefined'!"
expect(@map.ensureValidSlug null, 3).toBeUndefined()
expect(@map.errors[1]).toBe "[row 3:slug] Can't generate valid slug out of 'null'!"
it 'should fail for too short slug', ->
expect(@map.ensureValidSlug '1', 7).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:slug] Can't generate valid slug out of '1'!"
describe '#mapLocalizedAttrib', ->
it 'should create mapping for language attributes', (done) ->
csv =
"""
foo,name.de,bar,name.it
x,Hallo,y,ciao
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
values = @map.mapLocalizedAttrib parsed.data[0], CONS.HEADER_NAME, @validator.header.toLanguageIndex()
expect(_.size values).toBe 2
expect(values['de']).toBe 'Hallo'
expect(values['it']).toBe 'ciao'
done()
.catch done.fail
it 'should fallback to non localized column', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
aaa,,bbb
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a1', {})
expect(_.size values).toBe 1
expect(values['en']).toBe 'hi'
values = @map.mapLocalizedAttrib(parsed.data[1], 'a1', {})
expect(values).toBeUndefined()
done()
.catch done.fail
it 'should return undefined if header can not be found', (done) ->
csv =
"""
foo,a1,bar
x,hi,y
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.header.toIndex()
values = @map.mapLocalizedAttrib(parsed.data[0], 'a2', {})
expect(values).toBeUndefined()
done()
.catch done.fail
describe '#mapBaseProduct', ->
it 'should map base product', (done) ->
csv =
"""
productType,id,name,variantId,key
foo,xyz,myProduct,1,key123
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
key: 'PI:KEY:<KEY>END_PI'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'PI:NAME:<NAME>END_PIProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map base product with categories', (done) ->
csv =
"""
productType,id,name,variantId,categories
foo,xyz,myProduct,1,ext-123
"""
pt =
id: '123'
cts = [
id: '234'
name:
en: 'mockName'
slug:
en: 'mockSlug'
externalId: 'ext-123'
]
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@categories = new Categories
@categories.buildMaps cts
@map.categories = @categories
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'PI:NAME:<NAME>END_PI'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: [
typeId: 'category'
id: '234'
]
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en,searchKeywords.fr-FR
product-type,1,xyz,myProduct,myproduct,some;new;search;keywords,bruxelle;liege;brugge,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'PI:NAME:<NAME>END_PIProduct'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
searchKeywords: {"en":[{"text":"some"},{"text":"new"},{"text":"search"},{"text":"keywords"}],"fr-FR":[{"text":"bruxelle"},{"text":"liege"},{"text":"brugge"}]}
expect(product).toEqual expectedProduct
done()
.catch done.fail
it 'should map empty search keywords', (done) ->
csv =
"""
productType,variantId,id,name.en,slug.en,searchKeywords.en
product-type,1,xyz,myProduct,myproduct,
"""
pt =
id: '123'
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
product = @map.mapBaseProduct @validator.rawProducts[0].master, pt
expectedProduct =
id: 'xyz'
productType:
typeId: 'product-type'
id: '123'
name:
en: 'PI:NAME:<NAME>END_PI'
slug:
en: 'myproduct'
masterVariant: {}
categoryOrderHints: {}
variants: []
categories: []
expect(product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapVariant', ->
it 'should give feedback on bad variant id', ->
@map.header = new Header [ 'variantId' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'foo' ], 3, null, 7
expect(variant).toBeUndefined()
expect(_.size @map.errors).toBe 1
expect(@map.errors[0]).toBe "[row 7:variantId] The number 'foo' isn't valid!"
it 'should map variant with one attribute', ->
productType =
attributes: [
{ name: 'a2', type: { name: 'text' } }
]
@map.header = new Header [ 'a0', 'a1', 'a2', 'sku', 'variantId', 'variantKey' ]
@map.header.toIndex()
variant = @map.mapVariant [ 'v0', 'v1', 'v2', 'mySKU', '9', 'vKey123' ], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
key: 'PI:KEY:<KEY>END_PI'
prices: []
attributes: [
name: 'a2'
value: 'v2'
]
images: []
expect(variant).toEqual expectedVariant
it 'should map conflicting attribute names', ->
productType =
name: 'prodType'
attributes: [
{
name: "description"
type: {
name: "ltext"
}
}
{
name: "productType"
type: {
name: "ltext"
}
}
{
name: "createdAt"
type: {
name: "number"
}
}
{
name: "slug"
type: {
name: "text"
}
}
{
name: "name"
type: {
name: "ltext"
}
}
]
@map.header = new Header [
'productType', 'sku', 'name.en','name.de','slug.en','slug.de','attribute.description.en',
'attribute.description.de','attribute.productType.en','attribute.productType.de',
'attribute.createdAt','attribute.slug','attribute.name.en','attribute.name.de'
]
@map.header.toIndex()
variant = @map.mapVariant [
'testConflict','mySKU','testNameEn','testNameDe','slugEn','slugDe','abcdEn','abcdDe','ptEn','ptDe','1234','slugTextAttr','nameAttrEn','nameAttrDe'
], 9, productType, 77
expectedVariant =
id: 9
sku: 'mySKU'
prices: []
attributes: [
{ name: 'description', value: { en: 'abcdEn', de: 'abcdDe' } },
{ name: 'productType', value: { en: 'ptEn', de: 'ptDe' } },
{ name: 'createdAt', value: 1234 },
{ name: 'slug', value: 'slugTextAttr' },
{ name: 'name', value: { en: 'nameAttrEn', de: 'nameAttrDe' } }
]
images: []
expect(variant).toEqual expectedVariant
it 'should take over SameForAll contrainted attribute from master row', ->
@map.header = new Header [ 'aSame', 'variantId' ]
@map.header.toIndex()
productType =
attributes: [
{ name: 'aSame', type: { name: 'text' }, attributeConstraint: 'SameForAll' }
]
product =
masterVariant:
attributes: [
{ name: 'aSame', value: 'sameValue' }
]
variant = @map.mapVariant [ 'whatever', '11' ], 11, productType, 99, product
expectedVariant =
id: 11
prices: []
attributes: [
name: 'aSame'
value: 'sameValue'
]
images: []
expect(variant).toEqual expectedVariant
describe '#mapAttribute', ->
it 'should map simple text attribute', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ 'some text', 'blabla' ], productTypeAttribute
expectedAttribute =
name: 'foo'
value: 'some text'
expect(attribute).toEqual expectedAttribute
it 'should map ltext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'bar'
type:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'bar.en', 'bar.es' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'hi', 'hola' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'bar'
value:
en: 'hi'
es: 'hola'
expect(attribute).toEqual expectedAttribute
it 'should map set of lext attribute', ->
productType =
id: 'myType'
attributes: [
name: 'baz'
type:
name: 'set'
elementType:
name: 'ltext'
]
@map.header = new Header [ 'foo', 'baz.en', 'baz.de' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'some text', 'foo1;foo2', 'barA;barB;barC' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'baz'
value: [
{"en": "foo1", "de": "barA"},
{"en": "foo2", "de": "barB"},
{"de": "barC"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of money attributes', ->
productType =
id: 'myType'
attributes: [
name: 'money-rules'
type:
name: 'set'
elementType:
name: 'money'
]
@map.header = new Header [ 'money-rules' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'EUR 200;USD 100' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'money-rules'
value: [
{"centAmount": 200, "currencyCode": "EUR"},
{"centAmount": 100, "currencyCode": "USD"}
]
expect(attribute).toEqual expectedAttribute
it 'should map set of number attributes', ->
productType =
id: 'myType'
attributes: [
name: 'numbers'
type:
name: 'set'
elementType:
name: 'number'
]
@map.header = new Header [ 'numbers' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '1;0;-1' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'numbers'
value: [ 1, 0, -1 ]
expect(attribute).toEqual expectedAttribute
it 'should map set of boolean attributes', ->
productType =
id: 'myType'
attributes: [
name: 'booleanAttr'
type:
name: 'set'
elementType:
name: 'boolean'
]
@map.header = new Header [ 'booleanAttr' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ 'true;false;1;0' ], productType.attributes[0], languageHeader2Index
expectedAttribute =
name: 'booleanAttr'
value: [ true, false, true, false ]
expect(attribute).toEqual expectedAttribute
it 'should validate attribute value (undefined)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ undefined, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty object)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ {}, 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
it 'should validate attribute value (empty string)', ->
productTypeAttribute =
name: 'foo'
type:
name: 'text'
@map.header = new Header [ 'foo', 'bar' ]
attribute = @map.mapAttribute [ '', 'blabla' ], productTypeAttribute
expect(attribute).not.toBeDefined()
describe '#mapPrices', ->
it 'should map single simple price', ->
prices = @map.mapPrices 'EUR 999'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 999
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when number part is not a number', ->
prices = @map.mapPrices 'EUR 9.99', 7
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:prices] Can not parse price 'EUR 9.99'!"
it 'should give feedback when when currency and amount isnt proper separated', ->
prices = @map.mapPrices 'EUR1', 8
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 8:prices] Can not parse price 'EUR1'!"
it 'should map price with country', ->
prices = @map.mapPrices 'CH-EUR 700'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 700
currencyCode: 'EUR'
country: 'CH'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback when there are problems in parsing the country info ', ->
prices = @map.mapPrices 'CH-DE-EUR 700', 99
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 99:prices] Can not parse price 'CH-DE-EUR 700'!"
it 'should map price with customer group', ->
@map.customerGroups =
name2id:
'my Group 7': 'group123'
prices = @map.mapPrices 'GBP 0 my Group 7'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 0
currencyCode: 'GBP'
customerGroup:
typeId: 'customer-group'
id: 'group123'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom', ->
prices = @map.mapPrices 'EUR 234$2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
value:
centAmount: 234
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validUntil', ->
prices = @map.mapPrices 'EUR 1123~2001-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validUntil: '2001-09-11T14:00:00.000Z'
value:
centAmount: 1123
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should map price with validFrom and validUntil', ->
prices = @map.mapPrices 'EUR 6352$2001-09-11T14:00:00.000Z~2015-09-11T14:00:00.000Z'
expect(prices.length).toBe 1
expectedPrice =
validFrom: '2001-09-11T14:00:00.000Z'
validUntil: '2015-09-11T14:00:00.000Z'
value:
centAmount: 6352
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
it 'should give feedback that customer group does not exist', ->
prices = @map.mapPrices 'YEN 777 unknownGroup', 5
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 5:prices] Can not find customer group 'unknownGroup'!"
it 'should map price with channel', ->
@map.channels =
key2id:
retailerA: 'channelIdPI:KEY:<KEY>END_PI23'
prices = @map.mapPrices 'YEN 19999#retailerA;USD 1 #retailerA', 1234
expect(prices.length).toBe 2
expect(@map.errors.length).toBe 0
expectedPrice =
value:
centAmount: 19999
currencyCode: 'YEN'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 1
currencyCode: 'USD'
channel:
typeId: 'channel'
id: 'channelId123'
expect(prices[1]).toEqual expectedPrice
it 'should give feedback that channel with key does not exist', ->
prices = @map.mapPrices 'YEN 777 #nonExistingChannelKey', 42
expect(prices.length).toBe 0
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 42:prices] Can not find channel with key 'nonExistingChannelKey'!"
it 'should map price with customer group and channel', ->
@map.customerGroups =
name2id:
b2bCustomer: 'group_123'
@map.channels =
key2id:
'PI:KEY:<KEY>END_PI': 'PI:KEY:<KEY>END_PI'
prices = @map.mapPrices 'DE-EUR 100 b2bCustomer#ware House-42'
expect(prices.length).toBe 1
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
country: 'DE'
channel:
typeId: 'channel'
id: 'dwh_987'
customerGroup:
typeId: 'customer-group'
id: 'group_123'
expect(prices[0]).toEqual expectedPrice
it 'should map multiple prices', ->
prices = @map.mapPrices 'EUR 100;UK-USD 200;YEN -999'
expect(prices.length).toBe 3
expectedPrice =
value:
centAmount: 100
currencyCode: 'EUR'
expect(prices[0]).toEqual expectedPrice
expectedPrice =
value:
centAmount: 200
currencyCode: 'USD'
country: 'UK'
expect(prices[1]).toEqual expectedPrice
expectedPrice =
value:
centAmount: -999
currencyCode: 'PI:NAME:<NAME>END_PI'
expect(prices[2]).toEqual expectedPrice
describe '#mapNumber', ->
it 'should map integer', ->
expect(@map.mapNumber('0')).toBe 0
it 'should map negative integer', ->
expect(@map.mapNumber('-100')).toBe -100
it 'should map float', ->
expect(@map.mapNumber('0.99')).toBe 0.99
it 'should map negative float', ->
expect(@map.mapNumber('-13.3333')).toBe -13.3333
it 'should fail when input is not a valid number', ->
number = @map.mapNumber '-10e5', 'myAttrib', 4
expect(number).toBeUndefined()
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The number '-10e5' isn't valid!"
describe '#mapInteger', ->
it 'should map integer', ->
expect(@map.mapInteger('11')).toBe 11
it 'should not map floats', ->
number = @map.mapInteger '-0.1', 'foo', 7
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 7:foo] The number '-0.1' isn't valid!"
describe '#mapBoolean', ->
it 'should map true', ->
expect(@map.mapBoolean('true')).toBe true
it 'should map true represented as a number', ->
expect(@map.mapBoolean('1')).toBe true
it 'should map false represented as a number', ->
expect(@map.mapBoolean('0')).toBe false
it 'should not map invalid number as a boolean', ->
expect(@map.mapBoolean('12345', 'myAttrib', '4')).toBe undefined
expect(@map.errors.length).toBe 1
expect(@map.errors[0]).toBe "[row 4:myAttrib] The value '12345' isn't a valid boolean!"
it 'should map case insensitive', ->
expect(@map.mapBoolean('false')).toBe false
expect(@map.mapBoolean('False')).toBe false
expect(@map.mapBoolean('False')).toBe false
it 'should map the empty string', ->
expect(@map.mapBoolean('')).toBeUndefined()
it 'should map undefined', ->
expect(@map.mapBoolean()).toBeUndefined()
describe '#mapReference', ->
it 'should map a single reference', ->
attribute =
type:
referenceTypeId: 'product'
expect(@map.mapReference('123-456', attribute.type)).toEqual { id: '123-456', typeId: 'product' }
it 'should map set of references', ->
productType =
id: 'myType'
attributes: [
name: 'refAttrName'
type:
name: 'set'
elementType:
name: 'reference'
referenceTypeId: 'product'
]
@map.header = new Header [ 'refAttrName' ]
languageHeader2Index = @map.header._productTypeLanguageIndexes productType
attribute = @map.mapAttribute [ '123;456' ], productType.attributes[0], languageHeader2Index
expect(attribute).toEqual({
name: 'refAttrName'
value: [
{
id: '123',
typeId: 'product'
},
{
id: '456',
typeId: 'product'
}
]
})
describe '#mapProduct', ->
it 'should map a product', (done) ->
productType =
id: 'myType'
attributes: []
csv =
"""
productType,name,variantId,sku
foo,myProduct,1,x
,,2,y
,,3,z
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], productType
expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
categoryOrderHints: {}
variants: [
{ id: 2, sku: 'y', prices: [], attributes: [], images: [] }
{ id: 3, sku: 'z', prices: [], attributes: [], images: [] }
]
expect(data.product).toEqual expectedProduct
done()
.catch done.fail
describe '#mapCategoryOrderHints', ->
beforeEach ->
@exampleCategory =
id: 'categoryId'
name:
en: 'myCoolCategory',
slug:
en: 'slug-123'
externalId: 'myExternalId'
# mock the categories
@map.categories.buildMaps([
@exampleCategory
])
@productType =
id: 'myType'
attributes: []
@expectedProduct =
productType:
typeId: 'product-type'
id: 'myType'
name:
en: 'myProduct'
slug:
en: 'myproduct'
categories: []
categoryOrderHints: {
categoryId: '0.9'
}
masterVariant: {
id: 1
sku: 'x'
prices: []
attributes: []
images: []
}
variants: []
it 'should should map the categoryOrderHints using a category id', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.id}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category name', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.name.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category slug', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.slug.en}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
it 'should should map the categoryOrderHints using a category externalId', (done) ->
csv =
"""
productType,name,variantId,sku,categoryOrderHints
foo,myProduct,1,x,#{@exampleCategory.externalId}:0.9
"""
@validator.parse csv
.then (parsed) =>
@map.header = parsed.header
@validator.validateOffline parsed.data
data = @map.mapProduct @validator.rawProducts[0], @productType
expect(data.product).toEqual @expectedProduct
done()
.catch done.fail
|
[
{
"context": " \"localId\" : \"10\",\n \"name\" : \"a\",\n \"elementType\" : {\n ",
"end": 2481,
"score": 0.7457435131072998,
"start": 2480,
"tag": "NAME",
"value": "a"
},
{
"context": " \"localId\" : \"12\",\n \"name... | test/elm/parameters/data.coffee | luis1van/cql-execution-1 | 0 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
parameter IntParameter Integer
parameter ListParameter List<String>
parameter TupleParameter Tuple{a Integer, b String, c Boolean, d List<Integer>, e Tuple{ f String, g Boolean}}
context Patient
define foo: 'bar'
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "MeasureYear",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "IntParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "ListParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "7",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "6",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "25",
"name" : "TupleParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "24",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "10",
"name" : "a",
"elementType" : {
"localId" : "9",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "12",
"name" : "b",
"elementType" : {
"localId" : "11",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "14",
"name" : "c",
"elementType" : {
"localId" : "13",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "17",
"name" : "d",
"elementType" : {
"localId" : "16",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "15",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "23",
"name" : "e",
"elementType" : {
"localId" : "22",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "19",
"name" : "f",
"elementType" : {
"localId" : "18",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "21",
"name" : "g",
"elementType" : {
"localId" : "20",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
} ]
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "27",
"name" : "foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "27",
"s" : [ {
"value" : [ "define ","foo",": " ]
}, {
"r" : "26",
"s" : [ {
"value" : [ "'bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "26",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "bar",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo: FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "5",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "FooP",
"type" : "ParameterRef"
}
} ]
}
}
}
### BooleanParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Boolean
parameter FooDP default true
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['BooleanParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DecimalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Decimal
parameter FooDP default 1.5
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DecimalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Decimal",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "1.5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntegerParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Integer
parameter FooDP default 2
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntegerParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### StringParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP String
parameter FooDP default 'Hello'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['StringParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### CodeParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Code
parameter FooDP default Code 'FooTest' from "FOOTESTCS" display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['CodeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Code",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "7",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "6",
"code" : "FooTest",
"display" : "Foo Test",
"type" : "Code",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "9",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "11",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### ConceptParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Concept
parameter FooDP default Concept { Code 'FooTest' from "FOOTESTCS" } display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ConceptParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Concept",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"display" : "Foo Test",
"type" : "Concept",
"code" : [ {
"localId" : "6",
"code" : "FooTest",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
} ]
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateTimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP DateTime
parameter FooDP default @2012-04-01T12:11:10
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateTimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "11",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Date
parameter FooDP default @2012-04-01
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Date",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Date",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### QuantityParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Quantity
parameter FooDP default 10 'dL'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['QuantityParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Quantity",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"value" : 10,
"unit" : "dL",
"type" : "Quantity"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### TimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Time
parameter FooDP default @T12:00:00
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Time",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### ListParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP List<String>
parameter FooDP default { 'a', 'b', 'c' }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ListParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "9",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "8",
"type" : "List",
"element" : [ {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "a",
"type" : "Literal"
}, {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "b",
"type" : "Literal"
}, {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "c",
"type" : "Literal"
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "11",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "13",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntervalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Interval<Integer>
parameter FooDP default Interval[2,6]
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntervalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "8",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"high" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "6",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### TupleParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Tuple { Hello String, MeaningOfLife Integer }
parameter FooDP default Tuple { Hello: 'Universe', MeaningOfLife: 24 }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TupleParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "7",
"name" : "FooP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "6",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "3",
"name" : "Hello",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "MeaningOfLife",
"elementType" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}
}, {
"localId" : "11",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "10",
"type" : "Tuple",
"element" : [ {
"name" : "Hello",
"value" : {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Universe",
"type" : "Literal"
}
}, {
"name" : "MeaningOfLife",
"value" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "24",
"type" : "Literal"
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "13",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "FooP",
"type" : "ParameterRef"
}
}, {
"localId" : "15",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "15",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "14",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DefaultAndNoDefault
library TestSnippet version '1'
using QUICK
parameter FooWithNoDefault Integer
parameter FooWithDefault default 5
context Patient
define Foo: FooWithNoDefault
define Foo2: FooWithDefault
###
module.exports['DefaultAndNoDefault'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooWithNoDefault",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooWithDefault",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "Foo",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooWithNoDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooWithNoDefault",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooWithDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooWithDefault",
"type" : "ParameterRef"
}
} ]
}
}
}
### MeasurementPeriodParameter
library TestSnippet version '1'
using QUICK
parameter "Measurement Period" Interval<DateTime>
context Patient
define MeasurementPeriod: Interval[DateTime(2011, 1, 1), DateTime(2013, 1, 1)] overlaps "Measurement Period"
###
module.exports['MeasurementPeriodParameter'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "Measurement Period",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "16",
"name" : "MeasurementPeriod",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "16",
"s" : [ {
"value" : [ "define ","MeasurementPeriod",": " ]
}, {
"r" : "15",
"s" : [ {
"r" : "13",
"s" : [ {
"value" : [ "Interval[" ]
}, {
"r" : "8",
"s" : [ {
"r" : "5",
"value" : [ "DateTime","(","2011",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ ", " ]
}, {
"r" : "12",
"s" : [ {
"r" : "9",
"value" : [ "DateTime","(","2013",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ "]" ]
} ]
}, {
"r" : "15",
"value" : [ " ","overlaps"," " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "\"Measurement Period\"" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "15",
"type" : "Overlaps",
"operand" : [ {
"localId" : "13",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "8",
"type" : "DateTime",
"year" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2011",
"type" : "Literal"
},
"month" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"localId" : "12",
"type" : "DateTime",
"year" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"localId" : "10",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "11",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}, {
"localId" : "14",
"name" : "Measurement Period",
"type" : "ParameterRef"
} ]
}
} ]
}
}
}
| 137289 | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
parameter IntParameter Integer
parameter ListParameter List<String>
parameter TupleParameter Tuple{a Integer, b String, c Boolean, d List<Integer>, e Tuple{ f String, g Boolean}}
context Patient
define foo: 'bar'
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "MeasureYear",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "IntParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "ListParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "7",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "6",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "25",
"name" : "TupleParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "24",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "10",
"name" : "<NAME>",
"elementType" : {
"localId" : "9",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "12",
"name" : "<NAME>",
"elementType" : {
"localId" : "11",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "14",
"name" : "<NAME>",
"elementType" : {
"localId" : "13",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "17",
"name" : "<NAME>",
"elementType" : {
"localId" : "16",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "15",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "23",
"name" : "<NAME>",
"elementType" : {
"localId" : "22",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "19",
"name" : "f",
"elementType" : {
"localId" : "18",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "21",
"name" : "g",
"elementType" : {
"localId" : "20",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
} ]
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "27",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "27",
"s" : [ {
"value" : [ "define ","foo",": " ]
}, {
"r" : "26",
"s" : [ {
"value" : [ "'bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "26",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "bar",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo: FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "5",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### BooleanParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Boolean
parameter FooDP default true
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['BooleanParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### DecimalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Decimal
parameter FooDP default 1.5
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DecimalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Decimal",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "1.5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "Foo<NAME>" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>DP",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntegerParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Integer
parameter FooDP default 2
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntegerParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### StringParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP String
parameter FooDP default 'Hello'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['StringParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### CodeParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Code
parameter FooDP default Code 'FooTest' from "FOOTESTCS" display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['CodeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Code",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "7",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "6",
"code" : "FooTest",
"display" : "Foo Test",
"type" : "Code",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "<NAME>" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "11",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "<NAME>DP",
"type" : "ParameterRef"
}
} ]
}
}
}
### ConceptParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Concept
parameter FooDP default Concept { Code 'FooTest' from "FOOTESTCS" } display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ConceptParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "<NAME>P",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Concept",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"display" : "Foo Test",
"type" : "Concept",
"code" : [ {
"localId" : "6",
"code" : "FooTest",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
} ]
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateTimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP DateTime
parameter FooDP default @2012-04-01T12:11:10
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateTimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>P",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "11",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>DP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Date
parameter FooDP default @2012-04-01
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>P",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Date",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Date",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### QuantityParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Quantity
parameter FooDP default 10 'dL'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['QuantityParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>P",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Quantity",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"value" : 10,
"unit" : "dL",
"type" : "Quantity"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### TimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Time
parameter FooDP default @T12:00:00
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Time",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### ListParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP List<String>
parameter FooDP default { 'a', 'b', 'c' }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ListParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "9",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "8",
"type" : "List",
"element" : [ {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "a",
"type" : "Literal"
}, {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "b",
"type" : "Literal"
}, {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "c",
"type" : "Literal"
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "11",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "13",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntervalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Interval<Integer>
parameter FooDP default Interval[2,6]
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntervalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "8",
"name" : "<NAME>DP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"high" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "6",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "<NAME>P",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "<NAME>DP",
"type" : "ParameterRef"
}
} ]
}
}
}
### TupleParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Tuple { Hello String, MeaningOfLife Integer }
parameter FooDP default Tuple { Hello: 'Universe', MeaningOfLife: 24 }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TupleParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "7",
"name" : "<NAME>",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "6",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "3",
"name" : "<NAME>",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "<NAME>",
"elementType" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}
}, {
"localId" : "11",
"name" : "<NAME>",
"accessLevel" : "Public",
"default" : {
"localId" : "10",
"type" : "Tuple",
"element" : [ {
"name" : "<NAME>",
"value" : {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Universe",
"type" : "Literal"
}
}, {
"name" : "<NAME>",
"value" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "24",
"type" : "Literal"
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "13",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "<NAME>",
"type" : "ParameterRef"
}
}, {
"localId" : "15",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "15",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "<NAME>DP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "14",
"name" : "<NAME>",
"type" : "ParameterRef"
}
} ]
}
}
}
### DefaultAndNoDefault
library TestSnippet version '1'
using QUICK
parameter FooWithNoDefault Integer
parameter FooWithDefault default 5
context Patient
define Foo: FooWithNoDefault
define Foo2: FooWithDefault
###
module.exports['DefaultAndNoDefault'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooWithNoDefault",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooWithDefault",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "<NAME>",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooWithNoDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooWithNoDefault",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooWithDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooWithDefault",
"type" : "ParameterRef"
}
} ]
}
}
}
### MeasurementPeriodParameter
library TestSnippet version '1'
using QUICK
parameter "Measurement Period" Interval<DateTime>
context Patient
define MeasurementPeriod: Interval[DateTime(2011, 1, 1), DateTime(2013, 1, 1)] overlaps "Measurement Period"
###
module.exports['MeasurementPeriodParameter'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "Measurement Period",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "16",
"name" : "<NAME>",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "16",
"s" : [ {
"value" : [ "define ","MeasurementPeriod",": " ]
}, {
"r" : "15",
"s" : [ {
"r" : "13",
"s" : [ {
"value" : [ "Interval[" ]
}, {
"r" : "8",
"s" : [ {
"r" : "5",
"value" : [ "DateTime","(","2011",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ ", " ]
}, {
"r" : "12",
"s" : [ {
"r" : "9",
"value" : [ "DateTime","(","2013",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ "]" ]
} ]
}, {
"r" : "15",
"value" : [ " ","overlaps"," " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "\"Measurement Period\"" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "15",
"type" : "Overlaps",
"operand" : [ {
"localId" : "13",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "8",
"type" : "DateTime",
"year" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2011",
"type" : "Literal"
},
"month" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"localId" : "12",
"type" : "DateTime",
"year" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"localId" : "10",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "11",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}, {
"localId" : "14",
"name" : "Measurement Period",
"type" : "ParameterRef"
} ]
}
} ]
}
}
}
| true | ###
WARNING: This is a GENERATED file. Do not manually edit!
To generate this file:
- Edit data.cql to add a CQL Snippet
- From java dir: ./gradlew :cql-to-elm:generateTestData
###
### ParameterDef
library TestSnippet version '1'
using QUICK
parameter MeasureYear default 2012
parameter IntParameter Integer
parameter ListParameter List<String>
parameter TupleParameter Tuple{a Integer, b String, c Boolean, d List<Integer>, e Tuple{ f String, g Boolean}}
context Patient
define foo: 'bar'
###
module.exports['ParameterDef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "MeasureYear",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
}
}, {
"localId" : "5",
"name" : "IntParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "ListParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "7",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "6",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "25",
"name" : "TupleParameter",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "24",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "10",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "9",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "12",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "11",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "14",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "13",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "17",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "16",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "15",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "23",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "22",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "19",
"name" : "f",
"elementType" : {
"localId" : "18",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "21",
"name" : "g",
"elementType" : {
"localId" : "20",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
} ]
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "27",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "27",
"s" : [ {
"value" : [ "define ","foo",": " ]
}, {
"r" : "26",
"s" : [ {
"value" : [ "'bar'" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "26",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "bar",
"type" : "Literal"
}
} ]
}
}
}
### ParameterRef
library TestSnippet version '1'
using QUICK
parameter FooP default 'Bar'
context Patient
define Foo: FooP
###
module.exports['ParameterRef'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "2",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Bar",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "5",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "4",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### BooleanParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Boolean
parameter FooDP default true
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['BooleanParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Boolean",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Boolean",
"value" : "true",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### DecimalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Decimal
parameter FooDP default 1.5
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DecimalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Decimal",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Decimal",
"value" : "1.5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooPI:NAME:<NAME>END_PI" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PIDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntegerParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Integer
parameter FooDP default 2
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntegerParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### StringParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP String
parameter FooDP default 'Hello'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['StringParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Hello",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### CodeParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Code
parameter FooDP default Code 'FooTest' from "FOOTESTCS" display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['CodeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Code",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "7",
"name" : "FooDP",
"accessLevel" : "Public",
"default" : {
"localId" : "6",
"code" : "FooTest",
"display" : "Foo Test",
"type" : "Code",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "PI:NAME:<NAME>END_PI" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "PI:NAME:<NAME>END_PIDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### ConceptParameterTypes
library TestSnippet version '1'
using QUICK
codesystem "FOOTESTCS": 'http://footest.org'
parameter FooP Concept
parameter FooDP default Concept { Code 'FooTest' from "FOOTESTCS" } display 'Foo Test'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ConceptParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PIP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"name" : "{urn:hl7-org:elm-types:r1}Concept",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"display" : "Foo Test",
"type" : "Concept",
"code" : [ {
"localId" : "6",
"code" : "FooTest",
"system" : {
"localId" : "5",
"name" : "FOOTESTCS"
}
} ]
}
} ]
},
"codeSystems" : {
"def" : [ {
"localId" : "2",
"name" : "FOOTESTCS",
"id" : "http://footest.org",
"accessLevel" : "Public"
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateTimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP DateTime
parameter FooDP default @2012-04-01T12:11:10
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateTimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PIP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "DateTime",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "11",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "10",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PIDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### DateParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Date
parameter FooDP default @2012-04-01
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['DateParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PIP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Date",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Date",
"year" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2012",
"type" : "Literal"
},
"month" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "4",
"type" : "Literal"
},
"day" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### QuantityParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Quantity
parameter FooDP default 10 'dL'
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['QuantityParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PIP",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Quantity",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"value" : 10,
"unit" : "dL",
"type" : "Quantity"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### TimeParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Time
parameter FooDP default @T12:00:00
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TimeParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Time",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"type" : "Time",
"hour" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "12",
"type" : "Literal"
},
"minute" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
},
"second" : {
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "0",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### ListParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP List<String>
parameter FooDP default { 'a', 'b', 'c' }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['ListParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "ListTypeSpecifier",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "8",
"type" : "List",
"element" : [ {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "a",
"type" : "Literal"
}, {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "b",
"type" : "Literal"
}, {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "c",
"type" : "Literal"
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "11",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "10",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "10",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "13",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### IntervalParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Interval<Integer>
parameter FooDP default Interval[2,6]
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['IntervalParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}
}, {
"localId" : "8",
"name" : "PI:NAME:<NAME>END_PIDP",
"accessLevel" : "Public",
"default" : {
"localId" : "7",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2",
"type" : "Literal"
},
"high" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "6",
"type" : "Literal"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "10",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "10",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "9",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PIP",
"type" : "ParameterRef"
}
}, {
"localId" : "12",
"name" : "Foo2",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "12",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "11",
"s" : [ {
"value" : [ "FooDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PIDP",
"type" : "ParameterRef"
}
} ]
}
}
}
### TupleParameterTypes
library TestSnippet version '1'
using QUICK
parameter FooP Tuple { Hello String, MeaningOfLife Integer }
parameter FooDP default Tuple { Hello: 'Universe', MeaningOfLife: 24 }
context Patient
define Foo: FooP
define Foo2: FooDP
###
module.exports['TupleParameterTypes'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "6",
"type" : "TupleTypeSpecifier",
"element" : [ {
"localId" : "3",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}String",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "PI:NAME:<NAME>END_PI",
"elementType" : {
"localId" : "4",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
} ]
}
}, {
"localId" : "11",
"name" : "PI:NAME:<NAME>END_PI",
"accessLevel" : "Public",
"default" : {
"localId" : "10",
"type" : "Tuple",
"element" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"localId" : "8",
"valueType" : "{urn:hl7-org:elm-types:r1}String",
"value" : "Universe",
"type" : "Literal"
}
}, {
"name" : "PI:NAME:<NAME>END_PI",
"value" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "24",
"type" : "Literal"
}
} ]
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "13",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "13",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "12",
"s" : [ {
"value" : [ "FooP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "12",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
}, {
"localId" : "15",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "15",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "PI:NAME:<NAME>END_PIDP" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "14",
"name" : "PI:NAME:<NAME>END_PI",
"type" : "ParameterRef"
}
} ]
}
}
}
### DefaultAndNoDefault
library TestSnippet version '1'
using QUICK
parameter FooWithNoDefault Integer
parameter FooWithDefault default 5
context Patient
define Foo: FooWithNoDefault
define Foo2: FooWithDefault
###
module.exports['DefaultAndNoDefault'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "3",
"name" : "FooWithNoDefault",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}Integer",
"type" : "NamedTypeSpecifier"
}
}, {
"localId" : "5",
"name" : "FooWithDefault",
"accessLevel" : "Public",
"default" : {
"localId" : "4",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "5",
"type" : "Literal"
}
} ]
},
"statements" : {
"def" : [ {
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "7",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "7",
"s" : [ {
"value" : [ "define ","Foo",": " ]
}, {
"r" : "6",
"s" : [ {
"value" : [ "FooWithNoDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "6",
"name" : "FooWithNoDefault",
"type" : "ParameterRef"
}
}, {
"localId" : "9",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "9",
"s" : [ {
"value" : [ "define ","Foo2",": " ]
}, {
"r" : "8",
"s" : [ {
"value" : [ "FooWithDefault" ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "8",
"name" : "FooWithDefault",
"type" : "ParameterRef"
}
} ]
}
}
}
### MeasurementPeriodParameter
library TestSnippet version '1'
using QUICK
parameter "Measurement Period" Interval<DateTime>
context Patient
define MeasurementPeriod: Interval[DateTime(2011, 1, 1), DateTime(2013, 1, 1)] overlaps "Measurement Period"
###
module.exports['MeasurementPeriodParameter'] = {
"library" : {
"identifier" : {
"id" : "TestSnippet",
"version" : "1"
},
"schemaIdentifier" : {
"id" : "urn:hl7-org:elm",
"version" : "r1"
},
"usings" : {
"def" : [ {
"localIdentifier" : "System",
"uri" : "urn:hl7-org:elm-types:r1"
}, {
"localId" : "1",
"localIdentifier" : "QUICK",
"uri" : "http://hl7.org/fhir"
} ]
},
"parameters" : {
"def" : [ {
"localId" : "4",
"name" : "Measurement Period",
"accessLevel" : "Public",
"parameterTypeSpecifier" : {
"localId" : "3",
"type" : "IntervalTypeSpecifier",
"pointType" : {
"localId" : "2",
"name" : "{urn:hl7-org:elm-types:r1}DateTime",
"type" : "NamedTypeSpecifier"
}
}
} ]
},
"statements" : {
"def" : [ {
"name" : "Patient",
"context" : "Patient",
"expression" : {
"type" : "SingletonFrom",
"operand" : {
"dataType" : "{http://hl7.org/fhir}Patient",
"templateId" : "patient-qicore-qicore-patient",
"type" : "Retrieve"
}
}
}, {
"localId" : "16",
"name" : "PI:NAME:<NAME>END_PI",
"context" : "Patient",
"accessLevel" : "Public",
"annotation" : [ {
"type" : "Annotation",
"s" : {
"r" : "16",
"s" : [ {
"value" : [ "define ","MeasurementPeriod",": " ]
}, {
"r" : "15",
"s" : [ {
"r" : "13",
"s" : [ {
"value" : [ "Interval[" ]
}, {
"r" : "8",
"s" : [ {
"r" : "5",
"value" : [ "DateTime","(","2011",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ ", " ]
}, {
"r" : "12",
"s" : [ {
"r" : "9",
"value" : [ "DateTime","(","2013",", ","1",", ","1",")" ]
} ]
}, {
"value" : [ "]" ]
} ]
}, {
"r" : "15",
"value" : [ " ","overlaps"," " ]
}, {
"r" : "14",
"s" : [ {
"value" : [ "\"Measurement Period\"" ]
} ]
} ]
} ]
}
} ],
"expression" : {
"localId" : "15",
"type" : "Overlaps",
"operand" : [ {
"localId" : "13",
"lowClosed" : true,
"highClosed" : true,
"type" : "Interval",
"low" : {
"localId" : "8",
"type" : "DateTime",
"year" : {
"localId" : "5",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2011",
"type" : "Literal"
},
"month" : {
"localId" : "6",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "7",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
},
"high" : {
"localId" : "12",
"type" : "DateTime",
"year" : {
"localId" : "9",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "2013",
"type" : "Literal"
},
"month" : {
"localId" : "10",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
},
"day" : {
"localId" : "11",
"valueType" : "{urn:hl7-org:elm-types:r1}Integer",
"value" : "1",
"type" : "Literal"
}
}
}, {
"localId" : "14",
"name" : "Measurement Period",
"type" : "ParameterRef"
} ]
}
} ]
}
}
}
|
[
{
"context": "een', primary: true, id: greenId}\n {name: 'red', primary: true, id: redId}\n ]\n model.s",
"end": 5694,
"score": 0.8014671206474304,
"start": 5691,
"tag": "NAME",
"value": "red"
},
{
"context": " expect(model.get 'out').to.eql [\n {name: 'red', ... | test/Model/filter.mocha.coffee | vmakhaev/racer | 0 | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'filter', ->
describe 'getting', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number, i, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number, id, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
describe 'initial value set by ref', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
describe 'ref updates as items are modified', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
model.push 'numbers', 6
expect(model.get 'out').to.eql [0, 4, 2, 0, 6]
model.set 'numbers.2', 1
expect(model.get 'out').to.eql [0, 2, 0, 6]
model.del 'numbers'
expect(model.get 'out').to.eql []
model.set 'numbers', [1, 2, 0]
expect(model.get 'out').to.eql [2, 0]
it 'supports filter of object', ->
model = (new Model).at '_page'
greenId = model.add 'colors'
name: 'green'
primary: true
orangeId = model.add 'colors'
name: 'orange'
primary: false
redId = model.add 'colors'
name: 'red'
primary: true
filter = model.filter 'colors', (color) -> color.primary
filter.ref '_page.out'
expect(model.get 'out').to.eql [
{name: 'green', primary: true, id: greenId}
{name: 'red', primary: true, id: redId}
]
model.set 'colors.' + greenId + '.primary', false
expect(model.get 'out').to.eql [
{name: 'red', primary: true, id: redId}
]
yellowId = model.add 'colors'
name: 'yellow'
primary: true
expect(model.get 'out').to.eql [
{name: 'red', primary: true, id: redId}
{name: 'yellow', primary: true, id: yellowId}
]
| 66527 | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'filter', ->
describe 'getting', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number, i, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number, id, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
describe 'initial value set by ref', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
describe 'ref updates as items are modified', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
model.push 'numbers', 6
expect(model.get 'out').to.eql [0, 4, 2, 0, 6]
model.set 'numbers.2', 1
expect(model.get 'out').to.eql [0, 2, 0, 6]
model.del 'numbers'
expect(model.get 'out').to.eql []
model.set 'numbers', [1, 2, 0]
expect(model.get 'out').to.eql [2, 0]
it 'supports filter of object', ->
model = (new Model).at '_page'
greenId = model.add 'colors'
name: 'green'
primary: true
orangeId = model.add 'colors'
name: 'orange'
primary: false
redId = model.add 'colors'
name: 'red'
primary: true
filter = model.filter 'colors', (color) -> color.primary
filter.ref '_page.out'
expect(model.get 'out').to.eql [
{name: 'green', primary: true, id: greenId}
{name: '<NAME>', primary: true, id: redId}
]
model.set 'colors.' + greenId + '.primary', false
expect(model.get 'out').to.eql [
{name: '<NAME>', primary: true, id: redId}
]
yellowId = model.add 'colors'
name: 'yellow'
primary: true
expect(model.get 'out').to.eql [
{name: '<NAME>', primary: true, id: redId}
{name: 'yellow', primary: true, id: yellowId}
]
| true | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'filter', ->
describe 'getting', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number, i, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number, id, numbers) ->
return (number % 2) == 0
expect(filter.get()).to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
expect(filter.get()).to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
expect(filter.get()).to.eql [0, 0, 2, 4]
describe 'initial value set by ref', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
it 'supports filter of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
it 'supports sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
filter = model.sort 'numbers'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'asc'
expect(filter.get()).to.eql [0, 0, 1, 2, 3, 3, 4]
filter = model.sort 'numbers', 'desc'
filter.ref '_page.out'
expect(model.get 'out').to.eql [4, 3, 3, 2, 1, 0, 0]
it 'supports filter and sort of object', ->
model = (new Model).at '_page'
for number in [0, 3, 4, 1, 2, 3, 0]
model.set 'numbers.' + model.id(), number
model.fn 'even', (number) ->
return (number % 2) == 0
filter = model.filter('numbers', 'even').sort()
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 0, 2, 4]
describe 'ref updates as items are modified', ->
it 'supports filter of array', ->
model = (new Model).at '_page'
model.set 'numbers', [0, 3, 4, 1, 2, 3, 0]
filter = model.filter 'numbers', (number) ->
return (number % 2) == 0
filter.ref '_page.out'
expect(model.get 'out').to.eql [0, 4, 2, 0]
model.push 'numbers', 6
expect(model.get 'out').to.eql [0, 4, 2, 0, 6]
model.set 'numbers.2', 1
expect(model.get 'out').to.eql [0, 2, 0, 6]
model.del 'numbers'
expect(model.get 'out').to.eql []
model.set 'numbers', [1, 2, 0]
expect(model.get 'out').to.eql [2, 0]
it 'supports filter of object', ->
model = (new Model).at '_page'
greenId = model.add 'colors'
name: 'green'
primary: true
orangeId = model.add 'colors'
name: 'orange'
primary: false
redId = model.add 'colors'
name: 'red'
primary: true
filter = model.filter 'colors', (color) -> color.primary
filter.ref '_page.out'
expect(model.get 'out').to.eql [
{name: 'green', primary: true, id: greenId}
{name: 'PI:NAME:<NAME>END_PI', primary: true, id: redId}
]
model.set 'colors.' + greenId + '.primary', false
expect(model.get 'out').to.eql [
{name: 'PI:NAME:<NAME>END_PI', primary: true, id: redId}
]
yellowId = model.add 'colors'
name: 'yellow'
primary: true
expect(model.get 'out').to.eql [
{name: 'PI:NAME:<NAME>END_PI', primary: true, id: redId}
{name: 'yellow', primary: true, id: yellowId}
]
|
[
{
"context": "bio.com\nCopyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>\nLicensed under the Apache License, Version 2.0 (",
"end": 193,
"score": 0.999923825263977,
"start": 177,
"tag": "EMAIL",
"value": "info@chaibio.com"
}
] | frontend/javascripts/app/directives/scrollbar.js.coffee | MakerButt/chaipcr | 1 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <info@chaibio.com>
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.
###
window.ChaiBioTech.ngApp.directive 'scrollbar', [
'TextSelection'
'$timeout'
(textSelection, $timeout) ->
restrict: 'E'
replace: true
template: '<div class="scrollbar-directive"></div>'
scope:
state: '=' # [{0..1}, width]
require: 'ngModel'
link: ($scope, elem, attr, ngModel) ->
elem.css(width: '100%', cursor: 'pointer')
# width = elem.width()
height = 5
held = false
oldMargin = 0;
newMargin = 0;
pageX = 0
margin = 0
spaceWidth = 0
scrollbar_width = 0
xDiff = 0
scrollbarBGClicked = false
svg = null
scrollbarBG = null
scrollbarHandle = null
resizeTimeout = null
init = ->
width = elem.width()
svg = d3.select(elem[0]).append('svg')
.attr('width', width)
.attr('height', height)
scrollbarBG = svg.append('rect')
.attr('fill', '#ccc')
.attr('width', width)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
.on 'mousedown', ->
scrollbarBGClicked = true
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
.on 'mouseup', ->
if scrollbarBGClicked
scrollbarBGClicked = false
x = d3.mouse(this)[0]
newMargin = x - (getScrollBarWidth()/2)
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
handleWidth = width * getModelWidth()
scrollbarHandle = svg.append('rect')
.attr('fill', '#555')
.attr('width', handleWidth)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
updateMargin(getModelValue() * (width - handleWidth))
angular.element(scrollbarHandle.node()).on 'mousedown', (e) ->
held = true
pageX = e.pageX
textSelection.disable()
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
$scope.$on 'window:mousemove', (event, e) ->
if held
xDiff = e.pageX - pageX
newMargin = oldMargin + xDiff
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
$scope.$on 'window:mouseup', (event, e) ->
if held
held = false
textSelection.enable()
$scope.$watchCollection ->
ngModel.$viewValue
, (val, oldVal) ->
if (val?.value isnt oldVal?.value or val?.width isnt oldVal?.width) and !held
value = val.value*1 || getModelValue()
value = if (value > 1) then 1 else value
value = if (value < 0) then 0 else value
elem_width = getElemWidth()
width_percent = if angular.isNumber(val.width) then val.width else (if angular.isNumber(ngModel.$viewValue.width) then ngModel.$viewValue.width else 1)
new_width = elem_width * width_percent
new_width = if new_width >= 15 then new_width else 15
scrollbarHandle.attr('width', new_width)
new_margin = (elem_width - new_width) * value
updateMargin(new_margin)
$scope.$on 'window:resize', ->
width = elem.parent().width()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', width)
elem.parent().css(overflow: 'hidden')
if (resizeTimeout)
$timeout.cancel(resizeTimeout)
resizeTimeout = null
resizeTimeout = $timeout ->
elem.parent().css(overflow: '')
width = getElemWidth()
handleWidth = width * getModelWidth()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', handleWidth)
updateMargin(getModelValue() * (width - handleWidth))
resizeTimeout = null
, 100
# end init
getModelValue = ->
ngModel.$viewValue?.value || 0
getModelWidth = ->
ngModel.$viewValue?.width || 1
getMarginLeft = ->
scrollbarHandle.attr('x') * 1
getElemWidth = ->
elem.width()
getScrollBarWidth = ->
scrollbarHandle.attr('width') * 1
getSpaceWidth = ->
getElemWidth() - getScrollBarWidth()
updateMargin = (newMargin) ->
spaceWidth = getSpaceWidth()
if newMargin > spaceWidth then newMargin = spaceWidth
if newMargin < 0 then newMargin = 0
scrollbarHandle.attr('x', newMargin)
$timeout(init, 2000)
]
| 181846 | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <<EMAIL>>
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.
###
window.ChaiBioTech.ngApp.directive 'scrollbar', [
'TextSelection'
'$timeout'
(textSelection, $timeout) ->
restrict: 'E'
replace: true
template: '<div class="scrollbar-directive"></div>'
scope:
state: '=' # [{0..1}, width]
require: 'ngModel'
link: ($scope, elem, attr, ngModel) ->
elem.css(width: '100%', cursor: 'pointer')
# width = elem.width()
height = 5
held = false
oldMargin = 0;
newMargin = 0;
pageX = 0
margin = 0
spaceWidth = 0
scrollbar_width = 0
xDiff = 0
scrollbarBGClicked = false
svg = null
scrollbarBG = null
scrollbarHandle = null
resizeTimeout = null
init = ->
width = elem.width()
svg = d3.select(elem[0]).append('svg')
.attr('width', width)
.attr('height', height)
scrollbarBG = svg.append('rect')
.attr('fill', '#ccc')
.attr('width', width)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
.on 'mousedown', ->
scrollbarBGClicked = true
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
.on 'mouseup', ->
if scrollbarBGClicked
scrollbarBGClicked = false
x = d3.mouse(this)[0]
newMargin = x - (getScrollBarWidth()/2)
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
handleWidth = width * getModelWidth()
scrollbarHandle = svg.append('rect')
.attr('fill', '#555')
.attr('width', handleWidth)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
updateMargin(getModelValue() * (width - handleWidth))
angular.element(scrollbarHandle.node()).on 'mousedown', (e) ->
held = true
pageX = e.pageX
textSelection.disable()
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
$scope.$on 'window:mousemove', (event, e) ->
if held
xDiff = e.pageX - pageX
newMargin = oldMargin + xDiff
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
$scope.$on 'window:mouseup', (event, e) ->
if held
held = false
textSelection.enable()
$scope.$watchCollection ->
ngModel.$viewValue
, (val, oldVal) ->
if (val?.value isnt oldVal?.value or val?.width isnt oldVal?.width) and !held
value = val.value*1 || getModelValue()
value = if (value > 1) then 1 else value
value = if (value < 0) then 0 else value
elem_width = getElemWidth()
width_percent = if angular.isNumber(val.width) then val.width else (if angular.isNumber(ngModel.$viewValue.width) then ngModel.$viewValue.width else 1)
new_width = elem_width * width_percent
new_width = if new_width >= 15 then new_width else 15
scrollbarHandle.attr('width', new_width)
new_margin = (elem_width - new_width) * value
updateMargin(new_margin)
$scope.$on 'window:resize', ->
width = elem.parent().width()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', width)
elem.parent().css(overflow: 'hidden')
if (resizeTimeout)
$timeout.cancel(resizeTimeout)
resizeTimeout = null
resizeTimeout = $timeout ->
elem.parent().css(overflow: '')
width = getElemWidth()
handleWidth = width * getModelWidth()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', handleWidth)
updateMargin(getModelValue() * (width - handleWidth))
resizeTimeout = null
, 100
# end init
getModelValue = ->
ngModel.$viewValue?.value || 0
getModelWidth = ->
ngModel.$viewValue?.width || 1
getMarginLeft = ->
scrollbarHandle.attr('x') * 1
getElemWidth = ->
elem.width()
getScrollBarWidth = ->
scrollbarHandle.attr('width') * 1
getSpaceWidth = ->
getElemWidth() - getScrollBarWidth()
updateMargin = (newMargin) ->
spaceWidth = getSpaceWidth()
if newMargin > spaceWidth then newMargin = spaceWidth
if newMargin < 0 then newMargin = 0
scrollbarHandle.attr('x', newMargin)
$timeout(init, 2000)
]
| true | ###
Chai PCR - Software platform for Open qPCR and Chai's Real-Time PCR instruments.
For more information visit http://www.chaibio.com
Copyright 2016 Chai Biotechnologies Inc. <PI:EMAIL:<EMAIL>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.
###
window.ChaiBioTech.ngApp.directive 'scrollbar', [
'TextSelection'
'$timeout'
(textSelection, $timeout) ->
restrict: 'E'
replace: true
template: '<div class="scrollbar-directive"></div>'
scope:
state: '=' # [{0..1}, width]
require: 'ngModel'
link: ($scope, elem, attr, ngModel) ->
elem.css(width: '100%', cursor: 'pointer')
# width = elem.width()
height = 5
held = false
oldMargin = 0;
newMargin = 0;
pageX = 0
margin = 0
spaceWidth = 0
scrollbar_width = 0
xDiff = 0
scrollbarBGClicked = false
svg = null
scrollbarBG = null
scrollbarHandle = null
resizeTimeout = null
init = ->
width = elem.width()
svg = d3.select(elem[0]).append('svg')
.attr('width', width)
.attr('height', height)
scrollbarBG = svg.append('rect')
.attr('fill', '#ccc')
.attr('width', width)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
.on 'mousedown', ->
scrollbarBGClicked = true
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
.on 'mouseup', ->
if scrollbarBGClicked
scrollbarBGClicked = false
x = d3.mouse(this)[0]
newMargin = x - (getScrollBarWidth()/2)
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
handleWidth = width * getModelWidth()
scrollbarHandle = svg.append('rect')
.attr('fill', '#555')
.attr('width', handleWidth)
.attr('height', height)
.attr('rx', 2)
.attr('ry', 2)
updateMargin(getModelValue() * (width - handleWidth))
angular.element(scrollbarHandle.node()).on 'mousedown', (e) ->
held = true
pageX = e.pageX
textSelection.disable()
oldMargin = getMarginLeft()
spaceWidth = getSpaceWidth()
scrollbar_width = getScrollBarWidth()
$scope.$on 'window:mousemove', (event, e) ->
if held
xDiff = e.pageX - pageX
newMargin = oldMargin + xDiff
updateMargin(newMargin)
# avoid dividing with spaceWidth = 0, else result is NaN
val = if spaceWidth > 0 then Math.round((newMargin)/spaceWidth*1000)/1000 else 0
ngModel.$setViewValue({
value: val,
width: scrollbar_width / getElemWidth()
})
$scope.$on 'window:mouseup', (event, e) ->
if held
held = false
textSelection.enable()
$scope.$watchCollection ->
ngModel.$viewValue
, (val, oldVal) ->
if (val?.value isnt oldVal?.value or val?.width isnt oldVal?.width) and !held
value = val.value*1 || getModelValue()
value = if (value > 1) then 1 else value
value = if (value < 0) then 0 else value
elem_width = getElemWidth()
width_percent = if angular.isNumber(val.width) then val.width else (if angular.isNumber(ngModel.$viewValue.width) then ngModel.$viewValue.width else 1)
new_width = elem_width * width_percent
new_width = if new_width >= 15 then new_width else 15
scrollbarHandle.attr('width', new_width)
new_margin = (elem_width - new_width) * value
updateMargin(new_margin)
$scope.$on 'window:resize', ->
width = elem.parent().width()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', width)
elem.parent().css(overflow: 'hidden')
if (resizeTimeout)
$timeout.cancel(resizeTimeout)
resizeTimeout = null
resizeTimeout = $timeout ->
elem.parent().css(overflow: '')
width = getElemWidth()
handleWidth = width * getModelWidth()
svg.attr('width', width)
scrollbarBG.attr('width', width)
scrollbarHandle.attr('width', handleWidth)
updateMargin(getModelValue() * (width - handleWidth))
resizeTimeout = null
, 100
# end init
getModelValue = ->
ngModel.$viewValue?.value || 0
getModelWidth = ->
ngModel.$viewValue?.width || 1
getMarginLeft = ->
scrollbarHandle.attr('x') * 1
getElemWidth = ->
elem.width()
getScrollBarWidth = ->
scrollbarHandle.attr('width') * 1
getSpaceWidth = ->
getElemWidth() - getScrollBarWidth()
updateMargin = (newMargin) ->
spaceWidth = getSpaceWidth()
if newMargin > spaceWidth then newMargin = spaceWidth
if newMargin < 0 then newMargin = 0
scrollbarHandle.attr('x', newMargin)
$timeout(init, 2000)
]
|
[
{
"context": "/users\", {})\n .get(\"input[name=name]\").type(\"brian\")\n .get(\"#submit\").click()\n .get(\"form\"",
"end": 261,
"score": 0.9989110231399536,
"start": 256,
"tag": "NAME",
"value": "brian"
}
] | packages/server/test/support/fixtures/projects/e2e/cypress/integration/form_submission_failing_spec.coffee | nongmanh/cypress | 3 | describe "form submission fails", ->
beforeEach ->
cy.visit("/forms.html")
it "fails without an explicit wait when an element is immediately found", ->
cy
.server()
.route("POST", "/users", {})
.get("input[name=name]").type("brian")
.get("#submit").click()
.get("form").then ($form) ->
expect($form).to.contain("form success!")
| 209933 | describe "form submission fails", ->
beforeEach ->
cy.visit("/forms.html")
it "fails without an explicit wait when an element is immediately found", ->
cy
.server()
.route("POST", "/users", {})
.get("input[name=name]").type("<NAME>")
.get("#submit").click()
.get("form").then ($form) ->
expect($form).to.contain("form success!")
| true | describe "form submission fails", ->
beforeEach ->
cy.visit("/forms.html")
it "fails without an explicit wait when an element is immediately found", ->
cy
.server()
.route("POST", "/users", {})
.get("input[name=name]").type("PI:NAME:<NAME>END_PI")
.get("#submit").click()
.get("form").then ($form) ->
expect($form).to.contain("form success!")
|
[
{
"context": "erms of the MIT license.\nCopyright 2012 - 2016 (c) Markus Kohlhase <mail@markus-kohlhase.de>\n###\n\nltx = require ",
"end": 109,
"score": 0.99989914894104,
"start": 94,
"tag": "NAME",
"value": "Markus Kohlhase"
},
{
"context": "cense.\nCopyright 2012 - 2016 (c) Ma... | src/Parser.coffee | flosse/node-xmpp-joap | 0 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) Markus Kohlhase <mail@markus-kohlhase.de>
###
ltx = require "ltx"
joap = require "./node-xmpp-joap"
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
JOAP_STANZAS = ["describe", "read","add", "edit", "delete", "search"]
class Parser
@hasJOAPNS: (xml) -> xml.attrs?.xmlns is JOAP_NS
@hasRPCNS: (xml) -> xml.attrs?.xmlns is RPC_NS
@getType: (xml) ->
if @hasJOAPNS xml then xml.getName().toLowerCase()
else if Parser.isRPCStanza xml then "rpc"
@isCustomJOAPAction: (name) -> not (name in JOAP_STANZAS)
@isJOAPStanza: (xml) -> not @isCustomJOAPAction(xml.name) and @hasJOAPNS xml
@isRPCStanza: (xml) ->
(xml.name is "query" and @hasRPCNS xml)
@parse: (xml) ->
if typeof xml in ["string", "number", "boolean"] then xml
else if xml instanceof Array
(Parser.parse c for c in xml)
else if typeof xml is "object"
if Parser.hasJOAPNS xml
action = type: Parser.getType xml
attrs = {}
a = xml.getChildren "attribute"
if a.length > 0
attrs[c.name] = c.value for c in Parser.parse a
action.attributes = attrs
n = xml.getChildren "name"
action.limits = Parser.parse(n) if n.length > 0
action
else if Parser.isRPCStanza xml
call = xml.getChild "methodCall"
o =
type: Parser.getType xml
method: call.getChildText "methodName"
v = Parser.parse call.getChild "params"
o.params = v if v?
o
else
child = xml.children?[0]
switch xml.getName()
when "string", "name"
child
when "i4", "int", "double"
child * 1
when "boolean"
(child is "true" or child is "1")
when "value"
Parser.parse child
when "struct"
struct = {}
members = (Parser.parse m for m in xml.getChildren "member")
struct[m.name] = m.value for m in members
struct
when "array"
Parser.parse xml.getChild "data"
when "params"
(Parser.parse c.getChild "value" for c in xml.getChildren "param")
when "data"
data = []
for d in xml.getChildren "value"
data.push Parser.parse d
data
when "member", "attribute"
{
name: xml.getChildText "name"
value: Parser.parse xml.getChild "value"
}
module.exports = Parser
| 35238 | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) <NAME> <<EMAIL>>
###
ltx = require "ltx"
joap = require "./node-xmpp-joap"
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
JOAP_STANZAS = ["describe", "read","add", "edit", "delete", "search"]
class Parser
@hasJOAPNS: (xml) -> xml.attrs?.xmlns is JOAP_NS
@hasRPCNS: (xml) -> xml.attrs?.xmlns is RPC_NS
@getType: (xml) ->
if @hasJOAPNS xml then xml.getName().toLowerCase()
else if Parser.isRPCStanza xml then "rpc"
@isCustomJOAPAction: (name) -> not (name in JOAP_STANZAS)
@isJOAPStanza: (xml) -> not @isCustomJOAPAction(xml.name) and @hasJOAPNS xml
@isRPCStanza: (xml) ->
(xml.name is "query" and @hasRPCNS xml)
@parse: (xml) ->
if typeof xml in ["string", "number", "boolean"] then xml
else if xml instanceof Array
(Parser.parse c for c in xml)
else if typeof xml is "object"
if Parser.hasJOAPNS xml
action = type: Parser.getType xml
attrs = {}
a = xml.getChildren "attribute"
if a.length > 0
attrs[c.name] = c.value for c in Parser.parse a
action.attributes = attrs
n = xml.getChildren "name"
action.limits = Parser.parse(n) if n.length > 0
action
else if Parser.isRPCStanza xml
call = xml.getChild "methodCall"
o =
type: Parser.getType xml
method: call.getChildText "methodName"
v = Parser.parse call.getChild "params"
o.params = v if v?
o
else
child = xml.children?[0]
switch xml.getName()
when "string", "name"
child
when "i4", "int", "double"
child * 1
when "boolean"
(child is "true" or child is "1")
when "value"
Parser.parse child
when "struct"
struct = {}
members = (Parser.parse m for m in xml.getChildren "member")
struct[m.name] = m.value for m in members
struct
when "array"
Parser.parse xml.getChild "data"
when "params"
(Parser.parse c.getChild "value" for c in xml.getChildren "param")
when "data"
data = []
for d in xml.getChildren "value"
data.push Parser.parse d
data
when "member", "attribute"
{
name: xml.getChildText "name"
value: Parser.parse xml.getChild "value"
}
module.exports = Parser
| true | ###
This program is distributed under the terms of the MIT license.
Copyright 2012 - 2016 (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
###
ltx = require "ltx"
joap = require "./node-xmpp-joap"
JOAP_NS = "jabber:iq:joap"
RPC_NS = "jabber:iq:rpc"
JOAP_STANZAS = ["describe", "read","add", "edit", "delete", "search"]
class Parser
@hasJOAPNS: (xml) -> xml.attrs?.xmlns is JOAP_NS
@hasRPCNS: (xml) -> xml.attrs?.xmlns is RPC_NS
@getType: (xml) ->
if @hasJOAPNS xml then xml.getName().toLowerCase()
else if Parser.isRPCStanza xml then "rpc"
@isCustomJOAPAction: (name) -> not (name in JOAP_STANZAS)
@isJOAPStanza: (xml) -> not @isCustomJOAPAction(xml.name) and @hasJOAPNS xml
@isRPCStanza: (xml) ->
(xml.name is "query" and @hasRPCNS xml)
@parse: (xml) ->
if typeof xml in ["string", "number", "boolean"] then xml
else if xml instanceof Array
(Parser.parse c for c in xml)
else if typeof xml is "object"
if Parser.hasJOAPNS xml
action = type: Parser.getType xml
attrs = {}
a = xml.getChildren "attribute"
if a.length > 0
attrs[c.name] = c.value for c in Parser.parse a
action.attributes = attrs
n = xml.getChildren "name"
action.limits = Parser.parse(n) if n.length > 0
action
else if Parser.isRPCStanza xml
call = xml.getChild "methodCall"
o =
type: Parser.getType xml
method: call.getChildText "methodName"
v = Parser.parse call.getChild "params"
o.params = v if v?
o
else
child = xml.children?[0]
switch xml.getName()
when "string", "name"
child
when "i4", "int", "double"
child * 1
when "boolean"
(child is "true" or child is "1")
when "value"
Parser.parse child
when "struct"
struct = {}
members = (Parser.parse m for m in xml.getChildren "member")
struct[m.name] = m.value for m in members
struct
when "array"
Parser.parse xml.getChild "data"
when "params"
(Parser.parse c.getChild "value" for c in xml.getChildren "param")
when "data"
data = []
for d in xml.getChildren "value"
data.push Parser.parse d
data
when "member", "attribute"
{
name: xml.getChildText "name"
value: Parser.parse xml.getChild "value"
}
module.exports = Parser
|
[
{
"context": "ne) ->\n user = new User(\n email : \"user@user.com\"\n firstName: \"Full Name\"\n lastName ",
"end": 343,
"score": 0.9999138712882996,
"start": 330,
"tag": "EMAIL",
"value": "user@user.com"
},
{
"context": " lastName : \"Last Name\"\n... | test/user/api.coffee | gertu/gertu | 1 | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
User = mongoose.model "User"
server = request.agent(app)
apiPreffix = '/api/v1'
describe "<Unit Test>", ->
describe "API User:", ->
before (done) ->
user = new User(
email : "user@user.com"
firstName: "Full Name"
lastName : "Last Name"
password : "pass11"
)
user.save()
done()
describe "Authentication", ->
it "should be able to login locally", (done) ->
server.post(apiPreffix + "/users/session").send(
email : "user@user.com"
password: "pass11"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to sign up", (done) ->
server.post(apiPreffix + "/users").send(
email : "newuser@user.com"
password: "pass11"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to logout", (done) ->
server.get(apiPreffix + "/signout").send().end (err, res) ->
res.should.have.status 302
server.get("/").send().end (err, res) ->
res.should.have.status 200
done()
after (done) ->
User.remove().exec()
done()
| 47721 | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
User = mongoose.model "User"
server = request.agent(app)
apiPreffix = '/api/v1'
describe "<Unit Test>", ->
describe "API User:", ->
before (done) ->
user = new User(
email : "<EMAIL>"
firstName: "Full Name"
lastName : "Last Name"
password : "<PASSWORD>"
)
user.save()
done()
describe "Authentication", ->
it "should be able to login locally", (done) ->
server.post(apiPreffix + "/users/session").send(
email : "<EMAIL>"
password: "<PASSWORD>"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to sign up", (done) ->
server.post(apiPreffix + "/users").send(
email : "<EMAIL>"
password: "<PASSWORD>"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to logout", (done) ->
server.get(apiPreffix + "/signout").send().end (err, res) ->
res.should.have.status 302
server.get("/").send().end (err, res) ->
res.should.have.status 200
done()
after (done) ->
User.remove().exec()
done()
| true | should = require "should"
app = require "../../server"
mongoose = require "mongoose"
request = require "supertest"
User = mongoose.model "User"
server = request.agent(app)
apiPreffix = '/api/v1'
describe "<Unit Test>", ->
describe "API User:", ->
before (done) ->
user = new User(
email : "PI:EMAIL:<EMAIL>END_PI"
firstName: "Full Name"
lastName : "Last Name"
password : "PI:PASSWORD:<PASSWORD>END_PI"
)
user.save()
done()
describe "Authentication", ->
it "should be able to login locally", (done) ->
server.post(apiPreffix + "/users/session").send(
email : "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to sign up", (done) ->
server.post(apiPreffix + "/users").send(
email : "PI:EMAIL:<EMAIL>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
).end (err, res) ->
res.headers.location.should.have.equal "/"
done()
it "should be able to logout", (done) ->
server.get(apiPreffix + "/signout").send().end (err, res) ->
res.should.have.status 302
server.get("/").send().end (err, res) ->
res.should.have.status 200
done()
after (done) ->
User.remove().exec()
done()
|
[
{
"context": " username = req.body.username\n password = req.body.password\n if users[username]\n if users[usernam",
"end": 1015,
"score": 0.997606635093689,
"start": 998,
"tag": "PASSWORD",
"value": "req.body.password"
},
{
"context": "_User', (req,res)=>\n ... | test/controllers/Login-Controller.test.coffee | TeamMentor/TM_Site | 0 | express = require 'express'
bodyParser = require 'body-parser'
Login_Controller = require '../../src/controllers/Login-Controller'
config = require '../../src/config'
describe '| controllers | Login-Controller.test |', ->
#consts
loginPage = 'guest/login-Fail.jade'
loginPage_Unavailable = 'guest/login-cant-connect.jade'
indexPage = '/jade/show'
mainPage_no_user = '/jade/guest/default.html'
blank_credentials_message = 'Invalid Username or Password'
random_Port = 10000.random().add(10000)
#mocked server
server = null
users = { tm: 'tm' , user: 'a' }
on_Login_Response = null
add_TM_WebServices_Routes = (app)=>
app.post '/Aspx_Pages/TM_WebServices.asmx/Login_Response', (req,res)=>
if on_Login_Response
return on_Login_Response(req, res)
username = req.body.username
password = req.body.password
if users[username]
if users[username] is password
res.send { d: { Login_Status: 0} }
else
res.send { d: { Login_Status: 1, Simple_Error_Message: 'Wrong Password' } }
else
res.send { d: { Login_Status: 1, Validation_Results: [{Message: 'Bad user and pwd'} ] } }
app.post '/Aspx_Pages/TM_WebServices.asmx/Current_User', (req,res)=>
res.json { d: { Email: 'aaaa@bbb.com' } }
before (done)->
app = new express().use(bodyParser.json())
add_TM_WebServices_Routes(app)
server = app.listen(random_Port)
"http://localhost:#{random_Port}/Aspx_Pages/TM_WebServices.asmx".GET (html)->
html.assert_Is 'Cannot GET /Aspx_Pages/TM_WebServices.asmx\n'
done()
beforeEach ()->
config.options.tm_design.tm_35_Server = "http://localhost:#{random_Port}"
afterEach ->
config.restore()
after ->
server.close()
invoke_Method = (method, body, expected_Target, callback)->
req =
session: {}
url : '/passwordReset/temp/00000000-0000-0000-0000-000000000000'
body : body
res =
redirect: (target)->
target.assert_Is(expected_Target)
callback()
render_Page = (target) ->
target.assert_Is(expected_Target)
callback()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@[method]()
invoke_LoginUser = (username, password, expected_Target, callback)->
invoke_Method "loginUser",
{ username : username , password : password } ,
expected_Target,
callback
it 'constructor', ->
using new Login_Controller,->
@.req .assert_Is {}
@.res .assert_Is {}
using new Login_Controller('req', 'res'),->
@.req .assert_Is 'req'
@.res .assert_Is 'res'
it "loginUser (server not ok)", (done)->
req = body: {username:'aaaa', password:'bbb'}
res = null
render_Page = (jade_Page, params)->
jade_Page.assert_Is loginPage_Unavailable
params.assert_Is { viewModel: {"username":"","password":"", errorMessage: "TEAM Mentor is unavailable, please contact us at " } }
done()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
config.options.tm_design.tm_35_Server = 'http://aaaaaabbb.teammentor.net'
@.loginUser()
it "loginUser (server ok - null response)", (done)->
on_Login_Response = (req,res)->
res.send null
invoke_LoginUser 'aaa','bbb', loginPage_Unavailable, ->
on_Login_Response = null
done()
it "loginUser (bad username, password)", (done)->
invoke_LoginUser '','', loginPage, -> # empty username and pwd
invoke_LoginUser 'aaa','', loginPage, -> # empty pwd
invoke_LoginUser '','bbb', loginPage, -> # empty username
invoke_LoginUser 'aaa','bbb', loginPage, -> # bad username and pwd
invoke_LoginUser '','bb', loginPage, -> # blank username
invoke_LoginUser 'aa','', loginPage, -> # blank password
invoke_LoginUser '','', loginPage,done # blank credentials
it "loginUser (local-good username, password)", (done)->
invoke_LoginUser 'tm','tm', indexPage, ->
invoke_LoginUser 'user','a', indexPage, done
it "loginUser (undefined Login_Status using existential operator)", (done)->
invoke_LoginUser undefined ,undefined , loginPage, done
it 'logoutUser', (done)->
invoke_Method "logoutUser", {} ,mainPage_no_user,done
it 'invalid Username or Password (missing username)',(done)->
newUsername =''
newPassword = 'aaa'.add_5_Letters()
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing password)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword =''
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing both username and password)',(done)->
newUsername =''
newPassword =''
#render contains the file to render and the view model object
render_Page = (jadePage,model)->
#Verifying the message from the backend.
model.viewModel.errorMessage.assert_Is(blank_credentials_message)
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong Password)',(done)->
newUsername ='tm'
newPassword ='aaa'.add_5_Letters()
#render contains the file to render and the view model object
render_Page = (html,model)->
model.viewModel.username.assert_Is(newUsername)
model.viewModel.password.assert_Is('')
model.viewModel.errorMessage.assert_Is('Wrong Password')
done()
req = body:{username:newUsername,password:newPassword}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong username)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword = 'bbb'.add_5_Letters()
render_Page = (jade_Page,params)->
jade_Page.assert_Is loginPage
params.viewModel.errorMessage.assert_Is 'Bad user and pwd'
done()
req = body: {username:newUsername, password:newPassword}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'Redirect upon login when URL is correct',(done)->
newUsername = 'tm'
newPassword = 'tm'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is('/foo/bar')
done()
req = body: {username:newUsername, password:newPassword}, session:{redirectUrl:'/foo/bar'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
it 'Redirect upon login when URL is not a local URL',(done)->
newUsername = 'tm'
newPassword = 'tm'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is(indexPage)
done()
req = body: {username:newUsername, password:newPassword}, session:{redirectUrl:'https://www.google.com'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
| 224722 | express = require 'express'
bodyParser = require 'body-parser'
Login_Controller = require '../../src/controllers/Login-Controller'
config = require '../../src/config'
describe '| controllers | Login-Controller.test |', ->
#consts
loginPage = 'guest/login-Fail.jade'
loginPage_Unavailable = 'guest/login-cant-connect.jade'
indexPage = '/jade/show'
mainPage_no_user = '/jade/guest/default.html'
blank_credentials_message = 'Invalid Username or Password'
random_Port = 10000.random().add(10000)
#mocked server
server = null
users = { tm: 'tm' , user: 'a' }
on_Login_Response = null
add_TM_WebServices_Routes = (app)=>
app.post '/Aspx_Pages/TM_WebServices.asmx/Login_Response', (req,res)=>
if on_Login_Response
return on_Login_Response(req, res)
username = req.body.username
password = <PASSWORD>
if users[username]
if users[username] is password
res.send { d: { Login_Status: 0} }
else
res.send { d: { Login_Status: 1, Simple_Error_Message: 'Wrong Password' } }
else
res.send { d: { Login_Status: 1, Validation_Results: [{Message: 'Bad user and pwd'} ] } }
app.post '/Aspx_Pages/TM_WebServices.asmx/Current_User', (req,res)=>
res.json { d: { Email: '<EMAIL>' } }
before (done)->
app = new express().use(bodyParser.json())
add_TM_WebServices_Routes(app)
server = app.listen(random_Port)
"http://localhost:#{random_Port}/Aspx_Pages/TM_WebServices.asmx".GET (html)->
html.assert_Is 'Cannot GET /Aspx_Pages/TM_WebServices.asmx\n'
done()
beforeEach ()->
config.options.tm_design.tm_35_Server = "http://localhost:#{random_Port}"
afterEach ->
config.restore()
after ->
server.close()
invoke_Method = (method, body, expected_Target, callback)->
req =
session: {}
url : '/passwordReset/temp/00000000-0000-0000-0000-000000000000'
body : body
res =
redirect: (target)->
target.assert_Is(expected_Target)
callback()
render_Page = (target) ->
target.assert_Is(expected_Target)
callback()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@[method]()
invoke_LoginUser = (username, password, expected_Target, callback)->
invoke_Method "loginUser",
{ username : username , password : <PASSWORD> } ,
expected_Target,
callback
it 'constructor', ->
using new Login_Controller,->
@.req .assert_Is {}
@.res .assert_Is {}
using new Login_Controller('req', 'res'),->
@.req .assert_Is 'req'
@.res .assert_Is 'res'
it "loginUser (server not ok)", (done)->
req = body: {username:'aaaa', password:'<PASSWORD>'}
res = null
render_Page = (jade_Page, params)->
jade_Page.assert_Is loginPage_Unavailable
params.assert_Is { viewModel: {"username":"","password":"", errorMessage: "TEAM Mentor is unavailable, please contact us at " } }
done()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
config.options.tm_design.tm_35_Server = 'http://aaaaaabbb.teammentor.net'
@.loginUser()
it "loginUser (server ok - null response)", (done)->
on_Login_Response = (req,res)->
res.send null
invoke_LoginUser 'aaa','bbb', loginPage_Unavailable, ->
on_Login_Response = null
done()
it "loginUser (bad username, password)", (done)->
invoke_LoginUser '','', loginPage, -> # empty username and pwd
invoke_LoginUser 'aaa','', loginPage, -> # empty pwd
invoke_LoginUser '','bbb', loginPage, -> # empty username
invoke_LoginUser 'aaa','bbb', loginPage, -> # bad username and pwd
invoke_LoginUser '','bb', loginPage, -> # blank username
invoke_LoginUser 'aa','', loginPage, -> # blank password
invoke_LoginUser '','', loginPage,done # blank credentials
it "loginUser (local-good username, password)", (done)->
invoke_LoginUser 'tm','tm', indexPage, ->
invoke_LoginUser 'user','a', indexPage, done
it "loginUser (undefined Login_Status using existential operator)", (done)->
invoke_LoginUser undefined ,undefined , loginPage, done
it 'logoutUser', (done)->
invoke_Method "logoutUser", {} ,mainPage_no_user,done
it 'invalid Username or Password (missing username)',(done)->
newUsername =''
newPassword = '<PASSWORD>'.add_5_Letters()
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:<PASSWORD>},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing password)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword =''
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing both username and password)',(done)->
newUsername =''
newPassword =''
#render contains the file to render and the view model object
render_Page = (jadePage,model)->
#Verifying the message from the backend.
model.viewModel.errorMessage.assert_Is(blank_credentials_message)
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong Password)',(done)->
newUsername ='tm'
newPassword ='<PASSWORD>'.add_5_Letters()
#render contains the file to render and the view model object
render_Page = (html,model)->
model.viewModel.username.assert_Is(newUsername)
model.viewModel.password.assert_Is('')
model.viewModel.errorMessage.assert_Is('Wrong Password')
done()
req = body:{username:newUsername,password:<PASSWORD>}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong username)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword = '<PASSWORD>'.add_5_Letters()
render_Page = (jade_Page,params)->
jade_Page.assert_Is loginPage
params.viewModel.errorMessage.assert_Is 'Bad user and pwd'
done()
req = body: {username:newUsername, password:new<PASSWORD>}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'Redirect upon login when URL is correct',(done)->
newUsername = 'tm'
newPassword = '<PASSWORD>'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is('/foo/bar')
done()
req = body: {username:newUsername, password:<PASSWORD>}, session:{redirectUrl:'/foo/bar'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
it 'Redirect upon login when URL is not a local URL',(done)->
newUsername = 'tm'
newPassword = '<PASSWORD>'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is(indexPage)
done()
req = body: {username:newUsername, password:<PASSWORD>}, session:{redirectUrl:'https://www.google.com'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
| true | express = require 'express'
bodyParser = require 'body-parser'
Login_Controller = require '../../src/controllers/Login-Controller'
config = require '../../src/config'
describe '| controllers | Login-Controller.test |', ->
#consts
loginPage = 'guest/login-Fail.jade'
loginPage_Unavailable = 'guest/login-cant-connect.jade'
indexPage = '/jade/show'
mainPage_no_user = '/jade/guest/default.html'
blank_credentials_message = 'Invalid Username or Password'
random_Port = 10000.random().add(10000)
#mocked server
server = null
users = { tm: 'tm' , user: 'a' }
on_Login_Response = null
add_TM_WebServices_Routes = (app)=>
app.post '/Aspx_Pages/TM_WebServices.asmx/Login_Response', (req,res)=>
if on_Login_Response
return on_Login_Response(req, res)
username = req.body.username
password = PI:PASSWORD:<PASSWORD>END_PI
if users[username]
if users[username] is password
res.send { d: { Login_Status: 0} }
else
res.send { d: { Login_Status: 1, Simple_Error_Message: 'Wrong Password' } }
else
res.send { d: { Login_Status: 1, Validation_Results: [{Message: 'Bad user and pwd'} ] } }
app.post '/Aspx_Pages/TM_WebServices.asmx/Current_User', (req,res)=>
res.json { d: { Email: 'PI:EMAIL:<EMAIL>END_PI' } }
before (done)->
app = new express().use(bodyParser.json())
add_TM_WebServices_Routes(app)
server = app.listen(random_Port)
"http://localhost:#{random_Port}/Aspx_Pages/TM_WebServices.asmx".GET (html)->
html.assert_Is 'Cannot GET /Aspx_Pages/TM_WebServices.asmx\n'
done()
beforeEach ()->
config.options.tm_design.tm_35_Server = "http://localhost:#{random_Port}"
afterEach ->
config.restore()
after ->
server.close()
invoke_Method = (method, body, expected_Target, callback)->
req =
session: {}
url : '/passwordReset/temp/00000000-0000-0000-0000-000000000000'
body : body
res =
redirect: (target)->
target.assert_Is(expected_Target)
callback()
render_Page = (target) ->
target.assert_Is(expected_Target)
callback()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@[method]()
invoke_LoginUser = (username, password, expected_Target, callback)->
invoke_Method "loginUser",
{ username : username , password : PI:PASSWORD:<PASSWORD>END_PI } ,
expected_Target,
callback
it 'constructor', ->
using new Login_Controller,->
@.req .assert_Is {}
@.res .assert_Is {}
using new Login_Controller('req', 'res'),->
@.req .assert_Is 'req'
@.res .assert_Is 'res'
it "loginUser (server not ok)", (done)->
req = body: {username:'aaaa', password:'PI:PASSWORD:<PASSWORD>END_PI'}
res = null
render_Page = (jade_Page, params)->
jade_Page.assert_Is loginPage_Unavailable
params.assert_Is { viewModel: {"username":"","password":"", errorMessage: "TEAM Mentor is unavailable, please contact us at " } }
done()
using new Login_Controller(req, res), ->
@.render_Page = render_Page
config.options.tm_design.tm_35_Server = 'http://aaaaaabbb.teammentor.net'
@.loginUser()
it "loginUser (server ok - null response)", (done)->
on_Login_Response = (req,res)->
res.send null
invoke_LoginUser 'aaa','bbb', loginPage_Unavailable, ->
on_Login_Response = null
done()
it "loginUser (bad username, password)", (done)->
invoke_LoginUser '','', loginPage, -> # empty username and pwd
invoke_LoginUser 'aaa','', loginPage, -> # empty pwd
invoke_LoginUser '','bbb', loginPage, -> # empty username
invoke_LoginUser 'aaa','bbb', loginPage, -> # bad username and pwd
invoke_LoginUser '','bb', loginPage, -> # blank username
invoke_LoginUser 'aa','', loginPage, -> # blank password
invoke_LoginUser '','', loginPage,done # blank credentials
it "loginUser (local-good username, password)", (done)->
invoke_LoginUser 'tm','tm', indexPage, ->
invoke_LoginUser 'user','a', indexPage, done
it "loginUser (undefined Login_Status using existential operator)", (done)->
invoke_LoginUser undefined ,undefined , loginPage, done
it 'logoutUser', (done)->
invoke_Method "logoutUser", {} ,mainPage_no_user,done
it 'invalid Username or Password (missing username)',(done)->
newUsername =''
newPassword = 'PI:PASSWORD:<PASSWORD>END_PI'.add_5_Letters()
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:PI:PASSWORD:<PASSWORD>END_PI},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing password)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword =''
render_Page = (jadePage,model)-> # render contains the file to render and the view model object
model.viewModel.errorMessage.assert_Is(blank_credentials_message) # verifying the message from the backend.
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'invalid Username or Password (missing both username and password)',(done)->
newUsername =''
newPassword =''
#render contains the file to render and the view model object
render_Page = (jadePage,model)->
#Verifying the message from the backend.
model.viewModel.errorMessage.assert_Is(blank_credentials_message)
jadePage.assert_Is('guest/login-Fail.jade')
done()
req = body:{username:newUsername,password:newPassword},session:'';
res = null
using new Login_Controller(req, res) ,->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong Password)',(done)->
newUsername ='tm'
newPassword ='PI:PASSWORD:<PASSWORD>END_PI'.add_5_Letters()
#render contains the file to render and the view model object
render_Page = (html,model)->
model.viewModel.username.assert_Is(newUsername)
model.viewModel.password.assert_Is('')
model.viewModel.errorMessage.assert_Is('Wrong Password')
done()
req = body:{username:newUsername,password:PI:PASSWORD:<PASSWORD>END_PI}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'login form persist HTML form fields on error (Wrong username)',(done)->
newUsername = 'aaa'.add_5_Letters()
newPassword = 'PI:PASSWORD:<PASSWORD>END_PI'.add_5_Letters()
render_Page = (jade_Page,params)->
jade_Page.assert_Is loginPage
params.viewModel.errorMessage.assert_Is 'Bad user and pwd'
done()
req = body: {username:newUsername, password:newPI:PASSWORD:<PASSWORD>END_PI}, session:''
res = null
using new Login_Controller(req, res), ->
@.render_Page = render_Page
@.loginUser()
it 'Redirect upon login when URL is correct',(done)->
newUsername = 'tm'
newPassword = 'PI:PASSWORD:<PASSWORD>END_PI'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is('/foo/bar')
done()
req = body: {username:newUsername, password:PI:PASSWORD:<PASSWORD>END_PI}, session:{redirectUrl:'/foo/bar'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
it 'Redirect upon login when URL is not a local URL',(done)->
newUsername = 'tm'
newPassword = 'PI:PASSWORD:<PASSWORD>END_PI'
redirect = (jade_Page)->
jade_Page.assert_Is_Not_Null()
jade_Page.assert_Is(indexPage)
done()
req = body: {username:newUsername, password:PI:PASSWORD:<PASSWORD>END_PI}, session:{redirectUrl:'https://www.google.com'}
res = redirect: redirect
using new Login_Controller(req, res), ->
@.loginUser()
|
[
{
"context": "'De'\n\n # PERSONS\n 'persons.firstName': 'Vorname'\n 'persons.lastName': 'Nachname'\n\n # TA",
"end": 1091,
"score": 0.9980770349502563,
"start": 1084,
"tag": "NAME",
"value": "Vorname"
},
{
"context": ".firstName': 'Vorname'\n 'persons.lastNam... | src/app/index.config.coffee | bbasic/workload-planner | 0 | angular.module 'workloadPlanner'
.config ($logProvider, toastrConfig, moment) ->
'ngInject'
# Enable log
$logProvider.debugEnabled true
# Set options third-party lib
toastrConfig.allowHtml = true
toastrConfig.timeOut = 3000
toastrConfig.positionClass = 'toast-top-right'
toastrConfig.preventDuplicates = true
toastrConfig.progressBar = true
# set moment locale
moment.locale('de-at')
.config ($translateProvider) ->
'ngInject'
$translateProvider.useSanitizeValueStrategy('sanitize')
$translateProvider.useLocalStorage()
$translateProvider.preferredLanguage('de_DE')
$translateProvider.translations 'de_DE', {
# NAVIGATION
'navigation.planner': 'Planer'
'navigation.persons': 'Personen'
'navigation.tasks': 'Aufgaben'
'navigation.data': 'Daten'
'navigation.data.export': 'Exportieren'
'navigation.data.import': 'Importieren'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': 'Vorname'
'persons.lastName': 'Nachname'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Ausführende Tage'
# PLANNER
'planner.chooseWeek': 'Woche auswählen'
}
$translateProvider.translations 'en_EN', {
# NAVIGATION
'navigation.planner': 'Planner'
'navigation.persons': 'Persons'
'navigation.tasks': 'Tasks'
'navigation.data': 'Data'
'navigation.data.export': 'Export'
'navigation.data.import': 'Import'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': 'First Name'
'persons.lastName': 'Last Name'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Active days'
# PLANNER
'planner.chooseWeek': 'Choose Week'
}
| 15033 | angular.module 'workloadPlanner'
.config ($logProvider, toastrConfig, moment) ->
'ngInject'
# Enable log
$logProvider.debugEnabled true
# Set options third-party lib
toastrConfig.allowHtml = true
toastrConfig.timeOut = 3000
toastrConfig.positionClass = 'toast-top-right'
toastrConfig.preventDuplicates = true
toastrConfig.progressBar = true
# set moment locale
moment.locale('de-at')
.config ($translateProvider) ->
'ngInject'
$translateProvider.useSanitizeValueStrategy('sanitize')
$translateProvider.useLocalStorage()
$translateProvider.preferredLanguage('de_DE')
$translateProvider.translations 'de_DE', {
# NAVIGATION
'navigation.planner': 'Planer'
'navigation.persons': 'Personen'
'navigation.tasks': 'Aufgaben'
'navigation.data': 'Daten'
'navigation.data.export': 'Exportieren'
'navigation.data.import': 'Importieren'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': '<NAME>'
'persons.lastName': '<NAME>'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Ausführende Tage'
# PLANNER
'planner.chooseWeek': 'Woche auswählen'
}
$translateProvider.translations 'en_EN', {
# NAVIGATION
'navigation.planner': 'Planner'
'navigation.persons': 'Persons'
'navigation.tasks': 'Tasks'
'navigation.data': 'Data'
'navigation.data.export': 'Export'
'navigation.data.import': 'Import'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': '<NAME>'
'persons.lastName': '<NAME>'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Active days'
# PLANNER
'planner.chooseWeek': 'Choose Week'
}
| true | angular.module 'workloadPlanner'
.config ($logProvider, toastrConfig, moment) ->
'ngInject'
# Enable log
$logProvider.debugEnabled true
# Set options third-party lib
toastrConfig.allowHtml = true
toastrConfig.timeOut = 3000
toastrConfig.positionClass = 'toast-top-right'
toastrConfig.preventDuplicates = true
toastrConfig.progressBar = true
# set moment locale
moment.locale('de-at')
.config ($translateProvider) ->
'ngInject'
$translateProvider.useSanitizeValueStrategy('sanitize')
$translateProvider.useLocalStorage()
$translateProvider.preferredLanguage('de_DE')
$translateProvider.translations 'de_DE', {
# NAVIGATION
'navigation.planner': 'Planer'
'navigation.persons': 'Personen'
'navigation.tasks': 'Aufgaben'
'navigation.data': 'Daten'
'navigation.data.export': 'Exportieren'
'navigation.data.import': 'Importieren'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': 'PI:NAME:<NAME>END_PI'
'persons.lastName': 'PI:NAME:<NAME>END_PI'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Ausführende Tage'
# PLANNER
'planner.chooseWeek': 'Woche auswählen'
}
$translateProvider.translations 'en_EN', {
# NAVIGATION
'navigation.planner': 'Planner'
'navigation.persons': 'Persons'
'navigation.tasks': 'Tasks'
'navigation.data': 'Data'
'navigation.data.export': 'Export'
'navigation.data.import': 'Import'
'navigation.language.en_EN': 'En'
'navigation.language.de_DE': 'De'
# PERSONS
'persons.firstName': 'PI:NAME:<NAME>END_PI'
'persons.lastName': 'PI:NAME:<NAME>END_PI'
# TASKS
'tasks.taskName': 'Name'
'tasks.activeDays': 'Active days'
# PLANNER
'planner.chooseWeek': 'Choose Week'
}
|
[
{
"context": "ew NoDisplayNameModel({ sortable_id: \"zz\", name: \"Z Z\" })\n collection = new AToZCollection([], { m",
"end": 1912,
"score": 0.8818458318710327,
"start": 1909,
"tag": "NAME",
"value": "Z Z"
},
{
"context": " m = new NoHrefModel({ sortable_id: \"zz\", name: \"Z ... | test/a_to_z.coffee | joeyAghion/artsy-backbone-mixins | 0 | _ = require 'underscore'
Backbone = require 'backbone'
aToZ = require '../lib/a_to_z'
class AToZCollectionModel extends Backbone.Model
alphaSortKey: -> @get 'sortable_id'
displayName: -> @get 'name'
href: -> "/#{@get('sortable_id')}"
class AToZCollection extends Backbone.Collection
_.extend @prototype, aToZ
model: AToZCollectionModel
describe 'A to Z mixin', ->
beforeEach ->
@m1 = new AToZCollectionModel({ sortable_id: "twenty-thirteen", name: "Twenty Thirteen" })
@m2 = new AToZCollectionModel({ sortable_id: "2014", name: "2014" })
@m3 = new AToZCollectionModel({ sortable_id: "twenty-fourteen", name: "Twenty Fourteen" })
@m4 = new AToZCollectionModel({ sortable_id: "fifteen-plus-twenty", name: "Fifteen + Twenty" })
@m5 = new AToZCollectionModel({ sortable_id: "two-times", name: "Two Times" })
@m6 = new AToZCollectionModel({ sortable_id: "tim", name: "Tim" })
@collection = new AToZCollection([ @m1, @m2, @m3, @m4, @m5, @m6 ])
describe '#groupByAlpha', ->
it 'groups models by sort letter', ->
grouped = @collection.groupByAlpha()
grouped['0-9'].length.should.equal 1
grouped['0-9'][0].should.equal @m2
grouped.T.length.should.equal 4
grouped.F.length.should.equal 1
describe '#groupByAlphaWithColumns', ->
it 'groups sorted letters and formatted models in columns', ->
grouped = @collection.groupByAlphaWithColumns 3
grouped.length.should.equal 3
grouped[0].letter.should.equal "0-9"
grouped[1].letter.should.equal "F"
grouped[2].letter.should.equal "T"
_.each grouped, (group) -> group.columns.length.should.equal 3
it 'requires collection models to have a displayName method', ->
class NoDisplayNameModel extends Backbone.Model
displayName: null
href: -> "/#{@get('sortable_id')}"
m = new NoDisplayNameModel({ sortable_id: "zz", name: "Z Z" })
collection = new AToZCollection([], { model: NoDisplayNameModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'requires collection models to have an href method', ->
class NoHrefModel extends Backbone.Model
displayName: -> @get 'name'
href: null
m = new NoHrefModel({ sortable_id: "zz", name: "Z Z" })
collection = new AToZCollection([], { model: NoHrefModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'handles link to page', ->
m0 = new AToZCollectionModel({ sortable_id: "1", name: "Twenty1", artworks_count: 1 })
m1 = new AToZCollectionModel({ sortable_id: "2", name: "Twenty2", artworks_count: 0 })
m2 = new AToZCollectionModel({ sortable_id: "3", name: "Twenty3" })
collection = new AToZCollection([ m0, m1, m2 ])
grouped = collection.groupByAlphaWithColumns(1)[0].columns[0]
grouped[0].linkToPage.should.be.ok
grouped[1].linkToPage.should.not.be.ok
grouped[2].linkToPage.should.be.ok
| 22298 | _ = require 'underscore'
Backbone = require 'backbone'
aToZ = require '../lib/a_to_z'
class AToZCollectionModel extends Backbone.Model
alphaSortKey: -> @get 'sortable_id'
displayName: -> @get 'name'
href: -> "/#{@get('sortable_id')}"
class AToZCollection extends Backbone.Collection
_.extend @prototype, aToZ
model: AToZCollectionModel
describe 'A to Z mixin', ->
beforeEach ->
@m1 = new AToZCollectionModel({ sortable_id: "twenty-thirteen", name: "Twenty Thirteen" })
@m2 = new AToZCollectionModel({ sortable_id: "2014", name: "2014" })
@m3 = new AToZCollectionModel({ sortable_id: "twenty-fourteen", name: "Twenty Fourteen" })
@m4 = new AToZCollectionModel({ sortable_id: "fifteen-plus-twenty", name: "Fifteen + Twenty" })
@m5 = new AToZCollectionModel({ sortable_id: "two-times", name: "Two Times" })
@m6 = new AToZCollectionModel({ sortable_id: "tim", name: "Tim" })
@collection = new AToZCollection([ @m1, @m2, @m3, @m4, @m5, @m6 ])
describe '#groupByAlpha', ->
it 'groups models by sort letter', ->
grouped = @collection.groupByAlpha()
grouped['0-9'].length.should.equal 1
grouped['0-9'][0].should.equal @m2
grouped.T.length.should.equal 4
grouped.F.length.should.equal 1
describe '#groupByAlphaWithColumns', ->
it 'groups sorted letters and formatted models in columns', ->
grouped = @collection.groupByAlphaWithColumns 3
grouped.length.should.equal 3
grouped[0].letter.should.equal "0-9"
grouped[1].letter.should.equal "F"
grouped[2].letter.should.equal "T"
_.each grouped, (group) -> group.columns.length.should.equal 3
it 'requires collection models to have a displayName method', ->
class NoDisplayNameModel extends Backbone.Model
displayName: null
href: -> "/#{@get('sortable_id')}"
m = new NoDisplayNameModel({ sortable_id: "zz", name: "<NAME>" })
collection = new AToZCollection([], { model: NoDisplayNameModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'requires collection models to have an href method', ->
class NoHrefModel extends Backbone.Model
displayName: -> @get 'name'
href: null
m = new NoHrefModel({ sortable_id: "zz", name: "<NAME>" })
collection = new AToZCollection([], { model: NoHrefModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'handles link to page', ->
m0 = new AToZCollectionModel({ sortable_id: "1", name: "<NAME>", artworks_count: 1 })
m1 = new AToZCollectionModel({ sortable_id: "2", name: "<NAME>", artworks_count: 0 })
m2 = new AToZCollectionModel({ sortable_id: "3", name: "<NAME>" })
collection = new AToZCollection([ m0, m1, m2 ])
grouped = collection.groupByAlphaWithColumns(1)[0].columns[0]
grouped[0].linkToPage.should.be.ok
grouped[1].linkToPage.should.not.be.ok
grouped[2].linkToPage.should.be.ok
| true | _ = require 'underscore'
Backbone = require 'backbone'
aToZ = require '../lib/a_to_z'
class AToZCollectionModel extends Backbone.Model
alphaSortKey: -> @get 'sortable_id'
displayName: -> @get 'name'
href: -> "/#{@get('sortable_id')}"
class AToZCollection extends Backbone.Collection
_.extend @prototype, aToZ
model: AToZCollectionModel
describe 'A to Z mixin', ->
beforeEach ->
@m1 = new AToZCollectionModel({ sortable_id: "twenty-thirteen", name: "Twenty Thirteen" })
@m2 = new AToZCollectionModel({ sortable_id: "2014", name: "2014" })
@m3 = new AToZCollectionModel({ sortable_id: "twenty-fourteen", name: "Twenty Fourteen" })
@m4 = new AToZCollectionModel({ sortable_id: "fifteen-plus-twenty", name: "Fifteen + Twenty" })
@m5 = new AToZCollectionModel({ sortable_id: "two-times", name: "Two Times" })
@m6 = new AToZCollectionModel({ sortable_id: "tim", name: "Tim" })
@collection = new AToZCollection([ @m1, @m2, @m3, @m4, @m5, @m6 ])
describe '#groupByAlpha', ->
it 'groups models by sort letter', ->
grouped = @collection.groupByAlpha()
grouped['0-9'].length.should.equal 1
grouped['0-9'][0].should.equal @m2
grouped.T.length.should.equal 4
grouped.F.length.should.equal 1
describe '#groupByAlphaWithColumns', ->
it 'groups sorted letters and formatted models in columns', ->
grouped = @collection.groupByAlphaWithColumns 3
grouped.length.should.equal 3
grouped[0].letter.should.equal "0-9"
grouped[1].letter.should.equal "F"
grouped[2].letter.should.equal "T"
_.each grouped, (group) -> group.columns.length.should.equal 3
it 'requires collection models to have a displayName method', ->
class NoDisplayNameModel extends Backbone.Model
displayName: null
href: -> "/#{@get('sortable_id')}"
m = new NoDisplayNameModel({ sortable_id: "zz", name: "PI:NAME:<NAME>END_PI" })
collection = new AToZCollection([], { model: NoDisplayNameModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'requires collection models to have an href method', ->
class NoHrefModel extends Backbone.Model
displayName: -> @get 'name'
href: null
m = new NoHrefModel({ sortable_id: "zz", name: "PI:NAME:<NAME>END_PI" })
collection = new AToZCollection([], { model: NoHrefModel })
collection.add m
(()-> collection.groupByAlphaWithColumns()).should.throw()
it 'handles link to page', ->
m0 = new AToZCollectionModel({ sortable_id: "1", name: "PI:NAME:<NAME>END_PI", artworks_count: 1 })
m1 = new AToZCollectionModel({ sortable_id: "2", name: "PI:NAME:<NAME>END_PI", artworks_count: 0 })
m2 = new AToZCollectionModel({ sortable_id: "3", name: "PI:NAME:<NAME>END_PI" })
collection = new AToZCollection([ m0, m1, m2 ])
grouped = collection.groupByAlphaWithColumns(1)[0].columns[0]
grouped[0].linkToPage.should.be.ok
grouped[1].linkToPage.should.not.be.ok
grouped[2].linkToPage.should.be.ok
|
[
{
"context": "r\", ->\n\n\tbeforeEach ->\n\t\tself = @\n\t\t@user = {_id:\"12390i\"}\n\t\t@user.save = sinon.stub().callsArgWith(0",
"end": 279,
"score": 0.6473881006240845,
"start": 278,
"tag": "USERNAME",
"value": "1"
},
{
"context": "\", ->\n\n\tbeforeEach ->\n\t\tself = @\n\t\t@u... | test/UnitTests/coffee/User/UserCreatorTests.coffee | bowlofstew/web-sharelatex | 0 | sinon = require('sinon')
chai = require('chai')
assert = require("assert")
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserCreator.js"
SandboxedModule = require('sandboxed-module')
describe "UserCreator", ->
beforeEach ->
self = @
@user = {_id:"12390i"}
@user.save = sinon.stub().callsArgWith(0)
@UserModel = class Project
constructor: ->
return self.user
@UserLocator =
findByEmail: sinon.stub()
@UserCreator = SandboxedModule.require modulePath, requires:
"../../models/User": User:@UserModel
"./UserLocator":@UserLocator
"logger-sharelatex":{log:->}
@email = "bob.oswald@gmail.com"
describe "getUserOrCreateHoldingAccount", ->
it "should immediately return the user if found", (done)->
@UserLocator.findByEmail.callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
assert.deepEqual returnedUser, @user
done()
it "should create new holding account if the user is not found", (done)->
@UserLocator.findByEmail.callsArgWith(1)
@UserCreator.createNewUser = sinon.stub().callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
@UserCreator.createNewUser.calledWith(email:@email, holdingAccount:true).should.equal true
assert.deepEqual returnedUser, @user
done()
describe "createNewUser", ->
it "should take the opts and put them in the model", (done)->
opts =
email:@email
holdingAccount:true
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "bob.oswald"
done()
it "should use the start of the email if the first name is empty string", (done)->
opts =
email:@email
holdingAccount:true
first_name:""
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "bob.oswald"
done()
it "should use the first name if passed", (done)->
opts =
email:@email
holdingAccount:true
first_name:"fiiirstname"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "fiiirstname"
done()
it "should use the last name if passed", (done)->
opts =
email:@email
holdingAccount:true
last_name:"lastNammmmeee"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.last_name, "lastNammmmeee"
done()
| 133281 | sinon = require('sinon')
chai = require('chai')
assert = require("assert")
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserCreator.js"
SandboxedModule = require('sandboxed-module')
describe "UserCreator", ->
beforeEach ->
self = @
@user = {_id:"1<PASSWORD>"}
@user.save = sinon.stub().callsArgWith(0)
@UserModel = class Project
constructor: ->
return self.user
@UserLocator =
findByEmail: sinon.stub()
@UserCreator = SandboxedModule.require modulePath, requires:
"../../models/User": User:@UserModel
"./UserLocator":@UserLocator
"logger-sharelatex":{log:->}
@email = "<EMAIL>"
describe "getUserOrCreateHoldingAccount", ->
it "should immediately return the user if found", (done)->
@UserLocator.findByEmail.callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
assert.deepEqual returnedUser, @user
done()
it "should create new holding account if the user is not found", (done)->
@UserLocator.findByEmail.callsArgWith(1)
@UserCreator.createNewUser = sinon.stub().callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
@UserCreator.createNewUser.calledWith(email:@email, holdingAccount:true).should.equal true
assert.deepEqual returnedUser, @user
done()
describe "createNewUser", ->
it "should take the opts and put them in the model", (done)->
opts =
email:@email
holdingAccount:true
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "<NAME>"
done()
it "should use the start of the email if the first name is empty string", (done)->
opts =
email:@email
holdingAccount:true
first_name:""
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "<NAME>"
done()
it "should use the first name if passed", (done)->
opts =
email:@email
holdingAccount:true
first_name:"<NAME>"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "<NAME>"
done()
it "should use the last name if passed", (done)->
opts =
email:@email
holdingAccount:true
last_name:"<NAME>"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.last_name, "<NAME>"
done()
| true | sinon = require('sinon')
chai = require('chai')
assert = require("assert")
should = chai.should()
modulePath = "../../../../app/js/Features/User/UserCreator.js"
SandboxedModule = require('sandboxed-module')
describe "UserCreator", ->
beforeEach ->
self = @
@user = {_id:"1PI:PASSWORD:<PASSWORD>END_PI"}
@user.save = sinon.stub().callsArgWith(0)
@UserModel = class Project
constructor: ->
return self.user
@UserLocator =
findByEmail: sinon.stub()
@UserCreator = SandboxedModule.require modulePath, requires:
"../../models/User": User:@UserModel
"./UserLocator":@UserLocator
"logger-sharelatex":{log:->}
@email = "PI:EMAIL:<EMAIL>END_PI"
describe "getUserOrCreateHoldingAccount", ->
it "should immediately return the user if found", (done)->
@UserLocator.findByEmail.callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
assert.deepEqual returnedUser, @user
done()
it "should create new holding account if the user is not found", (done)->
@UserLocator.findByEmail.callsArgWith(1)
@UserCreator.createNewUser = sinon.stub().callsArgWith(1, null, @user)
@UserCreator.getUserOrCreateHoldingAccount @email, (err, returnedUser)=>
@UserCreator.createNewUser.calledWith(email:@email, holdingAccount:true).should.equal true
assert.deepEqual returnedUser, @user
done()
describe "createNewUser", ->
it "should take the opts and put them in the model", (done)->
opts =
email:@email
holdingAccount:true
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "PI:NAME:<NAME>END_PI"
done()
it "should use the start of the email if the first name is empty string", (done)->
opts =
email:@email
holdingAccount:true
first_name:""
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "PI:NAME:<NAME>END_PI"
done()
it "should use the first name if passed", (done)->
opts =
email:@email
holdingAccount:true
first_name:"PI:NAME:<NAME>END_PI"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.first_name, "PI:NAME:<NAME>END_PI"
done()
it "should use the last name if passed", (done)->
opts =
email:@email
holdingAccount:true
last_name:"PI:NAME:<NAME>END_PI"
@UserCreator.createNewUser opts, (err, user)=>
assert.equal user.email, @email
assert.equal user.holdingAccount, true
assert.equal user.last_name, "PI:NAME:<NAME>END_PI"
done()
|
[
{
"context": "'../../src/setup/setup-towns')\n\ntown = {\n name: \"Croma\"\n sealId: \"MKO\"\n mapX: 500\n mapY: 500\n}\n\ndescr",
"end": 105,
"score": 0.9997921586036682,
"start": 100,
"tag": "NAME",
"value": "Croma"
}
] | test/setup/setup-towns.test.coffee | starpeace-project/starpeace-server-galaxy-nodejs | 0 | assert = require('assert')
SetupTowns = require('../../src/setup/setup-towns')
town = {
name: "Croma"
sealId: "MKO"
mapX: 500
mapY: 500
}
describe('SetupTowns', () ->
describe('#planBuilding()', () ->
it('should plan building layout at same position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
)
it('should plan building layout at different x and same y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
)
it('should plan building layout at same x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -4])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -4])
)
it('should plan building layout at different x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, -4])
)
)
)
| 161421 | assert = require('assert')
SetupTowns = require('../../src/setup/setup-towns')
town = {
name: "<NAME>"
sealId: "MKO"
mapX: 500
mapY: 500
}
describe('SetupTowns', () ->
describe('#planBuilding()', () ->
it('should plan building layout at same position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
)
it('should plan building layout at different x and same y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
)
it('should plan building layout at same x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -4])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -4])
)
it('should plan building layout at different x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, -4])
)
)
)
| true | assert = require('assert')
SetupTowns = require('../../src/setup/setup-towns')
town = {
name: "PI:NAME:<NAME>END_PI"
sealId: "MKO"
mapX: 500
mapY: 500
}
describe('SetupTowns', () ->
describe('#planBuilding()', () ->
it('should plan building layout at same position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -3])
assert.deepEqual(new SetupTowns(1).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [2, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 2])
assert.deepEqual(new SetupTowns(1).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-3, 0])
)
it('should plan building layout at different x and same y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 0])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [-4, 0])
)
it('should plan building layout at same x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 3, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(3, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [0, -4])
assert.deepEqual(new SetupTowns(0).planBuilding(1, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [0, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 1, { tileWidth: 2, tileHeight: 2 }), [0, -4])
)
it('should plan building layout at different x and different y position', () ->
assert.deepEqual(new SetupTowns(0).planBuilding(0, { tileWidth: 3, tileHeight: 3 }, 2, { tileWidth: 2, tileHeight: 2 }), [3, 3])
assert.deepEqual(new SetupTowns(0).planBuilding(2, { tileWidth: 3, tileHeight: 3 }, 0, { tileWidth: 2, tileHeight: 2 }), [-4, -4])
)
)
)
|
[
{
"context": "\"#{server}/users/login\"\n json: \n username: username\n password: password\n request.post requestOp",
"end": 328,
"score": 0.999409556388855,
"start": 320,
"tag": "USERNAME",
"value": "username"
},
{
"context": " json: \n username: username\n ... | client/tools/reset_db.coffee | bcfuchs/RedWire | 0 | #!/usr/bin/env coffee
# IMPORTS
_ = require("underscore")
fs = require("fs.extra")
path = require("path")
util = require("util")
request = require("request")
# FUNCTIONS
statusIsError = (code) -> String(code)[0] == "4"
login = (cb) ->
requestOptions =
url: "#{server}/users/login"
json:
username: username
password: password
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Logged in")
cb()
deleteAllThings = (thingType, cb) ->
request "#{server}/#{thingType}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
things = JSON.parse(body)
console.log("Deleting #{things.length} #{thingType}...")
if things.length is 0 then cb()
doneCount = 0
for thing in things
deleteThing thingType, thing.id, ->
if ++doneCount == things.length then cb()
deleteThing = (thingType, id, cb) ->
request.del "#{server}/#{thingType}?id=#{id}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Deleting #{thingType} #{id} done.")
cb()
createGames = (cb) ->
doneCount = 0
for gameFile in gameFiles
createGame gameFile, ->
if ++doneCount == gameFiles.length then cb()
createGame = (gameFile, cb) ->
gameJson = fs.readFileSync(gameFile, { encoding: "utf8"})
game = JSON.parse(gameJson)
# Encode certain properties as JSON
for property in ['processors', 'switches', 'transformers', 'circuits', 'assets']
game[property] = JSON.stringify(game[property], null, 2)
requestOptions =
url: "#{server}/games"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game #{gameFile} done.")
# Create game version
game.gameId = body.id
requestOptions =
url: "#{server}/game-versions"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game version #{gameFile} done.")
cb()
# MAIN
if process.argv.length < 6
util.error("Usage: coffee reset_db.coffee <server_url> <username> <password> <games_files...>")
process.exit(1)
[server, username, password, gameFiles...] = process.argv[2..]
# Have request store and send cookies
request = request.defaults
jar: true
login ->
deleteAllThings "game-versions", ->
deleteAllThings "games", ->
createGames ->
console.log("Success!")
| 133505 | #!/usr/bin/env coffee
# IMPORTS
_ = require("underscore")
fs = require("fs.extra")
path = require("path")
util = require("util")
request = require("request")
# FUNCTIONS
statusIsError = (code) -> String(code)[0] == "4"
login = (cb) ->
requestOptions =
url: "#{server}/users/login"
json:
username: username
password: <PASSWORD>
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Logged in")
cb()
deleteAllThings = (thingType, cb) ->
request "#{server}/#{thingType}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
things = JSON.parse(body)
console.log("Deleting #{things.length} #{thingType}...")
if things.length is 0 then cb()
doneCount = 0
for thing in things
deleteThing thingType, thing.id, ->
if ++doneCount == things.length then cb()
deleteThing = (thingType, id, cb) ->
request.del "#{server}/#{thingType}?id=#{id}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Deleting #{thingType} #{id} done.")
cb()
createGames = (cb) ->
doneCount = 0
for gameFile in gameFiles
createGame gameFile, ->
if ++doneCount == gameFiles.length then cb()
createGame = (gameFile, cb) ->
gameJson = fs.readFileSync(gameFile, { encoding: "utf8"})
game = JSON.parse(gameJson)
# Encode certain properties as JSON
for property in ['processors', 'switches', 'transformers', 'circuits', 'assets']
game[property] = JSON.stringify(game[property], null, 2)
requestOptions =
url: "#{server}/games"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game #{gameFile} done.")
# Create game version
game.gameId = body.id
requestOptions =
url: "#{server}/game-versions"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game version #{gameFile} done.")
cb()
# MAIN
if process.argv.length < 6
util.error("Usage: coffee reset_db.coffee <server_url> <username> <password> <games_files...>")
process.exit(1)
[server, username, password, gameFiles...] = process.argv[2..]
# Have request store and send cookies
request = request.defaults
jar: true
login ->
deleteAllThings "game-versions", ->
deleteAllThings "games", ->
createGames ->
console.log("Success!")
| true | #!/usr/bin/env coffee
# IMPORTS
_ = require("underscore")
fs = require("fs.extra")
path = require("path")
util = require("util")
request = require("request")
# FUNCTIONS
statusIsError = (code) -> String(code)[0] == "4"
login = (cb) ->
requestOptions =
url: "#{server}/users/login"
json:
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Logged in")
cb()
deleteAllThings = (thingType, cb) ->
request "#{server}/#{thingType}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
things = JSON.parse(body)
console.log("Deleting #{things.length} #{thingType}...")
if things.length is 0 then cb()
doneCount = 0
for thing in things
deleteThing thingType, thing.id, ->
if ++doneCount == things.length then cb()
deleteThing = (thingType, id, cb) ->
request.del "#{server}/#{thingType}?id=#{id}", (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Deleting #{thingType} #{id} done.")
cb()
createGames = (cb) ->
doneCount = 0
for gameFile in gameFiles
createGame gameFile, ->
if ++doneCount == gameFiles.length then cb()
createGame = (gameFile, cb) ->
gameJson = fs.readFileSync(gameFile, { encoding: "utf8"})
game = JSON.parse(gameJson)
# Encode certain properties as JSON
for property in ['processors', 'switches', 'transformers', 'circuits', 'assets']
game[property] = JSON.stringify(game[property], null, 2)
requestOptions =
url: "#{server}/games"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game #{gameFile} done.")
# Create game version
game.gameId = body.id
requestOptions =
url: "#{server}/game-versions"
json: game
request.post requestOptions, (error, response, body) ->
if error then return console.error(error)
if statusIsError(response.statusCode) then return console.error(body)
console.log("Creating game version #{gameFile} done.")
cb()
# MAIN
if process.argv.length < 6
util.error("Usage: coffee reset_db.coffee <server_url> <username> <password> <games_files...>")
process.exit(1)
[server, username, password, gameFiles...] = process.argv[2..]
# Have request store and send cookies
request = request.defaults
jar: true
login ->
deleteAllThings "game-versions", ->
deleteAllThings "games", ->
createGames ->
console.log("Success!")
|
[
{
"context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 43,
"score": 0.6840955018997192,
"start": 33,
"tag": "NAME",
"value": "Technology"
}
] | community/server/src/main/coffeescript/neo4j/webadmin/modules/dashboard/models/DashboardState.coffee | rebaze/neo4j | 1 | ###
Copyright (c) 2002-2013 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['ribcage/Model'],
(Model) ->
class DashboardState extends Model
charts :
primitives :
layers : [
{label:"Nodes", key:'node_count'},
{label:"Properties", key:'property_count'},
{label:"Relationships", key:'relationship_count'}]
chartSettings:
yaxis :
min : 0
usageRequests :
layers : [
{label:"Count", key:'request_count'}]
chartSettings:
yaxis :
min : 0
usageTimes :
layers : [
{label:"Time Mean", key:'request_mean_time'},
{label:"Time Median", key:'request_median_time'},
{label:"Time Max", key:'request_max_time'},
{label:"Time Min", key:'request_min_time'}]
chartSettings:
yaxis :
min : 0
usageBytes :
layers : [
{label:"Bytes", key:'request_bytes'}]
chartSettings:
yaxis :
min : 0
memory :
layers : [{
label:"Memory usage",
key:'memory_usage_percent',
lines: { show: true, fill: true, fillColor: "#4f848f" }
}]
chartSettings:
yaxis :
min : 0
max : 100
tooltipYFormatter : (v) ->
return Math.floor(v) + "%"
zoomLevels : # All granularities approximate 30 points per timespan
year :
xSpan : 60 * 60 * 24 * 365
granularity : 60 * 60 * 24 * 12
timeformat: "%d/%m %y"
month :
xSpan : 60 * 60 * 24 * 30
granularity : 60 * 60 * 24
timeformat: "%d/%m"
week :
xSpan : 60 * 60 * 24 * 7
granularity : 60 * 60 * 6
timeformat: "%d/%m"
day :
xSpan : 60 * 60 * 24
granularity : 60 * 48
timeformat: "%H:%M"
six_hours :
xSpan : 60 * 60 * 6
granularity : 60 * 12
timeformat: "%H:%M"
thirty_minutes :
xSpan : 60 * 30
granularity : 60
timeformat: "%H:%M"
initialize : (options) =>
@setChartByKey "primitives"
#@setChartByKey "usageRequests"
#@setChartByKey "usageTimes"
#@setChartByKey "usageBytes"
@setZoomLevelByKey "six_hours"
getChart : (key) =>
@get "chart" + key
getChartKey : () =>
@get "chartKey"
getZoomLevel : () =>
@get "zoomLevel"
getZoomLevelKey : () =>
@get "zoomLevelKey"
setZoomLevelByKey : (key) =>
@set "zoomLevelKey" : key
@setZoomLevel @zoomLevels[key]
setZoomLevel : (zl) =>
@set zoomLevel : zl
setChartByKey : (key) =>
@set "chartKey" : key
@setChart key, @charts[key]
setChart : (key, chart) =>
tmp = {}
tmp["chart" + key] = chart
@set tmp
)
| 177045 | ###
Copyright (c) 2002-2013 "Neo <NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['ribcage/Model'],
(Model) ->
class DashboardState extends Model
charts :
primitives :
layers : [
{label:"Nodes", key:'node_count'},
{label:"Properties", key:'property_count'},
{label:"Relationships", key:'relationship_count'}]
chartSettings:
yaxis :
min : 0
usageRequests :
layers : [
{label:"Count", key:'request_count'}]
chartSettings:
yaxis :
min : 0
usageTimes :
layers : [
{label:"Time Mean", key:'request_mean_time'},
{label:"Time Median", key:'request_median_time'},
{label:"Time Max", key:'request_max_time'},
{label:"Time Min", key:'request_min_time'}]
chartSettings:
yaxis :
min : 0
usageBytes :
layers : [
{label:"Bytes", key:'request_bytes'}]
chartSettings:
yaxis :
min : 0
memory :
layers : [{
label:"Memory usage",
key:'memory_usage_percent',
lines: { show: true, fill: true, fillColor: "#4f848f" }
}]
chartSettings:
yaxis :
min : 0
max : 100
tooltipYFormatter : (v) ->
return Math.floor(v) + "%"
zoomLevels : # All granularities approximate 30 points per timespan
year :
xSpan : 60 * 60 * 24 * 365
granularity : 60 * 60 * 24 * 12
timeformat: "%d/%m %y"
month :
xSpan : 60 * 60 * 24 * 30
granularity : 60 * 60 * 24
timeformat: "%d/%m"
week :
xSpan : 60 * 60 * 24 * 7
granularity : 60 * 60 * 6
timeformat: "%d/%m"
day :
xSpan : 60 * 60 * 24
granularity : 60 * 48
timeformat: "%H:%M"
six_hours :
xSpan : 60 * 60 * 6
granularity : 60 * 12
timeformat: "%H:%M"
thirty_minutes :
xSpan : 60 * 30
granularity : 60
timeformat: "%H:%M"
initialize : (options) =>
@setChartByKey "primitives"
#@setChartByKey "usageRequests"
#@setChartByKey "usageTimes"
#@setChartByKey "usageBytes"
@setZoomLevelByKey "six_hours"
getChart : (key) =>
@get "chart" + key
getChartKey : () =>
@get "chartKey"
getZoomLevel : () =>
@get "zoomLevel"
getZoomLevelKey : () =>
@get "zoomLevelKey"
setZoomLevelByKey : (key) =>
@set "zoomLevelKey" : key
@setZoomLevel @zoomLevels[key]
setZoomLevel : (zl) =>
@set zoomLevel : zl
setChartByKey : (key) =>
@set "chartKey" : key
@setChart key, @charts[key]
setChart : (key, chart) =>
tmp = {}
tmp["chart" + key] = chart
@set tmp
)
| true | ###
Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
define(
['ribcage/Model'],
(Model) ->
class DashboardState extends Model
charts :
primitives :
layers : [
{label:"Nodes", key:'node_count'},
{label:"Properties", key:'property_count'},
{label:"Relationships", key:'relationship_count'}]
chartSettings:
yaxis :
min : 0
usageRequests :
layers : [
{label:"Count", key:'request_count'}]
chartSettings:
yaxis :
min : 0
usageTimes :
layers : [
{label:"Time Mean", key:'request_mean_time'},
{label:"Time Median", key:'request_median_time'},
{label:"Time Max", key:'request_max_time'},
{label:"Time Min", key:'request_min_time'}]
chartSettings:
yaxis :
min : 0
usageBytes :
layers : [
{label:"Bytes", key:'request_bytes'}]
chartSettings:
yaxis :
min : 0
memory :
layers : [{
label:"Memory usage",
key:'memory_usage_percent',
lines: { show: true, fill: true, fillColor: "#4f848f" }
}]
chartSettings:
yaxis :
min : 0
max : 100
tooltipYFormatter : (v) ->
return Math.floor(v) + "%"
zoomLevels : # All granularities approximate 30 points per timespan
year :
xSpan : 60 * 60 * 24 * 365
granularity : 60 * 60 * 24 * 12
timeformat: "%d/%m %y"
month :
xSpan : 60 * 60 * 24 * 30
granularity : 60 * 60 * 24
timeformat: "%d/%m"
week :
xSpan : 60 * 60 * 24 * 7
granularity : 60 * 60 * 6
timeformat: "%d/%m"
day :
xSpan : 60 * 60 * 24
granularity : 60 * 48
timeformat: "%H:%M"
six_hours :
xSpan : 60 * 60 * 6
granularity : 60 * 12
timeformat: "%H:%M"
thirty_minutes :
xSpan : 60 * 30
granularity : 60
timeformat: "%H:%M"
initialize : (options) =>
@setChartByKey "primitives"
#@setChartByKey "usageRequests"
#@setChartByKey "usageTimes"
#@setChartByKey "usageBytes"
@setZoomLevelByKey "six_hours"
getChart : (key) =>
@get "chart" + key
getChartKey : () =>
@get "chartKey"
getZoomLevel : () =>
@get "zoomLevel"
getZoomLevelKey : () =>
@get "zoomLevelKey"
setZoomLevelByKey : (key) =>
@set "zoomLevelKey" : key
@setZoomLevel @zoomLevels[key]
setZoomLevel : (zl) =>
@set zoomLevel : zl
setChartByKey : (key) =>
@set "chartKey" : key
@setChart key, @charts[key]
setChart : (key, chart) =>
tmp = {}
tmp["chart" + key] = chart
@set tmp
)
|
[
{
"context": "# set up the socket.io connection\n# user_id = '55a84d00e4b06e29cb4eb960'\n# user_token='my_token'\n#",
"end": 48,
"score": 0.547104001045227,
"start": 47,
"tag": "KEY",
"value": "5"
},
{
"context": "# set up the socket.io connection\n# user_id = '55a84d00e4b06e29cb4eb9... | mobile/www/js/controllers.coffee | 1egoman/bag-node | 0 | # set up the socket.io connection
# user_id = '55a84d00e4b06e29cb4eb960'
# user_token='my_token'
# window.host = "http://192.168.1.13:8000"
# window.host = "http://127.0.0.1:8000"
# window.host = "http://192.168.1.15:8000"
window.host = "http://api.getbag.io"
# window.host = "http://bagd.herokuapp.com"
auth_module = angular.module 'bag.authorization', []
if localStorage.user
# user_id = '55a84d00e4b06e29cb4eb960'
# user_token='my_token'
ref = JSON.parse localStorage.user
user_id = ref.id
user_token = ref.token
# get a reference to the logged-in user
socket = io "#{window.host}/#{user_id}", query: "token=#{user_token}"
# inject these details into the controller
do (auth_module) ->
auth_module
# give ourselves a status inndicaton
auth_module.provider 'auth', ->
getSuccess: -> true
$get: ->
success: true
user_id: localStorage.user.id
user_token: localStorage.user.token
# inject socket.io into angular
.factory 'socket', (socketFactory) -> socketFactory ioSocket: socket
# logged in user properties
# note: returns a promise
.factory 'user', (userFactory) -> userFactory user_id
else
# we aren't authorized...
# lets make sure we shout this as loud as possible
auth_module.provider 'auth', ->
getSuccess: -> false
$get: -> success: false
# onboarding factories
.factory 'socket', (socketFactory) ->
socketFactory ioSocket: io("#{window.host}/handshake")
.factory 'user', -> then: ->
# get rid of some of the angular crud
# this is needed when doing client <-> server stuff
# strip $hashkey
window.strip_$$ = (a) -> angular.fromJson angular.toJson(a)
angular.module 'bag.controllers', [
'btford.socket-io'
'ngSanitize'
# authorization stuff
'bag.authorization'
'bag.controllers.onboarding'
# settings
'bag.controllers.account'
'bag.controllers.stores_picker'
# local controllers in different files
'bag.controllers.tab_bag'
'bag.controllers.tab_recipe'
'bag.controllers.tab_picks'
# item info pages, both on bags view and recipes view
'bag.controllers.item_info'
# create new recipes and foodstuffs
'bag.controllers.new_foodstuff'
'bag.controllers.new_recipe'
# recipe card controller for recipe-card directive
'bag.controllers.recipe_card'
# login controller
'bag.controllers.login'
]
.controller 'RecipeListCtrl', ($scope, socket, $ionicSlideBoxDelegate) ->
# get all recipes
# this fires once at the load of the controller, but also repeadedly when
# any function wants th reload the whole view.
socket.emit 'list:index'
socket.on 'list:index:callback', (evt) ->
# console.log("list:index:callback", evt)
$scope.recipes = evt.data
# force the slide-box to update and make
# each "page" > 0px (stupid bugfix)
$ionicSlideBoxDelegate.update()
return
return
| 198498 | # set up the socket.io connection
# user_id = '<KEY> <PASSWORD>'
# user_token='<PASSWORD>'
# window.host = "http://192.168.1.13:8000"
# window.host = "http://127.0.0.1:8000"
# window.host = "http://192.168.1.15:8000"
window.host = "http://api.getbag.io"
# window.host = "http://bagd.herokuapp.com"
auth_module = angular.module 'bag.authorization', []
if localStorage.user
# user_id = '<KEY> <PASSWORD>'
# user_token='<PASSWORD>'
ref = JSON.parse localStorage.user
user_id = ref.id
user_token = ref.token
# get a reference to the logged-in user
socket = io "#{window.host}/#{user_id}", query: "token=#{user_token}"
# inject these details into the controller
do (auth_module) ->
auth_module
# give ourselves a status inndicaton
auth_module.provider 'auth', ->
getSuccess: -> true
$get: ->
success: true
user_id: localStorage.user.id
user_token: localStorage.user.token
# inject socket.io into angular
.factory 'socket', (socketFactory) -> socketFactory ioSocket: socket
# logged in user properties
# note: returns a promise
.factory 'user', (userFactory) -> userFactory user_id
else
# we aren't authorized...
# lets make sure we shout this as loud as possible
auth_module.provider 'auth', ->
getSuccess: -> false
$get: -> success: false
# onboarding factories
.factory 'socket', (socketFactory) ->
socketFactory ioSocket: io("#{window.host}/handshake")
.factory 'user', -> then: ->
# get rid of some of the angular crud
# this is needed when doing client <-> server stuff
# strip $hashkey
window.strip_$$ = (a) -> angular.fromJson angular.toJson(a)
angular.module 'bag.controllers', [
'btford.socket-io'
'ngSanitize'
# authorization stuff
'bag.authorization'
'bag.controllers.onboarding'
# settings
'bag.controllers.account'
'bag.controllers.stores_picker'
# local controllers in different files
'bag.controllers.tab_bag'
'bag.controllers.tab_recipe'
'bag.controllers.tab_picks'
# item info pages, both on bags view and recipes view
'bag.controllers.item_info'
# create new recipes and foodstuffs
'bag.controllers.new_foodstuff'
'bag.controllers.new_recipe'
# recipe card controller for recipe-card directive
'bag.controllers.recipe_card'
# login controller
'bag.controllers.login'
]
.controller 'RecipeListCtrl', ($scope, socket, $ionicSlideBoxDelegate) ->
# get all recipes
# this fires once at the load of the controller, but also repeadedly when
# any function wants th reload the whole view.
socket.emit 'list:index'
socket.on 'list:index:callback', (evt) ->
# console.log("list:index:callback", evt)
$scope.recipes = evt.data
# force the slide-box to update and make
# each "page" > 0px (stupid bugfix)
$ionicSlideBoxDelegate.update()
return
return
| true | # set up the socket.io connection
# user_id = 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
# user_token='PI:PASSWORD:<PASSWORD>END_PI'
# window.host = "http://192.168.1.13:8000"
# window.host = "http://127.0.0.1:8000"
# window.host = "http://192.168.1.15:8000"
window.host = "http://api.getbag.io"
# window.host = "http://bagd.herokuapp.com"
auth_module = angular.module 'bag.authorization', []
if localStorage.user
# user_id = 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI'
# user_token='PI:PASSWORD:<PASSWORD>END_PI'
ref = JSON.parse localStorage.user
user_id = ref.id
user_token = ref.token
# get a reference to the logged-in user
socket = io "#{window.host}/#{user_id}", query: "token=#{user_token}"
# inject these details into the controller
do (auth_module) ->
auth_module
# give ourselves a status inndicaton
auth_module.provider 'auth', ->
getSuccess: -> true
$get: ->
success: true
user_id: localStorage.user.id
user_token: localStorage.user.token
# inject socket.io into angular
.factory 'socket', (socketFactory) -> socketFactory ioSocket: socket
# logged in user properties
# note: returns a promise
.factory 'user', (userFactory) -> userFactory user_id
else
# we aren't authorized...
# lets make sure we shout this as loud as possible
auth_module.provider 'auth', ->
getSuccess: -> false
$get: -> success: false
# onboarding factories
.factory 'socket', (socketFactory) ->
socketFactory ioSocket: io("#{window.host}/handshake")
.factory 'user', -> then: ->
# get rid of some of the angular crud
# this is needed when doing client <-> server stuff
# strip $hashkey
window.strip_$$ = (a) -> angular.fromJson angular.toJson(a)
angular.module 'bag.controllers', [
'btford.socket-io'
'ngSanitize'
# authorization stuff
'bag.authorization'
'bag.controllers.onboarding'
# settings
'bag.controllers.account'
'bag.controllers.stores_picker'
# local controllers in different files
'bag.controllers.tab_bag'
'bag.controllers.tab_recipe'
'bag.controllers.tab_picks'
# item info pages, both on bags view and recipes view
'bag.controllers.item_info'
# create new recipes and foodstuffs
'bag.controllers.new_foodstuff'
'bag.controllers.new_recipe'
# recipe card controller for recipe-card directive
'bag.controllers.recipe_card'
# login controller
'bag.controllers.login'
]
.controller 'RecipeListCtrl', ($scope, socket, $ionicSlideBoxDelegate) ->
# get all recipes
# this fires once at the load of the controller, but also repeadedly when
# any function wants th reload the whole view.
socket.emit 'list:index'
socket.on 'list:index:callback', (evt) ->
# console.log("list:index:callback", evt)
$scope.recipes = evt.data
# force the slide-box to update and make
# each "page" > 0px (stupid bugfix)
$ionicSlideBoxDelegate.update()
return
return
|
[
{
"context": "minF.updatePassword = (password) ->\n username = UserF.user.username\n data =\n username: username\n passwor",
"end": 1315,
"score": 0.6975112557411194,
"start": 1296,
"tag": "USERNAME",
"value": "UserF.user.username"
},
{
"context": "e = UserF.user.user... | v1/coffee/admin/AdminF.coffee | lizechoo/Bromeliad-Database | 0 | app.factory 'AdminF', (ApiF, ngDialog, UserF, AvatarF, $q) ->
AdminF = {}
AdminF.usersList = []
AdminF.loadUsersList = ->
ApiF.get('users', 'all', null)
.then (results) ->
AdminF.usersList = results.users
promises = []
for user in AdminF.usersList
promise = AvatarF.getImageSrc user.avatar
promises.push promise
$q.all promises
.then (results) ->
for link, i in results
AdminF.usersList[i].avatar_link = link
AdminF.newUser = ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> null
AdminF.editUser = (user) ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> angular.copy user
AdminF.createUser = (user) ->
ApiF.post('users', 'create', null, user)
.then ->
AdminF.loadUsersList()
AdminF.updateUser = (user) ->
ApiF.post('users', 'edit', null, user)
.then ->
AdminF.loadUsersList()
AdminF.deleteUser = (username) ->
ApiF.post('users', 'delete', null, username: username)
.then (res) ->
AdminF.loadUsersList()
AdminF.updatePassword = (password) ->
username = UserF.user.username
data =
username: username
password: password
ApiF.post('users', 'edit', null, data)
return AdminF
| 43440 | app.factory 'AdminF', (ApiF, ngDialog, UserF, AvatarF, $q) ->
AdminF = {}
AdminF.usersList = []
AdminF.loadUsersList = ->
ApiF.get('users', 'all', null)
.then (results) ->
AdminF.usersList = results.users
promises = []
for user in AdminF.usersList
promise = AvatarF.getImageSrc user.avatar
promises.push promise
$q.all promises
.then (results) ->
for link, i in results
AdminF.usersList[i].avatar_link = link
AdminF.newUser = ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> null
AdminF.editUser = (user) ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> angular.copy user
AdminF.createUser = (user) ->
ApiF.post('users', 'create', null, user)
.then ->
AdminF.loadUsersList()
AdminF.updateUser = (user) ->
ApiF.post('users', 'edit', null, user)
.then ->
AdminF.loadUsersList()
AdminF.deleteUser = (username) ->
ApiF.post('users', 'delete', null, username: username)
.then (res) ->
AdminF.loadUsersList()
AdminF.updatePassword = (password) ->
username = UserF.user.username
data =
username: username
password: <PASSWORD>
ApiF.post('users', 'edit', null, data)
return AdminF
| true | app.factory 'AdminF', (ApiF, ngDialog, UserF, AvatarF, $q) ->
AdminF = {}
AdminF.usersList = []
AdminF.loadUsersList = ->
ApiF.get('users', 'all', null)
.then (results) ->
AdminF.usersList = results.users
promises = []
for user in AdminF.usersList
promise = AvatarF.getImageSrc user.avatar
promises.push promise
$q.all promises
.then (results) ->
for link, i in results
AdminF.usersList[i].avatar_link = link
AdminF.newUser = ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> null
AdminF.editUser = (user) ->
ngDialog.openConfirm
template: 'users/edit.html'
controller: 'UserEditC'
controllerAs: 'user'
resolve:
edit: -> angular.copy user
AdminF.createUser = (user) ->
ApiF.post('users', 'create', null, user)
.then ->
AdminF.loadUsersList()
AdminF.updateUser = (user) ->
ApiF.post('users', 'edit', null, user)
.then ->
AdminF.loadUsersList()
AdminF.deleteUser = (username) ->
ApiF.post('users', 'delete', null, username: username)
.then (res) ->
AdminF.loadUsersList()
AdminF.updatePassword = (password) ->
username = UserF.user.username
data =
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
ApiF.post('users', 'edit', null, data)
return AdminF
|
[
{
"context": " Meteor.isServer\n process.env.MAIL_URL = 'smtp://contato@grupoallconnect.com.br:Contato123@smtp.zoho.com:587'\n #process.env.MAIL",
"end": 82,
"score": 0.9441673159599304,
"start": 52,
"tag": "EMAIL",
"value": "contato@grupoallconnect.com.br"
},
{
"context": "MAIL_UR... | lib/_config/emails.coffee | thiago-zaidem/appVilaDosBichos | 0 | if Meteor.isServer
process.env.MAIL_URL = 'smtp://contato@grupoallconnect.com.br:Contato123@smtp.zoho.com:587'
#process.env.MAIL_URL = 'smtp://administrador@grupoallconnect.com.br:*ZOh@193482*@smtp.zoho.com:587'
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
options.companyTelephone = Config.legal.phone
options.companyEmail = Config.legal.email
options.from = Config.legal.email
options.showFooter = true
#options.logoUrl = Config.legal.logoUrl
PrettyEmail.options = options | 108795 | if Meteor.isServer
process.env.MAIL_URL = 'smtp://<EMAIL>:<EMAIL>:587'
#process.env.MAIL_URL = 'smtp://<EMAIL>:*<EMAIL>:587'
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
options.companyTelephone = Config.legal.phone
options.companyEmail = Config.legal.email
options.from = Config.legal.email
options.showFooter = true
#options.logoUrl = Config.legal.logoUrl
PrettyEmail.options = options | true | if Meteor.isServer
process.env.MAIL_URL = 'smtp://PI:EMAIL:<EMAIL>END_PI:PI:EMAIL:<EMAIL>END_PI:587'
#process.env.MAIL_URL = 'smtp://PI:EMAIL:<EMAIL>END_PI:*PI:EMAIL:<EMAIL>END_PI:587'
options =
siteName: Config.name
if Config.socialMedia
_.each Config.socialMedia, (v,k) ->
options[k] = v.url
if Config.legal
options.companyAddress = Config.legal.address
options.companyName = Config.legal.name
options.companyUrl = Config.legal.url
options.companyTelephone = Config.legal.phone
options.companyEmail = Config.legal.email
options.from = Config.legal.email
options.showFooter = true
#options.logoUrl = Config.legal.logoUrl
PrettyEmail.options = options |
[
{
"context": "': 'git'\n '#text': 'git://github.com/oozcitak/xmlbuilder-js.git'\n\n eq(\n xml(obj).end()\n",
"end": 235,
"score": 0.9988968968391418,
"start": 227,
"tag": "USERNAME",
"value": "oozcitak"
},
{
"context": " +\n '<repo type=\"git\">git://g... | test/basic/object.coffee | tomhughes/xmlbuilder-js | 0 | suite 'Creating XML:', ->
test 'From JS object (simple)', ->
obj =
root:
xmlbuilder:
'@for': 'node-js'
repo:
'@type': 'git'
'#text': 'git://github.com/oozcitak/xmlbuilder-js.git'
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'</root>'
)
test 'From JS object (functions)', ->
obj =
squares:
'#comment': 'f(x) = x^2'
'data': () ->
ret = for i in [1..5]
{ '@x': i, '@y': i * i }
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<squares>' +
'<!-- f(x) = x^2 -->' +
'<data x="1" y="1"/>' +
'<data x="2" y="4"/>' +
'<data x="3" y="9"/>' +
'<data x="4" y="16"/>' +
'<data x="5" y="25"/>' +
'</squares>'
)
test 'From JS object (decorators)', ->
obj =
ele: "simple element"
person:
name: "John"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
contact:
phone: [ "555-1234", "555-1235" ]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<?pi mypi?>' +
'<person age="35">' +
'<name>John</name>' +
'<!-- Good guy -->' +
'<![CDATA[well formed!]]>' +
'<unescaped>&<>&</unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<contact>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'</contact>' +
'<id>42</id>' +
'<details>classified</details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (ignore decorators)', ->
obj =
ele: "simple element"
person:
name: "John"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
"555-1234"
"555-1235"
]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true, ignoreDecorators: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<person>' +
'<name>John</name>' +
'<@age>35</@age>' +
'<?pi>mypi</?pi>' +
'<#comment>Good guy</#comment>' +
'<#cdata>well formed!</#cdata>' +
'<unescaped><#raw>&<>&</#raw></unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'<id>42</id>' +
'<details><#text>classified</#text></details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (deep nesting)', ->
obj =
one:
'@val': 1
two:
'@val': 2
three:
'@val': 3
four:
'@val': 4
five:
'@val': 5
six:
'@val': 6
ends: 'here'
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one val="1">' +
'<two val="2">' +
'<three val="3">' +
'<four val="4">' +
'<five val="5">' +
'<six val="6">' +
'<ends>here</ends>' +
'</six>' +
'</five>' +
'</four>' +
'</three>' +
'</two>' +
'</one>' +
'</root>'
)
test 'From JS object (root level)', ->
obj =
myroot:
ele: "simple element"
person:
name: "John"
'@age': 35
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
{ '#text': "555-1234", '@type': 'home' }
{ '#text': "555-1235", '@type': 'mobile' }
]
id: () -> return 42
eq(
xml(obj, { headless: true }).ele('added').end()
'<myroot>' +
'<ele>simple element</ele>' +
'<person age="35">' +
'<name>John</name>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone type="home">555-1234</phone>' +
'<phone type="mobile">555-1235</phone>' +
'<id>42</id>' +
'</person>' +
'<added/>' +
'</myroot>'
)
test 'From JS object (simple array)', ->
obj = [
"one"
"two"
() -> return "three"
]
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one/>' +
'<two/>' +
'<three/>' +
'</root>'
)
test 'From JS object (empty array)', ->
eq(
xml({ root: [] }).end()
'<?xml version="1.0"?><root/>'
)
test 'From JS object (empty object)', ->
eq(
xml({ root: {} }).end()
'<?xml version="1.0"?><root/>'
)
| 221726 | suite 'Creating XML:', ->
test 'From JS object (simple)', ->
obj =
root:
xmlbuilder:
'@for': 'node-js'
repo:
'@type': 'git'
'#text': 'git://github.com/oozcitak/xmlbuilder-js.git'
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'</root>'
)
test 'From JS object (functions)', ->
obj =
squares:
'#comment': 'f(x) = x^2'
'data': () ->
ret = for i in [1..5]
{ '@x': i, '@y': i * i }
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<squares>' +
'<!-- f(x) = x^2 -->' +
'<data x="1" y="1"/>' +
'<data x="2" y="4"/>' +
'<data x="3" y="9"/>' +
'<data x="4" y="16"/>' +
'<data x="5" y="25"/>' +
'</squares>'
)
test 'From JS object (decorators)', ->
obj =
ele: "simple element"
person:
name: "<NAME>"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
contact:
phone: [ "555-1234", "555-1235" ]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<?pi mypi?>' +
'<person age="35">' +
'<name><NAME></name>' +
'<!-- Good guy -->' +
'<![CDATA[well formed!]]>' +
'<unescaped>&<>&</unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<contact>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'</contact>' +
'<id>42</id>' +
'<details>classified</details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (ignore decorators)', ->
obj =
ele: "simple element"
person:
name: "<NAME>"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
"555-1234"
"555-1235"
]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true, ignoreDecorators: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<person>' +
'<name><NAME></name>' +
'<@age>35</@age>' +
'<?pi>mypi</?pi>' +
'<#comment>Good guy</#comment>' +
'<#cdata>well formed!</#cdata>' +
'<unescaped><#raw>&<>&</#raw></unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'<id>42</id>' +
'<details><#text>classified</#text></details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (deep nesting)', ->
obj =
one:
'@val': 1
two:
'@val': 2
three:
'@val': 3
four:
'@val': 4
five:
'@val': 5
six:
'@val': 6
ends: 'here'
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one val="1">' +
'<two val="2">' +
'<three val="3">' +
'<four val="4">' +
'<five val="5">' +
'<six val="6">' +
'<ends>here</ends>' +
'</six>' +
'</five>' +
'</four>' +
'</three>' +
'</two>' +
'</one>' +
'</root>'
)
test 'From JS object (root level)', ->
obj =
myroot:
ele: "simple element"
person:
name: "<NAME>"
'@age': 35
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
{ '#text': "555-1234", '@type': 'home' }
{ '#text': "555-1235", '@type': 'mobile' }
]
id: () -> return 42
eq(
xml(obj, { headless: true }).ele('added').end()
'<myroot>' +
'<ele>simple element</ele>' +
'<person age="35">' +
'<name><NAME></name>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone type="home">555-1234</phone>' +
'<phone type="mobile">555-1235</phone>' +
'<id>42</id>' +
'</person>' +
'<added/>' +
'</myroot>'
)
test 'From JS object (simple array)', ->
obj = [
"one"
"two"
() -> return "three"
]
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one/>' +
'<two/>' +
'<three/>' +
'</root>'
)
test 'From JS object (empty array)', ->
eq(
xml({ root: [] }).end()
'<?xml version="1.0"?><root/>'
)
test 'From JS object (empty object)', ->
eq(
xml({ root: {} }).end()
'<?xml version="1.0"?><root/>'
)
| true | suite 'Creating XML:', ->
test 'From JS object (simple)', ->
obj =
root:
xmlbuilder:
'@for': 'node-js'
repo:
'@type': 'git'
'#text': 'git://github.com/oozcitak/xmlbuilder-js.git'
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<root>' +
'<xmlbuilder for="node-js">' +
'<repo type="git">git://github.com/oozcitak/xmlbuilder-js.git</repo>' +
'</xmlbuilder>' +
'</root>'
)
test 'From JS object (functions)', ->
obj =
squares:
'#comment': 'f(x) = x^2'
'data': () ->
ret = for i in [1..5]
{ '@x': i, '@y': i * i }
eq(
xml(obj).end()
'<?xml version="1.0"?>' +
'<squares>' +
'<!-- f(x) = x^2 -->' +
'<data x="1" y="1"/>' +
'<data x="2" y="4"/>' +
'<data x="3" y="9"/>' +
'<data x="4" y="16"/>' +
'<data x="5" y="25"/>' +
'</squares>'
)
test 'From JS object (decorators)', ->
obj =
ele: "simple element"
person:
name: "PI:NAME:<NAME>END_PI"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
contact:
phone: [ "555-1234", "555-1235" ]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<?pi mypi?>' +
'<person age="35">' +
'<name>PI:NAME:<NAME>END_PI</name>' +
'<!-- Good guy -->' +
'<![CDATA[well formed!]]>' +
'<unescaped>&<>&</unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<contact>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'</contact>' +
'<id>42</id>' +
'<details>classified</details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (ignore decorators)', ->
obj =
ele: "simple element"
person:
name: "PI:NAME:<NAME>END_PI"
'@age': 35
'?pi': 'mypi'
'#comment': 'Good guy'
'#cdata': 'well formed!'
unescaped:
'#raw': '&<>&'
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
"555-1234"
"555-1235"
]
id: () -> return 42
details:
'#text': 'classified'
eq(
xml('root', { headless: true, ignoreDecorators: true })
.ele(obj).up()
.ele('added')
.end()
'<root>' +
'<ele>simple element</ele>' +
'<person>' +
'<name>PI:NAME:<NAME>END_PI</name>' +
'<@age>35</@age>' +
'<?pi>mypi</?pi>' +
'<#comment>Good guy</#comment>' +
'<#cdata>well formed!</#cdata>' +
'<unescaped><#raw>&<>&</#raw></unescaped>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone>555-1234</phone>' +
'<phone>555-1235</phone>' +
'<id>42</id>' +
'<details><#text>classified</#text></details>' +
'</person>' +
'<added/>' +
'</root>'
)
test 'From JS object (deep nesting)', ->
obj =
one:
'@val': 1
two:
'@val': 2
three:
'@val': 3
four:
'@val': 4
five:
'@val': 5
six:
'@val': 6
ends: 'here'
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one val="1">' +
'<two val="2">' +
'<three val="3">' +
'<four val="4">' +
'<five val="5">' +
'<six val="6">' +
'<ends>here</ends>' +
'</six>' +
'</five>' +
'</four>' +
'</three>' +
'</two>' +
'</one>' +
'</root>'
)
test 'From JS object (root level)', ->
obj =
myroot:
ele: "simple element"
person:
name: "PI:NAME:<NAME>END_PI"
'@age': 35
address:
city: "Istanbul"
street: "End of long and winding road"
phone: [
{ '#text': "555-1234", '@type': 'home' }
{ '#text': "555-1235", '@type': 'mobile' }
]
id: () -> return 42
eq(
xml(obj, { headless: true }).ele('added').end()
'<myroot>' +
'<ele>simple element</ele>' +
'<person age="35">' +
'<name>PI:NAME:<NAME>END_PI</name>' +
'<address>' +
'<city>Istanbul</city>' +
'<street>End of long and winding road</street>' +
'</address>' +
'<phone type="home">555-1234</phone>' +
'<phone type="mobile">555-1235</phone>' +
'<id>42</id>' +
'</person>' +
'<added/>' +
'</myroot>'
)
test 'From JS object (simple array)', ->
obj = [
"one"
"two"
() -> return "three"
]
eq(
xml('root', { headless: true }).ele(obj).end()
'<root>' +
'<one/>' +
'<two/>' +
'<three/>' +
'</root>'
)
test 'From JS object (empty array)', ->
eq(
xml({ root: [] }).end()
'<?xml version="1.0"?><root/>'
)
test 'From JS object (empty object)', ->
eq(
xml({ root: {} }).end()
'<?xml version="1.0"?><root/>'
)
|
[
{
"context": "nux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <password>\"\n robot.respond /((create|n",
"end": 1136,
"score": 0.9842272400856018,
"start": 1128,
"tag": "USERNAME",
"value": "username"
},
{
"context": ",AIX,No_OS,SUN-VCS] username <username> pass... | example/src/host.coffee | victorock/hubot-coprhd | 0 | module.exports = (robot) ->
initiator = (options) ->
return robot.cli( "host \
-tenant #{tenant} \
-project #{project} \
-varray #{varray} \
#{options}" )
robot.commands.push "hubot coprhd find host <name>"
robot.respond /((find|search) host) (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
#msg.reply robot.host( "find" )
robot.commands.push "hubot coprhd list host"
robot.respond /((list|ls) host)$/i, (msg) ->
msg.reply msg.random friendly "...listing hosts on Tenant: #{tenant}, Project: #{project}, Array: #{varray}..."
msg.reply robot.host( "list" )
robot.commands.push "hubot coprhd show host <name>"
robot.respond /((show|sh) host) (.*)$/i, (msg) ->
host = msg.match[2].trim()
msg.reply msg.random friendly "...showing #{name}..."
msg.reply robot.host( "show \
-name #{name}" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <password>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <password> vcenter <name> datacenter <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <password> vcenter <name> datacenter <name> cluster <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
cluster = msg.match[8].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-cluster #{cluster} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <password> wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-wwn #{wwn} \
-pwwn #{pwwn} \
-type fc \
-sync" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <password> iqn <iqn>"
robot.respond /((create|new) host) (.*) type (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-pwwn #{pwwn} \
-type iscsi \
-sync" )
robot.commands.push "hubot coprhd update host <name> add wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((update|change) host) (.*) add wwpn (.*) and wwnn (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
| 134016 | module.exports = (robot) ->
initiator = (options) ->
return robot.cli( "host \
-tenant #{tenant} \
-project #{project} \
-varray #{varray} \
#{options}" )
robot.commands.push "hubot coprhd find host <name>"
robot.respond /((find|search) host) (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
#msg.reply robot.host( "find" )
robot.commands.push "hubot coprhd list host"
robot.respond /((list|ls) host)$/i, (msg) ->
msg.reply msg.random friendly "...listing hosts on Tenant: #{tenant}, Project: #{project}, Array: #{varray}..."
msg.reply robot.host( "list" )
robot.commands.push "hubot coprhd show host <name>"
robot.respond /((show|sh) host) (.*)$/i, (msg) ->
host = msg.match[2].trim()
msg.reply msg.random friendly "...showing #{name}..."
msg.reply robot.host( "show \
-name #{name}" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <<PASSWORD>>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <<PASSWORD>> vcenter <name> datacenter <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <<PASSWORD>> vcenter <name> datacenter <name> cluster <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
cluster = msg.match[8].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-cluster #{cluster} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <<PASSWORD>> wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-wwn #{wwn} \
-pwwn #{pwwn} \
-type fc \
-sync" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <<PASSWORD>> iqn <iqn>"
robot.respond /((create|new) host) (.*) type (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-pwwn #{pwwn} \
-type iscsi \
-sync" )
robot.commands.push "hubot coprhd update host <name> add wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((update|change) host) (.*) add wwpn (.*) and wwnn (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
| true | module.exports = (robot) ->
initiator = (options) ->
return robot.cli( "host \
-tenant #{tenant} \
-project #{project} \
-varray #{varray} \
#{options}" )
robot.commands.push "hubot coprhd find host <name>"
robot.respond /((find|search) host) (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
#msg.reply robot.host( "find" )
robot.commands.push "hubot coprhd list host"
robot.respond /((list|ls) host)$/i, (msg) ->
msg.reply msg.random friendly "...listing hosts on Tenant: #{tenant}, Project: #{project}, Array: #{varray}..."
msg.reply robot.host( "list" )
robot.commands.push "hubot coprhd show host <name>"
robot.respond /((show|sh) host) (.*)$/i, (msg) ->
host = msg.match[2].trim()
msg.reply msg.random friendly "...showing #{name}..."
msg.reply robot.host( "show \
-name #{name}" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <PI:PASSWORD:<PASSWORD>END_PI>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <PI:PASSWORD:<PASSWORD>END_PI> vcenter <name> datacenter <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Esx] username <username> password <PI:PASSWORD:<PASSWORD>END_PI> vcenter <name> datacenter <name> cluster <name>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
vcenter = msg.match[6].trim()
datacenter = msg.match[7].trim()
cluster = msg.match[8].trim()
msg.reply msg.random friendly "...creating host and discoverying initiators..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-vcenter #{vcenter} \
-datacenter #{datacenter} \
-cluster #{cluster} \
-discover true" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <PI:PASSWORD:<PASSWORD>END_PI> wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((create|new) host) (.*) os (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-wwn #{wwn} \
-pwwn #{pwwn} \
-type fc \
-sync" )
robot.commands.push "hubot coprhd create host <name> os [Windows,HPUX,Linux,Esx,Other,AIXVIO,AIX,No_OS,SUN-VCS] username <username> password <PI:PASSWORD:<PASSWORD>END_PI> iqn <iqn>"
robot.respond /((create|new) host) (.*) type (.*) username (.*) password (.*) wwpn (.*) and wwnn (.*)$/i, (msg) ->
name = msg.match[2].trim()
type = msg.match[3].trim()
username = msg.match[4].trim()
password = msg.match[5].trim()
wwpn = msg.match[6].trim()
wwn = msg.match[7].trim()
msg.reply msg.random friendly "...creating host..."
msg.reply robot.host( "create \
-hostname #{name} \
-hostlabel #{name} \
-un #{username} \
-type #{type} \
-hostssl true \
-discover false" )
msg.reply msg.random friendly "...creating and attaching initiators..."
msg.reply robot.initiator( "create \
-hostlabel #{name} \
-pwwn #{pwwn} \
-type iscsi \
-sync" )
robot.commands.push "hubot coprhd update host <name> add wwpn <wwpn> and wwnn <wwnn>"
robot.respond /((update|change) host) (.*) add wwpn (.*) and wwnn (.*)$/i, (msg) ->
msg.reply msg.random friendly "...action not implemented yet..."
|
[
{
"context": ")\n return\n\ntest \"email is ok\", (t) ->\n err = v(\"name@domain.com\")\n t.type err, \"null\"\n t.end()\n return\n\n",
"end": 441,
"score": 0.9946956634521484,
"start": 426,
"tag": "EMAIL",
"value": "name@domain.com"
}
] | deps/npm/node_modules/npm-user-validate/test/email.test.coffee | lxe/io.coffee | 0 | test = require("tap").test
v = require("../npm-user-validate.js").email
test "email misses an @", (t) ->
err = v("namedomain")
t.type err, "object"
t.end()
return
test "email misses a dot", (t) ->
err = v("name@domain")
t.type err, "object"
t.end()
return
test "email misses a string before the @", (t) ->
err = v("@domain")
t.type err, "object"
t.end()
return
test "email is ok", (t) ->
err = v("name@domain.com")
t.type err, "null"
t.end()
return
| 107006 | test = require("tap").test
v = require("../npm-user-validate.js").email
test "email misses an @", (t) ->
err = v("namedomain")
t.type err, "object"
t.end()
return
test "email misses a dot", (t) ->
err = v("name@domain")
t.type err, "object"
t.end()
return
test "email misses a string before the @", (t) ->
err = v("@domain")
t.type err, "object"
t.end()
return
test "email is ok", (t) ->
err = v("<EMAIL>")
t.type err, "null"
t.end()
return
| true | test = require("tap").test
v = require("../npm-user-validate.js").email
test "email misses an @", (t) ->
err = v("namedomain")
t.type err, "object"
t.end()
return
test "email misses a dot", (t) ->
err = v("name@domain")
t.type err, "object"
t.end()
return
test "email misses a string before the @", (t) ->
err = v("@domain")
t.type err, "object"
t.end()
return
test "email is ok", (t) ->
err = v("PI:EMAIL:<EMAIL>END_PI")
t.type err, "null"
t.end()
return
|
[
{
"context": "on:\n opbs: opbs\n amr: ['pwd']\n res =\n set: sinon.spy()\n ",
"end": 3101,
"score": 0.9976931214332581,
"start": 3098,
"tag": "PASSWORD",
"value": "pwd"
}
] | test/unit/oidc/signout.coffee | LorianeE/connect | 331 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
settings = require '../../../boot/settings'
authenticator = require '../../../lib/authenticator'
Client = require '../../../models/Client'
IDToken = require '../../../models/IDToken'
InvalidTokenError = require '../../../errors/InvalidTokenError'
{signout} = require('../../../oidc')
describe 'Signout', ->
{opbs,req,res,next} = {}
describe 'with uri and hint,', ->
describe 'valid token', ->
validIDToken = new IDToken({
iss: 'https://anvil.io',
sub: 'user-uuid',
aud: 'client-uuid',
}).encode(settings.keys.sig.prv)
describe 'and client get error', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith(1, new Error())
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy (error) ->
err = error
done()
signout(req, res, next)
after ->
Client.get.restore()
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
describe 'and unknown client', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith 1, null, null
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
Client.get.restore()
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should not continue', ->
next.should.not.have.been.called
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should respond', ->
res.sendStatus.should.have.been.called
describe 'and unknown uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: []
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://wrong.com'
id_token_hint: validIDToken
session:
opbs: opbs
amr: ['pwd']
res =
set: sinon.spy()
sendStatus: sinon.spy()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
describe 'and valid uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: ['http://example.com']
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
state: 'encodedState'
session:
opbs: opbs
amr: ['otp']
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not respond 204', ->
res.send.should.not.have.been.calledWith 204
it 'should redirect with state param', ->
res.redirect.should.have.been.calledWith 303, req.query.post_logout_redirect_uri + '?state='+req.query.state
describe 'with invalid token', ->
invalidIDToken = 'WRONG'
before (done) ->
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: invalidIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy (err) ->
done()
signout(req, res, next)
it 'should not update OP browser state', ->
req.session.opbs.should.equal opbs
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
it 'should respond', ->
res.sendStatus.should.not.have.been.called
describe 'with uri only', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'https://example.com'
session:
opbs: opbs
amr: ['sms', 'otp']
res =
redirect: sinon.spy()
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not redirect', ->
res.redirect.should.not.have.been.called
describe 'without uri', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query: {}
session:
opbs: opbs
amr: ['pwd']
res =
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
it 'should respond with Cache-Control header', ->
res.set.should.have.been.calledWith sinon.match({
'Cache-Control': 'no-store'
})
it 'should respond with Pragma header', ->
res.set.should.have.been.calledWith sinon.match({
'Pragma': 'no-cache'
})
| 81519 | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
settings = require '../../../boot/settings'
authenticator = require '../../../lib/authenticator'
Client = require '../../../models/Client'
IDToken = require '../../../models/IDToken'
InvalidTokenError = require '../../../errors/InvalidTokenError'
{signout} = require('../../../oidc')
describe 'Signout', ->
{opbs,req,res,next} = {}
describe 'with uri and hint,', ->
describe 'valid token', ->
validIDToken = new IDToken({
iss: 'https://anvil.io',
sub: 'user-uuid',
aud: 'client-uuid',
}).encode(settings.keys.sig.prv)
describe 'and client get error', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith(1, new Error())
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy (error) ->
err = error
done()
signout(req, res, next)
after ->
Client.get.restore()
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
describe 'and unknown client', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith 1, null, null
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
Client.get.restore()
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should not continue', ->
next.should.not.have.been.called
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should respond', ->
res.sendStatus.should.have.been.called
describe 'and unknown uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: []
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://wrong.com'
id_token_hint: validIDToken
session:
opbs: opbs
amr: ['<PASSWORD>']
res =
set: sinon.spy()
sendStatus: sinon.spy()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
describe 'and valid uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: ['http://example.com']
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
state: 'encodedState'
session:
opbs: opbs
amr: ['otp']
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not respond 204', ->
res.send.should.not.have.been.calledWith 204
it 'should redirect with state param', ->
res.redirect.should.have.been.calledWith 303, req.query.post_logout_redirect_uri + '?state='+req.query.state
describe 'with invalid token', ->
invalidIDToken = 'WRONG'
before (done) ->
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: invalidIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy (err) ->
done()
signout(req, res, next)
it 'should not update OP browser state', ->
req.session.opbs.should.equal opbs
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
it 'should respond', ->
res.sendStatus.should.not.have.been.called
describe 'with uri only', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'https://example.com'
session:
opbs: opbs
amr: ['sms', 'otp']
res =
redirect: sinon.spy()
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not redirect', ->
res.redirect.should.not.have.been.called
describe 'without uri', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query: {}
session:
opbs: opbs
amr: ['pwd']
res =
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
it 'should respond with Cache-Control header', ->
res.set.should.have.been.calledWith sinon.match({
'Cache-Control': 'no-store'
})
it 'should respond with Pragma header', ->
res.set.should.have.been.calledWith sinon.match({
'Pragma': 'no-cache'
})
| true | chai = require 'chai'
sinon = require 'sinon'
sinonChai = require 'sinon-chai'
expect = chai.expect
chai.use sinonChai
chai.should()
settings = require '../../../boot/settings'
authenticator = require '../../../lib/authenticator'
Client = require '../../../models/Client'
IDToken = require '../../../models/IDToken'
InvalidTokenError = require '../../../errors/InvalidTokenError'
{signout} = require('../../../oidc')
describe 'Signout', ->
{opbs,req,res,next} = {}
describe 'with uri and hint,', ->
describe 'valid token', ->
validIDToken = new IDToken({
iss: 'https://anvil.io',
sub: 'user-uuid',
aud: 'client-uuid',
}).encode(settings.keys.sig.prv)
describe 'and client get error', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith(1, new Error())
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy (error) ->
err = error
done()
signout(req, res, next)
after ->
Client.get.restore()
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
describe 'and unknown client', ->
before (done) ->
sinon.stub(Client, 'get').callsArgWith 1, null, null
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
Client.get.restore()
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should not continue', ->
next.should.not.have.been.called
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should respond', ->
res.sendStatus.should.have.been.called
describe 'and unknown uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: []
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://wrong.com'
id_token_hint: validIDToken
session:
opbs: opbs
amr: ['PI:PASSWORD:<PASSWORD>END_PI']
res =
set: sinon.spy()
sendStatus: sinon.spy()
redirect: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
describe 'and valid uri', ->
before ->
sinon.spy authenticator, 'logout'
client = new Client
post_logout_redirect_uris: ['http://example.com']
sinon.stub(Client, 'get').callsArgWith(1, null, client)
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: validIDToken
state: 'encodedState'
session:
opbs: opbs
amr: ['otp']
res =
set: sinon.spy()
send: sinon.spy()
redirect: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
Client.get.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not respond 204', ->
res.send.should.not.have.been.calledWith 204
it 'should redirect with state param', ->
res.redirect.should.have.been.calledWith 303, req.query.post_logout_redirect_uri + '?state='+req.query.state
describe 'with invalid token', ->
invalidIDToken = 'WRONG'
before (done) ->
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'http://example.com'
id_token_hint: invalidIDToken
session:
opbs: opbs
res =
set: sinon.spy()
sendStatus: sinon.spy (status) ->
done()
redirect: sinon.spy()
next = sinon.spy (err) ->
done()
signout(req, res, next)
it 'should not update OP browser state', ->
req.session.opbs.should.equal opbs
it 'should not redirect', ->
res.redirect.should.not.have.been.called
it 'should provide an error', ->
# Next two lines are the proposed replacement test
errArg = next.firstCall.args[0]
expect(errArg).to.be.instanceof(Error)
# Next one line was the original test.
# next.should.have.been.calledWith new Error()
it 'should respond', ->
res.sendStatus.should.not.have.been.called
describe 'with uri only', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query:
post_logout_redirect_uri: 'https://example.com'
session:
opbs: opbs
amr: ['sms', 'otp']
res =
redirect: sinon.spy()
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should not redirect', ->
res.redirect.should.not.have.been.called
describe 'without uri', ->
before ->
sinon.spy authenticator, 'logout'
opbs = 'b3f0r3'
req =
query: {}
session:
opbs: opbs
amr: ['pwd']
res =
set: sinon.spy()
sendStatus: sinon.spy()
next = sinon.spy()
signout(req, res, next)
after ->
authenticator.logout.restore()
it 'should logout', ->
authenticator.logout.should.have.been.called
it 'should update OP browser state', ->
req.session.opbs.should.not.equal opbs
it 'should delete amr from session', ->
expect(req.session.amr).to.be.undefined
it 'should respond 204', ->
res.sendStatus.should.have.been.calledWith 204
it 'should respond with Cache-Control header', ->
res.set.should.have.been.calledWith sinon.match({
'Cache-Control': 'no-store'
})
it 'should respond with Pragma header', ->
res.set.should.have.been.calledWith sinon.match({
'Pragma': 'no-cache'
})
|
[
{
"context": "ce text with phonetic spelling\n\nWritten in 2013 by Karl Naylor <kpn103@yahoo.com>\n\nTo the extent possible under ",
"end": 104,
"score": 0.999885618686676,
"start": 93,
"tag": "NAME",
"value": "Karl Naylor"
},
{
"context": "honetic spelling\n\nWritten in 2013 by Karl... | src/content/coffee/phonetify.coffee | karlorg/phonetify | 1 | ###
phonetify - Firefox extension to replace text with phonetic spelling
Written in 2013 by Karl Naylor <kpn103@yahoo.com>
To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the
public domain worldwide. This software is distributed without any
warranty.
You should have received a copy of the CC0 Public Domain Dedication
along with this software. If not, see
<http://creativecommons.org/publicdomain/zero/1.0/>.
###
define [
'handywriteOnCanvas/handywriteOnCanvas',
'utils'], (handywriteOnCanvas, utils) ->
'use strict'
arpabetRawFileUri = 'chrome://phonetify/content/pronunciations.txt'
# the arpabet dictionary is loaded asynchronously since it could
# take a while, so we initialise it empty and use a flag to signal
# when it's ready.
arpabetDictionary = {}
arpabetDictReady = false
init = ->
button = window.document.getElementById 'phonetify-button'
button?.addEventListener 'command', onToolbarButton, false
window.setTimeout loadDictionary, 0
return true
onToolbarButton = ->
if arpabetDictReady
phonetifyDocument gBrowser.selectedBrowser.contentDocument.documentElement
return true
else
# try again in half a second
window.setTimeout onToolbarButton, 500
return false
loadDictionary = ->
raw = utils.readFileFromUri arpabetRawFileUri
lineRe = /// ^
([\w\']+) # term
\s+
(.*) # definition
$ ///
for line in raw.match /^.*$/gm
lineMatch = line.match lineRe
continue unless lineMatch
[term, definition] = lineMatch[1..]
arpabetDictionary[term] = definition.match /\b\w\w?\d?\b/g
arpabetDictReady = true
return true
handywriteFromArpabet = {
# monophthongs
AO0: ['aw'], AO1: ['aw'], AO2: ['aw']
AA0: ['a'], AA1: ['a'], AA2: ['a']
IY0: ['i'], IY1: ['i'], IY2: ['i']
UW0: ['u'], UW1: ['u'], UW2: ['u']
EH0: ['eh'], EH1: ['eh'], EH2: ['eh']
IH0: ['ih'], IH1: ['ih'], IH2: ['ih']
UH0: ['uh'], UH1: ['c'], UH2: ['c']
AH0: ['uh'], AH1: ['a'], AH2: ['a']
AX0: ['uh']
AE0: ['ae'], AE1: ['ae'], AE2: ['ae']
# diphthongs
EY0: ['ey'], EY1: ['ey'], EY2: ['ey'], AY0: ['ay'], AY1: ['ay'], AY2: ['ay']
OW0: ['o'], OW1: ['o'], OW2: ['o']
AW0: ['a', 'u'], AW1: ['a', 'u'], AW2: ['a', 'u']
OY0: ['o', 'ih'], OY1: ['o', 'ih'], OY2: ['o', 'ih']
# r coloured vowels
ER: ['r'], ER0: ['r'], ER1: ['r'], ER2: ['r']
# stops
P: ['p'], B: ['b'], T: ['t'], D: ['d'], K: ['k'], G: ['g']
# affricates
CH: ['ch'], JH: ['j']
# fricatives
F: ['f'], V: ['v'], TH: ['Th'], DH: ['th'],
S: ['s'], Z: ['z'], SH: ['sh'], ZH: ['zh'], HH: ['h']
# nasals
M: ['m'], EM: ['m'], N: ['n'], EN: ['n'], NG: ['ng'], ENG: ['ng']
# liquids
L: ['l'], EL: ['l'], R: ['r'], DX: ['t'], NX: ['n', 't']
# semivowels
Y: ['y'], W: ['w']
}
phonemesFromWord = (word) ->
upcaseWord = word.toUpperCase()
return null unless upcaseWord of arpabetDictionary
arpabetSpelling = arpabetDictionary[upcaseWord]
result = []
for arpaPhoneme in arpabetSpelling
continue unless arpaPhoneme of handywriteFromArpabet
result = result.concat handywriteFromArpabet[arpaPhoneme]
return result
# tags that we can recurse into and replace text with text
allowedTags = [
'a', 'address', 'article', 'aside', 'b', 'big', 'blockquote', 'body'
'button', 'caption', 'center', 'cite', 'command', 'datagrid', 'datalist'
'dd', 'del', 'dialog', 'div', 'dl', 'dt', 'em', 'fieldset', 'figure'
'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
'head', 'header', 'html', 'i', 'iframe', 'input', 'ins', 'kbd', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'optgroup', 'option', 'output', 'p', 'q', 's', 'section', 'select'
'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody'
'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul'
]
# tags that we can recurse into and replace text with arbitrary html
embedFriendlyTags = [
'a', 'article', 'aside', 'b', 'big', 'blockquote', 'body', 'button'
'center', 'cite', 'command', 'dd', 'del', 'dialog', 'div', 'dl', 'dt'
'em', 'fieldset', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2'
'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i', 'iframe', 'ins', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'p', 'q', 's', 'section', 'small', 'span', 'strike', 'strong', 'table'
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul'
]
phonetifyDocument = (document) ->
# as we traverse the DOM we'll build a list of replacements to perform
# (we can't replace while looping without messing up the loop logic).
# A replacement has the form:
#
# { old: <node to replace>,
# new: <array of nodes to insert> }
domReplacements = []
renderer = new handywriteOnCanvas.DocumentRenderer document.ownerDocument
phonetifyTextNode = (node, canEmbedHtml) ->
if canEmbedHtml
newContent = []
# capture any space before the first word as a text node
if match = /^([^\w]+)/.exec node.textContent
space = match[1]
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
# then capture each word and its succeeding whitespace for the
# remainder of the input node
wordSpaceRe = /([\w\'\u2019\u02BC]+)([^\w\']*)/g
while match = wordSpaceRe.exec node.textContent
[word, space] = match[1..2]
# replace non-ASCII apostrophes with ASCII
word = word.replace /[\u2019\u02BC]/g, "'"
phonemes = phonemesFromWord word
if phonemes
canvas = renderer.createCanvas(
phonemes, "#{word} (#{arpabetDictionary[word.toUpperCase()].join '-'})")
canvas.setAttribute 'style', 'vertical-align: middle'
newContent.push canvas
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
else
newContent.push window.document.createTextNode word + space
domReplacements.push(
old: node
new: newContent)
else
node.textContent = node.textContent.replace(/[\w\']+/g, phonetifyWord)
return true
phonetifyNodeRecursive = (node, canEmbedHtml) ->
switch node.nodeType
when Node.TEXT_NODE then phonetifyTextNode(node, canEmbedHtml)
when Node.ELEMENT_NODE, Node.DOCUMENT_NODE
name = node.nodeName.toLowerCase()
if name in allowedTags
canEmbedNext = canEmbedHtml and (name in embedFriendlyTags)
for child in node.childNodes
phonetifyNodeRecursive(child, canEmbedNext)
return true
phonetifyNodeRecursive(document, true)
for replacement in domReplacements
oldNode = replacement.old
parent = oldNode.parentNode
for newNode in replacement.new
parent.insertBefore(newNode, oldNode)
parent.removeChild(oldNode)
return true
phonetifyWord = (word) ->
phonemes = phonemesFromWord word
return if phonemes then phonemes.join('') else word
init()
return
| 12075 | ###
phonetify - Firefox extension to replace text with phonetic spelling
Written in 2013 by <NAME> <<EMAIL>>
To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the
public domain worldwide. This software is distributed without any
warranty.
You should have received a copy of the CC0 Public Domain Dedication
along with this software. If not, see
<http://creativecommons.org/publicdomain/zero/1.0/>.
###
define [
'handywriteOnCanvas/handywriteOnCanvas',
'utils'], (handywriteOnCanvas, utils) ->
'use strict'
arpabetRawFileUri = 'chrome://phonetify/content/pronunciations.txt'
# the arpabet dictionary is loaded asynchronously since it could
# take a while, so we initialise it empty and use a flag to signal
# when it's ready.
arpabetDictionary = {}
arpabetDictReady = false
init = ->
button = window.document.getElementById 'phonetify-button'
button?.addEventListener 'command', onToolbarButton, false
window.setTimeout loadDictionary, 0
return true
onToolbarButton = ->
if arpabetDictReady
phonetifyDocument gBrowser.selectedBrowser.contentDocument.documentElement
return true
else
# try again in half a second
window.setTimeout onToolbarButton, 500
return false
loadDictionary = ->
raw = utils.readFileFromUri arpabetRawFileUri
lineRe = /// ^
([\w\']+) # term
\s+
(.*) # definition
$ ///
for line in raw.match /^.*$/gm
lineMatch = line.match lineRe
continue unless lineMatch
[term, definition] = lineMatch[1..]
arpabetDictionary[term] = definition.match /\b\w\w?\d?\b/g
arpabetDictReady = true
return true
handywriteFromArpabet = {
# monophthongs
AO0: ['aw'], AO1: ['aw'], AO2: ['aw']
AA0: ['a'], AA1: ['a'], AA2: ['a']
IY0: ['i'], IY1: ['i'], IY2: ['i']
UW0: ['u'], UW1: ['u'], UW2: ['u']
EH0: ['eh'], EH1: ['eh'], EH2: ['eh']
IH0: ['ih'], IH1: ['ih'], IH2: ['ih']
UH0: ['uh'], UH1: ['c'], UH2: ['c']
AH0: ['uh'], AH1: ['a'], AH2: ['a']
AX0: ['uh']
AE0: ['ae'], AE1: ['ae'], AE2: ['ae']
# diphthongs
EY0: ['ey'], EY1: ['ey'], EY2: ['ey'], AY0: ['ay'], AY1: ['ay'], AY2: ['ay']
OW0: ['o'], OW1: ['o'], OW2: ['o']
AW0: ['a', 'u'], AW1: ['a', 'u'], AW2: ['a', 'u']
OY0: ['o', 'ih'], OY1: ['o', 'ih'], OY2: ['o', 'ih']
# r coloured vowels
ER: ['r'], ER0: ['r'], ER1: ['r'], ER2: ['r']
# stops
P: ['p'], B: ['b'], T: ['t'], D: ['d'], K: ['k'], G: ['g']
# affricates
CH: ['ch'], JH: ['j']
# fricatives
F: ['f'], V: ['v'], TH: ['Th'], DH: ['th'],
S: ['s'], Z: ['z'], SH: ['sh'], ZH: ['zh'], HH: ['h']
# nasals
M: ['m'], EM: ['m'], N: ['n'], EN: ['n'], NG: ['ng'], ENG: ['ng']
# liquids
L: ['l'], EL: ['l'], R: ['r'], DX: ['t'], NX: ['n', 't']
# semivowels
Y: ['y'], W: ['w']
}
phonemesFromWord = (word) ->
upcaseWord = word.toUpperCase()
return null unless upcaseWord of arpabetDictionary
arpabetSpelling = arpabetDictionary[upcaseWord]
result = []
for arpaPhoneme in arpabetSpelling
continue unless arpaPhoneme of handywriteFromArpabet
result = result.concat handywriteFromArpabet[arpaPhoneme]
return result
# tags that we can recurse into and replace text with text
allowedTags = [
'a', 'address', 'article', 'aside', 'b', 'big', 'blockquote', 'body'
'button', 'caption', 'center', 'cite', 'command', 'datagrid', 'datalist'
'dd', 'del', 'dialog', 'div', 'dl', 'dt', 'em', 'fieldset', 'figure'
'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
'head', 'header', 'html', 'i', 'iframe', 'input', 'ins', 'kbd', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'optgroup', 'option', 'output', 'p', 'q', 's', 'section', 'select'
'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody'
'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul'
]
# tags that we can recurse into and replace text with arbitrary html
embedFriendlyTags = [
'a', 'article', 'aside', 'b', 'big', 'blockquote', 'body', 'button'
'center', 'cite', 'command', 'dd', 'del', 'dialog', 'div', 'dl', 'dt'
'em', 'fieldset', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2'
'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i', 'iframe', 'ins', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'p', 'q', 's', 'section', 'small', 'span', 'strike', 'strong', 'table'
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul'
]
phonetifyDocument = (document) ->
# as we traverse the DOM we'll build a list of replacements to perform
# (we can't replace while looping without messing up the loop logic).
# A replacement has the form:
#
# { old: <node to replace>,
# new: <array of nodes to insert> }
domReplacements = []
renderer = new handywriteOnCanvas.DocumentRenderer document.ownerDocument
phonetifyTextNode = (node, canEmbedHtml) ->
if canEmbedHtml
newContent = []
# capture any space before the first word as a text node
if match = /^([^\w]+)/.exec node.textContent
space = match[1]
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
# then capture each word and its succeeding whitespace for the
# remainder of the input node
wordSpaceRe = /([\w\'\u2019\u02BC]+)([^\w\']*)/g
while match = wordSpaceRe.exec node.textContent
[word, space] = match[1..2]
# replace non-ASCII apostrophes with ASCII
word = word.replace /[\u2019\u02BC]/g, "'"
phonemes = phonemesFromWord word
if phonemes
canvas = renderer.createCanvas(
phonemes, "#{word} (#{arpabetDictionary[word.toUpperCase()].join '-'})")
canvas.setAttribute 'style', 'vertical-align: middle'
newContent.push canvas
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
else
newContent.push window.document.createTextNode word + space
domReplacements.push(
old: node
new: newContent)
else
node.textContent = node.textContent.replace(/[\w\']+/g, phonetifyWord)
return true
phonetifyNodeRecursive = (node, canEmbedHtml) ->
switch node.nodeType
when Node.TEXT_NODE then phonetifyTextNode(node, canEmbedHtml)
when Node.ELEMENT_NODE, Node.DOCUMENT_NODE
name = node.nodeName.toLowerCase()
if name in allowedTags
canEmbedNext = canEmbedHtml and (name in embedFriendlyTags)
for child in node.childNodes
phonetifyNodeRecursive(child, canEmbedNext)
return true
phonetifyNodeRecursive(document, true)
for replacement in domReplacements
oldNode = replacement.old
parent = oldNode.parentNode
for newNode in replacement.new
parent.insertBefore(newNode, oldNode)
parent.removeChild(oldNode)
return true
phonetifyWord = (word) ->
phonemes = phonemesFromWord word
return if phonemes then phonemes.join('') else word
init()
return
| true | ###
phonetify - Firefox extension to replace text with phonetic spelling
Written in 2013 by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
To the extent possible under law, the author(s) have dedicated all
copyright and related and neighboring rights to this software to the
public domain worldwide. This software is distributed without any
warranty.
You should have received a copy of the CC0 Public Domain Dedication
along with this software. If not, see
<http://creativecommons.org/publicdomain/zero/1.0/>.
###
define [
'handywriteOnCanvas/handywriteOnCanvas',
'utils'], (handywriteOnCanvas, utils) ->
'use strict'
arpabetRawFileUri = 'chrome://phonetify/content/pronunciations.txt'
# the arpabet dictionary is loaded asynchronously since it could
# take a while, so we initialise it empty and use a flag to signal
# when it's ready.
arpabetDictionary = {}
arpabetDictReady = false
init = ->
button = window.document.getElementById 'phonetify-button'
button?.addEventListener 'command', onToolbarButton, false
window.setTimeout loadDictionary, 0
return true
onToolbarButton = ->
if arpabetDictReady
phonetifyDocument gBrowser.selectedBrowser.contentDocument.documentElement
return true
else
# try again in half a second
window.setTimeout onToolbarButton, 500
return false
loadDictionary = ->
raw = utils.readFileFromUri arpabetRawFileUri
lineRe = /// ^
([\w\']+) # term
\s+
(.*) # definition
$ ///
for line in raw.match /^.*$/gm
lineMatch = line.match lineRe
continue unless lineMatch
[term, definition] = lineMatch[1..]
arpabetDictionary[term] = definition.match /\b\w\w?\d?\b/g
arpabetDictReady = true
return true
handywriteFromArpabet = {
# monophthongs
AO0: ['aw'], AO1: ['aw'], AO2: ['aw']
AA0: ['a'], AA1: ['a'], AA2: ['a']
IY0: ['i'], IY1: ['i'], IY2: ['i']
UW0: ['u'], UW1: ['u'], UW2: ['u']
EH0: ['eh'], EH1: ['eh'], EH2: ['eh']
IH0: ['ih'], IH1: ['ih'], IH2: ['ih']
UH0: ['uh'], UH1: ['c'], UH2: ['c']
AH0: ['uh'], AH1: ['a'], AH2: ['a']
AX0: ['uh']
AE0: ['ae'], AE1: ['ae'], AE2: ['ae']
# diphthongs
EY0: ['ey'], EY1: ['ey'], EY2: ['ey'], AY0: ['ay'], AY1: ['ay'], AY2: ['ay']
OW0: ['o'], OW1: ['o'], OW2: ['o']
AW0: ['a', 'u'], AW1: ['a', 'u'], AW2: ['a', 'u']
OY0: ['o', 'ih'], OY1: ['o', 'ih'], OY2: ['o', 'ih']
# r coloured vowels
ER: ['r'], ER0: ['r'], ER1: ['r'], ER2: ['r']
# stops
P: ['p'], B: ['b'], T: ['t'], D: ['d'], K: ['k'], G: ['g']
# affricates
CH: ['ch'], JH: ['j']
# fricatives
F: ['f'], V: ['v'], TH: ['Th'], DH: ['th'],
S: ['s'], Z: ['z'], SH: ['sh'], ZH: ['zh'], HH: ['h']
# nasals
M: ['m'], EM: ['m'], N: ['n'], EN: ['n'], NG: ['ng'], ENG: ['ng']
# liquids
L: ['l'], EL: ['l'], R: ['r'], DX: ['t'], NX: ['n', 't']
# semivowels
Y: ['y'], W: ['w']
}
phonemesFromWord = (word) ->
upcaseWord = word.toUpperCase()
return null unless upcaseWord of arpabetDictionary
arpabetSpelling = arpabetDictionary[upcaseWord]
result = []
for arpaPhoneme in arpabetSpelling
continue unless arpaPhoneme of handywriteFromArpabet
result = result.concat handywriteFromArpabet[arpaPhoneme]
return result
# tags that we can recurse into and replace text with text
allowedTags = [
'a', 'address', 'article', 'aside', 'b', 'big', 'blockquote', 'body'
'button', 'caption', 'center', 'cite', 'command', 'datagrid', 'datalist'
'dd', 'del', 'dialog', 'div', 'dl', 'dt', 'em', 'fieldset', 'figure'
'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
'head', 'header', 'html', 'i', 'iframe', 'input', 'ins', 'kbd', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'optgroup', 'option', 'output', 'p', 'q', 's', 'section', 'select'
'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tbody'
'td', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul'
]
# tags that we can recurse into and replace text with arbitrary html
embedFriendlyTags = [
'a', 'article', 'aside', 'b', 'big', 'blockquote', 'body', 'button'
'center', 'cite', 'command', 'dd', 'del', 'dialog', 'div', 'dl', 'dt'
'em', 'fieldset', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2'
'h3', 'h4', 'h5', 'h6', 'header', 'html', 'i', 'iframe', 'ins', 'label'
'legend', 'li', 'mark', 'menu', 'nav', 'noframes', 'noscript', 'ol'
'p', 'q', 's', 'section', 'small', 'span', 'strike', 'strong', 'table'
'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'u', 'ul'
]
phonetifyDocument = (document) ->
# as we traverse the DOM we'll build a list of replacements to perform
# (we can't replace while looping without messing up the loop logic).
# A replacement has the form:
#
# { old: <node to replace>,
# new: <array of nodes to insert> }
domReplacements = []
renderer = new handywriteOnCanvas.DocumentRenderer document.ownerDocument
phonetifyTextNode = (node, canEmbedHtml) ->
if canEmbedHtml
newContent = []
# capture any space before the first word as a text node
if match = /^([^\w]+)/.exec node.textContent
space = match[1]
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
# then capture each word and its succeeding whitespace for the
# remainder of the input node
wordSpaceRe = /([\w\'\u2019\u02BC]+)([^\w\']*)/g
while match = wordSpaceRe.exec node.textContent
[word, space] = match[1..2]
# replace non-ASCII apostrophes with ASCII
word = word.replace /[\u2019\u02BC]/g, "'"
phonemes = phonemesFromWord word
if phonemes
canvas = renderer.createCanvas(
phonemes, "#{word} (#{arpabetDictionary[word.toUpperCase()].join '-'})")
canvas.setAttribute 'style', 'vertical-align: middle'
newContent.push canvas
spaceTextNode = window.document.createTextNode space
newContent.push spaceTextNode
else
newContent.push window.document.createTextNode word + space
domReplacements.push(
old: node
new: newContent)
else
node.textContent = node.textContent.replace(/[\w\']+/g, phonetifyWord)
return true
phonetifyNodeRecursive = (node, canEmbedHtml) ->
switch node.nodeType
when Node.TEXT_NODE then phonetifyTextNode(node, canEmbedHtml)
when Node.ELEMENT_NODE, Node.DOCUMENT_NODE
name = node.nodeName.toLowerCase()
if name in allowedTags
canEmbedNext = canEmbedHtml and (name in embedFriendlyTags)
for child in node.childNodes
phonetifyNodeRecursive(child, canEmbedNext)
return true
phonetifyNodeRecursive(document, true)
for replacement in domReplacements
oldNode = replacement.old
parent = oldNode.parentNode
for newNode in replacement.new
parent.insertBefore(newNode, oldNode)
parent.removeChild(oldNode)
return true
phonetifyWord = (word) ->
phonemes = phonemesFromWord word
return if phonemes then phonemes.join('') else word
init()
return
|
[
{
"context": " )\n\n @resizeToSaved()\n\n resizeToSavedKey: \"mailcatcherSeparatorHeight\"\n\n resizeTo: (height) ->\n @onResize(height)\n ",
"end": 451,
"score": 0.9903589487075806,
"start": 425,
"tag": "KEY",
"value": "mailcatcherSeparatorHeight"
},
{
"context": "() ->\n... | assets/javascripts/mailcatcher.coffee | Visual-Craft/mailcatcher | 2 | class Resizer
constructor: (resizer, onResize) ->
@resizer = resizer
@onResize = onResize
mouseEvents =
mouseup: (e) =>
e.preventDefault()
$(window).unbind(mouseEvents)
mousemove: (e) =>
e.preventDefault()
@resizeTo(e.clientY)
@resizer.mousedown((e) =>
e.preventDefault()
$(window).bind(mouseEvents)
)
@resizeToSaved()
resizeToSavedKey: "mailcatcherSeparatorHeight"
resizeTo: (height) ->
@onResize(height)
try
window.localStorage?.setItem(@resizeToSavedKey, height)
catch
resizeToSaved: ->
height = 0
try
height = parseInt(window.localStorage?.getItem(@resizeToSavedKey))
catch
height = -1
if isNaN(height) || height <= 0
@resizeTo(200)
else
@resizeTo(height)
Vue.filter('moment', (value, format) ->
if value
moment(value).format(format)
else
''
)
jQuery(() ->
new Vue(
el: '#mc-app'
created: () ->
this.checkAuth()
.done((data) =>
if data && data.status
this.noAuth = data.no_auth
this.toMain(data.username)
else
this.toLogin()
noty({
text: "Please login"
type: 'information'
layout: 'bottomRight'
timeout: 3000
})
)
data:
currentComponent: null
currentUserName: null
noAuth: false
methods:
toLogin: () ->
this.currentUserName = null
this.currentComponent = 'login'
toMain: (username = null) ->
this.currentUserName = username
this.currentComponent = 'main'
authToken: () ->
Cookies.get('AUTH')
checkAuth: () ->
$.ajax
url: "/api/check-auth"
dataType: 'json'
type: "GET"
components:
login:
template: '#mc-login'
data: () ->
username: null
password: null
methods:
loginSubmit: () ->
$.ajax
url: "/api/login"
data:
login: this.username
pass: this.password
type: "POST"
success: (token) =>
Cookies.set('AUTH', token)
this.$parent.toMain(this.username)
error: () ->
noty({
text: "Invalid login or password"
type: 'error'
})
main:
template: '#mc-main'
created: () ->
this.loadMessages()
this.subscribe()
ready: () ->
key "up", =>
this.selectMessageRelative(-1)
false
key "down", =>
this.selectMessageRelative(+1)
false
key "⌘+up, ctrl+up, home", =>
this.selectMessageIndex(0)
false
key "⌘+down, ctrl+down, end", =>
this.selectMessageIndex(-1)
false
key "delete", =>
this.deleteSelectedMessage()
false
this.resizer = new Resizer($("#resizer"), (height) =>
blockHeight = Math.max(height, 60) - $(".wrapper").offset().top / 2
$(".folders-wrapper").css(height: blockHeight)
$("#messages").css(height: blockHeight + 4)
)
data: () ->
messages : []
selectedOwner: null
search: ''
selectedMessage: null
selectedPresentation: null
resizer: null
messageExpanded: null
watch:
'messages': (messages, oldMessages) ->
if this.selectedMessage != null
if messages.length == 0
this.selectedMessage = null
else
messages = _.filter(messages, this.filterMessage)
selectedId = this.selectedMessage.id
findById = (v) -> selectedId == v.id
selectedFound = _.any(messages, findById)
unless selectedFound
index = Math.min(_.findIndex(oldMessages, findById), messages.length - 1)
if index >= 0
this.selectedMessage = messages[index]
else
this.selectedMessage = null
'selectedMessage': (message) ->
if message
this.scrollToRow(message)
if message.new
this.wrapAjax
url: "/api/messages/#{message.id}/mark-readed"
type: "POST"
success: (data) =>
message.new = 0
this.selectedPresentation = this.presentations[0]
this.messageExpanded = false
else
this.selectedPresentation = null
this.messageExpanded = null
'messageExpanded': (value) ->
if value == null
return
$(".folders-wrapper")[if value then 'slideUp' else 'slideDown'](300)
$("#messages")[if value then 'slideUp' else 'slideDown'](300)
methods:
wrapAjax: (options) ->
$.ajax(options)
.fail((data) =>
if data && (data.status == 403 || data.status == 401)
this.$parent.toLogin()
if data.status == 401
noty({
text: "Invalid login or password"
type: 'error'
})
else
noty({
text: "Access denied"
type: 'error'
})
)
subscribe: () ->
if WebSocket?
return if this.websocket
secure = window.location.protocol is "https:"
protocol = if secure then "wss" else "ws"
this.websocket = new WebSocket("#{protocol}://#{window.location.host}/ws/messages")
this.websocket.onmessage = (event) =>
message = $.parseJSON(event.data)
# handle ping, which just returns empty object
if not _.isEmpty(message)
this.messages.unshift(message)
$(window).bind('beforeunload', () =>
if this.websocket
this.websocket.close()
this.websocket = null
)
else
return if this.refreshInterval?
this.refreshInterval = setInterval(() =>
this.loadMessages()
, 2000)
loadMessages: () ->
this.wrapAjax
url: "/api/messages"
type: "GET"
dataType: 'json'
success: (messages) =>
this.messages = messages
selectMessage: (message) ->
this.selectedMessage = message
selectMessageRelative: (offset) ->
unless this.selectedMessage
return
index = _.findIndex(this.messages, (v) => this.selectedMessage.id == v.id) + offset
if index >= 0
this.selectMessageIndex(index)
selectMessageIndex: (index) ->
if index >= 0
return if index >= this.messages.length
else
index = this.messages.length + index
return if index < 0
this.selectedMessage = this.messages[index]
selectOwner: (owner) ->
this.selectedOwner = owner
this.selectedMessage = null
clearMessages: (owner) ->
if owner == null
message = 'all messages'
else if owner == ''
message = 'messages without owner'
else
message = "messages with owner '#{owner}'"
if confirm("Are you sure you want to clear #{message}?")
if owner == null
params = ''
else
params = '?' + $.param({"owner": owner})
this.wrapAjax
url: "/api/messages#{params}"
type: "DELETE"
success: =>
this.loadMessages()
error: ->
alert "Error while clearing messages."
filterMessage: (message) ->
if this.selectedOwner != null and message.owner != this.selectedOwner
return false
search = $.trim(this.search)
if search == ''
return true
sources = []
sources.push(message.subject) if message.subject
sources.push(message.sender) if message.sender
sources.push(message.recipients.join(', ')) if message.recipients and message.recipients.length
for part in message.parts
sources.push(part.body) if part.body
search = search.toUpperCase().split(/\s+/)
for source in sources
for searchItem in search
if source.toUpperCase().indexOf(searchItem) >= 0
return true
false
downloadUrl: (message) ->
"/api/messages/#{message.id}/source?download"
presentationDisplayName: (presentation) ->
if presentation.type == 'source'
'Source'
else
switch presentation.contentType
when 'text/plain' then 'Plain Text'
when 'text/html' then 'HTML'
else 'Other'
isMessageSelected: (message) ->
this.selectedMessage and this.selectedMessage.id == message.id
deleteMessage: (message) ->
if not confirm("Are you sure?")
return
this.wrapAjax
url: "/api/messages/#{message.id}"
type: "DELETE"
success: =>
this.messages = _.reject(this.messages, (v) -> v.id == message.id)
error: ->
alert "Error while removing message."
deleteSelectedMessage: () ->
this.deleteMessage(this.selectedMessage) if this.selectedMessage
scrollToRow: (message) ->
row = $("[data-message-id='#{message.id}']")
if row.length == 0
return
$messages = $("#messages")
relativePosition = row.offset().top - $messages.offset().top
if relativePosition < 0
$messages.scrollTop($messages.scrollTop() + relativePosition - 20)
else
overflow = relativePosition + row.height() - $messages.height()
if overflow > 0
$messages.scrollTop($messages.scrollTop() + overflow + 20)
selectPresentation: (presentation) ->
this.selectedPresentation = presentation
isPresentationSelected: (presentation) ->
unless this.selectedPresentation
false
else if this.selectedPresentation.type == presentation.type
if this.selectedPresentation.id == null or this.selectedPresentation.id == presentation.id
true
else
false
selectedPresentationUrl: () ->
unless this.selectedPresentation
null
else if this.selectedPresentation.type == 'source'
"/api/messages/#{this.selectedMessage.id}/source"
else
"/api/messages/#{this.selectedMessage.id}/part/#{this.selectedPresentation.id}/body"
hasAttachments: (message) ->
not _.isEmpty(message.attachments)
attachmentUrl: (message, attachment) ->
"/api/messages/#{message.id}/attachment/#{attachment.id}/body"
logout: () ->
Cookies.set('AUTH', null)
this.$parent.toLogin()
showLogoutButton: () ->
!this.$parent.noAuth
userName: () ->
this.$parent.currentUserName
preparePresentationContent: (event) ->
if this.selectedPresentation && this.selectedPresentation.contentType == 'text/html'
$(event.target).contents().find('a').attr('target','_blank')
toggleMessageExpanded: () ->
this.messageExpanded = !this.messageExpanded
computed:
folders: () ->
result = []
owners = {}
totalNew = 0
addFolder = (name, owner, count) -> result.push({ name: name, owner: owner, count: count })
for k,v of this.messages
if owners[v.owner]
owners[v.owner]['total']++
else
owners[v.owner] = {
'total': 1
'new': 0
}
if v.new
totalNew++
owners[v.owner]['new']++
addFolder('! All', null, {
'total': this.messages.length
'new': totalNew
})
unless this.messages.length
return result
for k,v of owners
addFolder(k || '! No owner', k, v)
ownersNames = _.keys(owners).sort()
ownersPriority = {}
for v,index in ownersNames
ownersPriority[v] = index
result.sort((a, b) ->
if a.owner == null
-1
else if a.owner == ''
-1
else if a.owner == b.owner
0
else if ownersPriority[a.owner] < ownersPriority[b.owner]
-1
else
1
)
presentations: () ->
unless this.selectedMessage
return null
result = []
addPresentation = (type, id = null, contentType = null) -> result.push({ type: type, id: id, contentType: contentType })
priorityPresentation = (item) ->
switch item.contentType
when 'text/html' then 0
when 'text/plain' then 1
when null then 3
else 2
for k,p of this.selectedMessage.parts
addPresentation('part', p.id, p.type)
addPresentation('source')
result.sort((a, b) ->
if priorityPresentation(a) < priorityPresentation(b)
-1
else if priorityPresentation(a) == priorityPresentation(b)
0
else
1
)
filteredMessages: () ->
_.filter(this.messages, this.filterMessage)
)
)
| 107374 | class Resizer
constructor: (resizer, onResize) ->
@resizer = resizer
@onResize = onResize
mouseEvents =
mouseup: (e) =>
e.preventDefault()
$(window).unbind(mouseEvents)
mousemove: (e) =>
e.preventDefault()
@resizeTo(e.clientY)
@resizer.mousedown((e) =>
e.preventDefault()
$(window).bind(mouseEvents)
)
@resizeToSaved()
resizeToSavedKey: "<KEY>"
resizeTo: (height) ->
@onResize(height)
try
window.localStorage?.setItem(@resizeToSavedKey, height)
catch
resizeToSaved: ->
height = 0
try
height = parseInt(window.localStorage?.getItem(@resizeToSavedKey))
catch
height = -1
if isNaN(height) || height <= 0
@resizeTo(200)
else
@resizeTo(height)
Vue.filter('moment', (value, format) ->
if value
moment(value).format(format)
else
''
)
jQuery(() ->
new Vue(
el: '#mc-app'
created: () ->
this.checkAuth()
.done((data) =>
if data && data.status
this.noAuth = data.no_auth
this.toMain(data.username)
else
this.toLogin()
noty({
text: "Please login"
type: 'information'
layout: 'bottomRight'
timeout: 3000
})
)
data:
currentComponent: null
currentUserName: null
noAuth: false
methods:
toLogin: () ->
this.currentUserName = null
this.currentComponent = 'login'
toMain: (username = null) ->
this.currentUserName = username
this.currentComponent = 'main'
authToken: () ->
Cookies.get('AUTH')
checkAuth: () ->
$.ajax
url: "/api/check-auth"
dataType: 'json'
type: "GET"
components:
login:
template: '#mc-login'
data: () ->
username: null
password: <PASSWORD>
methods:
loginSubmit: () ->
$.ajax
url: "/api/login"
data:
login: this.username
pass: <PASSWORD>
type: "POST"
success: (token) =>
Cookies.set('AUTH', token)
this.$parent.toMain(this.username)
error: () ->
noty({
text: "Invalid login or password"
type: 'error'
})
main:
template: '#mc-main'
created: () ->
this.loadMessages()
this.subscribe()
ready: () ->
key "up", =>
this.selectMessageRelative(-1)
false
key "down", =>
this.selectMessageRelative(+1)
false
key "⌘+up, ctrl+up, home", =>
this.selectMessageIndex(0)
false
key "⌘+down, ctrl+down, end", =>
this.selectMessageIndex(-1)
false
key "delete", =>
this.deleteSelectedMessage()
false
this.resizer = new Resizer($("#resizer"), (height) =>
blockHeight = Math.max(height, 60) - $(".wrapper").offset().top / 2
$(".folders-wrapper").css(height: blockHeight)
$("#messages").css(height: blockHeight + 4)
)
data: () ->
messages : []
selectedOwner: null
search: ''
selectedMessage: null
selectedPresentation: null
resizer: null
messageExpanded: null
watch:
'messages': (messages, oldMessages) ->
if this.selectedMessage != null
if messages.length == 0
this.selectedMessage = null
else
messages = _.filter(messages, this.filterMessage)
selectedId = this.selectedMessage.id
findById = (v) -> selectedId == v.id
selectedFound = _.any(messages, findById)
unless selectedFound
index = Math.min(_.findIndex(oldMessages, findById), messages.length - 1)
if index >= 0
this.selectedMessage = messages[index]
else
this.selectedMessage = null
'selectedMessage': (message) ->
if message
this.scrollToRow(message)
if message.new
this.wrapAjax
url: "/api/messages/#{message.id}/mark-readed"
type: "POST"
success: (data) =>
message.new = 0
this.selectedPresentation = this.presentations[0]
this.messageExpanded = false
else
this.selectedPresentation = null
this.messageExpanded = null
'messageExpanded': (value) ->
if value == null
return
$(".folders-wrapper")[if value then 'slideUp' else 'slideDown'](300)
$("#messages")[if value then 'slideUp' else 'slideDown'](300)
methods:
wrapAjax: (options) ->
$.ajax(options)
.fail((data) =>
if data && (data.status == 403 || data.status == 401)
this.$parent.toLogin()
if data.status == 401
noty({
text: "Invalid login or password"
type: 'error'
})
else
noty({
text: "Access denied"
type: 'error'
})
)
subscribe: () ->
if WebSocket?
return if this.websocket
secure = window.location.protocol is "https:"
protocol = if secure then "wss" else "ws"
this.websocket = new WebSocket("#{protocol}://#{window.location.host}/ws/messages")
this.websocket.onmessage = (event) =>
message = $.parseJSON(event.data)
# handle ping, which just returns empty object
if not _.isEmpty(message)
this.messages.unshift(message)
$(window).bind('beforeunload', () =>
if this.websocket
this.websocket.close()
this.websocket = null
)
else
return if this.refreshInterval?
this.refreshInterval = setInterval(() =>
this.loadMessages()
, 2000)
loadMessages: () ->
this.wrapAjax
url: "/api/messages"
type: "GET"
dataType: 'json'
success: (messages) =>
this.messages = messages
selectMessage: (message) ->
this.selectedMessage = message
selectMessageRelative: (offset) ->
unless this.selectedMessage
return
index = _.findIndex(this.messages, (v) => this.selectedMessage.id == v.id) + offset
if index >= 0
this.selectMessageIndex(index)
selectMessageIndex: (index) ->
if index >= 0
return if index >= this.messages.length
else
index = this.messages.length + index
return if index < 0
this.selectedMessage = this.messages[index]
selectOwner: (owner) ->
this.selectedOwner = owner
this.selectedMessage = null
clearMessages: (owner) ->
if owner == null
message = 'all messages'
else if owner == ''
message = 'messages without owner'
else
message = "messages with owner '#{owner}'"
if confirm("Are you sure you want to clear #{message}?")
if owner == null
params = ''
else
params = '?' + $.param({"owner": owner})
this.wrapAjax
url: "/api/messages#{params}"
type: "DELETE"
success: =>
this.loadMessages()
error: ->
alert "Error while clearing messages."
filterMessage: (message) ->
if this.selectedOwner != null and message.owner != this.selectedOwner
return false
search = $.trim(this.search)
if search == ''
return true
sources = []
sources.push(message.subject) if message.subject
sources.push(message.sender) if message.sender
sources.push(message.recipients.join(', ')) if message.recipients and message.recipients.length
for part in message.parts
sources.push(part.body) if part.body
search = search.toUpperCase().split(/\s+/)
for source in sources
for searchItem in search
if source.toUpperCase().indexOf(searchItem) >= 0
return true
false
downloadUrl: (message) ->
"/api/messages/#{message.id}/source?download"
presentationDisplayName: (presentation) ->
if presentation.type == 'source'
'Source'
else
switch presentation.contentType
when 'text/plain' then 'Plain Text'
when 'text/html' then 'HTML'
else 'Other'
isMessageSelected: (message) ->
this.selectedMessage and this.selectedMessage.id == message.id
deleteMessage: (message) ->
if not confirm("Are you sure?")
return
this.wrapAjax
url: "/api/messages/#{message.id}"
type: "DELETE"
success: =>
this.messages = _.reject(this.messages, (v) -> v.id == message.id)
error: ->
alert "Error while removing message."
deleteSelectedMessage: () ->
this.deleteMessage(this.selectedMessage) if this.selectedMessage
scrollToRow: (message) ->
row = $("[data-message-id='#{message.id}']")
if row.length == 0
return
$messages = $("#messages")
relativePosition = row.offset().top - $messages.offset().top
if relativePosition < 0
$messages.scrollTop($messages.scrollTop() + relativePosition - 20)
else
overflow = relativePosition + row.height() - $messages.height()
if overflow > 0
$messages.scrollTop($messages.scrollTop() + overflow + 20)
selectPresentation: (presentation) ->
this.selectedPresentation = presentation
isPresentationSelected: (presentation) ->
unless this.selectedPresentation
false
else if this.selectedPresentation.type == presentation.type
if this.selectedPresentation.id == null or this.selectedPresentation.id == presentation.id
true
else
false
selectedPresentationUrl: () ->
unless this.selectedPresentation
null
else if this.selectedPresentation.type == 'source'
"/api/messages/#{this.selectedMessage.id}/source"
else
"/api/messages/#{this.selectedMessage.id}/part/#{this.selectedPresentation.id}/body"
hasAttachments: (message) ->
not _.isEmpty(message.attachments)
attachmentUrl: (message, attachment) ->
"/api/messages/#{message.id}/attachment/#{attachment.id}/body"
logout: () ->
Cookies.set('AUTH', null)
this.$parent.toLogin()
showLogoutButton: () ->
!this.$parent.noAuth
userName: () ->
this.$parent.currentUserName
preparePresentationContent: (event) ->
if this.selectedPresentation && this.selectedPresentation.contentType == 'text/html'
$(event.target).contents().find('a').attr('target','_blank')
toggleMessageExpanded: () ->
this.messageExpanded = !this.messageExpanded
computed:
folders: () ->
result = []
owners = {}
totalNew = 0
addFolder = (name, owner, count) -> result.push({ name: name, owner: owner, count: count })
for k,v of this.messages
if owners[v.owner]
owners[v.owner]['total']++
else
owners[v.owner] = {
'total': 1
'new': 0
}
if v.new
totalNew++
owners[v.owner]['new']++
addFolder('! All', null, {
'total': this.messages.length
'new': totalNew
})
unless this.messages.length
return result
for k,v of owners
addFolder(k || '! No owner', k, v)
ownersNames = _.keys(owners).sort()
ownersPriority = {}
for v,index in ownersNames
ownersPriority[v] = index
result.sort((a, b) ->
if a.owner == null
-1
else if a.owner == ''
-1
else if a.owner == b.owner
0
else if ownersPriority[a.owner] < ownersPriority[b.owner]
-1
else
1
)
presentations: () ->
unless this.selectedMessage
return null
result = []
addPresentation = (type, id = null, contentType = null) -> result.push({ type: type, id: id, contentType: contentType })
priorityPresentation = (item) ->
switch item.contentType
when 'text/html' then 0
when 'text/plain' then 1
when null then 3
else 2
for k,p of this.selectedMessage.parts
addPresentation('part', p.id, p.type)
addPresentation('source')
result.sort((a, b) ->
if priorityPresentation(a) < priorityPresentation(b)
-1
else if priorityPresentation(a) == priorityPresentation(b)
0
else
1
)
filteredMessages: () ->
_.filter(this.messages, this.filterMessage)
)
)
| true | class Resizer
constructor: (resizer, onResize) ->
@resizer = resizer
@onResize = onResize
mouseEvents =
mouseup: (e) =>
e.preventDefault()
$(window).unbind(mouseEvents)
mousemove: (e) =>
e.preventDefault()
@resizeTo(e.clientY)
@resizer.mousedown((e) =>
e.preventDefault()
$(window).bind(mouseEvents)
)
@resizeToSaved()
resizeToSavedKey: "PI:KEY:<KEY>END_PI"
resizeTo: (height) ->
@onResize(height)
try
window.localStorage?.setItem(@resizeToSavedKey, height)
catch
resizeToSaved: ->
height = 0
try
height = parseInt(window.localStorage?.getItem(@resizeToSavedKey))
catch
height = -1
if isNaN(height) || height <= 0
@resizeTo(200)
else
@resizeTo(height)
Vue.filter('moment', (value, format) ->
if value
moment(value).format(format)
else
''
)
jQuery(() ->
new Vue(
el: '#mc-app'
created: () ->
this.checkAuth()
.done((data) =>
if data && data.status
this.noAuth = data.no_auth
this.toMain(data.username)
else
this.toLogin()
noty({
text: "Please login"
type: 'information'
layout: 'bottomRight'
timeout: 3000
})
)
data:
currentComponent: null
currentUserName: null
noAuth: false
methods:
toLogin: () ->
this.currentUserName = null
this.currentComponent = 'login'
toMain: (username = null) ->
this.currentUserName = username
this.currentComponent = 'main'
authToken: () ->
Cookies.get('AUTH')
checkAuth: () ->
$.ajax
url: "/api/check-auth"
dataType: 'json'
type: "GET"
components:
login:
template: '#mc-login'
data: () ->
username: null
password: PI:PASSWORD:<PASSWORD>END_PI
methods:
loginSubmit: () ->
$.ajax
url: "/api/login"
data:
login: this.username
pass: PI:PASSWORD:<PASSWORD>END_PI
type: "POST"
success: (token) =>
Cookies.set('AUTH', token)
this.$parent.toMain(this.username)
error: () ->
noty({
text: "Invalid login or password"
type: 'error'
})
main:
template: '#mc-main'
created: () ->
this.loadMessages()
this.subscribe()
ready: () ->
key "up", =>
this.selectMessageRelative(-1)
false
key "down", =>
this.selectMessageRelative(+1)
false
key "⌘+up, ctrl+up, home", =>
this.selectMessageIndex(0)
false
key "⌘+down, ctrl+down, end", =>
this.selectMessageIndex(-1)
false
key "delete", =>
this.deleteSelectedMessage()
false
this.resizer = new Resizer($("#resizer"), (height) =>
blockHeight = Math.max(height, 60) - $(".wrapper").offset().top / 2
$(".folders-wrapper").css(height: blockHeight)
$("#messages").css(height: blockHeight + 4)
)
data: () ->
messages : []
selectedOwner: null
search: ''
selectedMessage: null
selectedPresentation: null
resizer: null
messageExpanded: null
watch:
'messages': (messages, oldMessages) ->
if this.selectedMessage != null
if messages.length == 0
this.selectedMessage = null
else
messages = _.filter(messages, this.filterMessage)
selectedId = this.selectedMessage.id
findById = (v) -> selectedId == v.id
selectedFound = _.any(messages, findById)
unless selectedFound
index = Math.min(_.findIndex(oldMessages, findById), messages.length - 1)
if index >= 0
this.selectedMessage = messages[index]
else
this.selectedMessage = null
'selectedMessage': (message) ->
if message
this.scrollToRow(message)
if message.new
this.wrapAjax
url: "/api/messages/#{message.id}/mark-readed"
type: "POST"
success: (data) =>
message.new = 0
this.selectedPresentation = this.presentations[0]
this.messageExpanded = false
else
this.selectedPresentation = null
this.messageExpanded = null
'messageExpanded': (value) ->
if value == null
return
$(".folders-wrapper")[if value then 'slideUp' else 'slideDown'](300)
$("#messages")[if value then 'slideUp' else 'slideDown'](300)
methods:
wrapAjax: (options) ->
$.ajax(options)
.fail((data) =>
if data && (data.status == 403 || data.status == 401)
this.$parent.toLogin()
if data.status == 401
noty({
text: "Invalid login or password"
type: 'error'
})
else
noty({
text: "Access denied"
type: 'error'
})
)
subscribe: () ->
if WebSocket?
return if this.websocket
secure = window.location.protocol is "https:"
protocol = if secure then "wss" else "ws"
this.websocket = new WebSocket("#{protocol}://#{window.location.host}/ws/messages")
this.websocket.onmessage = (event) =>
message = $.parseJSON(event.data)
# handle ping, which just returns empty object
if not _.isEmpty(message)
this.messages.unshift(message)
$(window).bind('beforeunload', () =>
if this.websocket
this.websocket.close()
this.websocket = null
)
else
return if this.refreshInterval?
this.refreshInterval = setInterval(() =>
this.loadMessages()
, 2000)
loadMessages: () ->
this.wrapAjax
url: "/api/messages"
type: "GET"
dataType: 'json'
success: (messages) =>
this.messages = messages
selectMessage: (message) ->
this.selectedMessage = message
selectMessageRelative: (offset) ->
unless this.selectedMessage
return
index = _.findIndex(this.messages, (v) => this.selectedMessage.id == v.id) + offset
if index >= 0
this.selectMessageIndex(index)
selectMessageIndex: (index) ->
if index >= 0
return if index >= this.messages.length
else
index = this.messages.length + index
return if index < 0
this.selectedMessage = this.messages[index]
selectOwner: (owner) ->
this.selectedOwner = owner
this.selectedMessage = null
clearMessages: (owner) ->
if owner == null
message = 'all messages'
else if owner == ''
message = 'messages without owner'
else
message = "messages with owner '#{owner}'"
if confirm("Are you sure you want to clear #{message}?")
if owner == null
params = ''
else
params = '?' + $.param({"owner": owner})
this.wrapAjax
url: "/api/messages#{params}"
type: "DELETE"
success: =>
this.loadMessages()
error: ->
alert "Error while clearing messages."
filterMessage: (message) ->
if this.selectedOwner != null and message.owner != this.selectedOwner
return false
search = $.trim(this.search)
if search == ''
return true
sources = []
sources.push(message.subject) if message.subject
sources.push(message.sender) if message.sender
sources.push(message.recipients.join(', ')) if message.recipients and message.recipients.length
for part in message.parts
sources.push(part.body) if part.body
search = search.toUpperCase().split(/\s+/)
for source in sources
for searchItem in search
if source.toUpperCase().indexOf(searchItem) >= 0
return true
false
downloadUrl: (message) ->
"/api/messages/#{message.id}/source?download"
presentationDisplayName: (presentation) ->
if presentation.type == 'source'
'Source'
else
switch presentation.contentType
when 'text/plain' then 'Plain Text'
when 'text/html' then 'HTML'
else 'Other'
isMessageSelected: (message) ->
this.selectedMessage and this.selectedMessage.id == message.id
deleteMessage: (message) ->
if not confirm("Are you sure?")
return
this.wrapAjax
url: "/api/messages/#{message.id}"
type: "DELETE"
success: =>
this.messages = _.reject(this.messages, (v) -> v.id == message.id)
error: ->
alert "Error while removing message."
deleteSelectedMessage: () ->
this.deleteMessage(this.selectedMessage) if this.selectedMessage
scrollToRow: (message) ->
row = $("[data-message-id='#{message.id}']")
if row.length == 0
return
$messages = $("#messages")
relativePosition = row.offset().top - $messages.offset().top
if relativePosition < 0
$messages.scrollTop($messages.scrollTop() + relativePosition - 20)
else
overflow = relativePosition + row.height() - $messages.height()
if overflow > 0
$messages.scrollTop($messages.scrollTop() + overflow + 20)
selectPresentation: (presentation) ->
this.selectedPresentation = presentation
isPresentationSelected: (presentation) ->
unless this.selectedPresentation
false
else if this.selectedPresentation.type == presentation.type
if this.selectedPresentation.id == null or this.selectedPresentation.id == presentation.id
true
else
false
selectedPresentationUrl: () ->
unless this.selectedPresentation
null
else if this.selectedPresentation.type == 'source'
"/api/messages/#{this.selectedMessage.id}/source"
else
"/api/messages/#{this.selectedMessage.id}/part/#{this.selectedPresentation.id}/body"
hasAttachments: (message) ->
not _.isEmpty(message.attachments)
attachmentUrl: (message, attachment) ->
"/api/messages/#{message.id}/attachment/#{attachment.id}/body"
logout: () ->
Cookies.set('AUTH', null)
this.$parent.toLogin()
showLogoutButton: () ->
!this.$parent.noAuth
userName: () ->
this.$parent.currentUserName
preparePresentationContent: (event) ->
if this.selectedPresentation && this.selectedPresentation.contentType == 'text/html'
$(event.target).contents().find('a').attr('target','_blank')
toggleMessageExpanded: () ->
this.messageExpanded = !this.messageExpanded
computed:
folders: () ->
result = []
owners = {}
totalNew = 0
addFolder = (name, owner, count) -> result.push({ name: name, owner: owner, count: count })
for k,v of this.messages
if owners[v.owner]
owners[v.owner]['total']++
else
owners[v.owner] = {
'total': 1
'new': 0
}
if v.new
totalNew++
owners[v.owner]['new']++
addFolder('! All', null, {
'total': this.messages.length
'new': totalNew
})
unless this.messages.length
return result
for k,v of owners
addFolder(k || '! No owner', k, v)
ownersNames = _.keys(owners).sort()
ownersPriority = {}
for v,index in ownersNames
ownersPriority[v] = index
result.sort((a, b) ->
if a.owner == null
-1
else if a.owner == ''
-1
else if a.owner == b.owner
0
else if ownersPriority[a.owner] < ownersPriority[b.owner]
-1
else
1
)
presentations: () ->
unless this.selectedMessage
return null
result = []
addPresentation = (type, id = null, contentType = null) -> result.push({ type: type, id: id, contentType: contentType })
priorityPresentation = (item) ->
switch item.contentType
when 'text/html' then 0
when 'text/plain' then 1
when null then 3
else 2
for k,p of this.selectedMessage.parts
addPresentation('part', p.id, p.type)
addPresentation('source')
result.sort((a, b) ->
if priorityPresentation(a) < priorityPresentation(b)
-1
else if priorityPresentation(a) == priorityPresentation(b)
0
else
1
)
filteredMessages: () ->
_.filter(this.messages, this.filterMessage)
)
)
|
[
{
"context": "giabot ? - Ring the nostalgiaphone\n#\n# Author:\n# MartinPetkov\n\nfs = require 'fs'\nrequest = require 'request'\nrg",
"end": 1427,
"score": 0.9987635016441345,
"start": 1415,
"tag": "NAME",
"value": "MartinPetkov"
}
] | scripts/nostalgia.coffee | MartinPetkov/NostalgiaBot | 5 | # Description:
# Remember past employees that you miss.
#
# Commands:
# nostalgiabot Remind (me|<person>) of <person> - Digs up a memorable quote from the past, and remind the person.
# nostalgiabot Quote <person> - Digs up a memorable quote from the past.
# nostalgiabot Random quote - Dig up random memory from random person
# nostalgiabot Remember that <person> said "<quote>" - Stores a new quote, to forever remain in the planes of Nostalgia.
# nostalgiabot Who do you remember? - See the memories the NostalgiaBot holds on to.
# nostalgiabot Converse <person1>, <person2> [, <person3>...] - Start a nonsensical convo
# nostalgiabot Alias <name> as <alias1> [<alias2> ...] - Add nicknames to the memorees
# nostalgiabot Start Guess Who - Start a game of Guess Who!
# nostalgiabot Show Guess Who - Show the current quote to guess
# nostalgiabot Guess <person> - Guess who said the current quote. Ends when guessed correctly.
# nostalgiabot End Guess Who - End the game of Guess Who!.
# nostalgiabot Give up - End the game of Guess Who! and get the answer.
# nostalgiabot Hacker me - Get a 100% real quote from a professional hacker.
# nostalgiabot Commit message me - Generate your next commit message
# nostalgiabot Remember past - Gather memories from the past
# nostalgiabot stats - See how memorable everyone is
# nostalgiabot ? - Ring the nostalgiaphone
#
# Author:
# MartinPetkov
fs = require 'fs'
request = require 'request'
rg = require 'random-greetings'
schedule = require 'node-schedule'
adminsFile = 'admins.json'
loadFile = (fileName) ->
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
admins = loadFile(adminsFile)
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) ->
txt[0].toUpperCase() + txt[1..txt.length - 1].toLowerCase()
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
memoryDir = "./memories"
weekday = new Array(7);
weekday[0]= "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
memories = {}
rememberPast = () ->
memories = {}
quoteFiles = fs.readdirSync memoryDir
for quoteFile in quoteFiles
do (quoteFile) ->
name = "#{quoteFile}".toString().toLowerCase().trim()
quotes = (fs.readFileSync "#{memoryDir}/#{quoteFile}", 'utf8').toString().split("\n").filter(Boolean)
memories[name] = quotes
rememberPast()
randomQuoteRespond = (res, nostalgiaName, targetName) ->
displayName = toTitleCase(nostalgiaName)
if ! (nostalgiaName of memories)
res.send "I don't remember #{displayName}"
return
randomQuote = (res.random memories[nostalgiaName])
if ! randomQuote
res.send "No memories to remember"
return
if (randomQuote.indexOf('$current_day') > 0)
d = new Date()
randomQuote = randomQuote.replace('$current_day', weekday[d.getDay()])
response = if isUndefined(targetName) then '' else "@#{targetName} Do you remember this?\n\n"
response += "\"#{randomQuote}\" - #{displayName}"
res.send response
remindRespond = (res) ->
targetName = res.match[1].toLowerCase().trim()
nostalgiaName = res.match[2].toLowerCase().trim()
if targetName.toLowerCase() == 'me'
targetName = res.message.user.name
randomQuoteRespond(res, nostalgiaName, targetName)
quoteRespond = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
randomQuoteRespond(res, nostalgiaName)
randomNameAndQuoteRespond = (res) ->
nostalgiaName = res.random Object.keys(memories)
randomQuoteRespond(res, nostalgiaName)
shuffleNames = (names) ->
i = names.length
while --i
j = Math.floor(Math.random() * (i+1))
[names[i], names[j]] = [names[j], names[i]] # use pattern matching to swap
return names
convoRespond = (res) ->
allNames = (res.match[1].toLowerCase().trim() + " " + res.match[2].toLowerCase().trim()).split(",")
fixedNames = []
for name in allNames
name = name.toLowerCase().trim()
# Remove @s at the front
if name[0] == '@'
name = name.substr(1)
fixedNames.push name
allNames = fixedNames
# Generate quotes
convoMap = {}
for name in allNames
if !(name of memories)
res.send "I don't recognize #{name}"
return
firstQuote = (res.random memories[name])
secondQuote = (res.random memories[name])
if memories[name].length > 1
while secondQuote == firstQuote
secondQuote = (res.random memories[name])
personQuotes = []
personQuotes.push "#{name}: " + firstQuote
personQuotes.push "#{name}: " + secondQuote
convoMap[name] = personQuotes
allNames = Object.keys(convoMap)
# Assemble quotes
convo = ""
lastName = ""
i = 2
while i--
allNames = shuffleNames(allNames)
while allNames[0] == lastName && allNames.length > 1
allNames = shuffleNames(allNames)
lastName = allNames[allNames.length-1]
for name in allNames
convo += convoMap[name][i] + "\n"
res.send convo
aliasRespond = (res) ->
regularName = res.match[1].toLowerCase().trim()
aliases = res.match[2].toLowerCase().trim().split(" ")
if !(regularName of memories)
res.send "Could not find #{regularName} in vast memory bank"
return
for alias in aliases
if alias of memories
res.send "Alias \"#{alias}\" already exists as a separate memory"
else
process.chdir(memoryDir)
fs.symlinkSync(regularName, alias)
res.send "Aliased #{regularName} as #{alias}!"
process.chdir('..')
rememberPast()
hackerRespond = (res) ->
hackerUrl = "https://hacker.actor/quote"
request.get {uri:"#{hackerUrl}", json: true}, (err, r, data) ->
if err
res.send "The Hackers are too busy stealing your data to provide a quote"
else
res.send "\"#{data.quote}\" - l33t h4xx0r"
commitMessageRespond = (res) ->
commitMessageUrl = "http://www.whatthecommit.com/index.txt"
request.get {uri:"#{commitMessageUrl}", json: true}, (err, r, data) ->
if err
res.send "Too busy coding to generate a message"
else
res.send "#{data}"
yoloRespond = (res) ->
res.send "alias yolo='git commit -am \"DEAL WITH IT\" && git push -f origin master'"
rememberPastRespond = (res) ->
rememberPast()
res.send "All memories have been gathered!"
statsRespond = (res) ->
stats = "Memories made:\n"
for person in Object.keys(memories)
stats = stats + "#{person}: " + memories[person].length + "\n"
res.send stats
saveQuotes = (nostalgiaName) ->
quotePath = "#{memoryDir}/#{nostalgiaName}"
quotes = memories[nostalgiaName]
# Write entire list of quotes to quotePath
fs.writeFileSync(quotePath, '')
for q in quotes
do (q) ->
fs.appendFileSync(quotePath, "#{q}\n")
rememberPerson = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
newQuote = res.match[2]
# Filter out @all's
newQuote = newQuote.replace(/@all/g, "[at]all")
# Make sure the messages don't contain non-alphabetical characters
if /.*[^a-zA-Z_0-9 @].*/.test(nostalgiaName)
res.send "I can't remember names with fancy symbols and characters"
else
if !(nostalgiaName of memories)
memories[nostalgiaName] = []
# Add new quote if it does not exist
quotes = memories[nostalgiaName]
if (quotes.indexOf(newQuote) < 0)
quotes.push(newQuote)
memories[nostalgiaName] = quotes
saveQuotes(nostalgiaName)
res.send "Memory stored!"
rememberPast()
# Admin functions
forgetPersonRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
# Delete the file with memories
quotePath = "#{memoryDir}/#{nostalgiaName}"
fs.unlinkSync(quotePath)
rememberPast()
res.send "#{nostalgiaName} forgotten forever :'("
forgetMemoryRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
quoteToForget = res.match[2]
if ! (quoteToForget in memories[nostalgiaName])
res.send "I don't remember #{nostalgiaName} saying \"#{quoteToForget}\""
return
memories[nostalgiaName].splice(memories[nostalgiaName].indexOf(quoteToForget), 1)
saveQuotes(nostalgiaName)
rememberPast()
res.send "Forgot that #{nostalgiaName} said \"#{quoteToForget}\""
reattributeRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
quote = res.match[1]
oldName = res.match[2].toLowerCase().trim()
if ! (oldName of memories)
res.send "I don't remember #{oldName}"
return
if ! (quote in memories[oldName])
res.send "I don't remember #{oldName} saying \"#{quote}\""
return
newName = res.match[3].toLowerCase().trim()
if ! (newName of memories)
res.send "I don't remember #{newName}"
return
# Actually move the quote over
memories[oldName].splice(memories[oldName].indexOf(quote), 1)
if (memories[newName].indexOf(quote) < 0)
memories[newName].push(quote)
saveQuotes(oldName)
saveQuotes(newName)
rememberPast()
res.send "Quote \"#{quote}\" reattributed from #{oldName} to #{newName}"
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
startGuessWhoRespond = (res) ->
guessWhoPlaying = true
res.send "Guess Who game started!"
guessWhoTarget = res.random Object.keys(memories)
guessWhoQuote = res.random memories[guessWhoTarget]
res.send "Who said \"#{guessWhoQuote}\"?"
showGuessWhoQuoteRespond = (res) ->
if guessWhoPlaying
res.send "Who said \"#{guessWhoQuote}\"?"
else
res.send "You are not playing Guess Who right now"
guessRespond = (res) ->
senderName = res.message.user.name
guess = res.match[1].toLowerCase().trim()
if guessWhoPlaying
if guess == guessWhoTarget
res.send "Correct! #{toTitleCase senderName} correctly guessed that #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond res
else
res.send "Wrong! Try again"
else
res.send "You are not playing Guess Who right now"
endGuessWhoRespond = (res) ->
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
res.send "Guess Who game over"
giveUpRespond = (res) ->
res.send "You gave up! #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond(res)
bobRossOnVacation = false
returnFromVacation = () ->
bobRossOnVacation = false
bobRossRespond = (res) ->
if !(bobRossOnVacation)
res.send "There are no bugs, just happy little accidents!"
res.send "http://s.newsweek.com/sites/www.newsweek.com/files/2014/09/29/1003bobrosstoc.jpg"
bobRossOnVacation = true
setTimeout(returnFromVacation, 3600000) # 1h
whoDoYouRememberRespond = (res) ->
res.send Object.keys(memories)
nostalgiaphoneRespond = (res) ->
res.send 'You rang?'
greetingRespond = (res) ->
res.send "#{rg.greet()} @#{res.message.user.name}!"
quoteOfTheDaySend = (robot) ->
return () ->
qotd = 'Here is your Quote Of The Day™!\n\n'
names = Object.keys(memories)
randomName = names[Math.round(Math.random() * (names.length - 1))]
quotes = memories[randomName]
randomQuote = quotes[Math.round(Math.random() * (quotes.length - 1))]
qotd += "\"#{randomQuote}\" - #{randomName}"
robot.send room: process.env.GENERAL_ROOM_ID, qotd
qotdScheduleRespond = (res) ->
res.send """
#{process.env.QOTD_SCHEDULE.replace(/\ /g, '\t')}
┬\t┬\t┬\t┬\t┬\t┬
|\t│\t│\t│\t│\t|
│\t│\t│\t│\t│\t└ day of week (0 - 7) (0 or 7 is Sun)
│\t│\t│\t│\t└─── month (1 - 12)
│\t│\t│\t└────── day of month (1 - 31)
│\t│\t└───────── hour (0 - 23)
│\t└──────────── minute (0 - 59)
└─────────────── second (0 - 59, OPTIONAL)
"""
module.exports = (robot) ->
robot.respond /Remember +(?:that )?(.+) +said +"([^"]+)"/i, rememberPerson
robot.respond /Remember +(?:that )?(.+) +said +“([^“”]+)”/i, rememberPerson
# Admin functions
robot.respond /Forget (\S+)$/i, forgetPersonRespond
robot.respond /Forget that (.+) +said +"([^"]+)"$/i, forgetMemoryRespond
robot.respond /Reattribute "([^"]+)" from (.+) to (.+)/i, reattributeRespond
robot.respond /Remind @?(.+) of (.+)/i, remindRespond
robot.respond /Quote (.+)/i, quoteRespond
robot.respond /Random quote/i, randomNameAndQuoteRespond
robot.respond /Converse (\S+)( *, *.+)+/i, convoRespond
robot.respond /Alias (\S+) as ( *.+)+/i, aliasRespond
robot.respond /Hacker me/i, hackerRespond
robot.respond /Commit message me/i, commitMessageRespond
robot.respond /YOLO/i, yoloRespond
robot.respond /Who do you remember\??/i, whoDoYouRememberRespond
robot.respond /Remember Past/i, rememberPastRespond
robot.respond /stats/i, statsRespond
robot.respond /( +\?)/i, nostalgiaphoneRespond
robot.respond /start guess who/i, startGuessWhoRespond
robot.respond /show guess who/i, showGuessWhoQuoteRespond
robot.respond /guess (.*)/i, guessRespond
robot.respond /end guess who/i, endGuessWhoRespond
robot.respond /give up/i, giveUpRespond
robot.hear /.*that's a bug.*/i, bobRossRespond
robot.hear /.*(guten tag|hallo|hola|Góðan daginn|good morning|morning|sup|hey|hello|howdy|greetings|yo|hiya|welcome|bonjour|buenas dias|buenas noches|good day|what's up|what's happening|how goes it|howdy do|shalom),? +@?nostalgiabot!?.*/i, greetingRespond
# Schedule a quote of the day
schedule.scheduleJob process.env.QOTD_SCHEDULE, quoteOfTheDaySend(robot)
robot.respond /qotd/i, qotdScheduleRespond
| 176407 | # Description:
# Remember past employees that you miss.
#
# Commands:
# nostalgiabot Remind (me|<person>) of <person> - Digs up a memorable quote from the past, and remind the person.
# nostalgiabot Quote <person> - Digs up a memorable quote from the past.
# nostalgiabot Random quote - Dig up random memory from random person
# nostalgiabot Remember that <person> said "<quote>" - Stores a new quote, to forever remain in the planes of Nostalgia.
# nostalgiabot Who do you remember? - See the memories the NostalgiaBot holds on to.
# nostalgiabot Converse <person1>, <person2> [, <person3>...] - Start a nonsensical convo
# nostalgiabot Alias <name> as <alias1> [<alias2> ...] - Add nicknames to the memorees
# nostalgiabot Start Guess Who - Start a game of Guess Who!
# nostalgiabot Show Guess Who - Show the current quote to guess
# nostalgiabot Guess <person> - Guess who said the current quote. Ends when guessed correctly.
# nostalgiabot End Guess Who - End the game of Guess Who!.
# nostalgiabot Give up - End the game of Guess Who! and get the answer.
# nostalgiabot Hacker me - Get a 100% real quote from a professional hacker.
# nostalgiabot Commit message me - Generate your next commit message
# nostalgiabot Remember past - Gather memories from the past
# nostalgiabot stats - See how memorable everyone is
# nostalgiabot ? - Ring the nostalgiaphone
#
# Author:
# <NAME>
fs = require 'fs'
request = require 'request'
rg = require 'random-greetings'
schedule = require 'node-schedule'
adminsFile = 'admins.json'
loadFile = (fileName) ->
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
admins = loadFile(adminsFile)
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) ->
txt[0].toUpperCase() + txt[1..txt.length - 1].toLowerCase()
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
memoryDir = "./memories"
weekday = new Array(7);
weekday[0]= "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
memories = {}
rememberPast = () ->
memories = {}
quoteFiles = fs.readdirSync memoryDir
for quoteFile in quoteFiles
do (quoteFile) ->
name = "#{quoteFile}".toString().toLowerCase().trim()
quotes = (fs.readFileSync "#{memoryDir}/#{quoteFile}", 'utf8').toString().split("\n").filter(Boolean)
memories[name] = quotes
rememberPast()
randomQuoteRespond = (res, nostalgiaName, targetName) ->
displayName = toTitleCase(nostalgiaName)
if ! (nostalgiaName of memories)
res.send "I don't remember #{displayName}"
return
randomQuote = (res.random memories[nostalgiaName])
if ! randomQuote
res.send "No memories to remember"
return
if (randomQuote.indexOf('$current_day') > 0)
d = new Date()
randomQuote = randomQuote.replace('$current_day', weekday[d.getDay()])
response = if isUndefined(targetName) then '' else "@#{targetName} Do you remember this?\n\n"
response += "\"#{randomQuote}\" - #{displayName}"
res.send response
remindRespond = (res) ->
targetName = res.match[1].toLowerCase().trim()
nostalgiaName = res.match[2].toLowerCase().trim()
if targetName.toLowerCase() == 'me'
targetName = res.message.user.name
randomQuoteRespond(res, nostalgiaName, targetName)
quoteRespond = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
randomQuoteRespond(res, nostalgiaName)
randomNameAndQuoteRespond = (res) ->
nostalgiaName = res.random Object.keys(memories)
randomQuoteRespond(res, nostalgiaName)
shuffleNames = (names) ->
i = names.length
while --i
j = Math.floor(Math.random() * (i+1))
[names[i], names[j]] = [names[j], names[i]] # use pattern matching to swap
return names
convoRespond = (res) ->
allNames = (res.match[1].toLowerCase().trim() + " " + res.match[2].toLowerCase().trim()).split(",")
fixedNames = []
for name in allNames
name = name.toLowerCase().trim()
# Remove @s at the front
if name[0] == '@'
name = name.substr(1)
fixedNames.push name
allNames = fixedNames
# Generate quotes
convoMap = {}
for name in allNames
if !(name of memories)
res.send "I don't recognize #{name}"
return
firstQuote = (res.random memories[name])
secondQuote = (res.random memories[name])
if memories[name].length > 1
while secondQuote == firstQuote
secondQuote = (res.random memories[name])
personQuotes = []
personQuotes.push "#{name}: " + firstQuote
personQuotes.push "#{name}: " + secondQuote
convoMap[name] = personQuotes
allNames = Object.keys(convoMap)
# Assemble quotes
convo = ""
lastName = ""
i = 2
while i--
allNames = shuffleNames(allNames)
while allNames[0] == lastName && allNames.length > 1
allNames = shuffleNames(allNames)
lastName = allNames[allNames.length-1]
for name in allNames
convo += convoMap[name][i] + "\n"
res.send convo
aliasRespond = (res) ->
regularName = res.match[1].toLowerCase().trim()
aliases = res.match[2].toLowerCase().trim().split(" ")
if !(regularName of memories)
res.send "Could not find #{regularName} in vast memory bank"
return
for alias in aliases
if alias of memories
res.send "Alias \"#{alias}\" already exists as a separate memory"
else
process.chdir(memoryDir)
fs.symlinkSync(regularName, alias)
res.send "Aliased #{regularName} as #{alias}!"
process.chdir('..')
rememberPast()
hackerRespond = (res) ->
hackerUrl = "https://hacker.actor/quote"
request.get {uri:"#{hackerUrl}", json: true}, (err, r, data) ->
if err
res.send "The Hackers are too busy stealing your data to provide a quote"
else
res.send "\"#{data.quote}\" - l33t h4xx0r"
commitMessageRespond = (res) ->
commitMessageUrl = "http://www.whatthecommit.com/index.txt"
request.get {uri:"#{commitMessageUrl}", json: true}, (err, r, data) ->
if err
res.send "Too busy coding to generate a message"
else
res.send "#{data}"
yoloRespond = (res) ->
res.send "alias yolo='git commit -am \"DEAL WITH IT\" && git push -f origin master'"
rememberPastRespond = (res) ->
rememberPast()
res.send "All memories have been gathered!"
statsRespond = (res) ->
stats = "Memories made:\n"
for person in Object.keys(memories)
stats = stats + "#{person}: " + memories[person].length + "\n"
res.send stats
saveQuotes = (nostalgiaName) ->
quotePath = "#{memoryDir}/#{nostalgiaName}"
quotes = memories[nostalgiaName]
# Write entire list of quotes to quotePath
fs.writeFileSync(quotePath, '')
for q in quotes
do (q) ->
fs.appendFileSync(quotePath, "#{q}\n")
rememberPerson = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
newQuote = res.match[2]
# Filter out @all's
newQuote = newQuote.replace(/@all/g, "[at]all")
# Make sure the messages don't contain non-alphabetical characters
if /.*[^a-zA-Z_0-9 @].*/.test(nostalgiaName)
res.send "I can't remember names with fancy symbols and characters"
else
if !(nostalgiaName of memories)
memories[nostalgiaName] = []
# Add new quote if it does not exist
quotes = memories[nostalgiaName]
if (quotes.indexOf(newQuote) < 0)
quotes.push(newQuote)
memories[nostalgiaName] = quotes
saveQuotes(nostalgiaName)
res.send "Memory stored!"
rememberPast()
# Admin functions
forgetPersonRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
# Delete the file with memories
quotePath = "#{memoryDir}/#{nostalgiaName}"
fs.unlinkSync(quotePath)
rememberPast()
res.send "#{nostalgiaName} forgotten forever :'("
forgetMemoryRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
quoteToForget = res.match[2]
if ! (quoteToForget in memories[nostalgiaName])
res.send "I don't remember #{nostalgiaName} saying \"#{quoteToForget}\""
return
memories[nostalgiaName].splice(memories[nostalgiaName].indexOf(quoteToForget), 1)
saveQuotes(nostalgiaName)
rememberPast()
res.send "Forgot that #{nostalgiaName} said \"#{quoteToForget}\""
reattributeRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
quote = res.match[1]
oldName = res.match[2].toLowerCase().trim()
if ! (oldName of memories)
res.send "I don't remember #{oldName}"
return
if ! (quote in memories[oldName])
res.send "I don't remember #{oldName} saying \"#{quote}\""
return
newName = res.match[3].toLowerCase().trim()
if ! (newName of memories)
res.send "I don't remember #{newName}"
return
# Actually move the quote over
memories[oldName].splice(memories[oldName].indexOf(quote), 1)
if (memories[newName].indexOf(quote) < 0)
memories[newName].push(quote)
saveQuotes(oldName)
saveQuotes(newName)
rememberPast()
res.send "Quote \"#{quote}\" reattributed from #{oldName} to #{newName}"
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
startGuessWhoRespond = (res) ->
guessWhoPlaying = true
res.send "Guess Who game started!"
guessWhoTarget = res.random Object.keys(memories)
guessWhoQuote = res.random memories[guessWhoTarget]
res.send "Who said \"#{guessWhoQuote}\"?"
showGuessWhoQuoteRespond = (res) ->
if guessWhoPlaying
res.send "Who said \"#{guessWhoQuote}\"?"
else
res.send "You are not playing Guess Who right now"
guessRespond = (res) ->
senderName = res.message.user.name
guess = res.match[1].toLowerCase().trim()
if guessWhoPlaying
if guess == guessWhoTarget
res.send "Correct! #{toTitleCase senderName} correctly guessed that #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond res
else
res.send "Wrong! Try again"
else
res.send "You are not playing Guess Who right now"
endGuessWhoRespond = (res) ->
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
res.send "Guess Who game over"
giveUpRespond = (res) ->
res.send "You gave up! #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond(res)
bobRossOnVacation = false
returnFromVacation = () ->
bobRossOnVacation = false
bobRossRespond = (res) ->
if !(bobRossOnVacation)
res.send "There are no bugs, just happy little accidents!"
res.send "http://s.newsweek.com/sites/www.newsweek.com/files/2014/09/29/1003bobrosstoc.jpg"
bobRossOnVacation = true
setTimeout(returnFromVacation, 3600000) # 1h
whoDoYouRememberRespond = (res) ->
res.send Object.keys(memories)
nostalgiaphoneRespond = (res) ->
res.send 'You rang?'
greetingRespond = (res) ->
res.send "#{rg.greet()} @#{res.message.user.name}!"
quoteOfTheDaySend = (robot) ->
return () ->
qotd = 'Here is your Quote Of The Day™!\n\n'
names = Object.keys(memories)
randomName = names[Math.round(Math.random() * (names.length - 1))]
quotes = memories[randomName]
randomQuote = quotes[Math.round(Math.random() * (quotes.length - 1))]
qotd += "\"#{randomQuote}\" - #{randomName}"
robot.send room: process.env.GENERAL_ROOM_ID, qotd
qotdScheduleRespond = (res) ->
res.send """
#{process.env.QOTD_SCHEDULE.replace(/\ /g, '\t')}
┬\t┬\t┬\t┬\t┬\t┬
|\t│\t│\t│\t│\t|
│\t│\t│\t│\t│\t└ day of week (0 - 7) (0 or 7 is Sun)
│\t│\t│\t│\t└─── month (1 - 12)
│\t│\t│\t└────── day of month (1 - 31)
│\t│\t└───────── hour (0 - 23)
│\t└──────────── minute (0 - 59)
└─────────────── second (0 - 59, OPTIONAL)
"""
module.exports = (robot) ->
robot.respond /Remember +(?:that )?(.+) +said +"([^"]+)"/i, rememberPerson
robot.respond /Remember +(?:that )?(.+) +said +“([^“”]+)”/i, rememberPerson
# Admin functions
robot.respond /Forget (\S+)$/i, forgetPersonRespond
robot.respond /Forget that (.+) +said +"([^"]+)"$/i, forgetMemoryRespond
robot.respond /Reattribute "([^"]+)" from (.+) to (.+)/i, reattributeRespond
robot.respond /Remind @?(.+) of (.+)/i, remindRespond
robot.respond /Quote (.+)/i, quoteRespond
robot.respond /Random quote/i, randomNameAndQuoteRespond
robot.respond /Converse (\S+)( *, *.+)+/i, convoRespond
robot.respond /Alias (\S+) as ( *.+)+/i, aliasRespond
robot.respond /Hacker me/i, hackerRespond
robot.respond /Commit message me/i, commitMessageRespond
robot.respond /YOLO/i, yoloRespond
robot.respond /Who do you remember\??/i, whoDoYouRememberRespond
robot.respond /Remember Past/i, rememberPastRespond
robot.respond /stats/i, statsRespond
robot.respond /( +\?)/i, nostalgiaphoneRespond
robot.respond /start guess who/i, startGuessWhoRespond
robot.respond /show guess who/i, showGuessWhoQuoteRespond
robot.respond /guess (.*)/i, guessRespond
robot.respond /end guess who/i, endGuessWhoRespond
robot.respond /give up/i, giveUpRespond
robot.hear /.*that's a bug.*/i, bobRossRespond
robot.hear /.*(guten tag|hallo|hola|Góðan daginn|good morning|morning|sup|hey|hello|howdy|greetings|yo|hiya|welcome|bonjour|buenas dias|buenas noches|good day|what's up|what's happening|how goes it|howdy do|shalom),? +@?nostalgiabot!?.*/i, greetingRespond
# Schedule a quote of the day
schedule.scheduleJob process.env.QOTD_SCHEDULE, quoteOfTheDaySend(robot)
robot.respond /qotd/i, qotdScheduleRespond
| true | # Description:
# Remember past employees that you miss.
#
# Commands:
# nostalgiabot Remind (me|<person>) of <person> - Digs up a memorable quote from the past, and remind the person.
# nostalgiabot Quote <person> - Digs up a memorable quote from the past.
# nostalgiabot Random quote - Dig up random memory from random person
# nostalgiabot Remember that <person> said "<quote>" - Stores a new quote, to forever remain in the planes of Nostalgia.
# nostalgiabot Who do you remember? - See the memories the NostalgiaBot holds on to.
# nostalgiabot Converse <person1>, <person2> [, <person3>...] - Start a nonsensical convo
# nostalgiabot Alias <name> as <alias1> [<alias2> ...] - Add nicknames to the memorees
# nostalgiabot Start Guess Who - Start a game of Guess Who!
# nostalgiabot Show Guess Who - Show the current quote to guess
# nostalgiabot Guess <person> - Guess who said the current quote. Ends when guessed correctly.
# nostalgiabot End Guess Who - End the game of Guess Who!.
# nostalgiabot Give up - End the game of Guess Who! and get the answer.
# nostalgiabot Hacker me - Get a 100% real quote from a professional hacker.
# nostalgiabot Commit message me - Generate your next commit message
# nostalgiabot Remember past - Gather memories from the past
# nostalgiabot stats - See how memorable everyone is
# nostalgiabot ? - Ring the nostalgiaphone
#
# Author:
# PI:NAME:<NAME>END_PI
fs = require 'fs'
request = require 'request'
rg = require 'random-greetings'
schedule = require 'node-schedule'
adminsFile = 'admins.json'
loadFile = (fileName) ->
return JSON.parse((fs.readFileSync fileName, 'utf8').toString().trim())
admins = loadFile(adminsFile)
toTitleCase = (str) ->
str.replace /\w\S*/g, (txt) ->
txt[0].toUpperCase() + txt[1..txt.length - 1].toLowerCase()
isUndefined = (myvar) ->
return typeof myvar == 'undefined'
memoryDir = "./memories"
weekday = new Array(7);
weekday[0]= "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
memories = {}
rememberPast = () ->
memories = {}
quoteFiles = fs.readdirSync memoryDir
for quoteFile in quoteFiles
do (quoteFile) ->
name = "#{quoteFile}".toString().toLowerCase().trim()
quotes = (fs.readFileSync "#{memoryDir}/#{quoteFile}", 'utf8').toString().split("\n").filter(Boolean)
memories[name] = quotes
rememberPast()
randomQuoteRespond = (res, nostalgiaName, targetName) ->
displayName = toTitleCase(nostalgiaName)
if ! (nostalgiaName of memories)
res.send "I don't remember #{displayName}"
return
randomQuote = (res.random memories[nostalgiaName])
if ! randomQuote
res.send "No memories to remember"
return
if (randomQuote.indexOf('$current_day') > 0)
d = new Date()
randomQuote = randomQuote.replace('$current_day', weekday[d.getDay()])
response = if isUndefined(targetName) then '' else "@#{targetName} Do you remember this?\n\n"
response += "\"#{randomQuote}\" - #{displayName}"
res.send response
remindRespond = (res) ->
targetName = res.match[1].toLowerCase().trim()
nostalgiaName = res.match[2].toLowerCase().trim()
if targetName.toLowerCase() == 'me'
targetName = res.message.user.name
randomQuoteRespond(res, nostalgiaName, targetName)
quoteRespond = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
randomQuoteRespond(res, nostalgiaName)
randomNameAndQuoteRespond = (res) ->
nostalgiaName = res.random Object.keys(memories)
randomQuoteRespond(res, nostalgiaName)
shuffleNames = (names) ->
i = names.length
while --i
j = Math.floor(Math.random() * (i+1))
[names[i], names[j]] = [names[j], names[i]] # use pattern matching to swap
return names
convoRespond = (res) ->
allNames = (res.match[1].toLowerCase().trim() + " " + res.match[2].toLowerCase().trim()).split(",")
fixedNames = []
for name in allNames
name = name.toLowerCase().trim()
# Remove @s at the front
if name[0] == '@'
name = name.substr(1)
fixedNames.push name
allNames = fixedNames
# Generate quotes
convoMap = {}
for name in allNames
if !(name of memories)
res.send "I don't recognize #{name}"
return
firstQuote = (res.random memories[name])
secondQuote = (res.random memories[name])
if memories[name].length > 1
while secondQuote == firstQuote
secondQuote = (res.random memories[name])
personQuotes = []
personQuotes.push "#{name}: " + firstQuote
personQuotes.push "#{name}: " + secondQuote
convoMap[name] = personQuotes
allNames = Object.keys(convoMap)
# Assemble quotes
convo = ""
lastName = ""
i = 2
while i--
allNames = shuffleNames(allNames)
while allNames[0] == lastName && allNames.length > 1
allNames = shuffleNames(allNames)
lastName = allNames[allNames.length-1]
for name in allNames
convo += convoMap[name][i] + "\n"
res.send convo
aliasRespond = (res) ->
regularName = res.match[1].toLowerCase().trim()
aliases = res.match[2].toLowerCase().trim().split(" ")
if !(regularName of memories)
res.send "Could not find #{regularName} in vast memory bank"
return
for alias in aliases
if alias of memories
res.send "Alias \"#{alias}\" already exists as a separate memory"
else
process.chdir(memoryDir)
fs.symlinkSync(regularName, alias)
res.send "Aliased #{regularName} as #{alias}!"
process.chdir('..')
rememberPast()
hackerRespond = (res) ->
hackerUrl = "https://hacker.actor/quote"
request.get {uri:"#{hackerUrl}", json: true}, (err, r, data) ->
if err
res.send "The Hackers are too busy stealing your data to provide a quote"
else
res.send "\"#{data.quote}\" - l33t h4xx0r"
commitMessageRespond = (res) ->
commitMessageUrl = "http://www.whatthecommit.com/index.txt"
request.get {uri:"#{commitMessageUrl}", json: true}, (err, r, data) ->
if err
res.send "Too busy coding to generate a message"
else
res.send "#{data}"
yoloRespond = (res) ->
res.send "alias yolo='git commit -am \"DEAL WITH IT\" && git push -f origin master'"
rememberPastRespond = (res) ->
rememberPast()
res.send "All memories have been gathered!"
statsRespond = (res) ->
stats = "Memories made:\n"
for person in Object.keys(memories)
stats = stats + "#{person}: " + memories[person].length + "\n"
res.send stats
saveQuotes = (nostalgiaName) ->
quotePath = "#{memoryDir}/#{nostalgiaName}"
quotes = memories[nostalgiaName]
# Write entire list of quotes to quotePath
fs.writeFileSync(quotePath, '')
for q in quotes
do (q) ->
fs.appendFileSync(quotePath, "#{q}\n")
rememberPerson = (res) ->
nostalgiaName = res.match[1].toLowerCase().trim()
newQuote = res.match[2]
# Filter out @all's
newQuote = newQuote.replace(/@all/g, "[at]all")
# Make sure the messages don't contain non-alphabetical characters
if /.*[^a-zA-Z_0-9 @].*/.test(nostalgiaName)
res.send "I can't remember names with fancy symbols and characters"
else
if !(nostalgiaName of memories)
memories[nostalgiaName] = []
# Add new quote if it does not exist
quotes = memories[nostalgiaName]
if (quotes.indexOf(newQuote) < 0)
quotes.push(newQuote)
memories[nostalgiaName] = quotes
saveQuotes(nostalgiaName)
res.send "Memory stored!"
rememberPast()
# Admin functions
forgetPersonRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
# Delete the file with memories
quotePath = "#{memoryDir}/#{nostalgiaName}"
fs.unlinkSync(quotePath)
rememberPast()
res.send "#{nostalgiaName} forgotten forever :'("
forgetMemoryRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
nostalgiaName = res.match[1].toLowerCase().trim()
if ! (nostalgiaName of memories)
res.send "I don't remember #{nostalgiaName}"
return
quoteToForget = res.match[2]
if ! (quoteToForget in memories[nostalgiaName])
res.send "I don't remember #{nostalgiaName} saying \"#{quoteToForget}\""
return
memories[nostalgiaName].splice(memories[nostalgiaName].indexOf(quoteToForget), 1)
saveQuotes(nostalgiaName)
rememberPast()
res.send "Forgot that #{nostalgiaName} said \"#{quoteToForget}\""
reattributeRespond = (res) ->
senderName = res.message.user.name
if ! (senderName in admins)
res.send "You must be an admin to perform this function"
return
quote = res.match[1]
oldName = res.match[2].toLowerCase().trim()
if ! (oldName of memories)
res.send "I don't remember #{oldName}"
return
if ! (quote in memories[oldName])
res.send "I don't remember #{oldName} saying \"#{quote}\""
return
newName = res.match[3].toLowerCase().trim()
if ! (newName of memories)
res.send "I don't remember #{newName}"
return
# Actually move the quote over
memories[oldName].splice(memories[oldName].indexOf(quote), 1)
if (memories[newName].indexOf(quote) < 0)
memories[newName].push(quote)
saveQuotes(oldName)
saveQuotes(newName)
rememberPast()
res.send "Quote \"#{quote}\" reattributed from #{oldName} to #{newName}"
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
startGuessWhoRespond = (res) ->
guessWhoPlaying = true
res.send "Guess Who game started!"
guessWhoTarget = res.random Object.keys(memories)
guessWhoQuote = res.random memories[guessWhoTarget]
res.send "Who said \"#{guessWhoQuote}\"?"
showGuessWhoQuoteRespond = (res) ->
if guessWhoPlaying
res.send "Who said \"#{guessWhoQuote}\"?"
else
res.send "You are not playing Guess Who right now"
guessRespond = (res) ->
senderName = res.message.user.name
guess = res.match[1].toLowerCase().trim()
if guessWhoPlaying
if guess == guessWhoTarget
res.send "Correct! #{toTitleCase senderName} correctly guessed that #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond res
else
res.send "Wrong! Try again"
else
res.send "You are not playing Guess Who right now"
endGuessWhoRespond = (res) ->
guessWhoPlaying = false
guessWhoTarget = ''
guessWhoQuote = ''
res.send "Guess Who game over"
giveUpRespond = (res) ->
res.send "You gave up! #{toTitleCase guessWhoTarget} said \"#{guessWhoQuote}\""
endGuessWhoRespond(res)
bobRossOnVacation = false
returnFromVacation = () ->
bobRossOnVacation = false
bobRossRespond = (res) ->
if !(bobRossOnVacation)
res.send "There are no bugs, just happy little accidents!"
res.send "http://s.newsweek.com/sites/www.newsweek.com/files/2014/09/29/1003bobrosstoc.jpg"
bobRossOnVacation = true
setTimeout(returnFromVacation, 3600000) # 1h
whoDoYouRememberRespond = (res) ->
res.send Object.keys(memories)
nostalgiaphoneRespond = (res) ->
res.send 'You rang?'
greetingRespond = (res) ->
res.send "#{rg.greet()} @#{res.message.user.name}!"
quoteOfTheDaySend = (robot) ->
return () ->
qotd = 'Here is your Quote Of The Day™!\n\n'
names = Object.keys(memories)
randomName = names[Math.round(Math.random() * (names.length - 1))]
quotes = memories[randomName]
randomQuote = quotes[Math.round(Math.random() * (quotes.length - 1))]
qotd += "\"#{randomQuote}\" - #{randomName}"
robot.send room: process.env.GENERAL_ROOM_ID, qotd
qotdScheduleRespond = (res) ->
res.send """
#{process.env.QOTD_SCHEDULE.replace(/\ /g, '\t')}
┬\t┬\t┬\t┬\t┬\t┬
|\t│\t│\t│\t│\t|
│\t│\t│\t│\t│\t└ day of week (0 - 7) (0 or 7 is Sun)
│\t│\t│\t│\t└─── month (1 - 12)
│\t│\t│\t└────── day of month (1 - 31)
│\t│\t└───────── hour (0 - 23)
│\t└──────────── minute (0 - 59)
└─────────────── second (0 - 59, OPTIONAL)
"""
module.exports = (robot) ->
robot.respond /Remember +(?:that )?(.+) +said +"([^"]+)"/i, rememberPerson
robot.respond /Remember +(?:that )?(.+) +said +“([^“”]+)”/i, rememberPerson
# Admin functions
robot.respond /Forget (\S+)$/i, forgetPersonRespond
robot.respond /Forget that (.+) +said +"([^"]+)"$/i, forgetMemoryRespond
robot.respond /Reattribute "([^"]+)" from (.+) to (.+)/i, reattributeRespond
robot.respond /Remind @?(.+) of (.+)/i, remindRespond
robot.respond /Quote (.+)/i, quoteRespond
robot.respond /Random quote/i, randomNameAndQuoteRespond
robot.respond /Converse (\S+)( *, *.+)+/i, convoRespond
robot.respond /Alias (\S+) as ( *.+)+/i, aliasRespond
robot.respond /Hacker me/i, hackerRespond
robot.respond /Commit message me/i, commitMessageRespond
robot.respond /YOLO/i, yoloRespond
robot.respond /Who do you remember\??/i, whoDoYouRememberRespond
robot.respond /Remember Past/i, rememberPastRespond
robot.respond /stats/i, statsRespond
robot.respond /( +\?)/i, nostalgiaphoneRespond
robot.respond /start guess who/i, startGuessWhoRespond
robot.respond /show guess who/i, showGuessWhoQuoteRespond
robot.respond /guess (.*)/i, guessRespond
robot.respond /end guess who/i, endGuessWhoRespond
robot.respond /give up/i, giveUpRespond
robot.hear /.*that's a bug.*/i, bobRossRespond
robot.hear /.*(guten tag|hallo|hola|Góðan daginn|good morning|morning|sup|hey|hello|howdy|greetings|yo|hiya|welcome|bonjour|buenas dias|buenas noches|good day|what's up|what's happening|how goes it|howdy do|shalom),? +@?nostalgiabot!?.*/i, greetingRespond
# Schedule a quote of the day
schedule.scheduleJob process.env.QOTD_SCHEDULE, quoteOfTheDaySend(robot)
robot.respond /qotd/i, qotdScheduleRespond
|
[
{
"context": "object hash ', (done) ->\n @create(name: \"Héllo & gøød nîght\").then (createdObject) ->\n ",
"end": 2661,
"score": 0.9997814893722534,
"start": 2656,
"tag": "NAME",
"value": "Héllo"
},
{
"context": "sh ', (done) ->\n @create(name: \"Héllo & g... | spec/adaptorMethods/createSpec.coffee | Kenspeckled/oomph-redis-adaptor | 0 | create = require '../../src/adaptorMethods/create'
Promise = require 'promise'
ValidationError = require 'oomph/lib/ValidationError'
_ = require 'lodash'
redis = require 'redis'
describe 'oomphRedisAdaptor#create', ->
beforeAll (done) ->
@redis = redis.createClient(1111, 'localhost')
done()
beforeEach ->
@parentObject =
className: 'TestCreateClass'
redis: @redis
classAttributes:
name:
dataType: 'string'
url:
dataType: 'string'
url: true
urlBaseAttribute: 'name'
one:
dataType: 'integer'
sortable: true
two:
dataType: 'integer'
sortable: true
three:
dataType: 'integer'
sortable: true
integer:
dataType: 'integer'
identifier:
dataType: 'string'
identifiable: true
reference:
dataType: 'reference'
referenceModelName: 'Reference'
manyReferences:
dataType: 'reference'
many: true
referenceModelName: 'Reference'
sortableString:
dataType: 'string'
sortable: true
sortableInteger:
dataType: 'integer'
sortable: true
searchableText:
dataType: 'text'
searchable: true
searchableString:
dataType: 'string'
searchable: true
boolean:
dataType: 'boolean'
@create = create.bind(@parentObject)
referenceModelparentObject =
className: 'Reference'
redis: @redis
classAttributes:
secondId:
dataType: 'string'
identifiable: true
@referenceModelCreate = create.bind(referenceModelparentObject)
afterEach (done) ->
@redis.flushdb()
done()
afterAll (done) ->
@redis.flushdb()
@redis.end()
done()
it 'should return a promise', ->
createPromise = @create(integer: 1)
expect(createPromise).toEqual jasmine.any(Promise)
describe 'stored data types', ->
describe 'for string attributes', ->
describe 'where identifiable is true', ->
it 'adds to a key-value pair', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(identifier: 'identifierValue').then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#identifier:identifierValue', createdObject.id)
done()
describe 'where url is true', ->
it 'stores the generated url string in the object hash ', (done) ->
@create(name: "Héllo & gøød nîght").then (createdObject) ->
expect(createdObject.url).toEqual 'hello-and-good-night'
done()
it 'adds to a key-value pair with a generated url string', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(name: "Héllo & gøød nîght").then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#url:hello-and-good-night', createdObject.id)
done()
it "appends a sequential number for duplicate generated url string", (done) ->
@create(name: "Héllo & gøød nîght").then (obj1) =>
@create(name: "Héllo & good night").then (obj2) =>
@create(name: "Hello & good night").then (obj3) ->
expect(obj1.url).toEqual 'hello-and-good-night'
expect(obj2.url).toEqual 'hello-and-good-night-1'
expect(obj3.url).toEqual 'hello-and-good-night-2'
done()
describe 'where sortable is true', ->
it 'adds to an ordered list', (done) ->
testPromise1 = @create( sortableString: 'd' )
testPromise2 = @create( sortableString: 'a' )
testPromise3 = @create( sortableString: 'c' )
testPromise4 = @create( sortableString: 'b' )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
test1Id = testObjectArray[0].id
test2Id = testObjectArray[1].id
test3Id = testObjectArray[2].id
test4Id = testObjectArray[3].id
@redis.zrange "TestCreateClass>sortableString", 0, -1, (error, list) ->
expect(list).toEqual [test1Id, test3Id, test4Id, test2Id]
done()
describe 'where searchable is true', ->
it 'adds to partial words sets when the modules class has attributes with the field type of "string" and is searchable', (done) ->
spyOn(@redis, 'zadd').and.callThrough()
@create(searchableText: 'Search This <div>funny</div>').then (createdObject) =>
calledArgs = @redis.zadd.calls.allArgs()
keysCalled = []
for call in calledArgs
keysCalled.push call[0]
expect(keysCalled).toContain('TestCreateClass#searchableText/s')
expect(keysCalled).toContain('TestCreateClass#searchableText/se')
expect(keysCalled).toContain('TestCreateClass#searchableText/sea')
expect(keysCalled).toContain('TestCreateClass#searchableText/sear')
expect(keysCalled).toContain('TestCreateClass#searchableText/search')
expect(keysCalled).toContain('TestCreateClass#searchableText/t')
expect(keysCalled).toContain('TestCreateClass#searchableText/th')
expect(keysCalled).toContain('TestCreateClass#searchableText/thi')
expect(keysCalled).toContain('TestCreateClass#searchableText/this')
expect(keysCalled).toContain('TestCreateClass#searchableText/funny')
expect(keysCalled).not.toContain('TestCreateClass#searchableText/<div>')
done()
describe 'for integer attributes', ->
# Integers are always sortable
it 'adds to a sorted set', (done) ->
testPromise1 = @create( integer: 11 )
testPromise2 = @create( integer: 8 )
testPromise3 = @create( integer: 10 )
testPromise4 = @create( integer: 9 )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
[test1, test2, test3, test4] = testObjectArray
@redis.zrange "TestCreateClass>integer", 0, -1, (error, list) ->
expect(list).toEqual [test2.id, test4.id, test3.id, test1.id]
done()
it 'adds to a sorted set with values', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(integer: 1).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass>integer', 1, createdObject.id)
done()
describe 'for boolean attributes', ->
it 'adds to a zset', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(boolean: true).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass#boolean:true', 1, createdObject.id)
done()
describe 'for reference attributes', ->
describe 'when many is true', ->
it "sets the reference to true", (done) ->
createReference = @referenceModelCreate(secondId: 'id1')
createTestObj = createReference.then (ref1) => @create(manyReferences: [ref1.id])
createTestObj.then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it "sets the reference to even when empty", (done) ->
@referenceModelCreate(secondId: 'id1').then (ref1) =>
@create(url: 'one').then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it 'adds to a set', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
@create = create.bind(@parentObject)
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#linkedModel:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#linkedModel:TestCreateClassRefs', createdObject.id)
done()
it 'adds to a set with a reverseReferenceAttribute', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
reverseReferenceAttribute: 'namespaced'
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create = create.bind(@parentObject)
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#namespaced:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#namespaced:TestCreateClassRefs', createdObject.id)
done()
describe 'when many is not true', ->
it 'stores the reference id', (done) ->
@referenceModelCreate(secondId: 'id1').done (ref1) =>
@create(reference: ref1.id).then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.reference).toEqual ref1.id
done()
it 'should return a promise', ->
testObjectPromise = @create(url: 'uniqueValue')
expect(testObjectPromise).toEqual jasmine.any(Promise)
it 'should resolve an object with a 10 character id', (done) ->
# This test will fail from Sun May 25 2059 18:38:27 BST (2821109907456 unix time)
# and the number of characters will increase by 1
testObjectPromise = @create(url: 'uniqueValue')
testObjectPromise.done (testObject) ->
expect(testObject.id.length).toEqual 10
done()
it "should create an object with properties that are defined in the class' attributes", (done) ->
testObjectPromise = @create(boolean: false)
testObjectPromise.then (testObject) ->
expect(testObject.boolean).toBe false
done()
it "should create an object and ignore properties that are not defined in the class' attributes", (done) ->
@create(notAnAttribute: 'value').catch (error) =>
expect(error).toEqual(new Error "No valid fields given")
done()
describe 'presence validation', ->
it 'should create objects that pass validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
validates:
presence: true
@create = create.bind(@parentObject)
@create(presenceValidation: 'value').then (testObject) =>
expect(testObject.presenceValidation).toEqual 'value'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
identifiable: true
validates:
presence: true
@create = create.bind(@parentObject)
@create(one: 1, presenceValidation: null).catch (errors) ->
expect(errors).toContain(new Error 'presenceValidation must be present')
done()
describe 'length validation', ->
it 'should not create objects that fail length validation by having a length that is greater than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: 'elevenchars').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should not create objects that fail length validation by having a length that is less than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'sixchr').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should create objects that have a length that is equal to the length validation', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'ninechars').then (testObject) ->
expect(testObject.lengthValidation).toEqual 'ninechars'
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: null).then (testObject) =>
expect(testObject.lengthValidation).toEqual undefined
done()
describe 'minimum length', ->
it 'should create objects that have a length that is equal to the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is greater than the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'elevenchars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'elevenchars'
done()
it 'should not create objects that fail minLength validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'sixchr').catch (error) =>
expect(error).toContain(new Error 'minLengthValidation should have a minimum length of 9')
done()
describe 'maximum length', ->
it 'should create objects that have a length that is equal to the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is less than the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'sixchr').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'sixchr'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'elevenchars').catch (error) =>
expect(error).toContain(new Error 'maxLengthValidation should have a maximum length of 9')
done()
describe 'greaterThan validation', ->
it 'should create objects that pass greaterThan validation', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 11).then (testObject) =>
expect(testObject.greaterThanValidation).toEqual 11
done()
it 'should not create objects that fail greaterThan validation by being less than', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 9')
done()
it 'should not create objects that fail greaterThan validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 10
@create = create.bind(@parentObject)
@create(greaterThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 10')
done()
describe 'greaterThanOrEqualTo validation', ->
it 'should create objects that pass greaterThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 10
done()
it 'should create objects that pass greaterThanOrEqualTo validation by being greater than', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 11).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 11
done()
it 'should not create objects that fail greaterThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanOrEqualToValidation should be greater than or equal to 10')
done()
describe 'lessThan validation', ->
it 'should create objects that pass lessThan validation', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 9).then (testObject) =>
expect(testObject.lessThanValidation).toEqual 9
done()
it 'should not create objects that fail lessThan validation by being more than', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
it 'should not create objects that fail lessThan validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
describe 'lessThanOrEqualTo validation', ->
it 'should create objects that pass lessThanOrEqualTo validation by being less than', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 9).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 9
done()
it 'should create objects that pass lessThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 10
done()
it 'should not create objects that fail lessThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanOrEqualToValidation should be less than or equal to 10')
done()
describe 'equalTo validation', ->
it 'should create objects that pass equalTo validation', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 10).then (testObject) =>
expect(testObject.equalToValidation).toEqual 10
done()
it 'should not create objects that fail equalTo validation by being more than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
it 'should not create objects that fail equalTo validation by being less than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 9).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
describe 'format validation', ->
describe "'with'", ->
it 'should not fail when the attribute is not present', (done) ->
pending()
it "should create objects that pass format validation 'with' a regular expression that accounts for all of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'abcd'
done()
it "should create objects that pass format validation 'with' a regular expression that only accounts for some of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'ab123cd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'ab123cd'
done()
it "should not create objects that fail format validation 'with' a regular expression", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').catch (error) =>
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(one: 1, formatValidation: null).then (testObject) =>
expect(testObject.formatValidation).toEqual undefined
done()
describe "'without'", ->
it "should not create objects that fail validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').catch (error) ->
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it "should create objects that pass format validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').then (testObject) =>
expect(testObject.formatValidation).toEqual '123'
done()
describe 'inclusionIn validation', ->
it 'should create objects that pass inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'one').then (testObject) =>
expect(testObject.inclusionInValidation).toEqual 'one'
done()
it 'should not create objects that fail inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'four').catch (error) =>
expect(error).toContain(new Error 'inclusionInValidation must be one of the accepted values')
done()
describe 'exclusionIn validation', ->
it 'should create objects that pass exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'four').then (testObject) =>
expect(testObject.exclusionInValidation).toEqual 'four'
done()
it 'should not create objects that fail exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'one').catch (error) =>
expect(error).toContain(new Error 'exclusionInValidation must not be one of the forbidden values')
done()
describe 'uniqueness validation', ->
it 'should not create objects that fail validation', (done) ->
pending()
@parentObject.classAttributes =
uniquenessValidation:
dataType: 'string'
identifiable: true
validates:
uniqueness: true
@create = create.bind(@parentObject)
@redis.set 'TestCreateClass#uniquenessValidation:notUnique', 'test', =>
@create(uniquenessValidation: 'notUnique').catch (errors) =>
expect(errors).toContain(new Error 'uniquenessValidation should be a unique value')
done()
describe 'afterSave', ->
it 'should perform an after save callback', (done) ->
pending()
@parentObject.afterSave = new Promise (resolve) ->
console.log "hiya!!!!!!"
resolve (4)
@create = create.bind(@parentObject)
@create(name: 'test').then (testObject) =>
expect()
done()
| 211141 | create = require '../../src/adaptorMethods/create'
Promise = require 'promise'
ValidationError = require 'oomph/lib/ValidationError'
_ = require 'lodash'
redis = require 'redis'
describe 'oomphRedisAdaptor#create', ->
beforeAll (done) ->
@redis = redis.createClient(1111, 'localhost')
done()
beforeEach ->
@parentObject =
className: 'TestCreateClass'
redis: @redis
classAttributes:
name:
dataType: 'string'
url:
dataType: 'string'
url: true
urlBaseAttribute: 'name'
one:
dataType: 'integer'
sortable: true
two:
dataType: 'integer'
sortable: true
three:
dataType: 'integer'
sortable: true
integer:
dataType: 'integer'
identifier:
dataType: 'string'
identifiable: true
reference:
dataType: 'reference'
referenceModelName: 'Reference'
manyReferences:
dataType: 'reference'
many: true
referenceModelName: 'Reference'
sortableString:
dataType: 'string'
sortable: true
sortableInteger:
dataType: 'integer'
sortable: true
searchableText:
dataType: 'text'
searchable: true
searchableString:
dataType: 'string'
searchable: true
boolean:
dataType: 'boolean'
@create = create.bind(@parentObject)
referenceModelparentObject =
className: 'Reference'
redis: @redis
classAttributes:
secondId:
dataType: 'string'
identifiable: true
@referenceModelCreate = create.bind(referenceModelparentObject)
afterEach (done) ->
@redis.flushdb()
done()
afterAll (done) ->
@redis.flushdb()
@redis.end()
done()
it 'should return a promise', ->
createPromise = @create(integer: 1)
expect(createPromise).toEqual jasmine.any(Promise)
describe 'stored data types', ->
describe 'for string attributes', ->
describe 'where identifiable is true', ->
it 'adds to a key-value pair', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(identifier: 'identifierValue').then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#identifier:identifierValue', createdObject.id)
done()
describe 'where url is true', ->
it 'stores the generated url string in the object hash ', (done) ->
@create(name: "<NAME> & g<NAME>îght").then (createdObject) ->
expect(createdObject.url).toEqual 'hello-and-good-night'
done()
it 'adds to a key-value pair with a generated url string', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(name: "<NAME> & g<NAME>î<NAME>").then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#url:hello-and-good-night', createdObject.id)
done()
it "appends a sequential number for duplicate generated url string", (done) ->
@create(name: "<NAME> & <NAME>").then (obj1) =>
@create(name: "<NAME> & good <NAME>").then (obj2) =>
@create(name: "Hello & good night").then (obj3) ->
expect(obj1.url).toEqual 'hello-and-good-night'
expect(obj2.url).toEqual 'hello-and-good-night-1'
expect(obj3.url).toEqual 'hello-and-good-night-2'
done()
describe 'where sortable is true', ->
it 'adds to an ordered list', (done) ->
testPromise1 = @create( sortableString: 'd' )
testPromise2 = @create( sortableString: 'a' )
testPromise3 = @create( sortableString: 'c' )
testPromise4 = @create( sortableString: 'b' )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
test1Id = testObjectArray[0].id
test2Id = testObjectArray[1].id
test3Id = testObjectArray[2].id
test4Id = testObjectArray[3].id
@redis.zrange "TestCreateClass>sortableString", 0, -1, (error, list) ->
expect(list).toEqual [test1Id, test3Id, test4Id, test2Id]
done()
describe 'where searchable is true', ->
it 'adds to partial words sets when the modules class has attributes with the field type of "string" and is searchable', (done) ->
spyOn(@redis, 'zadd').and.callThrough()
@create(searchableText: 'Search This <div>funny</div>').then (createdObject) =>
calledArgs = @redis.zadd.calls.allArgs()
keysCalled = []
for call in calledArgs
keysCalled.push call[0]
expect(keysCalled).toContain('TestCreateClass#searchableText/s')
expect(keysCalled).toContain('TestCreateClass#searchableText/se')
expect(keysCalled).toContain('TestCreateClass#searchableText/sea')
expect(keysCalled).toContain('TestCreateClass#searchableText/sear')
expect(keysCalled).toContain('TestCreateClass#searchableText/search')
expect(keysCalled).toContain('TestCreateClass#searchableText/t')
expect(keysCalled).toContain('TestCreateClass#searchableText/th')
expect(keysCalled).toContain('TestCreateClass#searchableText/thi')
expect(keysCalled).toContain('TestCreateClass#searchableText/this')
expect(keysCalled).toContain('TestCreateClass#searchableText/funny')
expect(keysCalled).not.toContain('TestCreateClass#searchableText/<div>')
done()
describe 'for integer attributes', ->
# Integers are always sortable
it 'adds to a sorted set', (done) ->
testPromise1 = @create( integer: 11 )
testPromise2 = @create( integer: 8 )
testPromise3 = @create( integer: 10 )
testPromise4 = @create( integer: 9 )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
[test1, test2, test3, test4] = testObjectArray
@redis.zrange "TestCreateClass>integer", 0, -1, (error, list) ->
expect(list).toEqual [test2.id, test4.id, test3.id, test1.id]
done()
it 'adds to a sorted set with values', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(integer: 1).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass>integer', 1, createdObject.id)
done()
describe 'for boolean attributes', ->
it 'adds to a zset', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(boolean: true).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass#boolean:true', 1, createdObject.id)
done()
describe 'for reference attributes', ->
describe 'when many is true', ->
it "sets the reference to true", (done) ->
createReference = @referenceModelCreate(secondId: 'id1')
createTestObj = createReference.then (ref1) => @create(manyReferences: [ref1.id])
createTestObj.then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it "sets the reference to even when empty", (done) ->
@referenceModelCreate(secondId: 'id1').then (ref1) =>
@create(url: 'one').then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it 'adds to a set', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
@create = create.bind(@parentObject)
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#linkedModel:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#linkedModel:TestCreateClassRefs', createdObject.id)
done()
it 'adds to a set with a reverseReferenceAttribute', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
reverseReferenceAttribute: 'namespaced'
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create = create.bind(@parentObject)
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#namespaced:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#namespaced:TestCreateClassRefs', createdObject.id)
done()
describe 'when many is not true', ->
it 'stores the reference id', (done) ->
@referenceModelCreate(secondId: 'id1').done (ref1) =>
@create(reference: ref1.id).then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.reference).toEqual ref1.id
done()
it 'should return a promise', ->
testObjectPromise = @create(url: 'uniqueValue')
expect(testObjectPromise).toEqual jasmine.any(Promise)
it 'should resolve an object with a 10 character id', (done) ->
# This test will fail from Sun May 25 2059 18:38:27 BST (2821109907456 unix time)
# and the number of characters will increase by 1
testObjectPromise = @create(url: 'uniqueValue')
testObjectPromise.done (testObject) ->
expect(testObject.id.length).toEqual 10
done()
it "should create an object with properties that are defined in the class' attributes", (done) ->
testObjectPromise = @create(boolean: false)
testObjectPromise.then (testObject) ->
expect(testObject.boolean).toBe false
done()
it "should create an object and ignore properties that are not defined in the class' attributes", (done) ->
@create(notAnAttribute: 'value').catch (error) =>
expect(error).toEqual(new Error "No valid fields given")
done()
describe 'presence validation', ->
it 'should create objects that pass validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
validates:
presence: true
@create = create.bind(@parentObject)
@create(presenceValidation: 'value').then (testObject) =>
expect(testObject.presenceValidation).toEqual 'value'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
identifiable: true
validates:
presence: true
@create = create.bind(@parentObject)
@create(one: 1, presenceValidation: null).catch (errors) ->
expect(errors).toContain(new Error 'presenceValidation must be present')
done()
describe 'length validation', ->
it 'should not create objects that fail length validation by having a length that is greater than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: 'elevenchars').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should not create objects that fail length validation by having a length that is less than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'sixchr').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should create objects that have a length that is equal to the length validation', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'ninechars').then (testObject) ->
expect(testObject.lengthValidation).toEqual 'ninechars'
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: null).then (testObject) =>
expect(testObject.lengthValidation).toEqual undefined
done()
describe 'minimum length', ->
it 'should create objects that have a length that is equal to the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is greater than the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'elevenchars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'elevenchars'
done()
it 'should not create objects that fail minLength validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'sixchr').catch (error) =>
expect(error).toContain(new Error 'minLengthValidation should have a minimum length of 9')
done()
describe 'maximum length', ->
it 'should create objects that have a length that is equal to the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is less than the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'sixchr').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'sixchr'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'elevenchars').catch (error) =>
expect(error).toContain(new Error 'maxLengthValidation should have a maximum length of 9')
done()
describe 'greaterThan validation', ->
it 'should create objects that pass greaterThan validation', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 11).then (testObject) =>
expect(testObject.greaterThanValidation).toEqual 11
done()
it 'should not create objects that fail greaterThan validation by being less than', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 9')
done()
it 'should not create objects that fail greaterThan validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 10
@create = create.bind(@parentObject)
@create(greaterThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 10')
done()
describe 'greaterThanOrEqualTo validation', ->
it 'should create objects that pass greaterThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 10
done()
it 'should create objects that pass greaterThanOrEqualTo validation by being greater than', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 11).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 11
done()
it 'should not create objects that fail greaterThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanOrEqualToValidation should be greater than or equal to 10')
done()
describe 'lessThan validation', ->
it 'should create objects that pass lessThan validation', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 9).then (testObject) =>
expect(testObject.lessThanValidation).toEqual 9
done()
it 'should not create objects that fail lessThan validation by being more than', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
it 'should not create objects that fail lessThan validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
describe 'lessThanOrEqualTo validation', ->
it 'should create objects that pass lessThanOrEqualTo validation by being less than', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 9).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 9
done()
it 'should create objects that pass lessThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 10
done()
it 'should not create objects that fail lessThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanOrEqualToValidation should be less than or equal to 10')
done()
describe 'equalTo validation', ->
it 'should create objects that pass equalTo validation', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 10).then (testObject) =>
expect(testObject.equalToValidation).toEqual 10
done()
it 'should not create objects that fail equalTo validation by being more than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
it 'should not create objects that fail equalTo validation by being less than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 9).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
describe 'format validation', ->
describe "'with'", ->
it 'should not fail when the attribute is not present', (done) ->
pending()
it "should create objects that pass format validation 'with' a regular expression that accounts for all of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'abcd'
done()
it "should create objects that pass format validation 'with' a regular expression that only accounts for some of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'ab123cd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'ab123cd'
done()
it "should not create objects that fail format validation 'with' a regular expression", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').catch (error) =>
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(one: 1, formatValidation: null).then (testObject) =>
expect(testObject.formatValidation).toEqual undefined
done()
describe "'without'", ->
it "should not create objects that fail validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').catch (error) ->
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it "should create objects that pass format validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').then (testObject) =>
expect(testObject.formatValidation).toEqual '123'
done()
describe 'inclusionIn validation', ->
it 'should create objects that pass inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'one').then (testObject) =>
expect(testObject.inclusionInValidation).toEqual 'one'
done()
it 'should not create objects that fail inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'four').catch (error) =>
expect(error).toContain(new Error 'inclusionInValidation must be one of the accepted values')
done()
describe 'exclusionIn validation', ->
it 'should create objects that pass exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'four').then (testObject) =>
expect(testObject.exclusionInValidation).toEqual 'four'
done()
it 'should not create objects that fail exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'one').catch (error) =>
expect(error).toContain(new Error 'exclusionInValidation must not be one of the forbidden values')
done()
describe 'uniqueness validation', ->
it 'should not create objects that fail validation', (done) ->
pending()
@parentObject.classAttributes =
uniquenessValidation:
dataType: 'string'
identifiable: true
validates:
uniqueness: true
@create = create.bind(@parentObject)
@redis.set 'TestCreateClass#uniquenessValidation:notUnique', 'test', =>
@create(uniquenessValidation: 'notUnique').catch (errors) =>
expect(errors).toContain(new Error 'uniquenessValidation should be a unique value')
done()
describe 'afterSave', ->
it 'should perform an after save callback', (done) ->
pending()
@parentObject.afterSave = new Promise (resolve) ->
console.log "hiya!!!!!!"
resolve (4)
@create = create.bind(@parentObject)
@create(name: '<NAME>').then (testObject) =>
expect()
done()
| true | create = require '../../src/adaptorMethods/create'
Promise = require 'promise'
ValidationError = require 'oomph/lib/ValidationError'
_ = require 'lodash'
redis = require 'redis'
describe 'oomphRedisAdaptor#create', ->
beforeAll (done) ->
@redis = redis.createClient(1111, 'localhost')
done()
beforeEach ->
@parentObject =
className: 'TestCreateClass'
redis: @redis
classAttributes:
name:
dataType: 'string'
url:
dataType: 'string'
url: true
urlBaseAttribute: 'name'
one:
dataType: 'integer'
sortable: true
two:
dataType: 'integer'
sortable: true
three:
dataType: 'integer'
sortable: true
integer:
dataType: 'integer'
identifier:
dataType: 'string'
identifiable: true
reference:
dataType: 'reference'
referenceModelName: 'Reference'
manyReferences:
dataType: 'reference'
many: true
referenceModelName: 'Reference'
sortableString:
dataType: 'string'
sortable: true
sortableInteger:
dataType: 'integer'
sortable: true
searchableText:
dataType: 'text'
searchable: true
searchableString:
dataType: 'string'
searchable: true
boolean:
dataType: 'boolean'
@create = create.bind(@parentObject)
referenceModelparentObject =
className: 'Reference'
redis: @redis
classAttributes:
secondId:
dataType: 'string'
identifiable: true
@referenceModelCreate = create.bind(referenceModelparentObject)
afterEach (done) ->
@redis.flushdb()
done()
afterAll (done) ->
@redis.flushdb()
@redis.end()
done()
it 'should return a promise', ->
createPromise = @create(integer: 1)
expect(createPromise).toEqual jasmine.any(Promise)
describe 'stored data types', ->
describe 'for string attributes', ->
describe 'where identifiable is true', ->
it 'adds to a key-value pair', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(identifier: 'identifierValue').then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#identifier:identifierValue', createdObject.id)
done()
describe 'where url is true', ->
it 'stores the generated url string in the object hash ', (done) ->
@create(name: "PI:NAME:<NAME>END_PI & gPI:NAME:<NAME>END_PIîght").then (createdObject) ->
expect(createdObject.url).toEqual 'hello-and-good-night'
done()
it 'adds to a key-value pair with a generated url string', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'set')
@create(name: "PI:NAME:<NAME>END_PI & gPI:NAME:<NAME>END_PIîPI:NAME:<NAME>END_PI").then (createdObject) ->
expect(multi.set).toHaveBeenCalledWith('TestCreateClass#url:hello-and-good-night', createdObject.id)
done()
it "appends a sequential number for duplicate generated url string", (done) ->
@create(name: "PI:NAME:<NAME>END_PI & PI:NAME:<NAME>END_PI").then (obj1) =>
@create(name: "PI:NAME:<NAME>END_PI & good PI:NAME:<NAME>END_PI").then (obj2) =>
@create(name: "Hello & good night").then (obj3) ->
expect(obj1.url).toEqual 'hello-and-good-night'
expect(obj2.url).toEqual 'hello-and-good-night-1'
expect(obj3.url).toEqual 'hello-and-good-night-2'
done()
describe 'where sortable is true', ->
it 'adds to an ordered list', (done) ->
testPromise1 = @create( sortableString: 'd' )
testPromise2 = @create( sortableString: 'a' )
testPromise3 = @create( sortableString: 'c' )
testPromise4 = @create( sortableString: 'b' )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
test1Id = testObjectArray[0].id
test2Id = testObjectArray[1].id
test3Id = testObjectArray[2].id
test4Id = testObjectArray[3].id
@redis.zrange "TestCreateClass>sortableString", 0, -1, (error, list) ->
expect(list).toEqual [test1Id, test3Id, test4Id, test2Id]
done()
describe 'where searchable is true', ->
it 'adds to partial words sets when the modules class has attributes with the field type of "string" and is searchable', (done) ->
spyOn(@redis, 'zadd').and.callThrough()
@create(searchableText: 'Search This <div>funny</div>').then (createdObject) =>
calledArgs = @redis.zadd.calls.allArgs()
keysCalled = []
for call in calledArgs
keysCalled.push call[0]
expect(keysCalled).toContain('TestCreateClass#searchableText/s')
expect(keysCalled).toContain('TestCreateClass#searchableText/se')
expect(keysCalled).toContain('TestCreateClass#searchableText/sea')
expect(keysCalled).toContain('TestCreateClass#searchableText/sear')
expect(keysCalled).toContain('TestCreateClass#searchableText/search')
expect(keysCalled).toContain('TestCreateClass#searchableText/t')
expect(keysCalled).toContain('TestCreateClass#searchableText/th')
expect(keysCalled).toContain('TestCreateClass#searchableText/thi')
expect(keysCalled).toContain('TestCreateClass#searchableText/this')
expect(keysCalled).toContain('TestCreateClass#searchableText/funny')
expect(keysCalled).not.toContain('TestCreateClass#searchableText/<div>')
done()
describe 'for integer attributes', ->
# Integers are always sortable
it 'adds to a sorted set', (done) ->
testPromise1 = @create( integer: 11 )
testPromise2 = @create( integer: 8 )
testPromise3 = @create( integer: 10 )
testPromise4 = @create( integer: 9 )
Promise.all([testPromise1,testPromise2,testPromise3,testPromise4]).done (testObjectArray) =>
[test1, test2, test3, test4] = testObjectArray
@redis.zrange "TestCreateClass>integer", 0, -1, (error, list) ->
expect(list).toEqual [test2.id, test4.id, test3.id, test1.id]
done()
it 'adds to a sorted set with values', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(integer: 1).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass>integer', 1, createdObject.id)
done()
describe 'for boolean attributes', ->
it 'adds to a zset', (done) ->
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'zadd')
@create(boolean: true).then (createdObject) ->
expect(multi.zadd).toHaveBeenCalledWith('TestCreateClass#boolean:true', 1, createdObject.id)
done()
describe 'for reference attributes', ->
describe 'when many is true', ->
it "sets the reference to true", (done) ->
createReference = @referenceModelCreate(secondId: 'id1')
createTestObj = createReference.then (ref1) => @create(manyReferences: [ref1.id])
createTestObj.then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it "sets the reference to even when empty", (done) ->
@referenceModelCreate(secondId: 'id1').then (ref1) =>
@create(url: 'one').then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.manyReferences).toEqual 'true'
done()
it 'adds to a set', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
@create = create.bind(@parentObject)
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#linkedModel:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#linkedModel:TestCreateClassRefs', createdObject.id)
done()
it 'adds to a set with a reverseReferenceAttribute', (done) ->
@parentObject.classAttributes =
linkedModel:
dataType: 'reference'
many: true
referenceModelName: 'LinkedModel'
reverseReferenceAttribute: 'namespaced'
multi = @redis.multi()
spyOn(@redis, 'multi').and.returnValue(multi)
spyOn(multi, 'sadd')
@create = create.bind(@parentObject)
@create(linkedModel: ['linkedModelId1', 'linkedModelId2']).then (createdObject) ->
expect(multi.sadd).toHaveBeenCalledWith('TestCreateClass:' + createdObject.id + '#linkedModel:LinkedModelRefs', 'linkedModelId1', 'linkedModelId2')
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId1#namespaced:TestCreateClassRefs', createdObject.id)
expect(multi.sadd).toHaveBeenCalledWith('LinkedModel:linkedModelId2#namespaced:TestCreateClassRefs', createdObject.id)
done()
describe 'when many is not true', ->
it 'stores the reference id', (done) ->
@referenceModelCreate(secondId: 'id1').done (ref1) =>
@create(reference: ref1.id).then (createdObject) =>
@redis.hgetall 'TestCreateClass:' + createdObject.id, (err, obj) ->
expect(obj.reference).toEqual ref1.id
done()
it 'should return a promise', ->
testObjectPromise = @create(url: 'uniqueValue')
expect(testObjectPromise).toEqual jasmine.any(Promise)
it 'should resolve an object with a 10 character id', (done) ->
# This test will fail from Sun May 25 2059 18:38:27 BST (2821109907456 unix time)
# and the number of characters will increase by 1
testObjectPromise = @create(url: 'uniqueValue')
testObjectPromise.done (testObject) ->
expect(testObject.id.length).toEqual 10
done()
it "should create an object with properties that are defined in the class' attributes", (done) ->
testObjectPromise = @create(boolean: false)
testObjectPromise.then (testObject) ->
expect(testObject.boolean).toBe false
done()
it "should create an object and ignore properties that are not defined in the class' attributes", (done) ->
@create(notAnAttribute: 'value').catch (error) =>
expect(error).toEqual(new Error "No valid fields given")
done()
describe 'presence validation', ->
it 'should create objects that pass validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
validates:
presence: true
@create = create.bind(@parentObject)
@create(presenceValidation: 'value').then (testObject) =>
expect(testObject.presenceValidation).toEqual 'value'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.presenceValidation =
dataType: 'string'
identifiable: true
validates:
presence: true
@create = create.bind(@parentObject)
@create(one: 1, presenceValidation: null).catch (errors) ->
expect(errors).toContain(new Error 'presenceValidation must be present')
done()
describe 'length validation', ->
it 'should not create objects that fail length validation by having a length that is greater than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: 'elevenchars').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should not create objects that fail length validation by having a length that is less than', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'sixchr').catch (errors) ->
expect(errors.length).toEqual 1
expect(errors).toContain jasmine.any ValidationError
expect(errors).toContain jasmine.objectContaining message: 'lengthValidation should have a length of 9'
done()
it 'should create objects that have a length that is equal to the length validation', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(lengthValidation: 'ninechars').then (testObject) ->
expect(testObject.lengthValidation).toEqual 'ninechars'
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.lengthValidation =
dataType: 'string'
validates:
length:
is: 9
@create = create.bind(@parentObject)
@create(one: 1, lengthValidation: null).then (testObject) =>
expect(testObject.lengthValidation).toEqual undefined
done()
describe 'minimum length', ->
it 'should create objects that have a length that is equal to the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is greater than the minimum length validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'elevenchars').then (testObject) =>
expect(testObject.minLengthValidation).toEqual 'elevenchars'
done()
it 'should not create objects that fail minLength validation', (done) ->
@parentObject.classAttributes.minLengthValidation =
dataType: 'string'
validates:
length:
minimum: 9
@create = create.bind(@parentObject)
@create(minLengthValidation: 'sixchr').catch (error) =>
expect(error).toContain(new Error 'minLengthValidation should have a minimum length of 9')
done()
describe 'maximum length', ->
it 'should create objects that have a length that is equal to the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'ninechars').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'ninechars'
done()
it 'should create objects that have a length that is less than the maximum length validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'sixchr').then (testObject) =>
expect(testObject.maxLengthValidation).toEqual 'sixchr'
done()
it 'should not create objects that fail validation', (done) ->
@parentObject.classAttributes.maxLengthValidation =
dataType: 'string'
validates:
length:
maximum: 9
@create = create.bind(@parentObject)
@create(maxLengthValidation: 'elevenchars').catch (error) =>
expect(error).toContain(new Error 'maxLengthValidation should have a maximum length of 9')
done()
describe 'greaterThan validation', ->
it 'should create objects that pass greaterThan validation', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 11).then (testObject) =>
expect(testObject.greaterThanValidation).toEqual 11
done()
it 'should not create objects that fail greaterThan validation by being less than', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 9
@create = create.bind(@parentObject)
@create(greaterThanValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 9')
done()
it 'should not create objects that fail greaterThan validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanValidation =
dataType: 'integer'
validates:
greaterThan: 10
@create = create.bind(@parentObject)
@create(greaterThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'greaterThanValidation should be greater than 10')
done()
describe 'greaterThanOrEqualTo validation', ->
it 'should create objects that pass greaterThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 10
done()
it 'should create objects that pass greaterThanOrEqualTo validation by being greater than', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 11).then (testObject) =>
expect(testObject.greaterThanOrEqualToValidation).toEqual 11
done()
it 'should not create objects that fail greaterThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.greaterThanOrEqualToValidation =
dataType: 'integer'
validates:
greaterThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(greaterThanOrEqualToValidation: 1).catch (error) =>
expect(error).toContain(new Error 'greaterThanOrEqualToValidation should be greater than or equal to 10')
done()
describe 'lessThan validation', ->
it 'should create objects that pass lessThan validation', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 9).then (testObject) =>
expect(testObject.lessThanValidation).toEqual 9
done()
it 'should not create objects that fail lessThan validation by being more than', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
it 'should not create objects that fail lessThan validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanValidation =
dataType: 'integer'
validates:
lessThan: 10
@create = create.bind(@parentObject)
@create(lessThanValidation: 10).catch (error) =>
expect(error).toContain(new Error 'lessThanValidation should be less than 10')
done()
describe 'lessThanOrEqualTo validation', ->
it 'should create objects that pass lessThanOrEqualTo validation by being less than', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 9).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 9
done()
it 'should create objects that pass lessThanOrEqualTo validation by being equal to', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 10).then (testObject) =>
expect(testObject.lessThanOrEqualToValidation).toEqual 10
done()
it 'should not create objects that fail lessThanOrEqualTo validation', (done) ->
@parentObject.classAttributes.lessThanOrEqualToValidation =
dataType: 'integer'
validates:
lessThanOrEqualTo: 10
@create = create.bind(@parentObject)
@create(lessThanOrEqualToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'lessThanOrEqualToValidation should be less than or equal to 10')
done()
describe 'equalTo validation', ->
it 'should create objects that pass equalTo validation', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 10).then (testObject) =>
expect(testObject.equalToValidation).toEqual 10
done()
it 'should not create objects that fail equalTo validation by being more than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 11).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
it 'should not create objects that fail equalTo validation by being less than', (done) ->
@parentObject.classAttributes.equalToValidation =
dataType: 'integer'
validates:
equalTo: 10
@create = create.bind(@parentObject)
@create(equalToValidation: 9).catch (error) =>
expect(error).toContain(new Error 'equalToValidation should equal 10')
done()
describe 'format validation', ->
describe "'with'", ->
it 'should not fail when the attribute is not present', (done) ->
pending()
it "should create objects that pass format validation 'with' a regular expression that accounts for all of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'abcd'
done()
it "should create objects that pass format validation 'with' a regular expression that only accounts for some of the data", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'ab123cd').then (testObject) =>
expect(testObject.formatValidation).toEqual 'ab123cd'
done()
it "should not create objects that fail format validation 'with' a regular expression", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').catch (error) =>
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it 'should perform the validation only when the property is present', (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
with: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(one: 1, formatValidation: null).then (testObject) =>
expect(testObject.formatValidation).toEqual undefined
done()
describe "'without'", ->
it "should not create objects that fail validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: 'abcd').catch (error) ->
expect(error).toContain(new Error 'formatValidation should meet the format requirements')
done()
it "should create objects that pass format validation", (done) ->
@parentObject.classAttributes.formatValidation =
dataType: 'string'
validates:
format:
without: /[a-zA-Z]+/
@create = create.bind(@parentObject)
@create(formatValidation: '123').then (testObject) =>
expect(testObject.formatValidation).toEqual '123'
done()
describe 'inclusionIn validation', ->
it 'should create objects that pass inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'one').then (testObject) =>
expect(testObject.inclusionInValidation).toEqual 'one'
done()
it 'should not create objects that fail inclusionIn validation', (done) ->
@parentObject.classAttributes.inclusionInValidation =
dataType: 'string'
validates:
inclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(inclusionInValidation: 'four').catch (error) =>
expect(error).toContain(new Error 'inclusionInValidation must be one of the accepted values')
done()
describe 'exclusionIn validation', ->
it 'should create objects that pass exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'four').then (testObject) =>
expect(testObject.exclusionInValidation).toEqual 'four'
done()
it 'should not create objects that fail exclusionIn validation', (done) ->
@parentObject.classAttributes.exclusionInValidation =
dataType: 'string'
validates:
exclusionIn: ['one', 'two', 'three']
@create = create.bind(@parentObject)
@create(exclusionInValidation: 'one').catch (error) =>
expect(error).toContain(new Error 'exclusionInValidation must not be one of the forbidden values')
done()
describe 'uniqueness validation', ->
it 'should not create objects that fail validation', (done) ->
pending()
@parentObject.classAttributes =
uniquenessValidation:
dataType: 'string'
identifiable: true
validates:
uniqueness: true
@create = create.bind(@parentObject)
@redis.set 'TestCreateClass#uniquenessValidation:notUnique', 'test', =>
@create(uniquenessValidation: 'notUnique').catch (errors) =>
expect(errors).toContain(new Error 'uniquenessValidation should be a unique value')
done()
describe 'afterSave', ->
it 'should perform an after save callback', (done) ->
pending()
@parentObject.afterSave = new Promise (resolve) ->
console.log "hiya!!!!!!"
resolve (4)
@create = create.bind(@parentObject)
@create(name: 'PI:NAME:<NAME>END_PI').then (testObject) =>
expect()
done()
|
[
{
"context": "admin.user and app.configuration.admin.password is password\n, basicAuthMessage)\n\n\napp.get \"/\", basicAuth, (re",
"end": 1150,
"score": 0.9937129616737366,
"start": 1142,
"tag": "PASSWORD",
"value": "password"
}
] | app.coffee | malixsys/node-simple-video-server | 0 | logErrors = (err, req, res, next) ->
console.error err.stack
next err
clientErrorHandler = (err, req, res, next) ->
if req.xhr
res.send 500,
error: "Something blew up!"
else
next err
errorHandler = (err, req, res, next) ->
res.status 500
res.render "error",
error: err
mime = require("mime")
express = require("express")
reload = require("reload")
livereload = require("express-livereload")
path = require("path")
ffmpeg = require("fluent-ffmpeg")
reload = require("reload")
livereload = require("express-livereload")
app = express()
app.configuration = require('config.json')('./config.json')
app.locals.version = "0.1.0"
app.is_prod = app.configuration.is_prod
app.base = "http://localhost:7777"
viewsDir = path.join(__dirname, "views")
app.set "views", viewsDir
app.set "view engine", "ejs"
app.use(express.favicon())
app.use(express.logger('dev'))
app.use(express.static(__dirname + '/flowplayer'))
basicAuthMessage = 'Restrict area, please identify'
basicAuth = express.basicAuth( (username, password) ->
return username is app.configuration.admin.user and app.configuration.admin.password is password
, basicAuthMessage)
app.get "/", basicAuth, (req,res) ->
res.render 'index'
app.get "/video/:filename", basicAuth, (req, res) ->
pathToMovie = "/home/malix/files/" + req.params.filename
#type = mime.lookup(pathToMovie)
#res.contentType type
res.contentType('flv')
proc = new ffmpeg(
source: pathToMovie
nolog: false
).usingPreset("flashvideo").writeToStream(res, (retcode, error) ->
console.log ["conversion", retcode, error]
)
app.use app.router
app.use logErrors
app.use clientErrorHandler
app.use errorHandler
port = process.env.PORT or 7777
server = require("http").createServer(app)
reload server, app, 1000
server.listen port, ->
unless app.is_prod
console.log "enabling live reload"
livereload app, config =
watchDir: viewsDir
applyJSLive: true
console.log "Server version #{app.locals.version} listening on " + port
| 139663 | logErrors = (err, req, res, next) ->
console.error err.stack
next err
clientErrorHandler = (err, req, res, next) ->
if req.xhr
res.send 500,
error: "Something blew up!"
else
next err
errorHandler = (err, req, res, next) ->
res.status 500
res.render "error",
error: err
mime = require("mime")
express = require("express")
reload = require("reload")
livereload = require("express-livereload")
path = require("path")
ffmpeg = require("fluent-ffmpeg")
reload = require("reload")
livereload = require("express-livereload")
app = express()
app.configuration = require('config.json')('./config.json')
app.locals.version = "0.1.0"
app.is_prod = app.configuration.is_prod
app.base = "http://localhost:7777"
viewsDir = path.join(__dirname, "views")
app.set "views", viewsDir
app.set "view engine", "ejs"
app.use(express.favicon())
app.use(express.logger('dev'))
app.use(express.static(__dirname + '/flowplayer'))
basicAuthMessage = 'Restrict area, please identify'
basicAuth = express.basicAuth( (username, password) ->
return username is app.configuration.admin.user and app.configuration.admin.password is <PASSWORD>
, basicAuthMessage)
app.get "/", basicAuth, (req,res) ->
res.render 'index'
app.get "/video/:filename", basicAuth, (req, res) ->
pathToMovie = "/home/malix/files/" + req.params.filename
#type = mime.lookup(pathToMovie)
#res.contentType type
res.contentType('flv')
proc = new ffmpeg(
source: pathToMovie
nolog: false
).usingPreset("flashvideo").writeToStream(res, (retcode, error) ->
console.log ["conversion", retcode, error]
)
app.use app.router
app.use logErrors
app.use clientErrorHandler
app.use errorHandler
port = process.env.PORT or 7777
server = require("http").createServer(app)
reload server, app, 1000
server.listen port, ->
unless app.is_prod
console.log "enabling live reload"
livereload app, config =
watchDir: viewsDir
applyJSLive: true
console.log "Server version #{app.locals.version} listening on " + port
| true | logErrors = (err, req, res, next) ->
console.error err.stack
next err
clientErrorHandler = (err, req, res, next) ->
if req.xhr
res.send 500,
error: "Something blew up!"
else
next err
errorHandler = (err, req, res, next) ->
res.status 500
res.render "error",
error: err
mime = require("mime")
express = require("express")
reload = require("reload")
livereload = require("express-livereload")
path = require("path")
ffmpeg = require("fluent-ffmpeg")
reload = require("reload")
livereload = require("express-livereload")
app = express()
app.configuration = require('config.json')('./config.json')
app.locals.version = "0.1.0"
app.is_prod = app.configuration.is_prod
app.base = "http://localhost:7777"
viewsDir = path.join(__dirname, "views")
app.set "views", viewsDir
app.set "view engine", "ejs"
app.use(express.favicon())
app.use(express.logger('dev'))
app.use(express.static(__dirname + '/flowplayer'))
basicAuthMessage = 'Restrict area, please identify'
basicAuth = express.basicAuth( (username, password) ->
return username is app.configuration.admin.user and app.configuration.admin.password is PI:PASSWORD:<PASSWORD>END_PI
, basicAuthMessage)
app.get "/", basicAuth, (req,res) ->
res.render 'index'
app.get "/video/:filename", basicAuth, (req, res) ->
pathToMovie = "/home/malix/files/" + req.params.filename
#type = mime.lookup(pathToMovie)
#res.contentType type
res.contentType('flv')
proc = new ffmpeg(
source: pathToMovie
nolog: false
).usingPreset("flashvideo").writeToStream(res, (retcode, error) ->
console.log ["conversion", retcode, error]
)
app.use app.router
app.use logErrors
app.use clientErrorHandler
app.use errorHandler
port = process.env.PORT or 7777
server = require("http").createServer(app)
reload server, app, 1000
server.listen port, ->
unless app.is_prod
console.log "enabling live reload"
livereload app, config =
watchDir: viewsDir
applyJSLive: true
console.log "Server version #{app.locals.version} listening on " + port
|
[
{
"context": " = (error, @device) => done()\n @sut {token: 'mah-secrets'}, storeDevice, @dependencies\n\n it 'should cal",
"end": 2393,
"score": 0.9916473031044006,
"start": 2382,
"tag": "PASSWORD",
"value": "mah-secrets"
},
{
"context": "ateDevice).to.be.calledWith device.uu... | test/lib/register-spec.coffee | Christopheraburns/projecttelemetry | 0 | _ = require 'lodash'
moment = require 'moment'
TestDatabase = require '../test-database'
describe 'register', ->
beforeEach (done) ->
@sut = require '../../lib/register'
@updateDevice = sinon.stub()
TestDatabase.open (error, database) =>
@database = database
@devices = @database.devices
@dependencies = {database: @database, updateDevice: @updateDevice}
done error
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with no params', ->
beforeEach (done) ->
@timestamp = moment().toISOString()
@updateDevice.yields null, timestamp: @timestamp
storeDevice = (@error, @device) => done()
@sut null, storeDevice, @dependencies
it 'should return a device', ->
expect(@device).to.exist
it 'should create a device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 1
done()
it 'should generate a new uuid', (done) ->
@database.devices.findOne {}, (error, device) =>
return done error if error?
expect(device.uuid).to.exist
done()
it 'should generate a new token', ->
expect(@device.token).to.exist
it 'should call updateDevice', ->
expect(@updateDevice).to.have.been.called
it 'should merge in the timestamp from update Device', ->
expect(@device.timestamp).to.equal @timestamp
describe 'when called again with no params', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @newerDevice) => done()
@sut null, storeDevice, @dependencies
it 'should create a new device', ->
expect(@newerDevice).to.exist
it 'should generate a different token', ->
expect(@newerDevice.token).to.not.equal @device.token
describe 'when called with a specific uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {uuid: 'some-uuid'}, done, @dependencies
it 'should create a device with that uuid', (done) ->
@devices.findOne uuid: 'some-uuid', (error, device) =>
expect(device).to.exist
done()
describe 'when called with a specific token', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@sut {token: 'mah-secrets'}, storeDevice, @dependencies
it 'should call update device with that token', ->
@devices.findOne (error, device) =>
expect(@updateDevice).to.be.calledWith device.uuid, {token: 'mah-secrets', uuid: device.uuid}
describe 'when called with an owner id', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@params = {uuid: 'some-uuid', token: 'token', owner: 'other-uuid'}
@sut @params, done, @dependencies
it 'should set the discoverWhitelist to the owners UUID', ->
expect(@updateDevice).to.have.been.calledWith 'some-uuid', {
uuid: 'some-uuid'
token: 'token'
owner: 'other-uuid'
discoverWhitelist: ['other-uuid']
}
describe 'when called without an online', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {}, done, @dependencies
it 'should create a device with an online of false', (done) ->
@devices.findOne {}, (error, device) =>
expect(device.online).to.be.false
done()
describe 'when there is an existing device', ->
beforeEach (done) ->
@devices.insert {uuid : 'some-uuid', name: 'Somebody.'}, done
describe 'trying to create a new device with the same uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-uuid', name: 'Nobody.'}, storeDevice, @dependencies
it 'it should call the callback with an error', ->
expect(@error).to.exist
describe 'trying to create a new device with a different uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-other-uuid'}, storeDevice, @dependencies
it 'it create a second device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 2
done()
describe 'when called with just a name', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@params = {name: 'bobby'}
@originalParams = _.cloneDeep @params
@sut @params, storeDevice, @dependencies
it 'should not mutate the params', ->
expect(@params).to.deep.equal @originalParams
| 208803 | _ = require 'lodash'
moment = require 'moment'
TestDatabase = require '../test-database'
describe 'register', ->
beforeEach (done) ->
@sut = require '../../lib/register'
@updateDevice = sinon.stub()
TestDatabase.open (error, database) =>
@database = database
@devices = @database.devices
@dependencies = {database: @database, updateDevice: @updateDevice}
done error
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with no params', ->
beforeEach (done) ->
@timestamp = moment().toISOString()
@updateDevice.yields null, timestamp: @timestamp
storeDevice = (@error, @device) => done()
@sut null, storeDevice, @dependencies
it 'should return a device', ->
expect(@device).to.exist
it 'should create a device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 1
done()
it 'should generate a new uuid', (done) ->
@database.devices.findOne {}, (error, device) =>
return done error if error?
expect(device.uuid).to.exist
done()
it 'should generate a new token', ->
expect(@device.token).to.exist
it 'should call updateDevice', ->
expect(@updateDevice).to.have.been.called
it 'should merge in the timestamp from update Device', ->
expect(@device.timestamp).to.equal @timestamp
describe 'when called again with no params', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @newerDevice) => done()
@sut null, storeDevice, @dependencies
it 'should create a new device', ->
expect(@newerDevice).to.exist
it 'should generate a different token', ->
expect(@newerDevice.token).to.not.equal @device.token
describe 'when called with a specific uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {uuid: 'some-uuid'}, done, @dependencies
it 'should create a device with that uuid', (done) ->
@devices.findOne uuid: 'some-uuid', (error, device) =>
expect(device).to.exist
done()
describe 'when called with a specific token', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@sut {token: '<PASSWORD>'}, storeDevice, @dependencies
it 'should call update device with that token', ->
@devices.findOne (error, device) =>
expect(@updateDevice).to.be.calledWith device.uuid, {token: '<PASSWORD>', uuid: device.uuid}
describe 'when called with an owner id', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@params = {uuid: 'some-uuid', token: 'token', owner: 'other-uuid'}
@sut @params, done, @dependencies
it 'should set the discoverWhitelist to the owners UUID', ->
expect(@updateDevice).to.have.been.calledWith 'some-uuid', {
uuid: 'some-uuid'
token: 'token'
owner: 'other-uuid'
discoverWhitelist: ['other-uuid']
}
describe 'when called without an online', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {}, done, @dependencies
it 'should create a device with an online of false', (done) ->
@devices.findOne {}, (error, device) =>
expect(device.online).to.be.false
done()
describe 'when there is an existing device', ->
beforeEach (done) ->
@devices.insert {uuid : 'some-uuid', name: '<NAME>body.'}, done
describe 'trying to create a new device with the same uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-uuid', name: '<NAME>obody.'}, storeDevice, @dependencies
it 'it should call the callback with an error', ->
expect(@error).to.exist
describe 'trying to create a new device with a different uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-other-uuid'}, storeDevice, @dependencies
it 'it create a second device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 2
done()
describe 'when called with just a name', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@params = {name: '<NAME>'}
@originalParams = _.cloneDeep @params
@sut @params, storeDevice, @dependencies
it 'should not mutate the params', ->
expect(@params).to.deep.equal @originalParams
| true | _ = require 'lodash'
moment = require 'moment'
TestDatabase = require '../test-database'
describe 'register', ->
beforeEach (done) ->
@sut = require '../../lib/register'
@updateDevice = sinon.stub()
TestDatabase.open (error, database) =>
@database = database
@devices = @database.devices
@dependencies = {database: @database, updateDevice: @updateDevice}
done error
it 'should be a function', ->
expect(@sut).to.be.a 'function'
describe 'when called with no params', ->
beforeEach (done) ->
@timestamp = moment().toISOString()
@updateDevice.yields null, timestamp: @timestamp
storeDevice = (@error, @device) => done()
@sut null, storeDevice, @dependencies
it 'should return a device', ->
expect(@device).to.exist
it 'should create a device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 1
done()
it 'should generate a new uuid', (done) ->
@database.devices.findOne {}, (error, device) =>
return done error if error?
expect(device.uuid).to.exist
done()
it 'should generate a new token', ->
expect(@device.token).to.exist
it 'should call updateDevice', ->
expect(@updateDevice).to.have.been.called
it 'should merge in the timestamp from update Device', ->
expect(@device.timestamp).to.equal @timestamp
describe 'when called again with no params', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @newerDevice) => done()
@sut null, storeDevice, @dependencies
it 'should create a new device', ->
expect(@newerDevice).to.exist
it 'should generate a different token', ->
expect(@newerDevice.token).to.not.equal @device.token
describe 'when called with a specific uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {uuid: 'some-uuid'}, done, @dependencies
it 'should create a device with that uuid', (done) ->
@devices.findOne uuid: 'some-uuid', (error, device) =>
expect(device).to.exist
done()
describe 'when called with a specific token', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@sut {token: 'PI:PASSWORD:<PASSWORD>END_PI'}, storeDevice, @dependencies
it 'should call update device with that token', ->
@devices.findOne (error, device) =>
expect(@updateDevice).to.be.calledWith device.uuid, {token: 'PI:PASSWORD:<PASSWORD>END_PI', uuid: device.uuid}
describe 'when called with an owner id', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@params = {uuid: 'some-uuid', token: 'token', owner: 'other-uuid'}
@sut @params, done, @dependencies
it 'should set the discoverWhitelist to the owners UUID', ->
expect(@updateDevice).to.have.been.calledWith 'some-uuid', {
uuid: 'some-uuid'
token: 'token'
owner: 'other-uuid'
discoverWhitelist: ['other-uuid']
}
describe 'when called without an online', ->
beforeEach (done) ->
@updateDevice.yields null, {}
@sut {}, done, @dependencies
it 'should create a device with an online of false', (done) ->
@devices.findOne {}, (error, device) =>
expect(device.online).to.be.false
done()
describe 'when there is an existing device', ->
beforeEach (done) ->
@devices.insert {uuid : 'some-uuid', name: 'PI:NAME:<NAME>END_PIbody.'}, done
describe 'trying to create a new device with the same uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-uuid', name: 'PI:NAME:<NAME>END_PIobody.'}, storeDevice, @dependencies
it 'it should call the callback with an error', ->
expect(@error).to.exist
describe 'trying to create a new device with a different uuid', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (@error, @device) => done()
@sut {uuid: 'some-other-uuid'}, storeDevice, @dependencies
it 'it create a second device', (done) ->
@database.devices.count {}, (error, count) =>
return done error if error?
expect(count).to.equal 2
done()
describe 'when called with just a name', ->
beforeEach (done) ->
@updateDevice.yields null, {}
storeDevice = (error, @device) => done()
@params = {name: 'PI:NAME:<NAME>END_PI'}
@originalParams = _.cloneDeep @params
@sut @params, storeDevice, @dependencies
it 'should not mutate the params', ->
expect(@params).to.deep.equal @originalParams
|
[
{
"context": "JSDoc comments are syntactically correct\n# @author Nicholas C. Zakas\n###\n'use strict'\n\n#------------------------------",
"end": 99,
"score": 0.9998378753662109,
"start": 82,
"tag": "NAME",
"value": "Nicholas C. Zakas"
},
{
"context": "ons: [requireReturn: no]\n ... | src/tests/rules/valid-jsdoc.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Validates JSDoc comments are syntactically correct
# @author Nicholas C. Zakas
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/valid-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'valid-jsdoc', rule,
valid: [
'''
###*
# Description
# @param {Object[]} screenings Array of screenings.
# @param {Number} screenings[].timestamp its a time stamp
@return {void}
###
foo = ->
'''
'''
###*
# Description
###
x = new Foo ->
'''
'''
###*
# Description
# @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @returns {undefined} ###
foo = ->
'''
'''
###*
* Description
* @alias Test#test
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
*@extends MyClass
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @constructor ###
Foo = ->
'''
'''
###*
* Description
* @class ###
Foo = ->
'''
'''
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @arg {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @argument {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {string} [p] bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string} p.name bar
* @returns {string} desc ###
Foo.bar = (p) ->
'''
'''
do ->
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
o =
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo: (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string[]} p.files qux
* @param {Function} cb baz
* @returns {void} ###
foo = (p, cb) ->
'''
'''
###*
* Description
* @override ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritdoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritDoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @Returns {void} ###
foo = ->
'''
,
code: '''
call(
###*
* Doc for a function expression in a call expression.
* @param {string} argName This is the param description.
* @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing
foo: ->
return 'bar'
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing {
###*
* @return {string} A string.
###
foo: ->
'bar'
}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {void} ###
foo = ->
'''
options: [{}]
,
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) => {}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = ({p}) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> func = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) ->
t = no
return if t
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {void} ###
Foo.bar = (p) ->
t = false
if t
return
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> name = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {h} i
###
Foo.bar = (p) ->
t = ->
name = ->
return name
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamDescription: no]
,
code: '''
###*
* Description
* @param {string} p mytest
* @returns {Object}###
Foo.bar = (p) -> name
'''
options: [requireReturnDescription: no]
,
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
###*
* Description for this.xs;
* @type {object[]}
###
@xs = xs.filter (x) => x != null
'''
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => return bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Start with caps and end with period.
* @return {void} ###
foo = ->
'''
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
,
code: '''
###* Foo
@return {void} Foo
###
foo = ->
'''
options: [prefer: return: 'return']
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
options: [requireReturnType: no]
,
code: '''
###*
* Description
* @param p bar
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamType: no]
,
code: '''
###*
* A thing interface.
* @interface
###
Thing = ->
'''
,
# options: [requireReturn: yes]
# classes
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description for A.
###
class A
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {f} g
###
print: (xs) ->
@a = xs
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {void}
###
print: (xs) ->
this.a = xs
'''
options: []
,
code: '''
###*
* Use of this with a 'namepath'.
* @this some.name
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Use of this with a type expression.
* @this {some.name}
* @returns {j} k
###
foo = ->
'''
,
# options: [requireReturn: no]
# async function
code: '''
###*
* An async function. Options requires return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: yes]
code: '''
###*
* An async function. Options do not require return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: no]
code: '''
###*
* An async function. Options do not require return.
* @returns {h} i
###
a = -> await b
'''
,
# options: [requireReturn: no]
# type validations
code: '''
###*
* Foo
* @param {Array.<*>} hi - desc
* @returns {*} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{String:foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
,
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) =>
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Test dash and slash.
* @extends module:stb/emitter~Emitter
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Test dash and slash.
* @requires module:config
* @requires module:modules/notifications
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @module module-name
* @returns {e} f
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @alias module:module-name
* @returns {b} c
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Array.<string|number>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<string|number>} hi - desc
* @returns {Array.<string>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Description
* @param {string} a bar
* @returns {string} desc ###
foo = (a = 1) ->
'''
,
code: '''
###*
* Description
* @param {string} b bar
* @param {string} a bar
* @returns {string} desc ###
foo = (b, a = 1) ->
'''
,
# abstract
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error 'Not Implemented'
'''
,
# options: [requireReturn: no]
# https://github.com/eslint/eslint/issues/9412 - different orders for jsodc tags
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
'* @param {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @param {string} hi - desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @constructor
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @constructor
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @class
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @override
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @inheritdoc
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @abstract
* @returns {ghi} jkl
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @virtual
* @returns {abc} def
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @interface
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = ->
'''
,
# options: [requireReturn: yes]
code: '''
###*
* @param {string} a - a.
* @param {object} [obj] - obj.
* @param {string} obj.b - b.
* @param {string} obj.c - c.
* @returns {void}
###
foo = (a, {b, c} = {}) ->
# empty
'''
,
code: '''
###*
* @param {string} a - a.
* @param {any[]} [list] - list.
* @returns {void}
###
foo = (a, [b, c] = []) ->
# empty
'''
,
# https://github.com/eslint/eslint/issues/7184
'''
###*
* Foo
* @param {{foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
'''
###*
* Foo
* @param {{foo:String, bar, baz:Array}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
,
code: '''
###*
* Foo
* @param {{String}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###* Foo
@return {sdf} jkl
###
foo = ->
'''
options: [
prefer: return: 'return'
# requireReturn: no
]
,
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {string} a desc
@returns {MyClass} a desc###
foo = (a) ->
t = false
if t
process(t)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @returns {string} something
* @param {string} p desc
###
foo = (@p) ->
'''
]
invalid: [
code: '''
call(
###*
# Doc for a function expression in a call expression.
# @param {string} bogusName This is the param description.
# @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
output: null
# options: [requireReturn: no]
errors: [
message: "Expected JSDoc for 'argName' but found 'bogusName'."
type: 'Block'
line: 4
column: 5
endLine: 4
endColumn: 61
]
,
code: '''
###* @@foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###*
# Create a new thing.
###
thing = new Thing
###*
# Missing return tag.
###
foo: ->
'bar'
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###* @@returns {void} Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@returns {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
# @return {void} Foo
###
foo = ->
'''
output: '''
###* Foo
# @returns {void} Foo
###
foo = ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
@argument {int} bar baz
###
foo = (bar) ->
'''
output: '''
###* Foo
@arg {int} bar baz
###
foo = (bar) ->
'''
options: [prefer: argument: 'arg']
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: 'Use @arg instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
###
foo = ->
'''
output: null
options: [prefer: returns: 'return']
errors: [
message: 'Missing JSDoc @return for function.'
type: 'Block'
]
,
code: '''
###* Foo
@return {void} Foo
###
foo.bar = () => {}
'''
output: '''
###* Foo
@returns {void} Foo
###
foo.bar = () => {}
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 8
]
,
code: '''
###* Foo
@param {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
@param {} p Bar
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@param {void Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
* @param p Desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'p'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 16
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo =
->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Description for a
###
A =
class
###*
* Description for method.
* @param {object[]} xs - xs
###
print: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string}
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc return description.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (@p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo =
(a = 1) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'a'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a Description
* @param {string} b Description
* @returns {string} something
###
foo =
(b, a = 1) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 32
,
message: "Expected JSDoc for 'a' but found 'b'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 32
]
,
code: '''
###*
* Foo
* @param {string} p desc
* @param {string} p desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Duplicate JSDoc parameter 'p'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
@returns {void}###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 25
]
,
code: '''
###*
* Foo
* @override
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @inheritdoc
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t
t
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t then return null
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '###* foo ### foo = () => bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '###* foo ### foo = () => return bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* @param fields [Array]
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'fields'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 24
]
,
code: '''
###*
* Start with caps and end with period
* @return {void} ###
foo = ->
'''
output: null
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
output: null
options: [prefer: return: 'return']
errors: [
message: 'Missing JSDoc return type.'
type: 'Block'
]
,
# classes
code: '''
###*
* Description for A
###
class A
###*
* Description for constructor
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: no
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###*
* Description for a
###
A = class
###*
* Description for constructor.
* @param {object[]} xs - xs
###
print: (xs) ->
@a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
###
print: (xs) ->
this.a = xs
'''
output: null
options: []
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc for parameter 'xs'."
type: 'Block'
]
,
code: '''
###*
* Use of this with an invalid type expression
* @this {not.a.valid.type.expression
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###*
* Use of this with a type that is not a member expression
* @this {Array<string>}
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
# async function
code: '''
###*
* An async function. Options requires return.
###
a = -> await b
'''
output: null
# options: [requireReturn: yes]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
# type validations
code: '''
###*
* Foo
* @param {String} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {{20:String}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 15
endLine: 3
endColumn: 21
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {String|number|test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
errors: [
message: "Use 'Test' instead of 'test'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 29
]
,
code: '''
###*
* Foo
* @param {Array.<String>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
]
,
code: '''
###*
* Foo
* @param {Array.<{id: Number, votes: Number}>} hi - desc
* @returns {Array.<{summary: String}>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 23
endLine: 3
endColumn: 29
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 38
endLine: 3
endColumn: 44
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 30
endLine: 4
endColumn: 36
]
,
code: '''
###*
* Foo
* @param {Array.<[String, Number]>} hi - desc
* @returns {Array.<[String, String]>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 19
endLine: 3
endColumn: 25
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 27
endLine: 3
endColumn: 33
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 21
endLine: 4
endColumn: 27
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 29
endLine: 4
endColumn: 35
]
,
code: '''
###*
* Foo
* @param {object<String,object<String, Number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
object: 'Object'
]
errors: [
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
,
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 31
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 32
endLine: 3
endColumn: 38
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 40
endLine: 3
endColumn: 46
]
,
# https://github.com/eslint/eslint/issues/7184
code: '''
###*
* Foo
* @param {{foo:String, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 16
endLine: 3
endColumn: 22
]
]
| 137366 | ###*
# @fileoverview Validates JSDoc comments are syntactically correct
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/valid-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'valid-jsdoc', rule,
valid: [
'''
###*
# Description
# @param {Object[]} screenings Array of screenings.
# @param {Number} screenings[].timestamp its a time stamp
@return {void}
###
foo = ->
'''
'''
###*
# Description
###
x = new Foo ->
'''
'''
###*
# Description
# @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @returns {undefined} ###
foo = ->
'''
'''
###*
* Description
* @alias Test#test
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
*@extends MyClass
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @constructor ###
Foo = ->
'''
'''
###*
* Description
* @class ###
Foo = ->
'''
'''
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @arg {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @argument {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {string} [p] bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string} p.name bar
* @returns {string} desc ###
Foo.bar = (p) ->
'''
'''
do ->
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
o =
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo: (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string[]} p.files qux
* @param {Function} cb baz
* @returns {void} ###
foo = (p, cb) ->
'''
'''
###*
* Description
* @override ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritdoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritDoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @Returns {void} ###
foo = ->
'''
,
code: '''
call(
###*
* Doc for a function expression in a call expression.
* @param {string} argName This is the param description.
* @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing
foo: ->
return 'bar'
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing {
###*
* @return {string} A string.
###
foo: ->
'bar'
}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {void} ###
foo = ->
'''
options: [{}]
,
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) => {}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = ({p}) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> func = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) ->
t = no
return if t
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {void} ###
Foo.bar = (p) ->
t = false
if t
return
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> name = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {h} i
###
Foo.bar = (p) ->
t = ->
name = ->
return name
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamDescription: no]
,
code: '''
###*
* Description
* @param {string} p mytest
* @returns {Object}###
Foo.bar = (p) -> name
'''
options: [requireReturnDescription: no]
,
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
###*
* Description for this.xs;
* @type {object[]}
###
@xs = xs.filter (x) => x != null
'''
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => return bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Start with caps and end with period.
* @return {void} ###
foo = ->
'''
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
,
code: '''
###* Foo
@return {void} Foo
###
foo = ->
'''
options: [prefer: return: 'return']
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
options: [requireReturnType: no]
,
code: '''
###*
* Description
* @param p bar
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamType: no]
,
code: '''
###*
* A thing interface.
* @interface
###
Thing = ->
'''
,
# options: [requireReturn: yes]
# classes
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description for A.
###
class A
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {f} g
###
print: (xs) ->
@a = xs
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {void}
###
print: (xs) ->
this.a = xs
'''
options: []
,
code: '''
###*
* Use of this with a 'namepath'.
* @this some.name
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Use of this with a type expression.
* @this {some.name}
* @returns {j} k
###
foo = ->
'''
,
# options: [requireReturn: no]
# async function
code: '''
###*
* An async function. Options requires return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: yes]
code: '''
###*
* An async function. Options do not require return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: no]
code: '''
###*
* An async function. Options do not require return.
* @returns {h} i
###
a = -> await b
'''
,
# options: [requireReturn: no]
# type validations
code: '''
###*
* Foo
* @param {Array.<*>} hi - desc
* @returns {*} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{String:foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
,
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) =>
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Test dash and slash.
* @extends module:stb/emitter~Emitter
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Test dash and slash.
* @requires module:config
* @requires module:modules/notifications
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @module module-name
* @returns {e} f
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @alias module:module-name
* @returns {b} c
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Array.<string|number>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<string|number>} hi - desc
* @returns {Array.<string>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Description
* @param {string} a bar
* @returns {string} desc ###
foo = (a = 1) ->
'''
,
code: '''
###*
* Description
* @param {string} b bar
* @param {string} a bar
* @returns {string} desc ###
foo = (b, a = 1) ->
'''
,
# abstract
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error 'Not Implemented'
'''
,
# options: [requireReturn: no]
# https://github.com/eslint/eslint/issues/9412 - different orders for jsodc tags
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
'* @param {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @param {string} hi - desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @constructor
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @constructor
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @class
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @override
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @inheritdoc
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @abstract
* @returns {ghi} jkl
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @virtual
* @returns {abc} def
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @interface
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = ->
'''
,
# options: [requireReturn: yes]
code: '''
###*
* @param {string} a - a.
* @param {object} [obj] - obj.
* @param {string} obj.b - b.
* @param {string} obj.c - c.
* @returns {void}
###
foo = (a, {b, c} = {}) ->
# empty
'''
,
code: '''
###*
* @param {string} a - a.
* @param {any[]} [list] - list.
* @returns {void}
###
foo = (a, [b, c] = []) ->
# empty
'''
,
# https://github.com/eslint/eslint/issues/7184
'''
###*
* Foo
* @param {{foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
'''
###*
* Foo
* @param {{foo:String, bar, baz:Array}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
,
code: '''
###*
* Foo
* @param {{String}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###* Foo
@return {sdf} jkl
###
foo = ->
'''
options: [
prefer: return: 'return'
# requireReturn: no
]
,
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {string} a desc
@returns {MyClass} a desc###
foo = (a) ->
t = false
if t
process(t)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @returns {string} something
* @param {string} p desc
###
foo = (@p) ->
'''
]
invalid: [
code: '''
call(
###*
# Doc for a function expression in a call expression.
# @param {string} bogusName This is the param description.
# @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
output: null
# options: [requireReturn: no]
errors: [
message: "Expected JSDoc for 'argName' but found 'bogusName'."
type: 'Block'
line: 4
column: 5
endLine: 4
endColumn: 61
]
,
code: '''
###* @@foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###*
# Create a new thing.
###
thing = new Thing
###*
# Missing return tag.
###
foo: ->
'bar'
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###* @@returns {void} Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@returns {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
# @return {void} Foo
###
foo = ->
'''
output: '''
###* Foo
# @returns {void} Foo
###
foo = ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
@argument {int} bar baz
###
foo = (bar) ->
'''
output: '''
###* Foo
@arg {int} bar baz
###
foo = (bar) ->
'''
options: [prefer: argument: 'arg']
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: 'Use @arg instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
###
foo = ->
'''
output: null
options: [prefer: returns: 'return']
errors: [
message: 'Missing JSDoc @return for function.'
type: 'Block'
]
,
code: '''
###* Foo
@return {void} Foo
###
foo.bar = () => {}
'''
output: '''
###* Foo
@returns {void} Foo
###
foo.bar = () => {}
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 8
]
,
code: '''
###* Foo
@param {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
@param {} p Bar
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@param {void Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
* @param p Desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'p'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 16
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo =
->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Description for a
###
A =
class
###*
* Description for method.
* @param {object[]} xs - xs
###
print: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string}
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc return description.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (@p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo =
(a = 1) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'a'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a Description
* @param {string} b Description
* @returns {string} something
###
foo =
(b, a = 1) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 32
,
message: "Expected JSDoc for 'a' but found 'b'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 32
]
,
code: '''
###*
* Foo
* @param {string} p desc
* @param {string} p desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Duplicate JSDoc parameter 'p'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
@returns {void}###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 25
]
,
code: '''
###*
* Foo
* @override
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @inheritdoc
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t
t
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t then return null
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '###* foo ### foo = () => bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '###* foo ### foo = () => return bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* @param fields [Array]
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'fields'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 24
]
,
code: '''
###*
* Start with caps and end with period
* @return {void} ###
foo = ->
'''
output: null
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
output: null
options: [prefer: return: 'return']
errors: [
message: 'Missing JSDoc return type.'
type: 'Block'
]
,
# classes
code: '''
###*
* Description for A
###
class A
###*
* Description for constructor
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: no
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###*
* Description for a
###
A = class
###*
* Description for constructor.
* @param {object[]} xs - xs
###
print: (xs) ->
@a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
###
print: (xs) ->
this.a = xs
'''
output: null
options: []
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc for parameter 'xs'."
type: 'Block'
]
,
code: '''
###*
* Use of this with an invalid type expression
* @this {not.a.valid.type.expression
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###*
* Use of this with a type that is not a member expression
* @this {Array<string>}
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
# async function
code: '''
###*
* An async function. Options requires return.
###
a = -> await b
'''
output: null
# options: [requireReturn: yes]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
# type validations
code: '''
###*
* Foo
* @param {String} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {{20:String}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 15
endLine: 3
endColumn: 21
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {String|number|test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
errors: [
message: "Use 'Test' instead of 'test'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 29
]
,
code: '''
###*
* Foo
* @param {Array.<String>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
]
,
code: '''
###*
* Foo
* @param {Array.<{id: Number, votes: Number}>} hi - desc
* @returns {Array.<{summary: String}>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 23
endLine: 3
endColumn: 29
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 38
endLine: 3
endColumn: 44
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 30
endLine: 4
endColumn: 36
]
,
code: '''
###*
* Foo
* @param {Array.<[String, Number]>} hi - desc
* @returns {Array.<[String, String]>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 19
endLine: 3
endColumn: 25
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 27
endLine: 3
endColumn: 33
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 21
endLine: 4
endColumn: 27
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 29
endLine: 4
endColumn: 35
]
,
code: '''
###*
* Foo
* @param {object<String,object<String, Number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
object: 'Object'
]
errors: [
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
,
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 31
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 32
endLine: 3
endColumn: 38
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 40
endLine: 3
endColumn: 46
]
,
# https://github.com/eslint/eslint/issues/7184
code: '''
###*
* Foo
* @param {{foo:String, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 16
endLine: 3
endColumn: 22
]
]
| true | ###*
# @fileoverview Validates JSDoc comments are syntactically correct
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/valid-jsdoc'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'valid-jsdoc', rule,
valid: [
'''
###*
# Description
# @param {Object[]} screenings Array of screenings.
# @param {Number} screenings[].timestamp its a time stamp
@return {void}
###
foo = ->
'''
'''
###*
# Description
###
x = new Foo ->
'''
'''
###*
# Description
# @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @returns {undefined} ###
foo = ->
'''
'''
###*
* Description
* @alias Test#test
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
*@extends MyClass
* @returns {void} ###
foo = ->
'''
'''
###*
* Description
* @constructor ###
Foo = ->
'''
'''
###*
* Description
* @class ###
Foo = ->
'''
'''
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @arg {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @argument {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {string} [p] bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string} p.name bar
* @returns {string} desc ###
Foo.bar = (p) ->
'''
'''
do ->
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo = (p) ->
'''
'''
o =
###*
* Description
* @param {string} p bar
* @returns {string} desc ###
foo: (p) ->
'''
'''
###*
* Description
* @param {Object} p bar
* @param {string[]} p.files qux
* @param {Function} cb baz
* @returns {void} ###
foo = (p, cb) ->
'''
'''
###*
* Description
* @override ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritdoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @inheritDoc ###
foo = (arg1, arg2) -> ''
'''
'''
###*
* Description
* @Returns {void} ###
foo = ->
'''
,
code: '''
call(
###*
* Doc for a function expression in a call expression.
* @param {string} argName This is the param description.
* @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing
foo: ->
return 'bar'
'''
,
# options: [requireReturn: no]
code: '''
###*
* Create a new thing.
###
thing = new Thing {
###*
* @return {string} A string.
###
foo: ->
'bar'
}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {void} ###
foo = ->
'''
options: [{}]
,
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) => {}
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = ({p}) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p bar
* @returns {f} g
###
Foo.bar = (p) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> func = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) ->
t = no
return if t
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {void} ###
Foo.bar = (p) ->
t = false
if t
return
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {f} g
###
Foo.bar = (p) -> t = -> name = -> return p
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p mytest
* @returns {h} i
###
Foo.bar = (p) ->
t = ->
name = ->
return name
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} p
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamDescription: no]
,
code: '''
###*
* Description
* @param {string} p mytest
* @returns {Object}###
Foo.bar = (p) -> name
'''
options: [requireReturnDescription: no]
,
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
###*
* Description for this.xs;
* @type {object[]}
###
@xs = xs.filter (x) => x != null
'''
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '###* @returns {object} foo ### foo = () => return bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Start with caps and end with period.
* @return {void} ###
foo = ->
'''
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
,
code: '''
###* Foo
@return {void} Foo
###
foo = ->
'''
options: [prefer: return: 'return']
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
options: [requireReturnType: no]
,
code: '''
###*
* Description
* @param p bar
* @returns {void}###
Foo.bar = (p) ->
t = ->
name = ->
name
'''
options: [requireParamType: no]
,
code: '''
###*
* A thing interface.
* @interface
###
Thing = ->
'''
,
# options: [requireReturn: yes]
# classes
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description for A.
###
class A
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {f} g
###
print: (xs) ->
@a = xs
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
* @param {object[]} xs - xs
* @returns {void}
###
print: (xs) ->
this.a = xs
'''
options: []
,
code: '''
###*
* Use of this with a 'namepath'.
* @this some.name
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Use of this with a type expression.
* @this {some.name}
* @returns {j} k
###
foo = ->
'''
,
# options: [requireReturn: no]
# async function
code: '''
###*
* An async function. Options requires return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: yes]
code: '''
###*
* An async function. Options do not require return.
* @returns {Promise} that is empty
###
a = -> await b
'''
,
# options: [requireReturn: no]
code: '''
###*
* An async function. Options do not require return.
* @returns {h} i
###
a = -> await b
'''
,
# options: [requireReturn: no]
# type validations
code: '''
###*
* Foo
* @param {Array.<*>} hi - desc
* @returns {*} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{String:foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
,
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) =>
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Test dash and slash.
* @extends module:stb/emitter~Emitter
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Test dash and slash.
* @requires module:config
* @requires module:modules/notifications
* @returns {f} g
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @module module-name
* @returns {e} f
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @alias module:module-name
* @returns {b} c
###
foo = ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Array.<string|number>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<string|number>} hi - desc
* @returns {Array.<string>} desc
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
,
code: '''
###*
* Description
* @param {string} a bar
* @returns {string} desc ###
foo = (a = 1) ->
'''
,
code: '''
###*
* Description
* @param {string} b bar
* @param {string} a bar
* @returns {string} desc ###
foo = (b, a = 1) ->
'''
,
# abstract
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error 'Not Implemented'
'''
,
# options: [requireReturn: no]
# https://github.com/eslint/eslint/issues/9412 - different orders for jsodc tags
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
'* @param {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @param {string} hi - desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @returns {Number} desc
* @class
* @inheritdoc
* @virtual
* @interface
* @argument {string} hi - desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @return {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @constructor
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @class
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @returns {Number} desc
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
###
foo = (hi) -> return 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @constructor
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @constructor
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @override
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @inheritdoc
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @class
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @override
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @inheritdoc
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @inheritdoc
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @abstract
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @abstract
* @returns {ghi} jkl
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @interface
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @virtual
* @returns {abc} def
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @param {string} hi - desc
* @return {Number} desc
* @constructor
* @override
* @abstract
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @arg {string} hi - desc
* @returns {Number} desc
* @class
* @override
* @virtual
* @interface
###
foo = (hi) -> 1
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @argument {string} hi - desc
* @interface
###
foo = (hi) ->
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @virtual
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: no]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = -> throw new Error('Not Implemented')
'''
,
# options: [requireReturn: yes]
code: '''
###*
* Description
* @abstract
* @returns {Number} desc
###
foo = ->
'''
,
# options: [requireReturn: yes]
code: '''
###*
* @param {string} a - a.
* @param {object} [obj] - obj.
* @param {string} obj.b - b.
* @param {string} obj.c - c.
* @returns {void}
###
foo = (a, {b, c} = {}) ->
# empty
'''
,
code: '''
###*
* @param {string} a - a.
* @param {any[]} [list] - list.
* @returns {void}
###
foo = (a, [b, c] = []) ->
# empty
'''
,
# https://github.com/eslint/eslint/issues/7184
'''
###*
* Foo
* @param {{foo}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
'''
###*
* Foo
* @param {{foo:String, bar, baz:Array}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
,
code: '''
###*
* Foo
* @param {{String}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
,
code: '''
###* Foo
@return {sdf} jkl
###
foo = ->
'''
options: [
prefer: return: 'return'
# requireReturn: no
]
,
code: '###* @returns {object} foo ### foo = () => bar()'
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @param {string} a desc
@returns {MyClass} a desc###
foo = (a) ->
t = false
if t
process(t)
'''
,
# options: [requireReturn: no]
code: '''
###*
* Foo
* @returns {string} something
* @param {string} p desc
###
foo = (@p) ->
'''
]
invalid: [
code: '''
call(
###*
# Doc for a function expression in a call expression.
# @param {string} bogusName This is the param description.
# @return {string} This is the return description.
###
(argName) ->
return 'the return'
)
'''
output: null
# options: [requireReturn: no]
errors: [
message: "Expected JSDoc for 'argName' but found 'bogusName'."
type: 'Block'
line: 4
column: 5
endLine: 4
endColumn: 61
]
,
code: '''
###* @@foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###*
# Create a new thing.
###
thing = new Thing
###*
# Missing return tag.
###
foo: ->
'bar'
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###* @@returns {void} Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@returns {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
# @return {void} Foo
###
foo = ->
'''
output: '''
###* Foo
# @returns {void} Foo
###
foo = ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
@argument {int} bar baz
###
foo = (bar) ->
'''
output: '''
###* Foo
@arg {int} bar baz
###
foo = (bar) ->
'''
options: [prefer: argument: 'arg']
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: 'Use @arg instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 10
]
,
code: '''
###* Foo
###
foo = ->
'''
output: null
options: [prefer: returns: 'return']
errors: [
message: 'Missing JSDoc @return for function.'
type: 'Block'
]
,
code: '''
###* Foo
@return {void} Foo
###
foo.bar = () => {}
'''
output: '''
###* Foo
@returns {void} Foo
###
foo.bar = () => {}
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 2
column: 1
endLine: 2
endColumn: 8
]
,
code: '''
###* Foo
@param {void Foo
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
@param {} p Bar
###
foo = ->
'''
output: null
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
code: '''
###* Foo
@param {void Foo ###
foo = ->
'''
output: null
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###* Foo
* @param p Desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'p'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 16
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {string} p
###
foo =
->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter description for 'p'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 20
]
,
code: '''
###*
* Description for a
###
A =
class
###*
* Description for method.
* @param {object[]} xs - xs
###
print: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string}
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc return description.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo = (@p) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'p'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @returns {string} something
###
foo =
(a = 1) ->
'''
output: null
errors: [
message: "Missing JSDoc for parameter 'a'."
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a Description
* @param {string} b Description
* @returns {string} something
###
foo =
(b, a = 1) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 32
,
message: "Expected JSDoc for 'a' but found 'b'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 32
]
,
code: '''
###*
* Foo
* @param {string} p desc
* @param {string} p desc
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Duplicate JSDoc parameter 'p'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
@returns {void}###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 3
column: 3
endLine: 3
endColumn: 25
]
,
code: '''
###*
* Foo
* @override
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @inheritdoc
* @param {string} a desc
###
foo = (b) ->
'''
output: null
errors: [
message: "Expected JSDoc for 'b' but found 'a'."
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 25
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t
t
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Foo
* @param {string} a desc
###
foo = (a) ->
t = false
if t then return null
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '''
###*
* Does something.
* @param {string} a - this is a
* @return {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
output: '''
###*
* Does something.
* @param {string} a - this is a
* @returns {Array<number>} The result of doing it
###
export default doSomething = (a) ->
'''
options: [prefer: return: 'returns']
errors: [
message: 'Use @returns instead.'
type: 'Block'
line: 4
column: 3
endLine: 4
endColumn: 10
]
,
code: '###* foo ### foo = () => bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '###* foo ### foo = () => return bar()'
output: null
# options: [requireReturn: no]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* @param fields [Array]
###
foo = ->
'''
output: null
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc parameter type for 'fields'."
type: 'Block'
line: 2
column: 3
endLine: 2
endColumn: 24
]
,
code: '''
###*
* Start with caps and end with period
* @return {void} ###
foo = ->
'''
output: null
options: [matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$']
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###* Foo
@return Foo
###
foo = ->
'''
output: null
options: [prefer: return: 'return']
errors: [
message: 'Missing JSDoc return type.'
type: 'Block'
]
,
# classes
code: '''
###*
* Description for A
###
class A
###*
* Description for constructor
* @param {object[]} xs - xs
###
constructor: (xs) ->
this.a = xs
'''
output: null
options: [
# requireReturn: no
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
]
,
code: '''
###*
* Description for a
###
A = class
###*
* Description for constructor.
* @param {object[]} xs - xs
###
print: (xs) ->
@a = xs
'''
output: null
options: [
# requireReturn: yes
matchDescription: '^[A-Z][A-Za-z0-9\\s]*[.]$'
]
errors: [
message: 'JSDoc description does not satisfy the regex pattern.'
type: 'Block'
,
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
code: '''
###*
* Description for A.
###
class A
###*
* Description for constructor.
* @param {object[]} xs - xs
* @returns {void}
###
constructor: (xs) ->
this.a = xs
###*
* Description for method.
###
print: (xs) ->
this.a = xs
'''
output: null
options: []
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
,
message: "Missing JSDoc for parameter 'xs'."
type: 'Block'
]
,
code: '''
###*
* Use of this with an invalid type expression
* @this {not.a.valid.type.expression
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc type missing brace.'
type: 'Block'
]
,
code: '''
###*
* Use of this with a type that is not a member expression
* @this {Array<string>}
###
foo = ->
'''
output: null
# options: [requireReturn: no]
errors: [
message: 'JSDoc syntax error.'
type: 'Block'
]
,
# async function
code: '''
###*
* An async function. Options requires return.
###
a = -> await b
'''
output: null
# options: [requireReturn: yes]
errors: [
message: 'Missing JSDoc @returns for function.'
type: 'Block'
]
,
# type validations
code: '''
###*
* Foo
* @param {String} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {string} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {{20:String}} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{20:string}} hi - desc
* @returns {ASTNode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
Astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 15
endLine: 3
endColumn: 21
,
message: "Use 'ASTNode' instead of 'Astnode'."
type: 'Block'
line: 4
column: 13
endLine: 4
endColumn: 20
]
,
code: '''
###*
* Foo
* @param {String|number|test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {String|number|Test} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
test: 'Test'
]
errors: [
message: "Use 'Test' instead of 'test'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 29
]
,
code: '''
###*
* Foo
* @param {Array.<String>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<string>} hi - desc
* @returns {Astnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
]
,
code: '''
###*
* Foo
* @param {Array.<{id: Number, votes: Number}>} hi - desc
* @returns {Array.<{summary: String}>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<{id: number, votes: number}>} hi - desc
* @returns {Array.<{summary: string}>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 23
endLine: 3
endColumn: 29
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 38
endLine: 3
endColumn: 44
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 30
endLine: 4
endColumn: 36
]
,
code: '''
###*
* Foo
* @param {Array.<[String, Number]>} hi - desc
* @returns {Array.<[String, String]>} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Array.<[string, number]>} hi - desc
* @returns {Array.<[string, string]>} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 19
endLine: 3
endColumn: 25
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 27
endLine: 3
endColumn: 33
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 21
endLine: 4
endColumn: 27
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 4
column: 29
endLine: 4
endColumn: 35
]
,
code: '''
###*
* Foo
* @param {object<String,object<String, Number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {Object<string,Object<string, number>>} hi - because why not
* @returns {Boolean} desc
###
foo = (hi) ->
'''
options: [
preferType:
Number: 'number'
String: 'string'
object: 'Object'
]
errors: [
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 11
endLine: 3
endColumn: 17
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 18
endLine: 3
endColumn: 24
,
message: "Use 'Object' instead of 'object'."
type: 'Block'
line: 3
column: 25
endLine: 3
endColumn: 31
,
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 32
endLine: 3
endColumn: 38
,
message: "Use 'number' instead of 'Number'."
type: 'Block'
line: 3
column: 40
endLine: 3
endColumn: 46
]
,
# https://github.com/eslint/eslint/issues/7184
code: '''
###*
* Foo
* @param {{foo:String, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
output: '''
###*
* Foo
* @param {{foo:string, astnode:Object, bar}} hi - desc
* @returns {ASTnode} returns a node
###
foo = (hi) ->
'''
options: [
preferType:
String: 'string'
astnode: 'ASTNode'
]
errors: [
message: "Use 'string' instead of 'String'."
type: 'Block'
line: 3
column: 16
endLine: 3
endColumn: 22
]
]
|
[
{
"context": "ELE_DETAIL:'Cbb_ele_detail'\n\n EMP_NAME_DEFAULT: 'eui'\n EMP_DEFAULT_VER: '0.1'\n EMP_TEMPLATES_PATH:",
"end": 2596,
"score": 0.6504067778587341,
"start": 2595,
"tag": "USERNAME",
"value": "e"
},
{
"context": "ack_detail.json'\n EMP_TEMPLATES_DEFAULT_KEY: 'emp-temp... | lib/exports/emp.coffee | jcrom/emp-template-management | 1 | #cs macro defined
fs = require 'fs'
path = require 'path'
os = require 'os'
remote = require 'remote'
dialog = remote.require 'dialog'
module.exports =
# 在 Cnfig 中保存数据
EMP_APP_EXPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Export-Path'
EMP_APP_IMPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Import-Path'
EMP_APP_STORE_UI_PATH :'emp-template-management.Store-UI-Snippet-Path'
PACKAGE_NAME:"emp-template-management"
TOOL_FIRST:"1"
TOOL_SECOND: "2"
TOOL_THIRD: "3"
TOOL_FOURTH: "4"
# 默认的 snippet 保存导出/导入路径
DEFAULT_SNIPPET_EXPORT_PATH:'snippets'
DEFAULT_CSS_EXPORT_PATH:'css'
# 默认的 source 类型
DEFAULT_SNIPPET_SOURE_TYPE:'.source.xhtml'
DEFAULT_SNIPPET_FILE_EXT: '.cson'
DEFAULT_CSS_FILE_EXT: '.css'
JSON_SNIPPET_FILE_EXT: '.json'
# 默认代码段传参类型
DEFAULT_SNIPPET_TYPE: '.emp.parameter'
DEFAULT_SNIPPET_TYPE_KEY: 'type_list'
EMP_DEFAULT_SNIPPETS:["emp-lua.cson", "eui.cson"]
# EMP_ALL_TYPE : "All Type"
EMP_HTML_GRAMMAR:"source.xhtml"
EMP_CSS_GRAMMAR:"source.css"
EMP_LUA_GRAMMAR:"source.lua"
# 创建模板临时文件路径
EMP_TMP_TEMP_FILE_PATH:'tmp_file'
EMP_TMP_TEMP_HTML:'tmp.xhtml'
EMP_TMP_TEMP_CSS:'tmp.css'
EMP_TMP_TEMP_LUA:'tmp.lua'
EMP_TMP_TEMP_CSON:'tmp.cson'
EMP_GRAMMAR_XHTML:'Emp View'
EMP_GRAMMAR_CSS:'CSS'
EMP_GRAMMAR_LUA:'LUA'
EMP_OFF_CHA_LV_PATH:"channels"
EMP_OFF_COM_LV_PATH:"common"
EMP_OFF_ROOT_LV_PATH:"resource_dev"
# 描述文件类型
EMP_JSON_ALL:'0'
EMP_JSON_PACK:'1'
EMP_JSON_TYPE:'2'
EMP_JSON_ELE:'3'
# 默认的描述
EMP_DEF_DESC: "这是一段默认的描述."
EMP_DEF_PAC_DESC: "该模板集是默认的模板集."
# 默认的警示
EMP_NO_EMPTY: "该输入项不能为空!"
EMP_DUPLICATE: "该输入项已经存在!"
EMP_EXIST: "该添加项已经存在!"
EMP_ADD_SUCCESS: "添加成功!"
EMP_EDIT_SUCCESS: "编辑成功!"
EMP_SAVE_SUCCESS: "保存成功!"
EMP_EXP_SUCCESS: "导出成功!"
EMP_IMPORT_SUCCESS: "导入成功!"
EMP_NO_EMPTY_PATH: "输入地址项不能为空!"
EMP_SRC_ELE_VIEW:"1"
EMP_DETAIL_ELE_VIEW:"2"
ENTERKEY:13
ESCAPEKEY:27
EMP_TEMP_URI : 'emp://template_management_wizard'
EMP_KEYMAP_MAN : 'emp://keymaps_man'
LOGO_IMAGE_SIZE : '48px'
LOGO_IMAGE_BIG_SIZE : '156px'
KEYMAP_WIZARD_VIEW: 'EmpKeymapsView'
TEMP_WIZARD_VIEW: 'EmpTemplateView'
DEFAULT_PANEL: 'OverView'
EMP_TEMPLATE:'Template'
EMP_UPLOAD:'Add Template'
EMP_DOWNLOAD:'Download'
EMP_Setting:'Cbb Tool Setting'
EMP_SHOW_UI_LIB:'Show UI Snippets'
EMP_UI_LIB:'Add UI Snippets'
EMP_EXI:'Export/Inport'
EMP_CONFIG:'Config'
EMP_NEW_CMI:'New Template'
EMP_SNIPPET_DETAIL:'show_snippet_detail'
EMP_CCB_PACK_DETAIL:'Cbb_pack_detail'
EMP_CBB_ELE_DETAIL:'Cbb_ele_detail'
EMP_NAME_DEFAULT: 'eui'
EMP_DEFAULT_VER: '0.1'
EMP_TEMPLATES_PATH:'templates'
EMP_TEMPLATES_JSON: 'templates.json'
EMP_TEMPLATE_JSON: 'template.json'
EMP_ZIP_DETAIL: 'pack_detail.json'
EMP_TEMPLATES_DEFAULT_KEY: 'emp-template-management.defaultStorePath'
# EMP_TEMPLATES_USER_KEY: 'emp-template-management.userStorePath'
EMP_LOGO_DIR:"logo"
EMP_IMG_DIR:"image"
EMP_HTML_DIR:"xhtml"
EMP_CSS_DIR:"css"
EMP_LUA_DIR:"lua"
EMP_IMGS_DIR:"images"
COMMON_DIR_LIST :["images", "css", "lua", "xhtml","channels"]
OFF_CHA_DIR_LIST : ["xhtml", "css", "lua", "images", "json"]
OFF_CHA_PLT_LIST:["wp", "iphone", "android", "common"]
# 存储类型
EMP_CON_TYPE: '0'
EMP_FILE_TYPE: '1'
EMP_DEFAULT_HTML_TEMP: "default.xhtml"
EMP_DEFAULT_CSS_TEMP: "default.css"
EMP_DEFAULT_LUA_TEMP: "default.lua"
EMP_DEFAULT_LOGO: "images/logo/logo_s.png"
# 代码全部目录
EMP_ALL_PACKAGE: "ALL"
EMP_ALL_TYPE: "ALL"
# 代码根目录
EMP_DEFAULT_PACKAGE: "default"
# 代码类型
EMP_DEFAULT_TYPE: "componment"
# 代码列表
EMP_CBB_LIST: "list_info"
# 快速添加 报文类型
EMP_QHTML:'0'
EMP_QCSS:'1'
EMP_QLUA:'2'
# config key
EMP_CBB_TYPE: 'emp-template-management.cbb_type'
#保存模板添加过程中选中的 package
EMP_ADD_TEMP_STORE_PACK:'emp-template-management.cbb_add_temp_pack'
EMP_ADD_TEMP_STORE_TYPE:'emp-template-management.cbb_add_temp_type'
# config value
EMP_CPP_TYPE_DEF:[]
# EMP APP Common Resource Path
EMP_RESOURCE_PATH: "public/www/resource_dev/common/"
EMP_TEMPLATE_CSS_NAME_HEAD : "ert_ui_"
EMP_TEMPLATE_CSS_HEAD: "/* Copyright (c) 2015-2016 Beijing RYTong Information Technologies, Ltd.\r\n
All rights reserved.\r\n
No part of this source code may be copied, used, or modified\r\n
without the express written consent of RYTong. \r\n
This file is created by EMP Template Management.\r\n*/\r\n"
STATIC_UI_CSS_TEMPLATE_DEST_PATH:"public/www/resource_dev/common/css/"
new_templates_obj: ->
tmp_obj = {templates:{}, length:0}
if !emp_cbb_types = atom.config.get @EMP_CBB_TYPE
atom.config.set @EMP_CBB_TYPE, @EMP_CPP_TYPE_DEF
emp_cbb_types = @EMP_CPP_TYPE_DEF
emp_cbb_types.push @EMP_DEFAULT_TYPE
for cbb_type in emp_cbb_types
tmp_obj.templates[cbb_type] = new Object(length:0)
tmp_obj
get_default_logo: ->
path.join __dirname,'..', '..', @EMP_DEFAULT_LOGO
get_default_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME), this.EMP_TEMPLATES_PATH
DEFAULT_SNIPPET_STORE_PATH:"store_snippet"
get_default_snippet_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_STORE_PATH
get_snippet_load_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_EXPORT_PATH
get_pack_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME)
create_editor:(tmp_file_path, tmp_grammar, callback, content) ->
changeFocus = true
tmp_editor = atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
gramers = @getGrammars(tmp_grammar)
# console.log content
unless content is undefined
tmp_editor.setText(content) #unless !content
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
callback(tmp_editor)
# set the opened editor grammar, default is HTML
getGrammars: (grammar_name)->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is grammar_name
grammars
get_project_path: ->
project_path_list = atom.project.getPaths()
project_path = project_path_list[0]
editor = atom.workspace.getActiveTextEditor()
if editor
# 判断 project 有多个的情况
efile_path = editor.getPath?()
if project_path_list.length > 1
for tmp_path in project_path_list
relate_path = path.relative tmp_path, efile_path
if relate_path.match(/^\.\..*/ig) isnt null
project_path = tmp_path
break
project_path
module.exports.mk_node_name = (node_name="") ->
default_name = " -sname "
tmp_re = node_name.split("@")
def_node_name = "atom_js" + Math.round(Math.random()*100)
def_host = " "
if tmp_re.length >1
# console.log "node name has HOST~"
if valid_ip(tmp_re[1])
default_name = " -name "
def_host = get_def_host()
def_node_name = def_node_name + "@" +def_host
# console.log def_host
re_name = default_name + def_node_name
{name:def_node_name, node_name: re_name}
get_def_host = ->
add_list = os.networkInterfaces()
tmp_address = ''
for key,val of add_list
# console.log val
for tmp_obj in val
if !tmp_obj.internal and tmp_obj.family is 'IPv4'
tmp_address = tmp_obj.address
break
tmp_address
module.exports.show_error = (err_msg) ->
atom.confirm
message:"Error"
detailedMessage:err_msg
buttons:["Ok"]
module.exports.show_warnning = (warn_msg) ->
atom.confirm
message:"Warnning"
detailedMessage:warn_msg
buttons:["Ok"]
module.exports.show_info = (info_msg) ->
atom.confirm
message:"Info"
detailedMessage:info_msg
buttons:["Ok"]
module.exports.self_info = (title_msg, detail_msg) ->
atom.confirm
message:title_msg
detailedMessage:detail_msg
buttons:["Ok"]
module.exports.show_alert = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'否': -> return 0
'是': -> return 1
module.exports.show_alert_cancel = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'是': -> return 1
'否': -> return 0
'取消': -> return 2
module.exports.isEmpty = (obj) ->
for key,name of obj
false;
true;
module.exports.get_emp_os = () ->
if !atom.project.emp_os
atom.project.emp_os = os.platform().toLowerCase()
atom.project.emp_os
module.exports.mkdir_sync = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
module.exports.mkdirs_sync = (root_dir, dir_list) ->
for dir in dir_list
tmp_dir = root_dir+dir
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
mkdir_sync_safe = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
mkdir_sync_safe(path.dirname tmp_dir)
fs.mkdirSync(tmp_dir);
mk_dirs_sync = (p, made) ->
# default mode is 0777
# mask = ~process.umask()
#
# mode = 0777 & (~process.umask()) unless mode
made = null unless made
# mode = parseInt(mode, 8) unless typeof mode isnt 'string'
p = path.resolve(p)
try
fs.mkdirSync(p)
made = made || p
catch err0
switch err0.code
when 'ENOENT'
made = mk_dirs_sync(path.dirname(p), made)
mk_dirs_sync(p, made)
# // In the case of any other error, just see if there's a dir
# // there already. If so, then hooray! If not, then something
# // is borked.
else
stat = null
try
stat = fs.statSync(p)
catch err1
throw err0
unless stat.isDirectory()
throw err0
made
# 添加资源描述图片
module.exports.chose_detail_f = (callback)->
@chose_detail(['openFile'], callback)
module.exports.chose_detail_d = (callback)->
@chose_detail(['openFile', 'openDirectory'], callback)
module.exports.chose_detail = (opts=['openFile', "openDirectory"], callback)->
dialog.showOpenDialog title: 'Select', properties: opts, (img_path) =>
if img_path
if callback
callback(img_path[0])
module.exports.get_random = (range) ->
Math.round(Math.random()*range)
module.exports.get_sep_path = (tmp_path='') ->
path_ele = tmp_path.split /[/\\]/ig
path_ele.join path.sep
valid_ip = (ip_add)->
# console.log ip_add
ip_add.match(///^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$///ig)
module.exports.mk_dirs_sync = mk_dirs_sync
module.exports.valid_ip = valid_ip
module.exports.mkdir_sync_safe = mkdir_sync_safe
| 19385 | #cs macro defined
fs = require 'fs'
path = require 'path'
os = require 'os'
remote = require 'remote'
dialog = remote.require 'dialog'
module.exports =
# 在 Cnfig 中保存数据
EMP_APP_EXPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Export-Path'
EMP_APP_IMPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Import-Path'
EMP_APP_STORE_UI_PATH :'emp-template-management.Store-UI-Snippet-Path'
PACKAGE_NAME:"emp-template-management"
TOOL_FIRST:"1"
TOOL_SECOND: "2"
TOOL_THIRD: "3"
TOOL_FOURTH: "4"
# 默认的 snippet 保存导出/导入路径
DEFAULT_SNIPPET_EXPORT_PATH:'snippets'
DEFAULT_CSS_EXPORT_PATH:'css'
# 默认的 source 类型
DEFAULT_SNIPPET_SOURE_TYPE:'.source.xhtml'
DEFAULT_SNIPPET_FILE_EXT: '.cson'
DEFAULT_CSS_FILE_EXT: '.css'
JSON_SNIPPET_FILE_EXT: '.json'
# 默认代码段传参类型
DEFAULT_SNIPPET_TYPE: '.emp.parameter'
DEFAULT_SNIPPET_TYPE_KEY: 'type_list'
EMP_DEFAULT_SNIPPETS:["emp-lua.cson", "eui.cson"]
# EMP_ALL_TYPE : "All Type"
EMP_HTML_GRAMMAR:"source.xhtml"
EMP_CSS_GRAMMAR:"source.css"
EMP_LUA_GRAMMAR:"source.lua"
# 创建模板临时文件路径
EMP_TMP_TEMP_FILE_PATH:'tmp_file'
EMP_TMP_TEMP_HTML:'tmp.xhtml'
EMP_TMP_TEMP_CSS:'tmp.css'
EMP_TMP_TEMP_LUA:'tmp.lua'
EMP_TMP_TEMP_CSON:'tmp.cson'
EMP_GRAMMAR_XHTML:'Emp View'
EMP_GRAMMAR_CSS:'CSS'
EMP_GRAMMAR_LUA:'LUA'
EMP_OFF_CHA_LV_PATH:"channels"
EMP_OFF_COM_LV_PATH:"common"
EMP_OFF_ROOT_LV_PATH:"resource_dev"
# 描述文件类型
EMP_JSON_ALL:'0'
EMP_JSON_PACK:'1'
EMP_JSON_TYPE:'2'
EMP_JSON_ELE:'3'
# 默认的描述
EMP_DEF_DESC: "这是一段默认的描述."
EMP_DEF_PAC_DESC: "该模板集是默认的模板集."
# 默认的警示
EMP_NO_EMPTY: "该输入项不能为空!"
EMP_DUPLICATE: "该输入项已经存在!"
EMP_EXIST: "该添加项已经存在!"
EMP_ADD_SUCCESS: "添加成功!"
EMP_EDIT_SUCCESS: "编辑成功!"
EMP_SAVE_SUCCESS: "保存成功!"
EMP_EXP_SUCCESS: "导出成功!"
EMP_IMPORT_SUCCESS: "导入成功!"
EMP_NO_EMPTY_PATH: "输入地址项不能为空!"
EMP_SRC_ELE_VIEW:"1"
EMP_DETAIL_ELE_VIEW:"2"
ENTERKEY:13
ESCAPEKEY:27
EMP_TEMP_URI : 'emp://template_management_wizard'
EMP_KEYMAP_MAN : 'emp://keymaps_man'
LOGO_IMAGE_SIZE : '48px'
LOGO_IMAGE_BIG_SIZE : '156px'
KEYMAP_WIZARD_VIEW: 'EmpKeymapsView'
TEMP_WIZARD_VIEW: 'EmpTemplateView'
DEFAULT_PANEL: 'OverView'
EMP_TEMPLATE:'Template'
EMP_UPLOAD:'Add Template'
EMP_DOWNLOAD:'Download'
EMP_Setting:'Cbb Tool Setting'
EMP_SHOW_UI_LIB:'Show UI Snippets'
EMP_UI_LIB:'Add UI Snippets'
EMP_EXI:'Export/Inport'
EMP_CONFIG:'Config'
EMP_NEW_CMI:'New Template'
EMP_SNIPPET_DETAIL:'show_snippet_detail'
EMP_CCB_PACK_DETAIL:'Cbb_pack_detail'
EMP_CBB_ELE_DETAIL:'Cbb_ele_detail'
EMP_NAME_DEFAULT: 'eui'
EMP_DEFAULT_VER: '0.1'
EMP_TEMPLATES_PATH:'templates'
EMP_TEMPLATES_JSON: 'templates.json'
EMP_TEMPLATE_JSON: 'template.json'
EMP_ZIP_DETAIL: 'pack_detail.json'
EMP_TEMPLATES_DEFAULT_KEY: 'emp-<KEY>'
# EMP_TEMPLATES_USER_KEY: 'emp<KEY>-template-management.user<KEY>'
EMP_LOGO_DIR:"logo"
EMP_IMG_DIR:"image"
EMP_HTML_DIR:"xhtml"
EMP_CSS_DIR:"css"
EMP_LUA_DIR:"lua"
EMP_IMGS_DIR:"images"
COMMON_DIR_LIST :["images", "css", "lua", "xhtml","channels"]
OFF_CHA_DIR_LIST : ["xhtml", "css", "lua", "images", "json"]
OFF_CHA_PLT_LIST:["wp", "iphone", "android", "common"]
# 存储类型
EMP_CON_TYPE: '0'
EMP_FILE_TYPE: '1'
EMP_DEFAULT_HTML_TEMP: "default.xhtml"
EMP_DEFAULT_CSS_TEMP: "default.css"
EMP_DEFAULT_LUA_TEMP: "default.lua"
EMP_DEFAULT_LOGO: "images/logo/logo_s.png"
# 代码全部目录
EMP_ALL_PACKAGE: "ALL"
EMP_ALL_TYPE: "ALL"
# 代码根目录
EMP_DEFAULT_PACKAGE: "default"
# 代码类型
EMP_DEFAULT_TYPE: "componment"
# 代码列表
EMP_CBB_LIST: "list_info"
# 快速添加 报文类型
EMP_QHTML:'0'
EMP_QCSS:'1'
EMP_QLUA:'2'
# config key
EMP_CBB_TYPE: 'emp-template-management.cbb_type'
#保存模板添加过程中选中的 package
EMP_ADD_TEMP_STORE_PACK:'emp-template-management.cbb_add_temp_pack'
EMP_ADD_TEMP_STORE_TYPE:'emp-template-management.cbb_add_temp_type'
# config value
EMP_CPP_TYPE_DEF:[]
# EMP APP Common Resource Path
EMP_RESOURCE_PATH: "public/www/resource_dev/common/"
EMP_TEMPLATE_CSS_NAME_HEAD : "ert_ui_"
EMP_TEMPLATE_CSS_HEAD: "/* Copyright (c) 2015-2016 Beijing RYTong Information Technologies, Ltd.\r\n
All rights reserved.\r\n
No part of this source code may be copied, used, or modified\r\n
without the express written consent of RYTong. \r\n
This file is created by EMP Template Management.\r\n*/\r\n"
STATIC_UI_CSS_TEMPLATE_DEST_PATH:"public/www/resource_dev/common/css/"
new_templates_obj: ->
tmp_obj = {templates:{}, length:0}
if !emp_cbb_types = atom.config.get @EMP_CBB_TYPE
atom.config.set @EMP_CBB_TYPE, @EMP_CPP_TYPE_DEF
emp_cbb_types = @EMP_CPP_TYPE_DEF
emp_cbb_types.push @EMP_DEFAULT_TYPE
for cbb_type in emp_cbb_types
tmp_obj.templates[cbb_type] = new Object(length:0)
tmp_obj
get_default_logo: ->
path.join __dirname,'..', '..', @EMP_DEFAULT_LOGO
get_default_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME), this.EMP_TEMPLATES_PATH
DEFAULT_SNIPPET_STORE_PATH:"store_snippet"
get_default_snippet_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_STORE_PATH
get_snippet_load_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_EXPORT_PATH
get_pack_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME)
create_editor:(tmp_file_path, tmp_grammar, callback, content) ->
changeFocus = true
tmp_editor = atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
gramers = @getGrammars(tmp_grammar)
# console.log content
unless content is undefined
tmp_editor.setText(content) #unless !content
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
callback(tmp_editor)
# set the opened editor grammar, default is HTML
getGrammars: (grammar_name)->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is grammar_name
grammars
get_project_path: ->
project_path_list = atom.project.getPaths()
project_path = project_path_list[0]
editor = atom.workspace.getActiveTextEditor()
if editor
# 判断 project 有多个的情况
efile_path = editor.getPath?()
if project_path_list.length > 1
for tmp_path in project_path_list
relate_path = path.relative tmp_path, efile_path
if relate_path.match(/^\.\..*/ig) isnt null
project_path = tmp_path
break
project_path
module.exports.mk_node_name = (node_name="") ->
default_name = " -sname "
tmp_re = node_name.split("@")
def_node_name = "atom_js" + Math.round(Math.random()*100)
def_host = " "
if tmp_re.length >1
# console.log "node name has HOST~"
if valid_ip(tmp_re[1])
default_name = " -name "
def_host = get_def_host()
def_node_name = def_node_name + "@" +def_host
# console.log def_host
re_name = default_name + def_node_name
{name:def_node_name, node_name: re_name}
get_def_host = ->
add_list = os.networkInterfaces()
tmp_address = ''
for key,val of add_list
# console.log val
for tmp_obj in val
if !tmp_obj.internal and tmp_obj.family is 'IPv4'
tmp_address = tmp_obj.address
break
tmp_address
module.exports.show_error = (err_msg) ->
atom.confirm
message:"Error"
detailedMessage:err_msg
buttons:["Ok"]
module.exports.show_warnning = (warn_msg) ->
atom.confirm
message:"Warnning"
detailedMessage:warn_msg
buttons:["Ok"]
module.exports.show_info = (info_msg) ->
atom.confirm
message:"Info"
detailedMessage:info_msg
buttons:["Ok"]
module.exports.self_info = (title_msg, detail_msg) ->
atom.confirm
message:title_msg
detailedMessage:detail_msg
buttons:["Ok"]
module.exports.show_alert = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'否': -> return 0
'是': -> return 1
module.exports.show_alert_cancel = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'是': -> return 1
'否': -> return 0
'取消': -> return 2
module.exports.isEmpty = (obj) ->
for key,name of obj
false;
true;
module.exports.get_emp_os = () ->
if !atom.project.emp_os
atom.project.emp_os = os.platform().toLowerCase()
atom.project.emp_os
module.exports.mkdir_sync = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
module.exports.mkdirs_sync = (root_dir, dir_list) ->
for dir in dir_list
tmp_dir = root_dir+dir
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
mkdir_sync_safe = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
mkdir_sync_safe(path.dirname tmp_dir)
fs.mkdirSync(tmp_dir);
mk_dirs_sync = (p, made) ->
# default mode is 0777
# mask = ~process.umask()
#
# mode = 0777 & (~process.umask()) unless mode
made = null unless made
# mode = parseInt(mode, 8) unless typeof mode isnt 'string'
p = path.resolve(p)
try
fs.mkdirSync(p)
made = made || p
catch err0
switch err0.code
when 'ENOENT'
made = mk_dirs_sync(path.dirname(p), made)
mk_dirs_sync(p, made)
# // In the case of any other error, just see if there's a dir
# // there already. If so, then hooray! If not, then something
# // is borked.
else
stat = null
try
stat = fs.statSync(p)
catch err1
throw err0
unless stat.isDirectory()
throw err0
made
# 添加资源描述图片
module.exports.chose_detail_f = (callback)->
@chose_detail(['openFile'], callback)
module.exports.chose_detail_d = (callback)->
@chose_detail(['openFile', 'openDirectory'], callback)
module.exports.chose_detail = (opts=['openFile', "openDirectory"], callback)->
dialog.showOpenDialog title: 'Select', properties: opts, (img_path) =>
if img_path
if callback
callback(img_path[0])
module.exports.get_random = (range) ->
Math.round(Math.random()*range)
module.exports.get_sep_path = (tmp_path='') ->
path_ele = tmp_path.split /[/\\]/ig
path_ele.join path.sep
valid_ip = (ip_add)->
# console.log ip_add
ip_add.match(///^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$///ig)
module.exports.mk_dirs_sync = mk_dirs_sync
module.exports.valid_ip = valid_ip
module.exports.mkdir_sync_safe = mkdir_sync_safe
| true | #cs macro defined
fs = require 'fs'
path = require 'path'
os = require 'os'
remote = require 'remote'
dialog = remote.require 'dialog'
module.exports =
# 在 Cnfig 中保存数据
EMP_APP_EXPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Export-Path'
EMP_APP_IMPORT_UI_PATH :'emp-template-management.Store-UI-Snippet-Import-Path'
EMP_APP_STORE_UI_PATH :'emp-template-management.Store-UI-Snippet-Path'
PACKAGE_NAME:"emp-template-management"
TOOL_FIRST:"1"
TOOL_SECOND: "2"
TOOL_THIRD: "3"
TOOL_FOURTH: "4"
# 默认的 snippet 保存导出/导入路径
DEFAULT_SNIPPET_EXPORT_PATH:'snippets'
DEFAULT_CSS_EXPORT_PATH:'css'
# 默认的 source 类型
DEFAULT_SNIPPET_SOURE_TYPE:'.source.xhtml'
DEFAULT_SNIPPET_FILE_EXT: '.cson'
DEFAULT_CSS_FILE_EXT: '.css'
JSON_SNIPPET_FILE_EXT: '.json'
# 默认代码段传参类型
DEFAULT_SNIPPET_TYPE: '.emp.parameter'
DEFAULT_SNIPPET_TYPE_KEY: 'type_list'
EMP_DEFAULT_SNIPPETS:["emp-lua.cson", "eui.cson"]
# EMP_ALL_TYPE : "All Type"
EMP_HTML_GRAMMAR:"source.xhtml"
EMP_CSS_GRAMMAR:"source.css"
EMP_LUA_GRAMMAR:"source.lua"
# 创建模板临时文件路径
EMP_TMP_TEMP_FILE_PATH:'tmp_file'
EMP_TMP_TEMP_HTML:'tmp.xhtml'
EMP_TMP_TEMP_CSS:'tmp.css'
EMP_TMP_TEMP_LUA:'tmp.lua'
EMP_TMP_TEMP_CSON:'tmp.cson'
EMP_GRAMMAR_XHTML:'Emp View'
EMP_GRAMMAR_CSS:'CSS'
EMP_GRAMMAR_LUA:'LUA'
EMP_OFF_CHA_LV_PATH:"channels"
EMP_OFF_COM_LV_PATH:"common"
EMP_OFF_ROOT_LV_PATH:"resource_dev"
# 描述文件类型
EMP_JSON_ALL:'0'
EMP_JSON_PACK:'1'
EMP_JSON_TYPE:'2'
EMP_JSON_ELE:'3'
# 默认的描述
EMP_DEF_DESC: "这是一段默认的描述."
EMP_DEF_PAC_DESC: "该模板集是默认的模板集."
# 默认的警示
EMP_NO_EMPTY: "该输入项不能为空!"
EMP_DUPLICATE: "该输入项已经存在!"
EMP_EXIST: "该添加项已经存在!"
EMP_ADD_SUCCESS: "添加成功!"
EMP_EDIT_SUCCESS: "编辑成功!"
EMP_SAVE_SUCCESS: "保存成功!"
EMP_EXP_SUCCESS: "导出成功!"
EMP_IMPORT_SUCCESS: "导入成功!"
EMP_NO_EMPTY_PATH: "输入地址项不能为空!"
EMP_SRC_ELE_VIEW:"1"
EMP_DETAIL_ELE_VIEW:"2"
ENTERKEY:13
ESCAPEKEY:27
EMP_TEMP_URI : 'emp://template_management_wizard'
EMP_KEYMAP_MAN : 'emp://keymaps_man'
LOGO_IMAGE_SIZE : '48px'
LOGO_IMAGE_BIG_SIZE : '156px'
KEYMAP_WIZARD_VIEW: 'EmpKeymapsView'
TEMP_WIZARD_VIEW: 'EmpTemplateView'
DEFAULT_PANEL: 'OverView'
EMP_TEMPLATE:'Template'
EMP_UPLOAD:'Add Template'
EMP_DOWNLOAD:'Download'
EMP_Setting:'Cbb Tool Setting'
EMP_SHOW_UI_LIB:'Show UI Snippets'
EMP_UI_LIB:'Add UI Snippets'
EMP_EXI:'Export/Inport'
EMP_CONFIG:'Config'
EMP_NEW_CMI:'New Template'
EMP_SNIPPET_DETAIL:'show_snippet_detail'
EMP_CCB_PACK_DETAIL:'Cbb_pack_detail'
EMP_CBB_ELE_DETAIL:'Cbb_ele_detail'
EMP_NAME_DEFAULT: 'eui'
EMP_DEFAULT_VER: '0.1'
EMP_TEMPLATES_PATH:'templates'
EMP_TEMPLATES_JSON: 'templates.json'
EMP_TEMPLATE_JSON: 'template.json'
EMP_ZIP_DETAIL: 'pack_detail.json'
EMP_TEMPLATES_DEFAULT_KEY: 'emp-PI:KEY:<KEY>END_PI'
# EMP_TEMPLATES_USER_KEY: 'empPI:KEY:<KEY>END_PI-template-management.userPI:KEY:<KEY>END_PI'
EMP_LOGO_DIR:"logo"
EMP_IMG_DIR:"image"
EMP_HTML_DIR:"xhtml"
EMP_CSS_DIR:"css"
EMP_LUA_DIR:"lua"
EMP_IMGS_DIR:"images"
COMMON_DIR_LIST :["images", "css", "lua", "xhtml","channels"]
OFF_CHA_DIR_LIST : ["xhtml", "css", "lua", "images", "json"]
OFF_CHA_PLT_LIST:["wp", "iphone", "android", "common"]
# 存储类型
EMP_CON_TYPE: '0'
EMP_FILE_TYPE: '1'
EMP_DEFAULT_HTML_TEMP: "default.xhtml"
EMP_DEFAULT_CSS_TEMP: "default.css"
EMP_DEFAULT_LUA_TEMP: "default.lua"
EMP_DEFAULT_LOGO: "images/logo/logo_s.png"
# 代码全部目录
EMP_ALL_PACKAGE: "ALL"
EMP_ALL_TYPE: "ALL"
# 代码根目录
EMP_DEFAULT_PACKAGE: "default"
# 代码类型
EMP_DEFAULT_TYPE: "componment"
# 代码列表
EMP_CBB_LIST: "list_info"
# 快速添加 报文类型
EMP_QHTML:'0'
EMP_QCSS:'1'
EMP_QLUA:'2'
# config key
EMP_CBB_TYPE: 'emp-template-management.cbb_type'
#保存模板添加过程中选中的 package
EMP_ADD_TEMP_STORE_PACK:'emp-template-management.cbb_add_temp_pack'
EMP_ADD_TEMP_STORE_TYPE:'emp-template-management.cbb_add_temp_type'
# config value
EMP_CPP_TYPE_DEF:[]
# EMP APP Common Resource Path
EMP_RESOURCE_PATH: "public/www/resource_dev/common/"
EMP_TEMPLATE_CSS_NAME_HEAD : "ert_ui_"
EMP_TEMPLATE_CSS_HEAD: "/* Copyright (c) 2015-2016 Beijing RYTong Information Technologies, Ltd.\r\n
All rights reserved.\r\n
No part of this source code may be copied, used, or modified\r\n
without the express written consent of RYTong. \r\n
This file is created by EMP Template Management.\r\n*/\r\n"
STATIC_UI_CSS_TEMPLATE_DEST_PATH:"public/www/resource_dev/common/css/"
new_templates_obj: ->
tmp_obj = {templates:{}, length:0}
if !emp_cbb_types = atom.config.get @EMP_CBB_TYPE
atom.config.set @EMP_CBB_TYPE, @EMP_CPP_TYPE_DEF
emp_cbb_types = @EMP_CPP_TYPE_DEF
emp_cbb_types.push @EMP_DEFAULT_TYPE
for cbb_type in emp_cbb_types
tmp_obj.templates[cbb_type] = new Object(length:0)
tmp_obj
get_default_logo: ->
path.join __dirname,'..', '..', @EMP_DEFAULT_LOGO
get_default_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME), this.EMP_TEMPLATES_PATH
DEFAULT_SNIPPET_STORE_PATH:"store_snippet"
get_default_snippet_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_STORE_PATH
get_snippet_load_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME),this.DEFAULT_SNIPPET_EXPORT_PATH
get_pack_path: () ->
path.join atom.packages.resolvePackagePath(this.PACKAGE_NAME)
create_editor:(tmp_file_path, tmp_grammar, callback, content) ->
changeFocus = true
tmp_editor = atom.workspace.open(tmp_file_path, { changeFocus }).then (tmp_editor) =>
gramers = @getGrammars(tmp_grammar)
# console.log content
unless content is undefined
tmp_editor.setText(content) #unless !content
tmp_editor.setGrammar(gramers[0]) unless gramers[0] is undefined
callback(tmp_editor)
# set the opened editor grammar, default is HTML
getGrammars: (grammar_name)->
grammars = atom.grammars.getGrammars().filter (grammar) ->
(grammar isnt atom.grammars.nullGrammar) and
grammar.name is grammar_name
grammars
get_project_path: ->
project_path_list = atom.project.getPaths()
project_path = project_path_list[0]
editor = atom.workspace.getActiveTextEditor()
if editor
# 判断 project 有多个的情况
efile_path = editor.getPath?()
if project_path_list.length > 1
for tmp_path in project_path_list
relate_path = path.relative tmp_path, efile_path
if relate_path.match(/^\.\..*/ig) isnt null
project_path = tmp_path
break
project_path
module.exports.mk_node_name = (node_name="") ->
default_name = " -sname "
tmp_re = node_name.split("@")
def_node_name = "atom_js" + Math.round(Math.random()*100)
def_host = " "
if tmp_re.length >1
# console.log "node name has HOST~"
if valid_ip(tmp_re[1])
default_name = " -name "
def_host = get_def_host()
def_node_name = def_node_name + "@" +def_host
# console.log def_host
re_name = default_name + def_node_name
{name:def_node_name, node_name: re_name}
get_def_host = ->
add_list = os.networkInterfaces()
tmp_address = ''
for key,val of add_list
# console.log val
for tmp_obj in val
if !tmp_obj.internal and tmp_obj.family is 'IPv4'
tmp_address = tmp_obj.address
break
tmp_address
module.exports.show_error = (err_msg) ->
atom.confirm
message:"Error"
detailedMessage:err_msg
buttons:["Ok"]
module.exports.show_warnning = (warn_msg) ->
atom.confirm
message:"Warnning"
detailedMessage:warn_msg
buttons:["Ok"]
module.exports.show_info = (info_msg) ->
atom.confirm
message:"Info"
detailedMessage:info_msg
buttons:["Ok"]
module.exports.self_info = (title_msg, detail_msg) ->
atom.confirm
message:title_msg
detailedMessage:detail_msg
buttons:["Ok"]
module.exports.show_alert = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'否': -> return 0
'是': -> return 1
module.exports.show_alert_cancel = (text_title, text_msg) ->
atom.confirm
message: "#{text_title}"
detailedMessage: "#{text_msg}"
buttons:
'是': -> return 1
'否': -> return 0
'取消': -> return 2
module.exports.isEmpty = (obj) ->
for key,name of obj
false;
true;
module.exports.get_emp_os = () ->
if !atom.project.emp_os
atom.project.emp_os = os.platform().toLowerCase()
atom.project.emp_os
module.exports.mkdir_sync = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
module.exports.mkdirs_sync = (root_dir, dir_list) ->
for dir in dir_list
tmp_dir = root_dir+dir
if !fs.existsSync(tmp_dir)
fs.mkdirSync(tmp_dir);
mkdir_sync_safe = (tmp_dir) ->
if !fs.existsSync(tmp_dir)
mkdir_sync_safe(path.dirname tmp_dir)
fs.mkdirSync(tmp_dir);
mk_dirs_sync = (p, made) ->
# default mode is 0777
# mask = ~process.umask()
#
# mode = 0777 & (~process.umask()) unless mode
made = null unless made
# mode = parseInt(mode, 8) unless typeof mode isnt 'string'
p = path.resolve(p)
try
fs.mkdirSync(p)
made = made || p
catch err0
switch err0.code
when 'ENOENT'
made = mk_dirs_sync(path.dirname(p), made)
mk_dirs_sync(p, made)
# // In the case of any other error, just see if there's a dir
# // there already. If so, then hooray! If not, then something
# // is borked.
else
stat = null
try
stat = fs.statSync(p)
catch err1
throw err0
unless stat.isDirectory()
throw err0
made
# 添加资源描述图片
module.exports.chose_detail_f = (callback)->
@chose_detail(['openFile'], callback)
module.exports.chose_detail_d = (callback)->
@chose_detail(['openFile', 'openDirectory'], callback)
module.exports.chose_detail = (opts=['openFile', "openDirectory"], callback)->
dialog.showOpenDialog title: 'Select', properties: opts, (img_path) =>
if img_path
if callback
callback(img_path[0])
module.exports.get_random = (range) ->
Math.round(Math.random()*range)
module.exports.get_sep_path = (tmp_path='') ->
path_ele = tmp_path.split /[/\\]/ig
path_ele.join path.sep
valid_ip = (ip_add)->
# console.log ip_add
ip_add.match(///^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$///ig)
module.exports.mk_dirs_sync = mk_dirs_sync
module.exports.valid_ip = valid_ip
module.exports.mkdir_sync_safe = mkdir_sync_safe
|
[
{
"context": "data.auth)\n if data.auth and data.auth is '123'\n if cb\n if data.service\n ",
"end": 568,
"score": 0.9909853339195251,
"start": 565,
"tag": "PASSWORD",
"value": "123"
},
{
"context": " conn = net.Socket()\n conn.connect(port,'127... | src/test/test.coffee | Casear/zmq-soa | 1 | soa = require '../index'
logger = require('../lib/logger').logger
async = require('async')
net = require 'net'
require 'should'
broker = null
worker = null
worker2 = null
worker3 = null
worker4 = null
worker5 = null
worker6 = null
client = null
port = 8008
describe 'Initial',()->
@timeout(10000)
describe 'broker start',()->
it('should create broker and test the connection',(done)->
broker = new soa.Broker('tcp://*:'+port,{})
broker.on('auth',(envelope,data,cb)->
logger.info('auth '+data.auth)
if data.auth and data.auth is '123'
if cb
if data.service
cb true,envelope,data.service,data,data.auth
else
cb true,envelope,data,data.auth
else
cb false,envelope
else
cb false,envelope
)
finish = false
conn = net.Socket()
conn.connect(port,'127.0.0.1',()->
conn.destroy()
unless finish
finsih = true
done()
)
conn.setTimeout(2000, ()->
unless finish
finish = true
conn.destroy()
throw new Error('connection failed')
)
)
describe 'woker start',()->
it('should create woker and test to connect the broker',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('123')
worker.on 'authenticate',(result)->
result.should.equal(true)
done()
)
describe 'woker auth failed',()->
it('should create woker and test to connect the broker and auth is working',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('5678')
worker.on 'authenticate',(result)->
result.should.equal(false)
broker.services['test'].worker.should.equal(1)
done()
)
describe 'client start',()->
it('should create client and test to connect the broker',(done)->
client = new soa.Client('localhost',port,{})
client.on 'connect',()->
logger.debug('client connected')
client.on 'ready',()->
logger.debug('client ready')
client.Authenticate('123')
client.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test'].worker.should.equal(1)
done()
)
it('should create client and test to connect the broker and auth is working',(done)->
client2 = new soa.Client('localhost',port,{})
client2.on 'connect',()->
logger.debug('client connected')
client2.on 'ready',()->
logger.debug('client failed ready')
client2.Authenticate('5678')
client2.on 'authenticate',(result)->
result.should.equal(false)
done()
)
describe 'Messaging',()->
@timeout(15000)
describe 'worker get messages',()->
it('should get message from client',(done)->
worker2 = new soa.Client('localhost',port,{service:'test2'},(data,cb)->
logger.debug('get test2 message')
data.toString().should.equal('message')
cb(data,false)
)
worker2.on 'connect',()->
logger.debug('woker4 connected')
worker2.on 'ready',()->
logger.debug('worker4 ready')
worker2.Authenticate('123')
worker2.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test2'].worker.should.equal(1)
client.send('test2',new Buffer('message'),false,(err,data)->
logger.debug('test2 client back')
if err
logger.error err
throw err
else
data.toString().should.equal('message')
done()
)
)
it('should get message from client without response',(done)->
worker3 = new soa.Client('localhost',port,{service:'test3'},(data,cb)->
logger.info('get test3 message')
data.toString().should.equal('message')
logger.info('send back from test3')
cb(data,false)
done()
)
worker3.on 'connect',()->
logger.debug('woker4 connected')
worker3.on 'ready',()->
logger.debug('worker4 ready')
worker3.Authenticate('123')
worker3.on 'authenticate',(result)->
result.should.equal(true)
logger.info('send test3 message')
broker.services['test3'].worker.should.equal(1)
client.send('test3',new Buffer('message'),false,()->
logger.info('back ')
)
)
it('should get message from client and other worker',(done)->
worker4 = new soa.Client('localhost',port,{service:'test4'},(data,cb)->
logger.debug('get test4 message')
data.toString().should.equal('message')
worker4.send('test',data,false,(err,data)->
logger.debug('get test message')
if err
throw err
data.toString().should.equal('message')
cb(data,false)
)
)
worker4.on 'connect',()->
logger.debug('woker4 connected')
worker4.on 'ready',()->
logger.debug('worker4 ready')
worker4.Authenticate('123')
worker4.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test4'].worker.should.equal(1)
client.send('test4',new Buffer('message'),false,(err,data)->
logger.debug('test4 client back')
if err
throw err
data.toString().should.equal('message')
done()
)
)
describe 'Pub',()->
@timeout(20000)
describe 'Broker Send Msg ',()->
it('should get message from broker',(done)->
async.parallel([
(callback)->
worker5 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker5.on 'connect',()->
logger.debug('woker5 connected')
worker5.on 'ready',()->
logger.debug('worker5 ready')
@Authenticate('123')
worker5.on 'authenticate',(result)->
logger.info('worker5 successful')
result.should.equal(true)
(callback)->
worker6 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker6.on 'connect',()->
logger.debug('woker6 connected')
worker6.on 'ready',()->
logger.debug('worker6 ready')
@Authenticate('123')
worker6.on 'authenticate',(result)->
result.should.equal(true)
logger.info('worker6 successful')
(callback)->
setTimeout ()->
broker.Pub("ppp","pub message")
callback(null)
,6000
], (err, result)->
done()
)
)
describe 'Service',()->
@timeout(20000)
describe 'Broker Add Service Msg ',()->
it('should get message from broker',(done)->
broker.on('service',(workerlabel,msg,cb)->
msg.data.toString().should.equal("{'service':'213'}")
done()
)
worker4.sendBService(new Buffer("{'service':'213'}"))
)
###
client = new soa.Client('tcp://localhost:8008',{service:'1234'},(err,data)->
logger.debug('get worker job')
)
setTimeout(()->
t.send('1234','test',(err,data)->
logger.debug('get worker feedback.'+ (err || data) )
)
,5000)
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
###
| 220836 | soa = require '../index'
logger = require('../lib/logger').logger
async = require('async')
net = require 'net'
require 'should'
broker = null
worker = null
worker2 = null
worker3 = null
worker4 = null
worker5 = null
worker6 = null
client = null
port = 8008
describe 'Initial',()->
@timeout(10000)
describe 'broker start',()->
it('should create broker and test the connection',(done)->
broker = new soa.Broker('tcp://*:'+port,{})
broker.on('auth',(envelope,data,cb)->
logger.info('auth '+data.auth)
if data.auth and data.auth is '<PASSWORD>'
if cb
if data.service
cb true,envelope,data.service,data,data.auth
else
cb true,envelope,data,data.auth
else
cb false,envelope
else
cb false,envelope
)
finish = false
conn = net.Socket()
conn.connect(port,'127.0.0.1',()->
conn.destroy()
unless finish
finsih = true
done()
)
conn.setTimeout(2000, ()->
unless finish
finish = true
conn.destroy()
throw new Error('connection failed')
)
)
describe 'woker start',()->
it('should create woker and test to connect the broker',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('123')
worker.on 'authenticate',(result)->
result.should.equal(true)
done()
)
describe 'woker auth failed',()->
it('should create woker and test to connect the broker and auth is working',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('5678')
worker.on 'authenticate',(result)->
result.should.equal(false)
broker.services['test'].worker.should.equal(1)
done()
)
describe 'client start',()->
it('should create client and test to connect the broker',(done)->
client = new soa.Client('localhost',port,{})
client.on 'connect',()->
logger.debug('client connected')
client.on 'ready',()->
logger.debug('client ready')
client.Authenticate('123')
client.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test'].worker.should.equal(1)
done()
)
it('should create client and test to connect the broker and auth is working',(done)->
client2 = new soa.Client('localhost',port,{})
client2.on 'connect',()->
logger.debug('client connected')
client2.on 'ready',()->
logger.debug('client failed ready')
client2.Authenticate('5678')
client2.on 'authenticate',(result)->
result.should.equal(false)
done()
)
describe 'Messaging',()->
@timeout(15000)
describe 'worker get messages',()->
it('should get message from client',(done)->
worker2 = new soa.Client('localhost',port,{service:'test2'},(data,cb)->
logger.debug('get test2 message')
data.toString().should.equal('message')
cb(data,false)
)
worker2.on 'connect',()->
logger.debug('woker4 connected')
worker2.on 'ready',()->
logger.debug('worker4 ready')
worker2.Authenticate('123')
worker2.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test2'].worker.should.equal(1)
client.send('test2',new Buffer('message'),false,(err,data)->
logger.debug('test2 client back')
if err
logger.error err
throw err
else
data.toString().should.equal('message')
done()
)
)
it('should get message from client without response',(done)->
worker3 = new soa.Client('localhost',port,{service:'test3'},(data,cb)->
logger.info('get test3 message')
data.toString().should.equal('message')
logger.info('send back from test3')
cb(data,false)
done()
)
worker3.on 'connect',()->
logger.debug('woker4 connected')
worker3.on 'ready',()->
logger.debug('worker4 ready')
worker3.Authenticate('123')
worker3.on 'authenticate',(result)->
result.should.equal(true)
logger.info('send test3 message')
broker.services['test3'].worker.should.equal(1)
client.send('test3',new Buffer('message'),false,()->
logger.info('back ')
)
)
it('should get message from client and other worker',(done)->
worker4 = new soa.Client('localhost',port,{service:'test4'},(data,cb)->
logger.debug('get test4 message')
data.toString().should.equal('message')
worker4.send('test',data,false,(err,data)->
logger.debug('get test message')
if err
throw err
data.toString().should.equal('message')
cb(data,false)
)
)
worker4.on 'connect',()->
logger.debug('woker4 connected')
worker4.on 'ready',()->
logger.debug('worker4 ready')
worker4.Authenticate('123')
worker4.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test4'].worker.should.equal(1)
client.send('test4',new Buffer('message'),false,(err,data)->
logger.debug('test4 client back')
if err
throw err
data.toString().should.equal('message')
done()
)
)
describe 'Pub',()->
@timeout(20000)
describe 'Broker Send Msg ',()->
it('should get message from broker',(done)->
async.parallel([
(callback)->
worker5 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker5.on 'connect',()->
logger.debug('woker5 connected')
worker5.on 'ready',()->
logger.debug('worker5 ready')
@Authenticate('123')
worker5.on 'authenticate',(result)->
logger.info('worker5 successful')
result.should.equal(true)
(callback)->
worker6 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker6.on 'connect',()->
logger.debug('woker6 connected')
worker6.on 'ready',()->
logger.debug('worker6 ready')
@Authenticate('123')
worker6.on 'authenticate',(result)->
result.should.equal(true)
logger.info('worker6 successful')
(callback)->
setTimeout ()->
broker.Pub("ppp","pub message")
callback(null)
,6000
], (err, result)->
done()
)
)
describe 'Service',()->
@timeout(20000)
describe 'Broker Add Service Msg ',()->
it('should get message from broker',(done)->
broker.on('service',(workerlabel,msg,cb)->
msg.data.toString().should.equal("{'service':'213'}")
done()
)
worker4.sendBService(new Buffer("{'service':'213'}"))
)
###
client = new soa.Client('tcp://localhost:8008',{service:'1234'},(err,data)->
logger.debug('get worker job')
)
setTimeout(()->
t.send('1234','test',(err,data)->
logger.debug('get worker feedback.'+ (err || data) )
)
,5000)
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
###
| true | soa = require '../index'
logger = require('../lib/logger').logger
async = require('async')
net = require 'net'
require 'should'
broker = null
worker = null
worker2 = null
worker3 = null
worker4 = null
worker5 = null
worker6 = null
client = null
port = 8008
describe 'Initial',()->
@timeout(10000)
describe 'broker start',()->
it('should create broker and test the connection',(done)->
broker = new soa.Broker('tcp://*:'+port,{})
broker.on('auth',(envelope,data,cb)->
logger.info('auth '+data.auth)
if data.auth and data.auth is 'PI:PASSWORD:<PASSWORD>END_PI'
if cb
if data.service
cb true,envelope,data.service,data,data.auth
else
cb true,envelope,data,data.auth
else
cb false,envelope
else
cb false,envelope
)
finish = false
conn = net.Socket()
conn.connect(port,'127.0.0.1',()->
conn.destroy()
unless finish
finsih = true
done()
)
conn.setTimeout(2000, ()->
unless finish
finish = true
conn.destroy()
throw new Error('connection failed')
)
)
describe 'woker start',()->
it('should create woker and test to connect the broker',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('123')
worker.on 'authenticate',(result)->
result.should.equal(true)
done()
)
describe 'woker auth failed',()->
it('should create woker and test to connect the broker and auth is working',(done)->
worker = new soa.Client('localhost',port,{service:'test'},(data,cb)->
logger.debug('get test message')
cb(data,false)
)
worker.on 'connect',()->
logger.debug('woker connected')
worker.on 'ready',()->
logger.debug('worker ready')
worker.Authenticate('5678')
worker.on 'authenticate',(result)->
result.should.equal(false)
broker.services['test'].worker.should.equal(1)
done()
)
describe 'client start',()->
it('should create client and test to connect the broker',(done)->
client = new soa.Client('localhost',port,{})
client.on 'connect',()->
logger.debug('client connected')
client.on 'ready',()->
logger.debug('client ready')
client.Authenticate('123')
client.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test'].worker.should.equal(1)
done()
)
it('should create client and test to connect the broker and auth is working',(done)->
client2 = new soa.Client('localhost',port,{})
client2.on 'connect',()->
logger.debug('client connected')
client2.on 'ready',()->
logger.debug('client failed ready')
client2.Authenticate('5678')
client2.on 'authenticate',(result)->
result.should.equal(false)
done()
)
describe 'Messaging',()->
@timeout(15000)
describe 'worker get messages',()->
it('should get message from client',(done)->
worker2 = new soa.Client('localhost',port,{service:'test2'},(data,cb)->
logger.debug('get test2 message')
data.toString().should.equal('message')
cb(data,false)
)
worker2.on 'connect',()->
logger.debug('woker4 connected')
worker2.on 'ready',()->
logger.debug('worker4 ready')
worker2.Authenticate('123')
worker2.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test2'].worker.should.equal(1)
client.send('test2',new Buffer('message'),false,(err,data)->
logger.debug('test2 client back')
if err
logger.error err
throw err
else
data.toString().should.equal('message')
done()
)
)
it('should get message from client without response',(done)->
worker3 = new soa.Client('localhost',port,{service:'test3'},(data,cb)->
logger.info('get test3 message')
data.toString().should.equal('message')
logger.info('send back from test3')
cb(data,false)
done()
)
worker3.on 'connect',()->
logger.debug('woker4 connected')
worker3.on 'ready',()->
logger.debug('worker4 ready')
worker3.Authenticate('123')
worker3.on 'authenticate',(result)->
result.should.equal(true)
logger.info('send test3 message')
broker.services['test3'].worker.should.equal(1)
client.send('test3',new Buffer('message'),false,()->
logger.info('back ')
)
)
it('should get message from client and other worker',(done)->
worker4 = new soa.Client('localhost',port,{service:'test4'},(data,cb)->
logger.debug('get test4 message')
data.toString().should.equal('message')
worker4.send('test',data,false,(err,data)->
logger.debug('get test message')
if err
throw err
data.toString().should.equal('message')
cb(data,false)
)
)
worker4.on 'connect',()->
logger.debug('woker4 connected')
worker4.on 'ready',()->
logger.debug('worker4 ready')
worker4.Authenticate('123')
worker4.on 'authenticate',(result)->
result.should.equal(true)
broker.services['test4'].worker.should.equal(1)
client.send('test4',new Buffer('message'),false,(err,data)->
logger.debug('test4 client back')
if err
throw err
data.toString().should.equal('message')
done()
)
)
describe 'Pub',()->
@timeout(20000)
describe 'Broker Send Msg ',()->
it('should get message from broker',(done)->
async.parallel([
(callback)->
worker5 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker5.on 'connect',()->
logger.debug('woker5 connected')
worker5.on 'ready',()->
logger.debug('worker5 ready')
@Authenticate('123')
worker5.on 'authenticate',(result)->
logger.info('worker5 successful')
result.should.equal(true)
(callback)->
worker6 = new soa.Client('localhost',port,{service:'ppp'},(data,cb)->
logger.debug('get pub message')
data.toString().should.equal('pub message')
callback(null)
)
worker6.on 'connect',()->
logger.debug('woker6 connected')
worker6.on 'ready',()->
logger.debug('worker6 ready')
@Authenticate('123')
worker6.on 'authenticate',(result)->
result.should.equal(true)
logger.info('worker6 successful')
(callback)->
setTimeout ()->
broker.Pub("ppp","pub message")
callback(null)
,6000
], (err, result)->
done()
)
)
describe 'Service',()->
@timeout(20000)
describe 'Broker Add Service Msg ',()->
it('should get message from broker',(done)->
broker.on('service',(workerlabel,msg,cb)->
msg.data.toString().should.equal("{'service':'213'}")
done()
)
worker4.sendBService(new Buffer("{'service':'213'}"))
)
###
client = new soa.Client('tcp://localhost:8008',{service:'1234'},(err,data)->
logger.debug('get worker job')
)
setTimeout(()->
t.send('1234','test',(err,data)->
logger.debug('get worker feedback.'+ (err || data) )
)
,5000)
describe('Array', function(){
describe('#indexOf()', function(){
it('should return -1 when the value is not present', function(){
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
})
})
})
###
|
[
{
"context": " return results\n\n\n# @Thanks to https://github.com/blazs/subsets for the inspiration!\nget_subsets = (set, ",
"end": 466,
"score": 0.9924490451812744,
"start": 461,
"tag": "USERNAME",
"value": "blazs"
},
{
"context": "t)\n key = key_prefix + permutation... | algorithms.coffee | jneuendorf/FormValidator | 0 | # from http://stackoverflow.com/questions/9960908/permutations-in-javascript
get_permutations = (arr) ->
permute = (arr, memo = []) ->
for i in [0...arr.length]
cur = arr.splice(i, 1)
if arr.length is 0
results.push memo.concat(cur)
permute(arr.slice(), memo.concat(cur))
arr.splice(i, 0, cur[0])
results = []
permute(arr)
return results
# @Thanks to https://github.com/blazs/subsets for the inspiration!
get_subsets = (set, k) ->
subsets = []
n = set.length
p = (i for i in [0...k])
loop
# push current subset
subsets.push (set[index] for index in p)
# if this is the last k-subset, we are done
if p[0] is n - k
break
# find the right element
i = k - 1
while i >= 0 and p[i] + k - i is n
i--
# exchange them
r = p[i]
p[i]++
j = 2
# move them
i++
while i < k
p[i] = r + j
i++
j++
return subsets
group_arr_by = (arr, get_prop) ->
grouped = {}
for elem in arr
if not (key = get_prop?(elem))?
key = elem
if not grouped[key]?
grouped[key] = []
grouped[key].push elem
return grouped
$_from_arr = (arr) ->
res = $()
for elem in arr
res = res.add(elem)
return res
# taken from http://rosettacode.org/wiki/Topological_sort#CoffeeScript
# toposort = (tuples) ->
# # tuples is a list of tuples, where the 1st tuple elems are parent nodes and
# # where the 2nd tuple elems are lists that contain nodes that must precede the parent
#
# # Start by identifying obviously independent nodes
# independents = []
# for tuple, i in tuples
# if tuple[1].length is 0
# tuples[i] = null
# independents.push tuple[0]
#
# tuples = (tuple for tuple in tuples when tuple?)
#
# # Note reverse dependencies for theoretical O(M+N) efficiency.
# reverse_deps = []
# for tuple in tuples
# for child in tuple[1]
# # find correct list
# idx = (i for list, i in reverse_deps when list[0] is child)[0] or -1
# if idx < 0
# idx = reverse_deps.length
# reverse_deps.push []
# reverse_deps[idx].push tuple[0]
#
# # Now greedily start with independent nodes, then start
# # breaking dependencies, and keep going as long as we still
# # have independent nodes left.
# result = []
# while independents.length > 0
# k = independents.pop()
# result.push k
# list = (list for list in reverse_deps when list[0] is k)
# for parent, i in list when i > 0
# # remove current independent node from list of dependencies of current parent
# for tuple, j in tuples when tuple[0] is parent
# tuples[j] = (dep for dep in tuple[1] when dep is k)
# idx = j
# break
#
# if tuples[idx][1].length is 0
# independents.push parent
# # remove tuple with no more dependencies
# tuples = (tuple for tuple, j in tuples when j isnt idx)
#
# # Show unresolvable dependencies
# for tuple in tuples
# console.log "WARNING: node is part of cyclical dependency:", tuple
# return result
# TODO:10 make this better (tried above but above is not working)
toposort = (targets) ->
targets = parse_deps(targets)
# targets is hash of sets, where keys are parent nodes and
# where values are sets that contain nodes that must precede the parent
# Start by identifying obviously independent nodes
independents = []
do ->
for k of targets
if targets[k].cnt is 0
delete targets[k]
independents.push k
# console.log independents
# NOTE: reverse dependencies for theoretical O(M+N) efficiency.
# REVIEW: does this actually improved anything? and if so is it worth reversing everything?
reverse_deps = []
do ->
for k of targets
for child of targets[k].v
reverse_deps[child] ?= []
reverse_deps[child].push k
# Now be greedy--start with independent nodes, then start
# breaking dependencies, and keep going as long as we still
# have independent nodes left.
result = []
while independents.length > 0
k = independents.pop()
result.push k
for parent in reverse_deps[k] or []
set_remove targets[parent], k
if targets[parent].cnt is 0
independents.push parent
delete targets[parent]
# Show unresolvable dependencies
for k of targets
# console.log "WARNING: node #{k} is part of cyclical dependency"
throw new Error("FormValidator::validate: Detected cyclical dependencies. Adjust your dependency definitions")
return result
parse_deps = (data) ->
# parse string data, remove self-deps, and fill in gaps
# e.g. this would transform {a: "a b c", d: "e"} to this:
# a: set(b, c)
# b: set()
# c: set()
# d: set(e)
# e: set()
targets = {}
deps = set()
for k, v of data
targets[k] = set()
children = v
for child in children
if child is ''
continue
set_add targets[k], child unless child is k
set_add deps, child
# make sure even leaf nodes are in targets
for dep of deps.v
if dep not of targets
targets[dep] = set()
return targets
set = () ->
return {
cnt: 0
v: {}
}
set_add = (s, e) ->
if not s.v[e]
s.cnt += 1
s.v[e] = true
return s
set_remove = (s, e) ->
if s.v[e]
s.cnt -= 1
delete s.v[e]
return s
# data =
# des_system_lib: "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee"
# dw01: "ieee dw01 dware gtech"
# dw02: "ieee dw02 dware"
# dw03: "std synopsys dware dw03 dw02 dw01 ieee gtech"
# dw04: "dw04 ieee dw01 dware gtech"
# dw05: "dw05 ieee dware"
# dw06: "dw06 ieee dware"
# dw07: "ieee dware"
# dware: "ieee dware"
# gtech: "ieee gtech"
# ramlib: "std ieee"
# std_cell_lib: "ieee std_cell_lib"
# synopsys: ""
#
#
# targets = parse_deps()
# console.log toposort targets
# class GraphNode
#
# # CONSTRUCTOR
# constructor: () ->
# @incoming_edges = []
#
# has_edge: () ->
#
# class Graph
#
# # CONSTRUCTOR
# constructor: () ->
# @nodes = []
#
# has_edges: () ->
# for node in @nodes when node.incoming_edges.length > 0
# return true
# return false
#
# add_edge: (from, to) ->
#
#
# remove_edge: (from, to) ->
#
# # L ← Empty list that will contain the sorted elements
# # S ← Set of all nodes with no incoming edges
# # while S is non-empty do
# # remove a node n from S
# # add n to tail of L
# # for each node m with an edge e from n to m do
# # remove edge e from the graph
# # if m has no other incoming edges then
# # insert m into S
# # if graph has edges then
# # return error (graph has at least one cycle)
# # else
# # return L (a topologically sorted order)
# toposort = (fields) ->
# # build graph
# graph = []
# for elem in fields
# data = @_get_element_data(elem)
#
# graph.push {
# field: elem
# incoming_edges: []
# }
#
# # do topological sort
# L = []
# S = []
# while S.length > 0
# n = S.pop()
# L.push n
# for m in graph when (e = m.has_edge(n, m))
# graph.remove_edge(e)
# if m.incoming_edges.length is 1
# S.push m
# if not graph.has_edges()
# return L
# throw new Error()
#####################################################################################################
# USED FOR CONSTRAINT ERROR MESSAGES (in error_message_builders.coffee)
# mapping from group to locale key: Set -> String
# max_min == min_max
# ==> the order does not matter because its a set (and all permutations of the set map to the same value)
# intially use permutation to find the actually existing locale key for the given set
# upon a match cache the key. whenever the match becomes invalid (-> returns null) return to the initial state (so permutation is used)
# REVIEW test caching
_permutation_cache = {}
get_combined_key = (keys, locale, key_prefix = "", key_suffix = "") ->
# clone keys
keys = keys.slice(0)
# sort because cached keys had been sorted and the convention is that locales are alphabetically sorted (joined with '_')
keys.sort()
cache_key = keys.join("_")
# try to get the key from the cache
if _permutation_cache[cache_key]?
return _permutation_cache[cache_key]
# no cache hit => try to find a key
# get all subsets (by size, from big to small), permute each subset
for k in [keys.length...0] by -1
for subset in get_subsets(keys, k)
for permutation in get_permutations(subset)
key = key_prefix + permutation.join("_") + key_suffix
if locales[locale][key]?
_permutation_cache[cache_key] = key
return key
return null
| 140157 | # from http://stackoverflow.com/questions/9960908/permutations-in-javascript
get_permutations = (arr) ->
permute = (arr, memo = []) ->
for i in [0...arr.length]
cur = arr.splice(i, 1)
if arr.length is 0
results.push memo.concat(cur)
permute(arr.slice(), memo.concat(cur))
arr.splice(i, 0, cur[0])
results = []
permute(arr)
return results
# @Thanks to https://github.com/blazs/subsets for the inspiration!
get_subsets = (set, k) ->
subsets = []
n = set.length
p = (i for i in [0...k])
loop
# push current subset
subsets.push (set[index] for index in p)
# if this is the last k-subset, we are done
if p[0] is n - k
break
# find the right element
i = k - 1
while i >= 0 and p[i] + k - i is n
i--
# exchange them
r = p[i]
p[i]++
j = 2
# move them
i++
while i < k
p[i] = r + j
i++
j++
return subsets
group_arr_by = (arr, get_prop) ->
grouped = {}
for elem in arr
if not (key = get_prop?(elem))?
key = elem
if not grouped[key]?
grouped[key] = []
grouped[key].push elem
return grouped
$_from_arr = (arr) ->
res = $()
for elem in arr
res = res.add(elem)
return res
# taken from http://rosettacode.org/wiki/Topological_sort#CoffeeScript
# toposort = (tuples) ->
# # tuples is a list of tuples, where the 1st tuple elems are parent nodes and
# # where the 2nd tuple elems are lists that contain nodes that must precede the parent
#
# # Start by identifying obviously independent nodes
# independents = []
# for tuple, i in tuples
# if tuple[1].length is 0
# tuples[i] = null
# independents.push tuple[0]
#
# tuples = (tuple for tuple in tuples when tuple?)
#
# # Note reverse dependencies for theoretical O(M+N) efficiency.
# reverse_deps = []
# for tuple in tuples
# for child in tuple[1]
# # find correct list
# idx = (i for list, i in reverse_deps when list[0] is child)[0] or -1
# if idx < 0
# idx = reverse_deps.length
# reverse_deps.push []
# reverse_deps[idx].push tuple[0]
#
# # Now greedily start with independent nodes, then start
# # breaking dependencies, and keep going as long as we still
# # have independent nodes left.
# result = []
# while independents.length > 0
# k = independents.pop()
# result.push k
# list = (list for list in reverse_deps when list[0] is k)
# for parent, i in list when i > 0
# # remove current independent node from list of dependencies of current parent
# for tuple, j in tuples when tuple[0] is parent
# tuples[j] = (dep for dep in tuple[1] when dep is k)
# idx = j
# break
#
# if tuples[idx][1].length is 0
# independents.push parent
# # remove tuple with no more dependencies
# tuples = (tuple for tuple, j in tuples when j isnt idx)
#
# # Show unresolvable dependencies
# for tuple in tuples
# console.log "WARNING: node is part of cyclical dependency:", tuple
# return result
# TODO:10 make this better (tried above but above is not working)
toposort = (targets) ->
targets = parse_deps(targets)
# targets is hash of sets, where keys are parent nodes and
# where values are sets that contain nodes that must precede the parent
# Start by identifying obviously independent nodes
independents = []
do ->
for k of targets
if targets[k].cnt is 0
delete targets[k]
independents.push k
# console.log independents
# NOTE: reverse dependencies for theoretical O(M+N) efficiency.
# REVIEW: does this actually improved anything? and if so is it worth reversing everything?
reverse_deps = []
do ->
for k of targets
for child of targets[k].v
reverse_deps[child] ?= []
reverse_deps[child].push k
# Now be greedy--start with independent nodes, then start
# breaking dependencies, and keep going as long as we still
# have independent nodes left.
result = []
while independents.length > 0
k = independents.pop()
result.push k
for parent in reverse_deps[k] or []
set_remove targets[parent], k
if targets[parent].cnt is 0
independents.push parent
delete targets[parent]
# Show unresolvable dependencies
for k of targets
# console.log "WARNING: node #{k} is part of cyclical dependency"
throw new Error("FormValidator::validate: Detected cyclical dependencies. Adjust your dependency definitions")
return result
parse_deps = (data) ->
# parse string data, remove self-deps, and fill in gaps
# e.g. this would transform {a: "a b c", d: "e"} to this:
# a: set(b, c)
# b: set()
# c: set()
# d: set(e)
# e: set()
targets = {}
deps = set()
for k, v of data
targets[k] = set()
children = v
for child in children
if child is ''
continue
set_add targets[k], child unless child is k
set_add deps, child
# make sure even leaf nodes are in targets
for dep of deps.v
if dep not of targets
targets[dep] = set()
return targets
set = () ->
return {
cnt: 0
v: {}
}
set_add = (s, e) ->
if not s.v[e]
s.cnt += 1
s.v[e] = true
return s
set_remove = (s, e) ->
if s.v[e]
s.cnt -= 1
delete s.v[e]
return s
# data =
# des_system_lib: "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee"
# dw01: "ieee dw01 dware gtech"
# dw02: "ieee dw02 dware"
# dw03: "std synopsys dware dw03 dw02 dw01 ieee gtech"
# dw04: "dw04 ieee dw01 dware gtech"
# dw05: "dw05 ieee dware"
# dw06: "dw06 ieee dware"
# dw07: "ieee dware"
# dware: "ieee dware"
# gtech: "ieee gtech"
# ramlib: "std ieee"
# std_cell_lib: "ieee std_cell_lib"
# synopsys: ""
#
#
# targets = parse_deps()
# console.log toposort targets
# class GraphNode
#
# # CONSTRUCTOR
# constructor: () ->
# @incoming_edges = []
#
# has_edge: () ->
#
# class Graph
#
# # CONSTRUCTOR
# constructor: () ->
# @nodes = []
#
# has_edges: () ->
# for node in @nodes when node.incoming_edges.length > 0
# return true
# return false
#
# add_edge: (from, to) ->
#
#
# remove_edge: (from, to) ->
#
# # L ← Empty list that will contain the sorted elements
# # S ← Set of all nodes with no incoming edges
# # while S is non-empty do
# # remove a node n from S
# # add n to tail of L
# # for each node m with an edge e from n to m do
# # remove edge e from the graph
# # if m has no other incoming edges then
# # insert m into S
# # if graph has edges then
# # return error (graph has at least one cycle)
# # else
# # return L (a topologically sorted order)
# toposort = (fields) ->
# # build graph
# graph = []
# for elem in fields
# data = @_get_element_data(elem)
#
# graph.push {
# field: elem
# incoming_edges: []
# }
#
# # do topological sort
# L = []
# S = []
# while S.length > 0
# n = S.pop()
# L.push n
# for m in graph when (e = m.has_edge(n, m))
# graph.remove_edge(e)
# if m.incoming_edges.length is 1
# S.push m
# if not graph.has_edges()
# return L
# throw new Error()
#####################################################################################################
# USED FOR CONSTRAINT ERROR MESSAGES (in error_message_builders.coffee)
# mapping from group to locale key: Set -> String
# max_min == min_max
# ==> the order does not matter because its a set (and all permutations of the set map to the same value)
# intially use permutation to find the actually existing locale key for the given set
# upon a match cache the key. whenever the match becomes invalid (-> returns null) return to the initial state (so permutation is used)
# REVIEW test caching
_permutation_cache = {}
get_combined_key = (keys, locale, key_prefix = "", key_suffix = "") ->
# clone keys
keys = keys.slice(0)
# sort because cached keys had been sorted and the convention is that locales are alphabetically sorted (joined with '_')
keys.sort()
cache_key = keys.join("_")
# try to get the key from the cache
if _permutation_cache[cache_key]?
return _permutation_cache[cache_key]
# no cache hit => try to find a key
# get all subsets (by size, from big to small), permute each subset
for k in [keys.length...0] by -1
for subset in get_subsets(keys, k)
for permutation in get_permutations(subset)
key = key_prefix + permutation.<KEY>") + key_suffix
if locales[locale][key]?
_permutation_cache[cache_key] = key
return key
return null
| true | # from http://stackoverflow.com/questions/9960908/permutations-in-javascript
get_permutations = (arr) ->
permute = (arr, memo = []) ->
for i in [0...arr.length]
cur = arr.splice(i, 1)
if arr.length is 0
results.push memo.concat(cur)
permute(arr.slice(), memo.concat(cur))
arr.splice(i, 0, cur[0])
results = []
permute(arr)
return results
# @Thanks to https://github.com/blazs/subsets for the inspiration!
get_subsets = (set, k) ->
subsets = []
n = set.length
p = (i for i in [0...k])
loop
# push current subset
subsets.push (set[index] for index in p)
# if this is the last k-subset, we are done
if p[0] is n - k
break
# find the right element
i = k - 1
while i >= 0 and p[i] + k - i is n
i--
# exchange them
r = p[i]
p[i]++
j = 2
# move them
i++
while i < k
p[i] = r + j
i++
j++
return subsets
group_arr_by = (arr, get_prop) ->
grouped = {}
for elem in arr
if not (key = get_prop?(elem))?
key = elem
if not grouped[key]?
grouped[key] = []
grouped[key].push elem
return grouped
$_from_arr = (arr) ->
res = $()
for elem in arr
res = res.add(elem)
return res
# taken from http://rosettacode.org/wiki/Topological_sort#CoffeeScript
# toposort = (tuples) ->
# # tuples is a list of tuples, where the 1st tuple elems are parent nodes and
# # where the 2nd tuple elems are lists that contain nodes that must precede the parent
#
# # Start by identifying obviously independent nodes
# independents = []
# for tuple, i in tuples
# if tuple[1].length is 0
# tuples[i] = null
# independents.push tuple[0]
#
# tuples = (tuple for tuple in tuples when tuple?)
#
# # Note reverse dependencies for theoretical O(M+N) efficiency.
# reverse_deps = []
# for tuple in tuples
# for child in tuple[1]
# # find correct list
# idx = (i for list, i in reverse_deps when list[0] is child)[0] or -1
# if idx < 0
# idx = reverse_deps.length
# reverse_deps.push []
# reverse_deps[idx].push tuple[0]
#
# # Now greedily start with independent nodes, then start
# # breaking dependencies, and keep going as long as we still
# # have independent nodes left.
# result = []
# while independents.length > 0
# k = independents.pop()
# result.push k
# list = (list for list in reverse_deps when list[0] is k)
# for parent, i in list when i > 0
# # remove current independent node from list of dependencies of current parent
# for tuple, j in tuples when tuple[0] is parent
# tuples[j] = (dep for dep in tuple[1] when dep is k)
# idx = j
# break
#
# if tuples[idx][1].length is 0
# independents.push parent
# # remove tuple with no more dependencies
# tuples = (tuple for tuple, j in tuples when j isnt idx)
#
# # Show unresolvable dependencies
# for tuple in tuples
# console.log "WARNING: node is part of cyclical dependency:", tuple
# return result
# TODO:10 make this better (tried above but above is not working)
toposort = (targets) ->
targets = parse_deps(targets)
# targets is hash of sets, where keys are parent nodes and
# where values are sets that contain nodes that must precede the parent
# Start by identifying obviously independent nodes
independents = []
do ->
for k of targets
if targets[k].cnt is 0
delete targets[k]
independents.push k
# console.log independents
# NOTE: reverse dependencies for theoretical O(M+N) efficiency.
# REVIEW: does this actually improved anything? and if so is it worth reversing everything?
reverse_deps = []
do ->
for k of targets
for child of targets[k].v
reverse_deps[child] ?= []
reverse_deps[child].push k
# Now be greedy--start with independent nodes, then start
# breaking dependencies, and keep going as long as we still
# have independent nodes left.
result = []
while independents.length > 0
k = independents.pop()
result.push k
for parent in reverse_deps[k] or []
set_remove targets[parent], k
if targets[parent].cnt is 0
independents.push parent
delete targets[parent]
# Show unresolvable dependencies
for k of targets
# console.log "WARNING: node #{k} is part of cyclical dependency"
throw new Error("FormValidator::validate: Detected cyclical dependencies. Adjust your dependency definitions")
return result
parse_deps = (data) ->
# parse string data, remove self-deps, and fill in gaps
# e.g. this would transform {a: "a b c", d: "e"} to this:
# a: set(b, c)
# b: set()
# c: set()
# d: set(e)
# e: set()
targets = {}
deps = set()
for k, v of data
targets[k] = set()
children = v
for child in children
if child is ''
continue
set_add targets[k], child unless child is k
set_add deps, child
# make sure even leaf nodes are in targets
for dep of deps.v
if dep not of targets
targets[dep] = set()
return targets
set = () ->
return {
cnt: 0
v: {}
}
set_add = (s, e) ->
if not s.v[e]
s.cnt += 1
s.v[e] = true
return s
set_remove = (s, e) ->
if s.v[e]
s.cnt -= 1
delete s.v[e]
return s
# data =
# des_system_lib: "std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee"
# dw01: "ieee dw01 dware gtech"
# dw02: "ieee dw02 dware"
# dw03: "std synopsys dware dw03 dw02 dw01 ieee gtech"
# dw04: "dw04 ieee dw01 dware gtech"
# dw05: "dw05 ieee dware"
# dw06: "dw06 ieee dware"
# dw07: "ieee dware"
# dware: "ieee dware"
# gtech: "ieee gtech"
# ramlib: "std ieee"
# std_cell_lib: "ieee std_cell_lib"
# synopsys: ""
#
#
# targets = parse_deps()
# console.log toposort targets
# class GraphNode
#
# # CONSTRUCTOR
# constructor: () ->
# @incoming_edges = []
#
# has_edge: () ->
#
# class Graph
#
# # CONSTRUCTOR
# constructor: () ->
# @nodes = []
#
# has_edges: () ->
# for node in @nodes when node.incoming_edges.length > 0
# return true
# return false
#
# add_edge: (from, to) ->
#
#
# remove_edge: (from, to) ->
#
# # L ← Empty list that will contain the sorted elements
# # S ← Set of all nodes with no incoming edges
# # while S is non-empty do
# # remove a node n from S
# # add n to tail of L
# # for each node m with an edge e from n to m do
# # remove edge e from the graph
# # if m has no other incoming edges then
# # insert m into S
# # if graph has edges then
# # return error (graph has at least one cycle)
# # else
# # return L (a topologically sorted order)
# toposort = (fields) ->
# # build graph
# graph = []
# for elem in fields
# data = @_get_element_data(elem)
#
# graph.push {
# field: elem
# incoming_edges: []
# }
#
# # do topological sort
# L = []
# S = []
# while S.length > 0
# n = S.pop()
# L.push n
# for m in graph when (e = m.has_edge(n, m))
# graph.remove_edge(e)
# if m.incoming_edges.length is 1
# S.push m
# if not graph.has_edges()
# return L
# throw new Error()
#####################################################################################################
# USED FOR CONSTRAINT ERROR MESSAGES (in error_message_builders.coffee)
# mapping from group to locale key: Set -> String
# max_min == min_max
# ==> the order does not matter because its a set (and all permutations of the set map to the same value)
# intially use permutation to find the actually existing locale key for the given set
# upon a match cache the key. whenever the match becomes invalid (-> returns null) return to the initial state (so permutation is used)
# REVIEW test caching
_permutation_cache = {}
get_combined_key = (keys, locale, key_prefix = "", key_suffix = "") ->
# clone keys
keys = keys.slice(0)
# sort because cached keys had been sorted and the convention is that locales are alphabetically sorted (joined with '_')
keys.sort()
cache_key = keys.join("_")
# try to get the key from the cache
if _permutation_cache[cache_key]?
return _permutation_cache[cache_key]
# no cache hit => try to find a key
# get all subsets (by size, from big to small), permute each subset
for k in [keys.length...0] by -1
for subset in get_subsets(keys, k)
for permutation in get_permutations(subset)
key = key_prefix + permutation.PI:KEY:<KEY>END_PI") + key_suffix
if locales[locale][key]?
_permutation_cache[cache_key] = key
return key
return null
|
[
{
"context": "\n .on 'use-q:start', Player.useQ\n\nfor key in [1, 2, 3, 4, 5]\n $.on \"alt + #{key}\", ->\n\n if key =",
"end": 164,
"score": 0.6805514097213745,
"start": 163,
"tag": "KEY",
"value": "2"
}
] | source/action/use-skill.coffee | Tedd157/genshin-impact-script | 1 | # binding
Player
.on 'use-e:start', -> SkillTimer.record 'start'
.on 'use-e:end', -> SkillTimer.record 'end'
.on 'use-q:start', Player.useQ
for key in [1, 2, 3, 4, 5]
$.on "alt + #{key}", ->
if key == Party.current
Player.useQ()
return
Player.switchQ key | 667 | # binding
Player
.on 'use-e:start', -> SkillTimer.record 'start'
.on 'use-e:end', -> SkillTimer.record 'end'
.on 'use-q:start', Player.useQ
for key in [1, <KEY>, 3, 4, 5]
$.on "alt + #{key}", ->
if key == Party.current
Player.useQ()
return
Player.switchQ key | true | # binding
Player
.on 'use-e:start', -> SkillTimer.record 'start'
.on 'use-e:end', -> SkillTimer.record 'end'
.on 'use-q:start', Player.useQ
for key in [1, PI:KEY:<KEY>END_PI, 3, 4, 5]
$.on "alt + #{key}", ->
if key == Party.current
Player.useQ()
return
Player.switchQ key |
[
{
"context": "\t\t\t'emails'\n\t\t\t'status'\n\t\t\t'statusConnection'\n\t\t\t'username'\n\t\t\t'utcOffset'\n\t\t\t'active'\n\t\t\t'language'\n\t\t]\n\n\n#",
"end": 238,
"score": 0.9988283514976501,
"start": 230,
"tag": "USERNAME",
"value": "username"
},
{
"context": "eturn Sequoia.A... | packages/sequoia-api/server/routes.coffee | rychken/rocket.chat-slim | 0 | Sequoia.API.v1.addRoute 'info', authRequired: false,
get: -> Sequoia.Info
Sequoia.API.v1.addRoute 'me', authRequired: true,
get: ->
return _.pick @user, [
'_id'
'name'
'emails'
'status'
'statusConnection'
'username'
'utcOffset'
'active'
'language'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.messageExamples', authRequired: true,
get: ->
return Sequoia.API.v1.success
body: [
token: Random.id(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 1'
trigger_word: 'Sample'
,
token: Random.id(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 2'
trigger_word: 'Sample'
,
token: Random.id(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 3'
trigger_word: 'Sample'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.postMessage', authRequired: true,
post: ->
try
messageReturn = processWebhookMessage @bodyParams, @user
if not messageReturn?
return Sequoia.API.v1.failure 'unknown-error'
return Sequoia.API.v1.success
ts: Date.now()
channel: messageReturn.channel
message: messageReturn.message
catch e
return Sequoia.API.v1.failure e.error
# Set Channel Topic
Sequoia.API.v1.addRoute 'channels.setTopic', authRequired: true,
post: ->
if not @bodyParams.channel?
return Sequoia.API.v1.failure 'Body param "channel" is required'
if not @bodyParams.topic?
return Sequoia.API.v1.failure 'Body param "topic" is required'
unless Sequoia.authz.hasPermission(@userId, 'edit-room', @bodyParams.channel)
return Sequoia.API.v1.unauthorized()
if not Sequoia.saveRoomTopic(@bodyParams.channel, @bodyParams.topic, @user)
return Sequoia.API.v1.failure 'invalid_channel'
return Sequoia.API.v1.success
topic: @bodyParams.topic
# Create Channel
Sequoia.API.v1.addRoute 'channels.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-c')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createChannel', @bodyParams.name, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(id.rid)
# List Private Groups a user has access to
Sequoia.API.v1.addRoute 'groups.list', authRequired: true,
get: ->
roomIds = _.pluck Sequoia.models.Subscriptions.findByTypeAndUserId('p', @userId).fetch(), 'rid'
return { groups: Sequoia.models.Rooms.findByIds(roomIds).fetch() }
# Add All Users to Channel
Sequoia.API.v1.addRoute 'channel.addall', authRequired: true,
post: ->
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'addAllUserToRoom', @bodyParams.roomId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(@bodyParams.roomId)
# List all users
Sequoia.API.v1.addRoute 'users.list', authRequired: true,
get: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { users: Sequoia.models.Users.find().fetch() }
# Create user
Sequoia.API.v1.addRoute 'users.create', authRequired: true,
post: ->
try
check @bodyParams,
email: String
name: String
password: String
username: String
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
# check username availability first (to not create an user without a username)
try
nameValidation = new RegExp '^' + Sequoia.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if not nameValidation.test @bodyParams.username
return Sequoia.API.v1.failure 'Invalid username'
unless Sequoia.checkUsernameAvailability @bodyParams.username
return Sequoia.API.v1.failure 'Username not available'
userData = {}
newUserId = Sequoia.saveUser(@userId, @bodyParams)
if @bodyParams.customFields?
Sequoia.saveCustomFields(newUserId, @bodyParams.customFields)
user = Sequoia.models.Users.findOneById(newUserId)
if typeof @bodyParams.joinDefaultChannels is 'undefined' or @bodyParams.joinDefaultChannels
Sequoia.addUserToDefaultChannels(user)
return Sequoia.API.v1.success
user: user
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Update user
Sequoia.API.v1.addRoute 'user.update', authRequired: true,
post: ->
try
check @bodyParams,
userId: String
data:
email: Match.Maybe(String)
name: Match.Maybe(String)
password: Match.Maybe(String)
username: Match.Maybe(String)
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
userData = _.extend({ _id: @bodyParams.userId }, @bodyParams.data)
Sequoia.saveUser(@userId, userData)
if @bodyParams.data.customFields?
Sequoia.saveCustomFields(@bodyParams.userId, @bodyParams.data.customFields)
return Sequoia.API.v1.success
user: Sequoia.models.Users.findOneById(@bodyParams.userId)
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Get User Information
Sequoia.API.v1.addRoute 'user.info', authRequired: true,
post: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { user: Sequoia.models.Users.findOneByUsername @bodyParams.name }
# Get User Presence
Sequoia.API.v1.addRoute 'user.getpresence', authRequired: true,
post: ->
return { user: Sequoia.models.Users.findOne( { username: @bodyParams.name} , {fields: {status: 1}} ) }
# Delete User
Sequoia.API.v1.addRoute 'users.delete', authRequired: true,
post: ->
if not @bodyParams.userId?
return Sequoia.API.v1.failure 'Body param "userId" is required'
if not Sequoia.authz.hasPermission(@userId, 'delete-user')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'deleteUser', @bodyParams.userId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
# Create Private Group
Sequoia.API.v1.addRoute 'groups.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-p')
return Sequoia.API.v1.unauthorized()
id = undefined
try
if not @bodyParams.members?
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, []
else
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, @bodyParams.members, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
group: Sequoia.models.Rooms.findOneById(id.rid)
| 204736 | Sequoia.API.v1.addRoute 'info', authRequired: false,
get: -> Sequoia.Info
Sequoia.API.v1.addRoute 'me', authRequired: true,
get: ->
return _.pick @user, [
'_id'
'name'
'emails'
'status'
'statusConnection'
'username'
'utcOffset'
'active'
'language'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.messageExamples', authRequired: true,
get: ->
return Sequoia.API.v1.success
body: [
token: <KEY>(<KEY>)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 1'
trigger_word: 'Sample'
,
token: <KEY>(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 2'
trigger_word: 'Sample'
,
token: <KEY>(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 3'
trigger_word: 'Sample'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.postMessage', authRequired: true,
post: ->
try
messageReturn = processWebhookMessage @bodyParams, @user
if not messageReturn?
return Sequoia.API.v1.failure 'unknown-error'
return Sequoia.API.v1.success
ts: Date.now()
channel: messageReturn.channel
message: messageReturn.message
catch e
return Sequoia.API.v1.failure e.error
# Set Channel Topic
Sequoia.API.v1.addRoute 'channels.setTopic', authRequired: true,
post: ->
if not @bodyParams.channel?
return Sequoia.API.v1.failure 'Body param "channel" is required'
if not @bodyParams.topic?
return Sequoia.API.v1.failure 'Body param "topic" is required'
unless Sequoia.authz.hasPermission(@userId, 'edit-room', @bodyParams.channel)
return Sequoia.API.v1.unauthorized()
if not Sequoia.saveRoomTopic(@bodyParams.channel, @bodyParams.topic, @user)
return Sequoia.API.v1.failure 'invalid_channel'
return Sequoia.API.v1.success
topic: @bodyParams.topic
# Create Channel
Sequoia.API.v1.addRoute 'channels.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-c')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createChannel', @bodyParams.name, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(id.rid)
# List Private Groups a user has access to
Sequoia.API.v1.addRoute 'groups.list', authRequired: true,
get: ->
roomIds = _.pluck Sequoia.models.Subscriptions.findByTypeAndUserId('p', @userId).fetch(), 'rid'
return { groups: Sequoia.models.Rooms.findByIds(roomIds).fetch() }
# Add All Users to Channel
Sequoia.API.v1.addRoute 'channel.addall', authRequired: true,
post: ->
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'addAllUserToRoom', @bodyParams.roomId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(@bodyParams.roomId)
# List all users
Sequoia.API.v1.addRoute 'users.list', authRequired: true,
get: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { users: Sequoia.models.Users.find().fetch() }
# Create user
Sequoia.API.v1.addRoute 'users.create', authRequired: true,
post: ->
try
check @bodyParams,
email: String
name: String
password: <PASSWORD>
username: String
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
# check username availability first (to not create an user without a username)
try
nameValidation = new RegExp '^' + Sequoia.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if not nameValidation.test @bodyParams.username
return Sequoia.API.v1.failure 'Invalid username'
unless Sequoia.checkUsernameAvailability @bodyParams.username
return Sequoia.API.v1.failure 'Username not available'
userData = {}
newUserId = Sequoia.saveUser(@userId, @bodyParams)
if @bodyParams.customFields?
Sequoia.saveCustomFields(newUserId, @bodyParams.customFields)
user = Sequoia.models.Users.findOneById(newUserId)
if typeof @bodyParams.joinDefaultChannels is 'undefined' or @bodyParams.joinDefaultChannels
Sequoia.addUserToDefaultChannels(user)
return Sequoia.API.v1.success
user: user
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Update user
Sequoia.API.v1.addRoute 'user.update', authRequired: true,
post: ->
try
check @bodyParams,
userId: String
data:
email: Match.Maybe(String)
name: Match.Maybe(String)
password: Match.Maybe(String)
username: Match.Maybe(String)
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
userData = _.extend({ _id: @bodyParams.userId }, @bodyParams.data)
Sequoia.saveUser(@userId, userData)
if @bodyParams.data.customFields?
Sequoia.saveCustomFields(@bodyParams.userId, @bodyParams.data.customFields)
return Sequoia.API.v1.success
user: Sequoia.models.Users.findOneById(@bodyParams.userId)
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Get User Information
Sequoia.API.v1.addRoute 'user.info', authRequired: true,
post: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { user: Sequoia.models.Users.findOneByUsername @bodyParams.name }
# Get User Presence
Sequoia.API.v1.addRoute 'user.getpresence', authRequired: true,
post: ->
return { user: Sequoia.models.Users.findOne( { username: @bodyParams.name} , {fields: {status: 1}} ) }
# Delete User
Sequoia.API.v1.addRoute 'users.delete', authRequired: true,
post: ->
if not @bodyParams.userId?
return Sequoia.API.v1.failure 'Body param "userId" is required'
if not Sequoia.authz.hasPermission(@userId, 'delete-user')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'deleteUser', @bodyParams.userId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
# Create Private Group
Sequoia.API.v1.addRoute 'groups.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-p')
return Sequoia.API.v1.unauthorized()
id = undefined
try
if not @bodyParams.members?
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, []
else
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, @bodyParams.members, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
group: Sequoia.models.Rooms.findOneById(id.rid)
| true | Sequoia.API.v1.addRoute 'info', authRequired: false,
get: -> Sequoia.Info
Sequoia.API.v1.addRoute 'me', authRequired: true,
get: ->
return _.pick @user, [
'_id'
'name'
'emails'
'status'
'statusConnection'
'username'
'utcOffset'
'active'
'language'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.messageExamples', authRequired: true,
get: ->
return Sequoia.API.v1.success
body: [
token: PI:KEY:<KEY>END_PI(PI:KEY:<KEY>END_PI)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 1'
trigger_word: 'Sample'
,
token: PI:KEY:<KEY>END_PI(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 2'
trigger_word: 'Sample'
,
token: PI:KEY:<KEY>END_PI(24)
channel_id: Random.id()
channel_name: 'general'
timestamp: new Date
user_id: Random.id()
user_name: 'rocket.cat'
text: 'Sample text 3'
trigger_word: 'Sample'
]
# Send Channel Message
Sequoia.API.v1.addRoute 'chat.postMessage', authRequired: true,
post: ->
try
messageReturn = processWebhookMessage @bodyParams, @user
if not messageReturn?
return Sequoia.API.v1.failure 'unknown-error'
return Sequoia.API.v1.success
ts: Date.now()
channel: messageReturn.channel
message: messageReturn.message
catch e
return Sequoia.API.v1.failure e.error
# Set Channel Topic
Sequoia.API.v1.addRoute 'channels.setTopic', authRequired: true,
post: ->
if not @bodyParams.channel?
return Sequoia.API.v1.failure 'Body param "channel" is required'
if not @bodyParams.topic?
return Sequoia.API.v1.failure 'Body param "topic" is required'
unless Sequoia.authz.hasPermission(@userId, 'edit-room', @bodyParams.channel)
return Sequoia.API.v1.unauthorized()
if not Sequoia.saveRoomTopic(@bodyParams.channel, @bodyParams.topic, @user)
return Sequoia.API.v1.failure 'invalid_channel'
return Sequoia.API.v1.success
topic: @bodyParams.topic
# Create Channel
Sequoia.API.v1.addRoute 'channels.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-c')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createChannel', @bodyParams.name, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(id.rid)
# List Private Groups a user has access to
Sequoia.API.v1.addRoute 'groups.list', authRequired: true,
get: ->
roomIds = _.pluck Sequoia.models.Subscriptions.findByTypeAndUserId('p', @userId).fetch(), 'rid'
return { groups: Sequoia.models.Rooms.findByIds(roomIds).fetch() }
# Add All Users to Channel
Sequoia.API.v1.addRoute 'channel.addall', authRequired: true,
post: ->
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'addAllUserToRoom', @bodyParams.roomId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
channel: Sequoia.models.Rooms.findOneById(@bodyParams.roomId)
# List all users
Sequoia.API.v1.addRoute 'users.list', authRequired: true,
get: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { users: Sequoia.models.Users.find().fetch() }
# Create user
Sequoia.API.v1.addRoute 'users.create', authRequired: true,
post: ->
try
check @bodyParams,
email: String
name: String
password: PI:PASSWORD:<PASSWORD>END_PI
username: String
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
# check username availability first (to not create an user without a username)
try
nameValidation = new RegExp '^' + Sequoia.settings.get('UTF8_Names_Validation') + '$'
catch
nameValidation = new RegExp '^[0-9a-zA-Z-_.]+$'
if not nameValidation.test @bodyParams.username
return Sequoia.API.v1.failure 'Invalid username'
unless Sequoia.checkUsernameAvailability @bodyParams.username
return Sequoia.API.v1.failure 'Username not available'
userData = {}
newUserId = Sequoia.saveUser(@userId, @bodyParams)
if @bodyParams.customFields?
Sequoia.saveCustomFields(newUserId, @bodyParams.customFields)
user = Sequoia.models.Users.findOneById(newUserId)
if typeof @bodyParams.joinDefaultChannels is 'undefined' or @bodyParams.joinDefaultChannels
Sequoia.addUserToDefaultChannels(user)
return Sequoia.API.v1.success
user: user
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Update user
Sequoia.API.v1.addRoute 'user.update', authRequired: true,
post: ->
try
check @bodyParams,
userId: String
data:
email: Match.Maybe(String)
name: Match.Maybe(String)
password: Match.Maybe(String)
username: Match.Maybe(String)
role: Match.Maybe(String)
joinDefaultChannels: Match.Maybe(Boolean)
requirePasswordChange: Match.Maybe(Boolean)
sendWelcomeEmail: Match.Maybe(Boolean)
verified: Match.Maybe(Boolean)
customFields: Match.Maybe(Object)
userData = _.extend({ _id: @bodyParams.userId }, @bodyParams.data)
Sequoia.saveUser(@userId, userData)
if @bodyParams.data.customFields?
Sequoia.saveCustomFields(@bodyParams.userId, @bodyParams.data.customFields)
return Sequoia.API.v1.success
user: Sequoia.models.Users.findOneById(@bodyParams.userId)
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
# Get User Information
Sequoia.API.v1.addRoute 'user.info', authRequired: true,
post: ->
if Sequoia.authz.hasRole(@userId, 'admin') is false
return Sequoia.API.v1.unauthorized()
return { user: Sequoia.models.Users.findOneByUsername @bodyParams.name }
# Get User Presence
Sequoia.API.v1.addRoute 'user.getpresence', authRequired: true,
post: ->
return { user: Sequoia.models.Users.findOne( { username: @bodyParams.name} , {fields: {status: 1}} ) }
# Delete User
Sequoia.API.v1.addRoute 'users.delete', authRequired: true,
post: ->
if not @bodyParams.userId?
return Sequoia.API.v1.failure 'Body param "userId" is required'
if not Sequoia.authz.hasPermission(@userId, 'delete-user')
return Sequoia.API.v1.unauthorized()
id = undefined
try
Meteor.runAsUser this.userId, =>
id = Meteor.call 'deleteUser', @bodyParams.userId, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
# Create Private Group
Sequoia.API.v1.addRoute 'groups.create', authRequired: true,
post: ->
if not @bodyParams.name?
return Sequoia.API.v1.failure 'Body param "name" is required'
if not Sequoia.authz.hasPermission(@userId, 'create-p')
return Sequoia.API.v1.unauthorized()
id = undefined
try
if not @bodyParams.members?
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, []
else
Meteor.runAsUser this.userId, =>
id = Meteor.call 'createPrivateGroup', @bodyParams.name, @bodyParams.members, []
catch e
return Sequoia.API.v1.failure e.name + ': ' + e.message
return Sequoia.API.v1.success
group: Sequoia.models.Rooms.findOneById(id.rid)
|
[
{
"context": "st\n user: attrs.database_user\n password: attrs.database_password\n connection.query 'SHOW DATABASES;', (err, dat",
"end": 1780,
"score": 0.9991358518600464,
"start": 1757,
"tag": "PASSWORD",
"value": "attrs.database_password"
}
] | lib/hue/recipes/configure.coffee | zforkdump/heco | 0 |
fs = require 'fs'
path = require 'path'
exec = require('child_process').exec
mecano = require 'mecano'
mysql = require 'mysql'
recipe = require '../../recipe'
module.exports =
'Hue # Configuration # Attributes': (c, next) ->
attrs = c.conf.hue.attributes
attrs['hadoop.hadoop_home'] = c.conf.hadoop.prefix
attrs['hadoop.hdfs_clusters.hdfs_port'] = c.conf.hadoop.attributes['fs.default.name'].split(':')[2]
attrs['hadoop.hdfs_clusters.http_port'] = c.conf.hadoop.attributes['dfs.http.address'].split(':')[1]
attrs['hdfs.thrift_port'] = c.conf.hadoop.attributes['dfs.thrift.address'].split(':')[1]
attrs['mapred.thrift_port'] = c.conf.hadoop.attributes['jobtracker.thrift.address'].split(':')[1]
attrs['hive_home_dir'] = c.conf.hive.prefix
attrs['hive_conf_dir'] = c.conf.hive.conf
mecano.render [
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue.ini"
destination: "#{c.conf.hue.prefix}/desktop/conf/hue.ini"
context: attrs
,
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue-beeswax.ini"
destination: "#{c.conf.hue.prefix}/apps/beeswax/conf/hue-beeswax.ini"
context: attrs
], (err, updated) ->
next err, if updated then recipe.OK else recipe.SKIPPED
'Hue # Configuration # Directories': (c, next) ->
mecano.mkdir [
directory: c.conf.hue.pid
chmod: 0o0755
], (err, created) ->
next err, if created then recipe.OK else recipe.SKIPPED
'Hue # Configure # Database': (c, next) ->
attrs = c.conf.hue.attributes
connection_end = (callback) ->
connection.end (err) ->
callback err
connection = mysql.createConnection
host: attrs.database_host
user: attrs.database_user
password: attrs.database_password
connection.query 'SHOW DATABASES;', (err, databases) ->
return next err if err
if (databases.filter (database) -> database.Database is 'hue').length
return connection_end ->
next null, recipe.SKIPPED
connection.query 'CREATE DATABASE `hue`;', (err, result) ->
connection_end ->
next err, recipe.OK
# TODO: Build only if configuration has changed to reflect changes in database settings
# Among the created file: './app.reg'
'Hue # Configure # Build': (c, next) ->
mecano.exec
cmd: 'export CC=gcc && make apps'
cwd: c.conf.hue.prefix
not_if_exists: "#{c.conf.hue.prefix}/app.reg"
, (err, executed, stdout, stderr) ->
next err, if executed then recipe.OK else recipe.SKIPPED
| 221440 |
fs = require 'fs'
path = require 'path'
exec = require('child_process').exec
mecano = require 'mecano'
mysql = require 'mysql'
recipe = require '../../recipe'
module.exports =
'Hue # Configuration # Attributes': (c, next) ->
attrs = c.conf.hue.attributes
attrs['hadoop.hadoop_home'] = c.conf.hadoop.prefix
attrs['hadoop.hdfs_clusters.hdfs_port'] = c.conf.hadoop.attributes['fs.default.name'].split(':')[2]
attrs['hadoop.hdfs_clusters.http_port'] = c.conf.hadoop.attributes['dfs.http.address'].split(':')[1]
attrs['hdfs.thrift_port'] = c.conf.hadoop.attributes['dfs.thrift.address'].split(':')[1]
attrs['mapred.thrift_port'] = c.conf.hadoop.attributes['jobtracker.thrift.address'].split(':')[1]
attrs['hive_home_dir'] = c.conf.hive.prefix
attrs['hive_conf_dir'] = c.conf.hive.conf
mecano.render [
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue.ini"
destination: "#{c.conf.hue.prefix}/desktop/conf/hue.ini"
context: attrs
,
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue-beeswax.ini"
destination: "#{c.conf.hue.prefix}/apps/beeswax/conf/hue-beeswax.ini"
context: attrs
], (err, updated) ->
next err, if updated then recipe.OK else recipe.SKIPPED
'Hue # Configuration # Directories': (c, next) ->
mecano.mkdir [
directory: c.conf.hue.pid
chmod: 0o0755
], (err, created) ->
next err, if created then recipe.OK else recipe.SKIPPED
'Hue # Configure # Database': (c, next) ->
attrs = c.conf.hue.attributes
connection_end = (callback) ->
connection.end (err) ->
callback err
connection = mysql.createConnection
host: attrs.database_host
user: attrs.database_user
password: <PASSWORD>
connection.query 'SHOW DATABASES;', (err, databases) ->
return next err if err
if (databases.filter (database) -> database.Database is 'hue').length
return connection_end ->
next null, recipe.SKIPPED
connection.query 'CREATE DATABASE `hue`;', (err, result) ->
connection_end ->
next err, recipe.OK
# TODO: Build only if configuration has changed to reflect changes in database settings
# Among the created file: './app.reg'
'Hue # Configure # Build': (c, next) ->
mecano.exec
cmd: 'export CC=gcc && make apps'
cwd: c.conf.hue.prefix
not_if_exists: "#{c.conf.hue.prefix}/app.reg"
, (err, executed, stdout, stderr) ->
next err, if executed then recipe.OK else recipe.SKIPPED
| true |
fs = require 'fs'
path = require 'path'
exec = require('child_process').exec
mecano = require 'mecano'
mysql = require 'mysql'
recipe = require '../../recipe'
module.exports =
'Hue # Configuration # Attributes': (c, next) ->
attrs = c.conf.hue.attributes
attrs['hadoop.hadoop_home'] = c.conf.hadoop.prefix
attrs['hadoop.hdfs_clusters.hdfs_port'] = c.conf.hadoop.attributes['fs.default.name'].split(':')[2]
attrs['hadoop.hdfs_clusters.http_port'] = c.conf.hadoop.attributes['dfs.http.address'].split(':')[1]
attrs['hdfs.thrift_port'] = c.conf.hadoop.attributes['dfs.thrift.address'].split(':')[1]
attrs['mapred.thrift_port'] = c.conf.hadoop.attributes['jobtracker.thrift.address'].split(':')[1]
attrs['hive_home_dir'] = c.conf.hive.prefix
attrs['hive_conf_dir'] = c.conf.hive.conf
mecano.render [
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue.ini"
destination: "#{c.conf.hue.prefix}/desktop/conf/hue.ini"
context: attrs
,
source: "#{__dirname}/../templates/#{c.conf.hue.version}/hue-beeswax.ini"
destination: "#{c.conf.hue.prefix}/apps/beeswax/conf/hue-beeswax.ini"
context: attrs
], (err, updated) ->
next err, if updated then recipe.OK else recipe.SKIPPED
'Hue # Configuration # Directories': (c, next) ->
mecano.mkdir [
directory: c.conf.hue.pid
chmod: 0o0755
], (err, created) ->
next err, if created then recipe.OK else recipe.SKIPPED
'Hue # Configure # Database': (c, next) ->
attrs = c.conf.hue.attributes
connection_end = (callback) ->
connection.end (err) ->
callback err
connection = mysql.createConnection
host: attrs.database_host
user: attrs.database_user
password: PI:PASSWORD:<PASSWORD>END_PI
connection.query 'SHOW DATABASES;', (err, databases) ->
return next err if err
if (databases.filter (database) -> database.Database is 'hue').length
return connection_end ->
next null, recipe.SKIPPED
connection.query 'CREATE DATABASE `hue`;', (err, result) ->
connection_end ->
next err, recipe.OK
# TODO: Build only if configuration has changed to reflect changes in database settings
# Among the created file: './app.reg'
'Hue # Configure # Build': (c, next) ->
mecano.exec
cmd: 'export CC=gcc && make apps'
cwd: c.conf.hue.prefix
not_if_exists: "#{c.conf.hue.prefix}/app.reg"
, (err, executed, stdout, stderr) ->
next err, if executed then recipe.OK else recipe.SKIPPED
|
[
{
"context": "module.exports = [\n {\n id: 'guggenheim',\n headline: 'Guggenheim: Åzone Futures Market",
"end": 42,
"score": 0.9985252618789673,
"start": 32,
"tag": "USERNAME",
"value": "guggenheim"
},
{
"context": "rts = [\n {\n id: 'guggenheim',\n headline: 'Guggenhei... | apps/about/client/experiments.coffee | 1aurabrown/ervell | 118 | module.exports = [
{
id: 'guggenheim',
headline: 'Guggenheim: Åzone Futures Market',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077504/original_1d13c028817c3b014a7e5053ae07dae8.png',
copy: 'A digital exhibition in the form of a marketplace for trading predictions about the future.',
link: "https://www.guggenheim.org/blogs/checklist/the-futures-are-now-troy-conrad-therrien-on-the-guggenheims-new-online-exhibition"
},
{
id: 'tci',
headline: 'Library of Practical & Conceptual Resources',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077502/original_7a557ced63d7e01a4326768a891ad395.png',
copy: 'A series of advice, reflections, and resources compiled by artists and published with The Creative Independent',
link: 'https://thecreativeindependent.com/notes/arena-tci-how-do-you-use-the-internet-mindfully/'
},
{
id: 'cab',
headline: 'Chicago Architecture Biennial Blog',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077505/original_6e96feaa4966a4935c520fe955185ec8.png',
copy: 'An exhibition blog with embedded Are.na channels for exploring related content.',
link: "http://chicagoarchitecturebiennial.org/blog/"
},
{
id: 'knight',
headline: 'Knight Foundation Prototype: Pilgrim',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077503/original_72bc6a12885e17d647974aca082faab1.png',
copy: 'An experimental web crawler created by Are.na that visualizes your browsing history.',
link: "http://pilgrim.are.na"
},
] | 123779 | module.exports = [
{
id: 'guggenheim',
headline: 'G<NAME>heim: Åzone Futures Market',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077504/original_1d13c028817c3b014a7e5053ae07dae8.png',
copy: 'A digital exhibition in the form of a marketplace for trading predictions about the future.',
link: "https://www.guggenheim.org/blogs/checklist/the-futures-are-now-troy-conrad-therrien-on-the-guggenheims-new-online-exhibition"
},
{
id: 'tci',
headline: 'Library of Practical & Conceptual Resources',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077502/original_7a557ced63d7e01a4326768a891ad395.png',
copy: 'A series of advice, reflections, and resources compiled by artists and published with The Creative Independent',
link: 'https://thecreativeindependent.com/notes/arena-tci-how-do-you-use-the-internet-mindfully/'
},
{
id: 'cab',
headline: 'Chicago Architecture Biennial Blog',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077505/original_6e96feaa4966a4935c520fe955185ec8.png',
copy: 'An exhibition blog with embedded Are.na channels for exploring related content.',
link: "http://chicagoarchitecturebiennial.org/blog/"
},
{
id: 'knight',
headline: 'Knight Foundation Prototype: Pilgrim',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077503/original_72bc6a12885e17d647974aca082faab1.png',
copy: 'An experimental web crawler created by Are.na that visualizes your browsing history.',
link: "http://pilgrim.are.na"
},
] | true | module.exports = [
{
id: 'guggenheim',
headline: 'GPI:NAME:<NAME>END_PIheim: Åzone Futures Market',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077504/original_1d13c028817c3b014a7e5053ae07dae8.png',
copy: 'A digital exhibition in the form of a marketplace for trading predictions about the future.',
link: "https://www.guggenheim.org/blogs/checklist/the-futures-are-now-troy-conrad-therrien-on-the-guggenheims-new-online-exhibition"
},
{
id: 'tci',
headline: 'Library of Practical & Conceptual Resources',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077502/original_7a557ced63d7e01a4326768a891ad395.png',
copy: 'A series of advice, reflections, and resources compiled by artists and published with The Creative Independent',
link: 'https://thecreativeindependent.com/notes/arena-tci-how-do-you-use-the-internet-mindfully/'
},
{
id: 'cab',
headline: 'Chicago Architecture Biennial Blog',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077505/original_6e96feaa4966a4935c520fe955185ec8.png',
copy: 'An exhibition blog with embedded Are.na channels for exploring related content.',
link: "http://chicagoarchitecturebiennial.org/blog/"
},
{
id: 'knight',
headline: 'Knight Foundation Prototype: Pilgrim',
image: 'https://d2w9rnfcy7mm78.cloudfront.net/2077503/original_72bc6a12885e17d647974aca082faab1.png',
copy: 'An experimental web crawler created by Are.na that visualizes your browsing history.',
link: "http://pilgrim.are.na"
},
] |
[
{
"context": " hex: '#0f0'\n red:\n id: 'red'\n rgb: [255, 0, 0]\n hex: '#f00'",
"end": 2319,
"score": 0.6384544968605042,
"start": 2316,
"tag": "NAME",
"value": "red"
},
{
"context": " expect(model.get 'list').to.eql [\n {id: 'red',... | test/Model/refList.mocha.coffee | vmakhaev/racer | 0 | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'refList', ->
setup = (options) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids', options
return model
expectEvents = (pattern, model, done, events) ->
model.on 'all', pattern, ->
events.shift() arguments...
done() unless events.length
done() unless events?.length
expectFromEvents = (model, done, events) ->
expectEvents 'list**', model, done, events
expectToEvents = (model, done, events) ->
expectEvents 'colors**', model, done, events
expectIdsEvents = (model, done, events) ->
expectEvents 'ids**', model, done, events
describe 'sets output on initial call', ->
it 'sets the initial value to empty array if no inputs', ->
model = (new Model).at '_page'
model.refList 'empty', 'colors', 'noIds'
expect(model.get 'empty').to.eql []
it 'sets the initial value for already populated data', ->
model = setup()
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
describe 'updates on `ids` mutations', ->
it 'updates the value when `ids` is set', ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql []
model.set 'ids', ['red', 'green', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` is set', (done) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
model.on 'all', 'list**', (capture, method, index, values) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(values).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.set 'ids', ['red', 'green', 'red']
it 'updates the value when `ids` children are set', ->
model = setup()
model.set 'ids.0', 'green'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.set 'ids.2', 'blue'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
it 'emits on `from` when `ids` children are set', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
expect(previous).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
done()
model.set 'ids.2', 'green'
it 'updates the value when `ids` are inserted', ->
model = setup()
model.push 'ids', 'green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.insert 'ids', 1, ['blue', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
it 'emits on `from` when `ids` are inserted', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 1
expect(inserted).to.eql [
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.insert 'ids', 1, ['blue', 'red']
it 'updates the value when `ids` are removed', ->
model = setup()
model.pop 'ids'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.remove 'ids', 0, 2
expect(model.get 'list').to.eql []
it 'emits on `from` when `ids` are removed', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
done()
model.remove 'ids', 0, 2
it 'updates the value when `ids` are moved', ->
model = setup()
model.move 'ids', 0, 2, 2
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.move 'ids', 2, 0
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` are moved', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, from, to, howMany) ->
expect(capture).to.equal ''
expect(method).to.equal 'move'
expect(from).to.equal 0
expect(to).to.equal 2
expect(howMany).to.eql 2
done()
model.move 'ids', 0, 2, 2
describe 'emits events involving multiple refLists', ->
it 'removes data from a refList pointing to data in another refList', ->
model = (new Model).at '_page'
tagId = model.add 'tags', { text: 'hi' }
tagIds = [tagId]
#profiles collection
id = model.add 'profiles', { tagIds: tagIds }
model.push 'profileIds', id
model.refList 'profilesList', 'profiles', 'profileIds'
#ref a single item from collection
model.ref 'profile', 'profilesList.0'
#remove from nested refList
model.refList 'tagsList', 'tags', 'profile.tagIds'
model.remove('tagsList', 0)
describe 'updates on `to` mutations', ->
it 'updates the value when `to` is set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql [undefined, undefined, undefined]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` is set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [undefined, undefined, undefined]
, (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(inserted).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` children are set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
model.set 'colors.green',
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
expect(model.get 'list').to.eql [
undefined
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.del 'colors.green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` children are set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
, (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` descendants are set', ->
model = setup()
model.set 'colors.red.hex', '#e00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
]
model.set 'colors.red.rgb.0', 238
expect(model.get 'list').to.eql [
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
]
it 'emits on `from` when `to` descendants are set', (done) ->
model = setup()
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '2.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '0.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
, (capture, method, value, previous) ->
expect(capture).to.equal '2.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
]
model.set 'colors.red.hex', '#e00'
model.set 'colors.red.rgb.0', 238
it 'updates the value when inserting on `to` children', ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expect(model.get 'list').to.eql [
[2, 4, 6]
[1, 3]
[2, 4, 6]
]
model.push 'nums.even', 8
expect(model.get 'list').to.eql [
[2, 4, 6, 8]
[1, 3]
[2, 4, 6, 8]
]
it 'emits on `from` when inserting on `to` children', (done) ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expectFromEvents model, done, [
(capture, method, index, inserted) ->
expect(capture).to.equal '0'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
, (capture, method, index, inserted) ->
expect(capture).to.equal '2'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
]
model.push 'nums.even', 8
describe 'updates on `from` mutations', ->
it 'updates `to` and `ids` when `from` is set', ->
model = setup()
model.set 'list', [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['green', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
# Changing items in the `from` list can only create new objects
# under `to`, and it does not remove them
model.del 'list'
expect(model.get 'ids').to.eql []
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['blue', 'yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
model.at('list.0').remove()
expect(model.get 'ids').to.eql ['yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
it 'emits on `to` when `from` is set', (done) ->
model = setup()
expectToEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal 'blue'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
expect(previous).to.eql undefined
(capture, method, value, previous) ->
expect(capture).to.equal 'yellow'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
expect(previous).to.eql undefined
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
model.get('colors.red')
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits on `ids` when `from is set', (done) ->
model = setup()
expectIdsEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal ''
expect(method).to.equal 'change'
expect(value).to.eql ['blue', 'red', 'yellow']
expect(previous).to.eql ['red', 'green', 'red']
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits nothing on `to` when `from` is set, removing items', (done) ->
model = setup()
expectToEvents model, done, []
model.set 'list', []
it 'creates a document in `to` on an insert', ->
model = setup()
model.insert 'list', 0, {id: 'yellow'}
expect(model.get('colors.yellow')).to.eql {id: 'yellow'}
it 'creates a document in `to` on an insert of a doc with no id', ->
model = setup()
model.insert 'list', 0, {rgb: [1, 1, 1]}
newId = model.get('list.0').id
expect(model.get("colors.#{newId}")).to.eql {id: newId, rgb: [1, 1, 1]}
describe 'event ordering', ->
it 'should be able to resolve a non-existent nested property as undefined, inside an event listener on refA (where refA -> refList)', (done) ->
model = setup()
model.refList 'array', 'colors', 'arrayIds'
model.ref 'arrayAlias', 'array'
model.on 'insert', 'arrayAlias', ->
expect(model.get 'array.0.names.0').to.eql undefined
done()
model.insert 'arrayAlias', 0, {rgb: [1, 1, 1]}
expect(model.get 'arrayIds').to.have.length(1)
describe 'deleteRemoved', ->
it 'deletes the underlying object when an item is removed', ->
model = setup {deleteRemoved: true}
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.remove 'list', 0
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
| 65210 | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'refList', ->
setup = (options) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids', options
return model
expectEvents = (pattern, model, done, events) ->
model.on 'all', pattern, ->
events.shift() arguments...
done() unless events.length
done() unless events?.length
expectFromEvents = (model, done, events) ->
expectEvents 'list**', model, done, events
expectToEvents = (model, done, events) ->
expectEvents 'colors**', model, done, events
expectIdsEvents = (model, done, events) ->
expectEvents 'ids**', model, done, events
describe 'sets output on initial call', ->
it 'sets the initial value to empty array if no inputs', ->
model = (new Model).at '_page'
model.refList 'empty', 'colors', 'noIds'
expect(model.get 'empty').to.eql []
it 'sets the initial value for already populated data', ->
model = setup()
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
describe 'updates on `ids` mutations', ->
it 'updates the value when `ids` is set', ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql []
model.set 'ids', ['red', 'green', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` is set', (done) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: '<NAME>'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
model.on 'all', 'list**', (capture, method, index, values) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(values).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.set 'ids', ['red', 'green', 'red']
it 'updates the value when `ids` children are set', ->
model = setup()
model.set 'ids.0', 'green'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.set 'ids.2', 'blue'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
it 'emits on `from` when `ids` children are set', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
expect(previous).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
done()
model.set 'ids.2', 'green'
it 'updates the value when `ids` are inserted', ->
model = setup()
model.push 'ids', 'green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.insert 'ids', 1, ['blue', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
it 'emits on `from` when `ids` are inserted', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 1
expect(inserted).to.eql [
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.insert 'ids', 1, ['blue', 'red']
it 'updates the value when `ids` are removed', ->
model = setup()
model.pop 'ids'
expect(model.get 'list').to.eql [
{id: '<NAME>', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.remove 'ids', 0, 2
expect(model.get 'list').to.eql []
it 'emits on `from` when `ids` are removed', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
done()
model.remove 'ids', 0, 2
it 'updates the value when `ids` are moved', ->
model = setup()
model.move 'ids', 0, 2, 2
expect(model.get 'list').to.eql [
{id: '<NAME>', rgb: [255, 0, 0], hex: '#f00'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.move 'ids', 2, 0
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: '<NAME>', rgb: [255, 0, 0], hex: '#f00'}
{id: '<NAME>', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` are moved', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, from, to, howMany) ->
expect(capture).to.equal ''
expect(method).to.equal 'move'
expect(from).to.equal 0
expect(to).to.equal 2
expect(howMany).to.eql 2
done()
model.move 'ids', 0, 2, 2
describe 'emits events involving multiple refLists', ->
it 'removes data from a refList pointing to data in another refList', ->
model = (new Model).at '_page'
tagId = model.add 'tags', { text: 'hi' }
tagIds = [tagId]
#profiles collection
id = model.add 'profiles', { tagIds: tagIds }
model.push 'profileIds', id
model.refList 'profilesList', 'profiles', 'profileIds'
#ref a single item from collection
model.ref 'profile', 'profilesList.0'
#remove from nested refList
model.refList 'tagsList', 'tags', 'profile.tagIds'
model.remove('tagsList', 0)
describe 'updates on `to` mutations', ->
it 'updates the value when `to` is set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql [undefined, undefined, undefined]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` is set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [undefined, undefined, undefined]
, (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(inserted).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` children are set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
model.set 'colors.green',
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
expect(model.get 'list').to.eql [
undefined
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.del 'colors.green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` children are set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
, (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` descendants are set', ->
model = setup()
model.set 'colors.red.hex', '#e00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
]
model.set 'colors.red.rgb.0', 238
expect(model.get 'list').to.eql [
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
]
it 'emits on `from` when `to` descendants are set', (done) ->
model = setup()
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '2.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '0.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
, (capture, method, value, previous) ->
expect(capture).to.equal '2.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
]
model.set 'colors.red.hex', '#e00'
model.set 'colors.red.rgb.0', 238
it 'updates the value when inserting on `to` children', ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expect(model.get 'list').to.eql [
[2, 4, 6]
[1, 3]
[2, 4, 6]
]
model.push 'nums.even', 8
expect(model.get 'list').to.eql [
[2, 4, 6, 8]
[1, 3]
[2, 4, 6, 8]
]
it 'emits on `from` when inserting on `to` children', (done) ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expectFromEvents model, done, [
(capture, method, index, inserted) ->
expect(capture).to.equal '0'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
, (capture, method, index, inserted) ->
expect(capture).to.equal '2'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
]
model.push 'nums.even', 8
describe 'updates on `from` mutations', ->
it 'updates `to` and `ids` when `from` is set', ->
model = setup()
model.set 'list', [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['green', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
# Changing items in the `from` list can only create new objects
# under `to`, and it does not remove them
model.del 'list'
expect(model.get 'ids').to.eql []
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['blue', 'yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
model.at('list.0').remove()
expect(model.get 'ids').to.eql ['yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
it 'emits on `to` when `from` is set', (done) ->
model = setup()
expectToEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal 'blue'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
expect(previous).to.eql undefined
(capture, method, value, previous) ->
expect(capture).to.equal 'yellow'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
expect(previous).to.eql undefined
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
model.get('colors.red')
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits on `ids` when `from is set', (done) ->
model = setup()
expectIdsEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal ''
expect(method).to.equal 'change'
expect(value).to.eql ['blue', 'red', 'yellow']
expect(previous).to.eql ['red', 'green', 'red']
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits nothing on `to` when `from` is set, removing items', (done) ->
model = setup()
expectToEvents model, done, []
model.set 'list', []
it 'creates a document in `to` on an insert', ->
model = setup()
model.insert 'list', 0, {id: 'yellow'}
expect(model.get('colors.yellow')).to.eql {id: 'yellow'}
it 'creates a document in `to` on an insert of a doc with no id', ->
model = setup()
model.insert 'list', 0, {rgb: [1, 1, 1]}
newId = model.get('list.0').id
expect(model.get("colors.#{newId}")).to.eql {id: newId, rgb: [1, 1, 1]}
describe 'event ordering', ->
it 'should be able to resolve a non-existent nested property as undefined, inside an event listener on refA (where refA -> refList)', (done) ->
model = setup()
model.refList 'array', 'colors', 'arrayIds'
model.ref 'arrayAlias', 'array'
model.on 'insert', 'arrayAlias', ->
expect(model.get 'array.0.names.0').to.eql undefined
done()
model.insert 'arrayAlias', 0, {rgb: [1, 1, 1]}
expect(model.get 'arrayIds').to.have.length(1)
describe 'deleteRemoved', ->
it 'deletes the underlying object when an item is removed', ->
model = setup {deleteRemoved: true}
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.remove 'list', 0
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
| true | {expect} = require '../util'
Model = require '../../lib/Model'
describe 'refList', ->
setup = (options) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids', options
return model
expectEvents = (pattern, model, done, events) ->
model.on 'all', pattern, ->
events.shift() arguments...
done() unless events.length
done() unless events?.length
expectFromEvents = (model, done, events) ->
expectEvents 'list**', model, done, events
expectToEvents = (model, done, events) ->
expectEvents 'colors**', model, done, events
expectIdsEvents = (model, done, events) ->
expectEvents 'ids**', model, done, events
describe 'sets output on initial call', ->
it 'sets the initial value to empty array if no inputs', ->
model = (new Model).at '_page'
model.refList 'empty', 'colors', 'noIds'
expect(model.get 'empty').to.eql []
it 'sets the initial value for already populated data', ->
model = setup()
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
describe 'updates on `ids` mutations', ->
it 'updates the value when `ids` is set', ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql []
model.set 'ids', ['red', 'green', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` is set', (done) ->
model = (new Model).at '_page'
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'PI:NAME:<NAME>END_PI'
rgb: [255, 0, 0]
hex: '#f00'
model.refList 'list', 'colors', 'ids'
model.on 'all', 'list**', (capture, method, index, values) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(values).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.set 'ids', ['red', 'green', 'red']
it 'updates the value when `ids` children are set', ->
model = setup()
model.set 'ids.0', 'green'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.set 'ids.2', 'blue'
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
it 'emits on `from` when `ids` children are set', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
expect(previous).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
done()
model.set 'ids.2', 'green'
it 'updates the value when `ids` are inserted', ->
model = setup()
model.push 'ids', 'green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.insert 'ids', 1, ['blue', 'red']
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
it 'emits on `from` when `ids` are inserted', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 1
expect(inserted).to.eql [
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
done()
model.insert 'ids', 1, ['blue', 'red']
it 'updates the value when `ids` are removed', ->
model = setup()
model.pop 'ids'
expect(model.get 'list').to.eql [
{id: 'PI:NAME:<NAME>END_PI', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.remove 'ids', 0, 2
expect(model.get 'list').to.eql []
it 'emits on `from` when `ids` are removed', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
done()
model.remove 'ids', 0, 2
it 'updates the value when `ids` are moved', ->
model = setup()
model.move 'ids', 0, 2, 2
expect(model.get 'list').to.eql [
{id: 'PI:NAME:<NAME>END_PI', rgb: [255, 0, 0], hex: '#f00'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
]
model.move 'ids', 2, 0
expect(model.get 'list').to.eql [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'PI:NAME:<NAME>END_PI', rgb: [255, 0, 0], hex: '#f00'}
{id: 'PI:NAME:<NAME>END_PI', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `ids` are moved', (done) ->
model = setup()
model.on 'all', 'list**', (capture, method, from, to, howMany) ->
expect(capture).to.equal ''
expect(method).to.equal 'move'
expect(from).to.equal 0
expect(to).to.equal 2
expect(howMany).to.eql 2
done()
model.move 'ids', 0, 2, 2
describe 'emits events involving multiple refLists', ->
it 'removes data from a refList pointing to data in another refList', ->
model = (new Model).at '_page'
tagId = model.add 'tags', { text: 'hi' }
tagIds = [tagId]
#profiles collection
id = model.add 'profiles', { tagIds: tagIds }
model.push 'profileIds', id
model.refList 'profilesList', 'profiles', 'profileIds'
#ref a single item from collection
model.ref 'profile', 'profilesList.0'
#remove from nested refList
model.refList 'tagsList', 'tags', 'profile.tagIds'
model.remove('tagsList', 0)
describe 'updates on `to` mutations', ->
it 'updates the value when `to` is set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expect(model.get 'list').to.eql [undefined, undefined, undefined]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` is set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, index, removed) ->
expect(capture).to.equal ''
expect(method).to.equal 'remove'
expect(index).to.equal 0
expect(removed).to.eql [undefined, undefined, undefined]
, (capture, method, index, inserted) ->
expect(capture).to.equal ''
expect(method).to.equal 'insert'
expect(index).to.equal 0
expect(inserted).to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
]
model.set 'colors',
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` children are set', ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
model.set 'colors.green',
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
expect(model.get 'list').to.eql [
undefined
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
model.del 'colors.green'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
undefined
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
it 'emits on `from` when `to` children are set', (done) ->
model = (new Model).at '_page'
model.set 'ids', ['red', 'green', 'red']
model.refList 'list', 'colors', 'ids'
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
, (capture, method, value, previous) ->
expect(capture).to.equal '2'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
expect(previous).to.equal undefined
]
model.set 'colors.red',
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
it 'updates the value when `to` descendants are set', ->
model = setup()
model.set 'colors.red.hex', '#e00'
expect(model.get 'list').to.eql [
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#e00'}
]
model.set 'colors.red.rgb.0', 238
expect(model.get 'list').to.eql [
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [238, 0, 0], hex: '#e00'}
]
it 'emits on `from` when `to` descendants are set', (done) ->
model = setup()
expectFromEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal '0.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '2.hex'
expect(method).to.equal 'change'
expect(value).to.eql '#e00'
expect(previous).to.equal '#f00'
, (capture, method, value, previous) ->
expect(capture).to.equal '0.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
, (capture, method, value, previous) ->
expect(capture).to.equal '2.rgb.0'
expect(method).to.equal 'change'
expect(value).to.eql 238
expect(previous).to.equal 255
]
model.set 'colors.red.hex', '#e00'
model.set 'colors.red.rgb.0', 238
it 'updates the value when inserting on `to` children', ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expect(model.get 'list').to.eql [
[2, 4, 6]
[1, 3]
[2, 4, 6]
]
model.push 'nums.even', 8
expect(model.get 'list').to.eql [
[2, 4, 6, 8]
[1, 3]
[2, 4, 6, 8]
]
it 'emits on `from` when inserting on `to` children', (done) ->
model = (new Model).at '_page'
model.set 'nums',
even: [2, 4, 6]
odd: [1, 3]
model.set 'ids', ['even', 'odd', 'even']
model.refList 'list', 'nums', 'ids'
expectFromEvents model, done, [
(capture, method, index, inserted) ->
expect(capture).to.equal '0'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
, (capture, method, index, inserted) ->
expect(capture).to.equal '2'
expect(method).to.equal 'insert'
expect(index).to.equal 3
expect(inserted).to.eql [8]
]
model.push 'nums.even', 8
describe 'updates on `from` mutations', ->
it 'updates `to` and `ids` when `from` is set', ->
model = setup()
model.set 'list', [
{id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['green', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
# Changing items in the `from` list can only create new objects
# under `to`, and it does not remove them
model.del 'list'
expect(model.get 'ids').to.eql []
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
]
expect(model.get 'ids').to.eql ['blue', 'yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
model.at('list.0').remove()
expect(model.get 'ids').to.eql ['yellow', 'red']
expect(model.get 'colors').to.eql
green: {id: 'green', rgb: [0, 255, 0], hex: '#0f0'}
red: {id: 'red', rgb: [255, 0, 0], hex: '#f00'}
blue: {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
yellow: {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
it 'emits on `to` when `from` is set', (done) ->
model = setup()
expectToEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal 'blue'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
expect(previous).to.eql undefined
(capture, method, value, previous) ->
expect(capture).to.equal 'yellow'
expect(method).to.equal 'change'
expect(value).to.eql {id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
expect(previous).to.eql undefined
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
model.get('colors.red')
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits on `ids` when `from is set', (done) ->
model = setup()
expectIdsEvents model, done, [
(capture, method, value, previous) ->
expect(capture).to.equal ''
expect(method).to.equal 'change'
expect(value).to.eql ['blue', 'red', 'yellow']
expect(previous).to.eql ['red', 'green', 'red']
]
model.set 'list', [
{id: 'blue', rgb: [0, 0, 255], hex: '#00f'}
{id: 'red', rgb: [255, 0, 0], hex: '#f00'}
{id: 'yellow', rgb: [255, 255, 0], hex: '#ff0'}
]
it 'emits nothing on `to` when `from` is set, removing items', (done) ->
model = setup()
expectToEvents model, done, []
model.set 'list', []
it 'creates a document in `to` on an insert', ->
model = setup()
model.insert 'list', 0, {id: 'yellow'}
expect(model.get('colors.yellow')).to.eql {id: 'yellow'}
it 'creates a document in `to` on an insert of a doc with no id', ->
model = setup()
model.insert 'list', 0, {rgb: [1, 1, 1]}
newId = model.get('list.0').id
expect(model.get("colors.#{newId}")).to.eql {id: newId, rgb: [1, 1, 1]}
describe 'event ordering', ->
it 'should be able to resolve a non-existent nested property as undefined, inside an event listener on refA (where refA -> refList)', (done) ->
model = setup()
model.refList 'array', 'colors', 'arrayIds'
model.ref 'arrayAlias', 'array'
model.on 'insert', 'arrayAlias', ->
expect(model.get 'array.0.names.0').to.eql undefined
done()
model.insert 'arrayAlias', 0, {rgb: [1, 1, 1]}
expect(model.get 'arrayIds').to.have.length(1)
describe 'deleteRemoved', ->
it 'deletes the underlying object when an item is removed', ->
model = setup {deleteRemoved: true}
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
red:
id: 'red'
rgb: [255, 0, 0]
hex: '#f00'
model.remove 'list', 0
expect(model.get 'colors').to.eql
green:
id: 'green'
rgb: [0, 255, 0]
hex: '#0f0'
|
[
{
"context": " Quo Module\n\n@namespace Quo\n@class Output\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\nd",
"end": 81,
"score": 0.9998382925987244,
"start": 60,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "Quo\n@class Outp... | source/quo.output.coffee | TNT-RoX/QuoJS | 1 | ###
Basic Quo Module
@namespace Quo
@class Output
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set text to a given instance element
@method text
@param {string} [OPTIONAL] Value of text
###
$$.fn.text = (value) ->
if value?
@each -> @textContent = value
else
if @length > 0 then @[0].textContent else ""
###
Get/Set html to a given instance element
@method html
@param {variable} [OPTIONAL] Value of html
###
$$.fn.html = (value) ->
if value?
type = $$.toType(value)
@each ->
if type is "string"
@innerHTML = value
else if type is "array"
value.forEach (slice) => $$(@).html(slice)
else
@innerHTML += $$(value).html()
else
if @length > 0 then @[0].innerHTML else ""
###
Remove the set of matched elements to a given instance element
@method remove
###
$$.fn.remove = ->
@each -> @parentNode.removeChild this if @parentNode?
###
Remove all child nodes of the set of matched elements to a given instance element
@method remove
###
$$.fn.empty = ->
@each -> @innerHTML = null
###
Append a html to a given instance element
@method append
@param {html} Value of html
###
$$.fn.append = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "beforeend", value
else if type is "array"
value.forEach (slice) => $$(@).append(slice)
else
@appendChild value
###
Prepend a html to a given instance element
@method prepend
@param {html} Value of html
###
$$.fn.prepend = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "afterbegin", value
else if type is "array"
value.each (index, value) => @insertBefore value, @firstChild
else
@insertBefore value, @firstChild
###
Replace each element in the set of matched elements with the provided new
content and return the set of elements that was removed.
@method replaceWith
@param {html} The content to insert (HTML string, DOMelement, array of DOMelements)
###
$$.fn.replaceWith = (value) ->
type = $$.toType(value)
@each ->
if @parentNode
if type is "string"
@insertAdjacentHTML "beforeBegin", value
else if type is "array"
value.each (index, value) => @parentNode.insertBefore value, @
else
@parentNode.insertBefore value, @
@remove()
| 106019 | ###
Basic Quo Module
@namespace Quo
@class Output
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set text to a given instance element
@method text
@param {string} [OPTIONAL] Value of text
###
$$.fn.text = (value) ->
if value?
@each -> @textContent = value
else
if @length > 0 then @[0].textContent else ""
###
Get/Set html to a given instance element
@method html
@param {variable} [OPTIONAL] Value of html
###
$$.fn.html = (value) ->
if value?
type = $$.toType(value)
@each ->
if type is "string"
@innerHTML = value
else if type is "array"
value.forEach (slice) => $$(@).html(slice)
else
@innerHTML += $$(value).html()
else
if @length > 0 then @[0].innerHTML else ""
###
Remove the set of matched elements to a given instance element
@method remove
###
$$.fn.remove = ->
@each -> @parentNode.removeChild this if @parentNode?
###
Remove all child nodes of the set of matched elements to a given instance element
@method remove
###
$$.fn.empty = ->
@each -> @innerHTML = null
###
Append a html to a given instance element
@method append
@param {html} Value of html
###
$$.fn.append = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "beforeend", value
else if type is "array"
value.forEach (slice) => $$(@).append(slice)
else
@appendChild value
###
Prepend a html to a given instance element
@method prepend
@param {html} Value of html
###
$$.fn.prepend = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "afterbegin", value
else if type is "array"
value.each (index, value) => @insertBefore value, @firstChild
else
@insertBefore value, @firstChild
###
Replace each element in the set of matched elements with the provided new
content and return the set of elements that was removed.
@method replaceWith
@param {html} The content to insert (HTML string, DOMelement, array of DOMelements)
###
$$.fn.replaceWith = (value) ->
type = $$.toType(value)
@each ->
if @parentNode
if type is "string"
@insertAdjacentHTML "beforeBegin", value
else if type is "array"
value.each (index, value) => @parentNode.insertBefore value, @
else
@parentNode.insertBefore value, @
@remove()
| true | ###
Basic Quo Module
@namespace Quo
@class Output
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set text to a given instance element
@method text
@param {string} [OPTIONAL] Value of text
###
$$.fn.text = (value) ->
if value?
@each -> @textContent = value
else
if @length > 0 then @[0].textContent else ""
###
Get/Set html to a given instance element
@method html
@param {variable} [OPTIONAL] Value of html
###
$$.fn.html = (value) ->
if value?
type = $$.toType(value)
@each ->
if type is "string"
@innerHTML = value
else if type is "array"
value.forEach (slice) => $$(@).html(slice)
else
@innerHTML += $$(value).html()
else
if @length > 0 then @[0].innerHTML else ""
###
Remove the set of matched elements to a given instance element
@method remove
###
$$.fn.remove = ->
@each -> @parentNode.removeChild this if @parentNode?
###
Remove all child nodes of the set of matched elements to a given instance element
@method remove
###
$$.fn.empty = ->
@each -> @innerHTML = null
###
Append a html to a given instance element
@method append
@param {html} Value of html
###
$$.fn.append = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "beforeend", value
else if type is "array"
value.forEach (slice) => $$(@).append(slice)
else
@appendChild value
###
Prepend a html to a given instance element
@method prepend
@param {html} Value of html
###
$$.fn.prepend = (value) ->
type = $$.toType(value)
@each ->
if type is "string"
@insertAdjacentHTML "afterbegin", value
else if type is "array"
value.each (index, value) => @insertBefore value, @firstChild
else
@insertBefore value, @firstChild
###
Replace each element in the set of matched elements with the provided new
content and return the set of elements that was removed.
@method replaceWith
@param {html} The content to insert (HTML string, DOMelement, array of DOMelements)
###
$$.fn.replaceWith = (value) ->
type = $$.toType(value)
@each ->
if @parentNode
if type is "string"
@insertAdjacentHTML "beforeBegin", value
else if type is "array"
value.each (index, value) => @parentNode.insertBefore value, @
else
@parentNode.insertBefore value, @
@remove()
|
[
{
"context": ".test key\n key = key.replace 'placeholder', 'label'\n if messages[key]\n return if obj the",
"end": 1440,
"score": 0.4630591869354248,
"start": 1435,
"tag": "KEY",
"value": "label"
}
] | generators/message-service/templates/message.coffee | ndxbxrme/generator-ndx | 0 | 'use strict'
angular.module '<%= settings.appName %>'
.factory 'message', ->
messages =<% if(settings.Menu) { %>
#menu
"menu-dashboard": 'Dashboard'<% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
"menu-<%= settings.myEndpoints[f].plural %>": '<%= settings.myEndpoints[f].plural %>'<% } } } %><% if(settings.FormExtras) { %>
#forms
"forms-cancel": 'Cancel'
"forms-submit": 'Submit'<% } %><% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
#<%= settings.myEndpoints[f].single %>
"<%= settings.myEndpoints[f].single %>-heading": '<%= settings.myEndpoints[f].single %>'
"<%= settings.myEndpoints[f].single %>-name-label": 'Name'
#<%= settings.myEndpoints[f].plural %>
"<%= settings.myEndpoints[f].plural %>-heading": '<%= settings.myEndpoints[f].plural %>'
"<%= settings.myEndpoints[f].plural %>-button-new": 'New <%= settings.myEndpoints[f].single %>'<% } } %>
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
m = (key, obj) ->
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
if /-placeholder$/.test key
key = key.replace 'placeholder', 'label'
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
console.log 'missing message:', key
m: m
.run ($rootScope, message) ->
root = Object.getPrototypeOf $rootScope
root.m = message.m | 90796 | 'use strict'
angular.module '<%= settings.appName %>'
.factory 'message', ->
messages =<% if(settings.Menu) { %>
#menu
"menu-dashboard": 'Dashboard'<% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
"menu-<%= settings.myEndpoints[f].plural %>": '<%= settings.myEndpoints[f].plural %>'<% } } } %><% if(settings.FormExtras) { %>
#forms
"forms-cancel": 'Cancel'
"forms-submit": 'Submit'<% } %><% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
#<%= settings.myEndpoints[f].single %>
"<%= settings.myEndpoints[f].single %>-heading": '<%= settings.myEndpoints[f].single %>'
"<%= settings.myEndpoints[f].single %>-name-label": 'Name'
#<%= settings.myEndpoints[f].plural %>
"<%= settings.myEndpoints[f].plural %>-heading": '<%= settings.myEndpoints[f].plural %>'
"<%= settings.myEndpoints[f].plural %>-button-new": 'New <%= settings.myEndpoints[f].single %>'<% } } %>
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
m = (key, obj) ->
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
if /-placeholder$/.test key
key = key.replace 'placeholder', '<KEY>'
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
console.log 'missing message:', key
m: m
.run ($rootScope, message) ->
root = Object.getPrototypeOf $rootScope
root.m = message.m | true | 'use strict'
angular.module '<%= settings.appName %>'
.factory 'message', ->
messages =<% if(settings.Menu) { %>
#menu
"menu-dashboard": 'Dashboard'<% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
"menu-<%= settings.myEndpoints[f].plural %>": '<%= settings.myEndpoints[f].plural %>'<% } } } %><% if(settings.FormExtras) { %>
#forms
"forms-cancel": 'Cancel'
"forms-submit": 'Submit'<% } %><% if(settings.makeRoutesForEndpoints) { for(var f=0; f<settings.myEndpoints.length; f++) { %>
#<%= settings.myEndpoints[f].single %>
"<%= settings.myEndpoints[f].single %>-heading": '<%= settings.myEndpoints[f].single %>'
"<%= settings.myEndpoints[f].single %>-name-label": 'Name'
#<%= settings.myEndpoints[f].plural %>
"<%= settings.myEndpoints[f].plural %>-heading": '<%= settings.myEndpoints[f].plural %>'
"<%= settings.myEndpoints[f].plural %>-button-new": 'New <%= settings.myEndpoints[f].single %>'<% } } %>
fillTemplate = (template, data) ->
template.replace /\{\{(.+?)\}\}/g, (all, match) ->
evalInContext = (str, context) ->
(new Function("with(this) {return #{str}}"))
.call context
evalInContext match, data
m = (key, obj) ->
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
if /-placeholder$/.test key
key = key.replace 'placeholder', 'PI:KEY:<KEY>END_PI'
if messages[key]
return if obj then fillTemplate(messages[key], obj) else messages[key]
console.log 'missing message:', key
m: m
.run ($rootScope, message) ->
root = Object.getPrototypeOf $rootScope
root.m = message.m |
[
{
"context": "st.LocalStorage.Customer.createFromValues({name: 'Tom'})\n Test.LocalStorage.Customer.registerLocal",
"end": 2170,
"score": 0.999797523021698,
"start": 2167,
"tag": "NAME",
"value": "Tom"
},
{
"context": " Test.LocalStorage.Store.createFromValues({name: 'Bigcom'})\... | src/spec/localstorage-spec.coffee | creativeprogramming/mozart | 1 | Test = {}
Test.LocalStorage = {}
Test.LocalStorage.getId = ->
Math.round(Math.random()*9999999)
localStorage.clear()
describe 'Mozart.LocalStorage', ->
beforeEach ->
Test.LocalStorage.Customer = Mozart.Model.create { modelName: 'Customer' }
Test.LocalStorage.Customer.attributes { 'name': 'string' }
Test.LocalStorage.Customer.localStorage()
Test.LocalStorage.Store = Mozart.Model.create { modelName: 'Store' }
Test.LocalStorage.Store.attributes { 'name': 'string' }
Test.LocalStorage.Store.localStorage()
Test.LocalStorage.Product = Mozart.Model.create { modelName: 'Product' }
Test.LocalStorage.Product.attributes { 'name': 'string' }
Test.LocalStorage.Product.localStorage()
Test.LocalStorage.Order = Mozart.Model.create { modelName: 'Order' }
Test.LocalStorage.Order.localStorage({prefix:"TestLSPrefix"})
Test.LocalStorage.Store.hasMany Test.LocalStorage.Product, 'products'
Test.LocalStorage.Product.belongsTo Test.LocalStorage.Store, 'store'
Test.LocalStorage.Order.belongsToPoly [Test.LocalStorage.Store, Test.LocalStorage.Customer], 'from', 'from_id', 'from_type'
afterEach ->
Test.LocalStorage.Customer.destroyAllLocalStorage()
Test.LocalStorage.Store.destroyAllLocalStorage()
Test.LocalStorage.Product.destroyAllLocalStorage()
Test.LocalStorage.Order.destroyAllLocalStorage()
describe 'core', ->
it 'should provide the localStorage model extension method', ->
expect(Test.LocalStorage.Customer.localStorageOptions).toBeDefined()
expect(Test.LocalStorage.Customer.localStorageOptions.prefix).toEqual('MozartLS')
it 'should allow a different prefix', ->
expect(Test.LocalStorage.Order.localStorageOptions.prefix).toEqual('TestLSPrefix')
it 'shoudl provide the getLocalStoragePrefix method', ->
expect(Test.LocalStorage.Customer.getLocalStoragePrefix()).toEqual("MozartLS-Customer")
expect(Test.LocalStorage.Order.getLocalStoragePrefix()).toEqual("TestLSPrefix-Order")
describe 'localStorage id mapping methods', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'Tom'})
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, '1236')
Test.LocalStorage.bigcom = Test.LocalStorage.Store.createFromValues({name: 'Bigcom'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bigcom.id, '2348')
it 'should provide the registerLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should provide the unRegisterLocalStorageId method on model', ->
Test.LocalStorage.Customer.unRegisterLocalStorageId(Test.LocalStorage.tom.id, '1236')
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(undefined)
it 'should provide the getLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual('1236')
it 'should provide the getLocalStorageId method on instance', ->
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual('1236')
it 'should provide the getLocalStorageClientId method', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should not pollute other models when registering localStorage ids', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('2348')).toEqual(undefined)
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.bigcom.id)).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageClientId('1236')).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual(undefined)
describe 'localStorage integration', ->
beforeEach ->
# Setup LocalStorage Records
localStorage['MozartLS-Customer-index'] = "[2346,456345,345346,234235,876976,786788,123884,7732]"
localStorage['MozartLS-Customer-2346'] = '{"name":"Tom Cully"}'
localStorage['MozartLS-Customer-456345'] = '{"name":"Jason O\'Conal"}'
localStorage['MozartLS-Customer-345346'] = '{"name":"Scott Christopher"}'
localStorage['MozartLS-Customer-234235'] = '{"name":"Drew Karrasch"}'
localStorage['MozartLS-Customer-876976'] = '{"name":"Luke Eller"}'
localStorage['MozartLS-Customer-786788'] = '{"name":"Chris Roper"}'
localStorage['MozartLS-Customer-123884'] = '{"name":"Pascal Zajac"}'
localStorage['MozartLS-Customer-7732'] = '{"name":"Tim Massey"}'
# Setup JSSide records
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'Tom'})
Test.LocalStorage.jason = Test.LocalStorage.Customer.initInstance({name: 'Jason'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.getId())
Test.LocalStorage.subcaller =
onLoad: ->
onLoadAll: ->
onCreate: ->
onUpdate: ->
onDestroy: ->
onChange: ->
it 'should load all from localStorage on model loadAllLocalStorage', ->
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadAllLocalStorage()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
jason = Test.LocalStorage.Customer.findByAttribute("name","Jason O'Conal")[0]
expect(jason).toBeDefined()
expect(jason.getLocalStorageId()).toEqual(456345)
expect(Test.LocalStorage.Customer.findByAttribute("name","Jason O'Conal")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","Scott Christopher")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","Drew Karrasch")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","Luke Eller")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","Chris Roper")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","Pascal Zajac")).toBeDefined()
it 'should load data from localStorage on loadLocalStorageId', ->
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadLocalStorageId(7732)
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
instid = Test.LocalStorage.Customer.getLocalStorageClientId(7732)
expect(instid).not.toBeNull()
instance = Test.LocalStorage.Customer.findById(instid)
expect(instance.name).toEqual('Tim Massey')
it 'should load data from localStorage on instance loadLocalStorage', ->
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, 2346)
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.tom.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.tom.loadLocalStorage()
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
expect(Test.LocalStorage.tom.name).toEqual("Tom Cully")
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual(2346)
it 'should post data to localStorage on save when instance isn\'t registered', ->
spyOn(Test.LocalStorage.subcaller,'onCreate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('createLocalStorageComplete', Test.LocalStorage.subcaller.onCreate)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.jason.save()
expect(Test.LocalStorage.subcaller.onCreate).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
localStorageId = Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.jason.id)
expect(parseInt(localStorageId)).toBeGreaterThan(0)
it 'should put data to localStorage on save', ->
spyOn(Test.LocalStorage.subcaller,'onUpdate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('updateLocalStorageComplete', Test.LocalStorage.subcaller.onUpdate)
Test.LocalStorage.tom.set('name','Thomas Hugh Cully')
Test.LocalStorage.tom.save()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onUpdate).toHaveBeenCalledWith(Test.LocalStorage.tom, undefined)
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
it 'should destroy on localStorage and unregister on destroy', ->
spyOn(Test.LocalStorage.subcaller,'onDestroy')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('destroyLocalStorageComplete', Test.LocalStorage.subcaller.onDestroy)
Test.LocalStorage.tom.destroy()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onDestroy).toHaveBeenCalledWith(Test.LocalStorage.tomId, undefined)
expect(Test.LocalStorage.Customer.getLocalStorageClientId(Test.LocalStorage.tomId)).not.toBeDefined()
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
describe 'model client -> localStorage object mapping', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'Tom'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id,Test.LocalStorage.getId())
describe 'for simple objects', ->
it 'should provide the toLocalStorageObject method', ->
object = Test.LocalStorage.Customer.toLocalStorageObject(Test.LocalStorage.tom)
expect(object).not.toBe(Test.LocalStorage.tom)
expect(object.name).toEqual(Test.LocalStorage.tom.name)
expect(object.id).not.toEqual(Test.LocalStorage.tom.id)
expect(object.id).toEqual(Test.LocalStorage.tomId)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does not exist', ->
Test.LocalStorage.chrisID = Test.LocalStorage.getId()
object = {
id: Test.LocalStorage.chrisID
name: 'Chris'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(clientObject.id).toEqual(undefined)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toEqual(undefined)
expect(clientObject.name).toEqual('Chris')
expect(clientObject.id).not.toEqual(Test.LocalStorage.chrisID)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does exist', ->
object = {
id: Test.LocalStorage.tomId
name: 'Tony'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toBe(Test.LocalStorage.tom)
expect(clientObject.name).toEqual('Tony')
expect(clientObject.id).not.toEqual(Test.LocalStorage.tomId)
describe 'for objects with foreign keys', ->
beforeEach ->
Test.LocalStorage.bcId = Test.LocalStorage.getId()
Test.LocalStorage.bc = Test.LocalStorage.Store.createFromValues({name: 'BigCom'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bc.id, Test.LocalStorage.bcId)
Test.LocalStorage.shoeId = Test.LocalStorage.getId()
Test.LocalStorage.shoe = Test.LocalStorage.Product.createFromValues { name: 'Red Shoe' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.shoe.id, Test.LocalStorage.shoeId)
Test.LocalStorage.hatId = Test.LocalStorage.getId()
Test.LocalStorage.hat = Test.LocalStorage.Product.createFromValues { name: 'Blue Hat' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.hat.id, Test.LocalStorage.hatId)
Test.LocalStorage.scarf = Test.LocalStorage.Product.createFromValues { name: 'Green Scarf' }
# No Scarf LocalStorageId = unsaved to localStorage.
Test.LocalStorage.tomId = Test.LocalStorage.getId()
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues { name: 'Tom' }
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.tomId)
Test.LocalStorage.shoeOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeOrder = Test.LocalStorage.Order.createFromValues( { name: 'Customer Shoe Order' })
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeOrder.id, Test.LocalStorage.shoeOrderId)
Test.LocalStorage.shoeSupplyOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeSupplyOrder = Test.LocalStorage.Order.createFromValues( { name: 'Store Shoe Order'})
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeSupplyOrder.id, Test.LocalStorage.shoeSupplyOrderId)
Test.LocalStorage.bc.products().add(Test.LocalStorage.shoe)
Test.LocalStorage.bc.products().add(Test.LocalStorage.hat)
Test.LocalStorage.bc.products().add(Test.LocalStorage.scarf)
Test.LocalStorage.shoeOrder.from(Test.LocalStorage.tom)
#Test.LocalStorage.shoeSupplyOrder.from(Test.LocalStorage.bc)
it 'should translate non-poly fks properly in toLocalStorageObject method', ->
object = {
id: Test.LocalStorage.shoeId
name: 'Old Shoe'
store_id: Test.LocalStorage.bcId
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(Test.LocalStorage.Store.records[clientObject.store_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
id: Test.LocalStorage.shoeId
name: 'Old Shoe'
store_id: null
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(clientObject.store_id).toBeNull()
it 'should translate poly fks properly in toLocalStorageObject method', ->
object = {
name: 'Old Shoe'
from_id: Test.LocalStorage.tomId
from_type: 'Customer'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.from_id]).toBe(Test.LocalStorage.tom)
object = {
name: 'Old Shoe'
from_id: Test.LocalStorage.bcId
from_type: 'Store'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Store.records[clientObject.from_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
name: 'Old Shoe'
from_id: null
from_type: null
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(clientObject.from_id).toBeNull()
| 6110 | Test = {}
Test.LocalStorage = {}
Test.LocalStorage.getId = ->
Math.round(Math.random()*9999999)
localStorage.clear()
describe 'Mozart.LocalStorage', ->
beforeEach ->
Test.LocalStorage.Customer = Mozart.Model.create { modelName: 'Customer' }
Test.LocalStorage.Customer.attributes { 'name': 'string' }
Test.LocalStorage.Customer.localStorage()
Test.LocalStorage.Store = Mozart.Model.create { modelName: 'Store' }
Test.LocalStorage.Store.attributes { 'name': 'string' }
Test.LocalStorage.Store.localStorage()
Test.LocalStorage.Product = Mozart.Model.create { modelName: 'Product' }
Test.LocalStorage.Product.attributes { 'name': 'string' }
Test.LocalStorage.Product.localStorage()
Test.LocalStorage.Order = Mozart.Model.create { modelName: 'Order' }
Test.LocalStorage.Order.localStorage({prefix:"TestLSPrefix"})
Test.LocalStorage.Store.hasMany Test.LocalStorage.Product, 'products'
Test.LocalStorage.Product.belongsTo Test.LocalStorage.Store, 'store'
Test.LocalStorage.Order.belongsToPoly [Test.LocalStorage.Store, Test.LocalStorage.Customer], 'from', 'from_id', 'from_type'
afterEach ->
Test.LocalStorage.Customer.destroyAllLocalStorage()
Test.LocalStorage.Store.destroyAllLocalStorage()
Test.LocalStorage.Product.destroyAllLocalStorage()
Test.LocalStorage.Order.destroyAllLocalStorage()
describe 'core', ->
it 'should provide the localStorage model extension method', ->
expect(Test.LocalStorage.Customer.localStorageOptions).toBeDefined()
expect(Test.LocalStorage.Customer.localStorageOptions.prefix).toEqual('MozartLS')
it 'should allow a different prefix', ->
expect(Test.LocalStorage.Order.localStorageOptions.prefix).toEqual('TestLSPrefix')
it 'shoudl provide the getLocalStoragePrefix method', ->
expect(Test.LocalStorage.Customer.getLocalStoragePrefix()).toEqual("MozartLS-Customer")
expect(Test.LocalStorage.Order.getLocalStoragePrefix()).toEqual("TestLSPrefix-Order")
describe 'localStorage id mapping methods', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: '<NAME>'})
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, '1236')
Test.LocalStorage.bigcom = Test.LocalStorage.Store.createFromValues({name: '<NAME>'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bigcom.id, '2348')
it 'should provide the registerLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should provide the unRegisterLocalStorageId method on model', ->
Test.LocalStorage.Customer.unRegisterLocalStorageId(Test.LocalStorage.tom.id, '1236')
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(undefined)
it 'should provide the getLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual('1236')
it 'should provide the getLocalStorageId method on instance', ->
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual('1236')
it 'should provide the getLocalStorageClientId method', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should not pollute other models when registering localStorage ids', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('2348')).toEqual(undefined)
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.bigcom.id)).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageClientId('1236')).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual(undefined)
describe 'localStorage integration', ->
beforeEach ->
# Setup LocalStorage Records
localStorage['MozartLS-Customer-index'] = "[2346,456345,345346,234235,876976,786788,123884,7732]"
localStorage['MozartLS-Customer-2346'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-456345'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-345346'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-234235'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-876976'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-786788'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-123884'] = '{"name":"<NAME>"}'
localStorage['MozartLS-Customer-7732'] = '{"name":"<NAME>"}'
# Setup JSSide records
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: '<NAME>'})
Test.LocalStorage.jason = Test.LocalStorage.Customer.initInstance({name: '<NAME>'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.getId())
Test.LocalStorage.subcaller =
onLoad: ->
onLoadAll: ->
onCreate: ->
onUpdate: ->
onDestroy: ->
onChange: ->
it 'should load all from localStorage on model loadAllLocalStorage', ->
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadAllLocalStorage()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
jason = Test.LocalStorage.Customer.findByAttribute("name","<NAME>")[0]
expect(jason).toBeDefined()
expect(jason.getLocalStorageId()).toEqual(456345)
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","<NAME>")).toBeDefined()
it 'should load data from localStorage on loadLocalStorageId', ->
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadLocalStorageId(7732)
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
instid = Test.LocalStorage.Customer.getLocalStorageClientId(7732)
expect(instid).not.toBeNull()
instance = Test.LocalStorage.Customer.findById(instid)
expect(instance.name).toEqual('<NAME>')
it 'should load data from localStorage on instance loadLocalStorage', ->
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, 2346)
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.tom.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.tom.loadLocalStorage()
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
expect(Test.LocalStorage.tom.name).toEqual("<NAME>")
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual(2346)
it 'should post data to localStorage on save when instance isn\'t registered', ->
spyOn(Test.LocalStorage.subcaller,'onCreate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('createLocalStorageComplete', Test.LocalStorage.subcaller.onCreate)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.jason.save()
expect(Test.LocalStorage.subcaller.onCreate).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
localStorageId = Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.jason.id)
expect(parseInt(localStorageId)).toBeGreaterThan(0)
it 'should put data to localStorage on save', ->
spyOn(Test.LocalStorage.subcaller,'onUpdate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('updateLocalStorageComplete', Test.LocalStorage.subcaller.onUpdate)
Test.LocalStorage.tom.set('name','<NAME>')
Test.LocalStorage.tom.save()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onUpdate).toHaveBeenCalledWith(Test.LocalStorage.tom, undefined)
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
it 'should destroy on localStorage and unregister on destroy', ->
spyOn(Test.LocalStorage.subcaller,'onDestroy')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('destroyLocalStorageComplete', Test.LocalStorage.subcaller.onDestroy)
Test.LocalStorage.tom.destroy()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onDestroy).toHaveBeenCalledWith(Test.LocalStorage.tomId, undefined)
expect(Test.LocalStorage.Customer.getLocalStorageClientId(Test.LocalStorage.tomId)).not.toBeDefined()
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
describe 'model client -> localStorage object mapping', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: '<NAME>'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id,Test.LocalStorage.getId())
describe 'for simple objects', ->
it 'should provide the toLocalStorageObject method', ->
object = Test.LocalStorage.Customer.toLocalStorageObject(Test.LocalStorage.tom)
expect(object).not.toBe(Test.LocalStorage.tom)
expect(object.name).toEqual(Test.LocalStorage.tom.name)
expect(object.id).not.toEqual(Test.LocalStorage.tom.id)
expect(object.id).toEqual(Test.LocalStorage.tomId)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does not exist', ->
Test.LocalStorage.chrisID = Test.LocalStorage.getId()
object = {
id: Test.LocalStorage.chrisID
name: '<NAME>'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(clientObject.id).toEqual(undefined)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toEqual(undefined)
expect(clientObject.name).toEqual('<NAME>')
expect(clientObject.id).not.toEqual(Test.LocalStorage.chrisID)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does exist', ->
object = {
id: Test.LocalStorage.tomId
name: '<NAME>'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toBe(Test.LocalStorage.tom)
expect(clientObject.name).toEqual('<NAME>')
expect(clientObject.id).not.toEqual(Test.LocalStorage.tomId)
describe 'for objects with foreign keys', ->
beforeEach ->
Test.LocalStorage.bcId = Test.LocalStorage.getId()
Test.LocalStorage.bc = Test.LocalStorage.Store.createFromValues({name: 'BigCom'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bc.id, Test.LocalStorage.bcId)
Test.LocalStorage.shoeId = Test.LocalStorage.getId()
Test.LocalStorage.shoe = Test.LocalStorage.Product.createFromValues { name: 'Red Shoe' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.shoe.id, Test.LocalStorage.shoeId)
Test.LocalStorage.hatId = Test.LocalStorage.getId()
Test.LocalStorage.hat = Test.LocalStorage.Product.createFromValues { name: 'Blue Hat' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.hat.id, Test.LocalStorage.hatId)
Test.LocalStorage.scarf = Test.LocalStorage.Product.createFromValues { name: 'Green Scarf' }
# No Scarf LocalStorageId = unsaved to localStorage.
Test.LocalStorage.tomId = Test.LocalStorage.getId()
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues { name: '<NAME>' }
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.tomId)
Test.LocalStorage.shoeOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeOrder = Test.LocalStorage.Order.createFromValues( { name: 'Customer Shoe Order' })
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeOrder.id, Test.LocalStorage.shoeOrderId)
Test.LocalStorage.shoeSupplyOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeSupplyOrder = Test.LocalStorage.Order.createFromValues( { name: 'Store Shoe Order'})
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeSupplyOrder.id, Test.LocalStorage.shoeSupplyOrderId)
Test.LocalStorage.bc.products().add(Test.LocalStorage.shoe)
Test.LocalStorage.bc.products().add(Test.LocalStorage.hat)
Test.LocalStorage.bc.products().add(Test.LocalStorage.scarf)
Test.LocalStorage.shoeOrder.from(Test.LocalStorage.tom)
#Test.LocalStorage.shoeSupplyOrder.from(Test.LocalStorage.bc)
it 'should translate non-poly fks properly in toLocalStorageObject method', ->
object = {
id: Test.LocalStorage.shoeId
name: '<NAME>'
store_id: Test.LocalStorage.bcId
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(Test.LocalStorage.Store.records[clientObject.store_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
id: Test.LocalStorage.shoeId
name: '<NAME> Shoe'
store_id: null
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(clientObject.store_id).toBeNull()
it 'should translate poly fks properly in toLocalStorageObject method', ->
object = {
name: '<NAME>'
from_id: Test.LocalStorage.tomId
from_type: 'Customer'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.from_id]).toBe(Test.LocalStorage.tom)
object = {
name: '<NAME>'
from_id: Test.LocalStorage.bcId
from_type: 'Store'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Store.records[clientObject.from_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
name: '<NAME>'
from_id: null
from_type: null
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(clientObject.from_id).toBeNull()
| true | Test = {}
Test.LocalStorage = {}
Test.LocalStorage.getId = ->
Math.round(Math.random()*9999999)
localStorage.clear()
describe 'Mozart.LocalStorage', ->
beforeEach ->
Test.LocalStorage.Customer = Mozart.Model.create { modelName: 'Customer' }
Test.LocalStorage.Customer.attributes { 'name': 'string' }
Test.LocalStorage.Customer.localStorage()
Test.LocalStorage.Store = Mozart.Model.create { modelName: 'Store' }
Test.LocalStorage.Store.attributes { 'name': 'string' }
Test.LocalStorage.Store.localStorage()
Test.LocalStorage.Product = Mozart.Model.create { modelName: 'Product' }
Test.LocalStorage.Product.attributes { 'name': 'string' }
Test.LocalStorage.Product.localStorage()
Test.LocalStorage.Order = Mozart.Model.create { modelName: 'Order' }
Test.LocalStorage.Order.localStorage({prefix:"TestLSPrefix"})
Test.LocalStorage.Store.hasMany Test.LocalStorage.Product, 'products'
Test.LocalStorage.Product.belongsTo Test.LocalStorage.Store, 'store'
Test.LocalStorage.Order.belongsToPoly [Test.LocalStorage.Store, Test.LocalStorage.Customer], 'from', 'from_id', 'from_type'
afterEach ->
Test.LocalStorage.Customer.destroyAllLocalStorage()
Test.LocalStorage.Store.destroyAllLocalStorage()
Test.LocalStorage.Product.destroyAllLocalStorage()
Test.LocalStorage.Order.destroyAllLocalStorage()
describe 'core', ->
it 'should provide the localStorage model extension method', ->
expect(Test.LocalStorage.Customer.localStorageOptions).toBeDefined()
expect(Test.LocalStorage.Customer.localStorageOptions.prefix).toEqual('MozartLS')
it 'should allow a different prefix', ->
expect(Test.LocalStorage.Order.localStorageOptions.prefix).toEqual('TestLSPrefix')
it 'shoudl provide the getLocalStoragePrefix method', ->
expect(Test.LocalStorage.Customer.getLocalStoragePrefix()).toEqual("MozartLS-Customer")
expect(Test.LocalStorage.Order.getLocalStoragePrefix()).toEqual("TestLSPrefix-Order")
describe 'localStorage id mapping methods', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'})
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, '1236')
Test.LocalStorage.bigcom = Test.LocalStorage.Store.createFromValues({name: 'PI:NAME:<NAME>END_PI'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bigcom.id, '2348')
it 'should provide the registerLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should provide the unRegisterLocalStorageId method on model', ->
Test.LocalStorage.Customer.unRegisterLocalStorageId(Test.LocalStorage.tom.id, '1236')
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(undefined)
it 'should provide the getLocalStorageId method on model', ->
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual('1236')
it 'should provide the getLocalStorageId method on instance', ->
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual('1236')
it 'should provide the getLocalStorageClientId method', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('1236')).toEqual(Test.LocalStorage.tom.id)
it 'should not pollute other models when registering localStorage ids', ->
expect(Test.LocalStorage.Customer.getLocalStorageClientId('2348')).toEqual(undefined)
expect(Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.bigcom.id)).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageClientId('1236')).toEqual(undefined)
expect(Test.LocalStorage.Store.getLocalStorageId(Test.LocalStorage.tom.id)).toEqual(undefined)
describe 'localStorage integration', ->
beforeEach ->
# Setup LocalStorage Records
localStorage['MozartLS-Customer-index'] = "[2346,456345,345346,234235,876976,786788,123884,7732]"
localStorage['MozartLS-Customer-2346'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-456345'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-345346'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-234235'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-876976'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-786788'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-123884'] = '{"name":"PI:NAME:<NAME>END_PI"}'
localStorage['MozartLS-Customer-7732'] = '{"name":"PI:NAME:<NAME>END_PI"}'
# Setup JSSide records
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'})
Test.LocalStorage.jason = Test.LocalStorage.Customer.initInstance({name: 'PI:NAME:<NAME>END_PI'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.getId())
Test.LocalStorage.subcaller =
onLoad: ->
onLoadAll: ->
onCreate: ->
onUpdate: ->
onDestroy: ->
onChange: ->
it 'should load all from localStorage on model loadAllLocalStorage', ->
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadAllLocalStorage()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
jason = Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")[0]
expect(jason).toBeDefined()
expect(jason.getLocalStorageId()).toEqual(456345)
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
expect(Test.LocalStorage.Customer.findByAttribute("name","PI:NAME:<NAME>END_PI")).toBeDefined()
it 'should load data from localStorage on loadLocalStorageId', ->
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.Customer.loadLocalStorageId(7732)
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
instid = Test.LocalStorage.Customer.getLocalStorageClientId(7732)
expect(instid).not.toBeNull()
instance = Test.LocalStorage.Customer.findById(instid)
expect(instance.name).toEqual('PI:NAME:<NAME>END_PI')
it 'should load data from localStorage on instance loadLocalStorage', ->
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, 2346)
spyOn(Test.LocalStorage.subcaller,'onLoad')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('loadLocalStorageComplete', Test.LocalStorage.subcaller.onLoad)
Test.LocalStorage.tom.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.tom.loadLocalStorage()
expect(Test.LocalStorage.subcaller.onLoad).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
expect(Test.LocalStorage.tom.name).toEqual("PI:NAME:<NAME>END_PI")
expect(Test.LocalStorage.tom.getLocalStorageId()).toEqual(2346)
it 'should post data to localStorage on save when instance isn\'t registered', ->
spyOn(Test.LocalStorage.subcaller,'onCreate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('createLocalStorageComplete', Test.LocalStorage.subcaller.onCreate)
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
Test.LocalStorage.jason.save()
expect(Test.LocalStorage.subcaller.onCreate).toHaveBeenCalled()
expect(Test.LocalStorage.subcaller.onChange).toHaveBeenCalled()
localStorageId = Test.LocalStorage.Customer.getLocalStorageId(Test.LocalStorage.jason.id)
expect(parseInt(localStorageId)).toBeGreaterThan(0)
it 'should put data to localStorage on save', ->
spyOn(Test.LocalStorage.subcaller,'onUpdate')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('updateLocalStorageComplete', Test.LocalStorage.subcaller.onUpdate)
Test.LocalStorage.tom.set('name','PI:NAME:<NAME>END_PI')
Test.LocalStorage.tom.save()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onUpdate).toHaveBeenCalledWith(Test.LocalStorage.tom, undefined)
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
it 'should destroy on localStorage and unregister on destroy', ->
spyOn(Test.LocalStorage.subcaller,'onDestroy')
spyOn(Test.LocalStorage.subcaller,'onChange')
Test.LocalStorage.Customer.subscribeOnce('destroyLocalStorageComplete', Test.LocalStorage.subcaller.onDestroy)
Test.LocalStorage.tom.destroy()
Test.LocalStorage.Customer.subscribeOnce('change', Test.LocalStorage.subcaller.onChange)
expect(Test.LocalStorage.subcaller.onDestroy).toHaveBeenCalledWith(Test.LocalStorage.tomId, undefined)
expect(Test.LocalStorage.Customer.getLocalStorageClientId(Test.LocalStorage.tomId)).not.toBeDefined()
expect(Test.LocalStorage.subcaller.onChange).not.toHaveBeenCalled()
describe 'model client -> localStorage object mapping', ->
beforeEach ->
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues({name: 'PI:NAME:<NAME>END_PI'})
Test.LocalStorage.tomId = Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id,Test.LocalStorage.getId())
describe 'for simple objects', ->
it 'should provide the toLocalStorageObject method', ->
object = Test.LocalStorage.Customer.toLocalStorageObject(Test.LocalStorage.tom)
expect(object).not.toBe(Test.LocalStorage.tom)
expect(object.name).toEqual(Test.LocalStorage.tom.name)
expect(object.id).not.toEqual(Test.LocalStorage.tom.id)
expect(object.id).toEqual(Test.LocalStorage.tomId)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does not exist', ->
Test.LocalStorage.chrisID = Test.LocalStorage.getId()
object = {
id: Test.LocalStorage.chrisID
name: 'PI:NAME:<NAME>END_PI'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(clientObject.id).toEqual(undefined)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toEqual(undefined)
expect(clientObject.name).toEqual('PI:NAME:<NAME>END_PI')
expect(clientObject.id).not.toEqual(Test.LocalStorage.chrisID)
it 'should provide the toLocalStorageClientObject method, when the clientside instance does exist', ->
object = {
id: Test.LocalStorage.tomId
name: 'PI:NAME:<NAME>END_PI'
}
clientObject = Test.LocalStorage.Customer.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.id]).toBe(Test.LocalStorage.tom)
expect(clientObject.name).toEqual('PI:NAME:<NAME>END_PI')
expect(clientObject.id).not.toEqual(Test.LocalStorage.tomId)
describe 'for objects with foreign keys', ->
beforeEach ->
Test.LocalStorage.bcId = Test.LocalStorage.getId()
Test.LocalStorage.bc = Test.LocalStorage.Store.createFromValues({name: 'BigCom'})
Test.LocalStorage.Store.registerLocalStorageId(Test.LocalStorage.bc.id, Test.LocalStorage.bcId)
Test.LocalStorage.shoeId = Test.LocalStorage.getId()
Test.LocalStorage.shoe = Test.LocalStorage.Product.createFromValues { name: 'Red Shoe' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.shoe.id, Test.LocalStorage.shoeId)
Test.LocalStorage.hatId = Test.LocalStorage.getId()
Test.LocalStorage.hat = Test.LocalStorage.Product.createFromValues { name: 'Blue Hat' }
Test.LocalStorage.Product.registerLocalStorageId(Test.LocalStorage.hat.id, Test.LocalStorage.hatId)
Test.LocalStorage.scarf = Test.LocalStorage.Product.createFromValues { name: 'Green Scarf' }
# No Scarf LocalStorageId = unsaved to localStorage.
Test.LocalStorage.tomId = Test.LocalStorage.getId()
Test.LocalStorage.tom = Test.LocalStorage.Customer.createFromValues { name: 'PI:NAME:<NAME>END_PI' }
Test.LocalStorage.Customer.registerLocalStorageId(Test.LocalStorage.tom.id, Test.LocalStorage.tomId)
Test.LocalStorage.shoeOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeOrder = Test.LocalStorage.Order.createFromValues( { name: 'Customer Shoe Order' })
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeOrder.id, Test.LocalStorage.shoeOrderId)
Test.LocalStorage.shoeSupplyOrderId = Test.LocalStorage.getId()
Test.LocalStorage.shoeSupplyOrder = Test.LocalStorage.Order.createFromValues( { name: 'Store Shoe Order'})
Test.LocalStorage.Order.registerLocalStorageId(Test.LocalStorage.shoeSupplyOrder.id, Test.LocalStorage.shoeSupplyOrderId)
Test.LocalStorage.bc.products().add(Test.LocalStorage.shoe)
Test.LocalStorage.bc.products().add(Test.LocalStorage.hat)
Test.LocalStorage.bc.products().add(Test.LocalStorage.scarf)
Test.LocalStorage.shoeOrder.from(Test.LocalStorage.tom)
#Test.LocalStorage.shoeSupplyOrder.from(Test.LocalStorage.bc)
it 'should translate non-poly fks properly in toLocalStorageObject method', ->
object = {
id: Test.LocalStorage.shoeId
name: 'PI:NAME:<NAME>END_PI'
store_id: Test.LocalStorage.bcId
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(Test.LocalStorage.Store.records[clientObject.store_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
id: Test.LocalStorage.shoeId
name: 'PI:NAME:<NAME>END_PI Shoe'
store_id: null
}
clientObject = Test.LocalStorage.Product.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Product.records[clientObject.id]).toBe(Test.LocalStorage.shoe)
expect(clientObject.store_id).toBeNull()
it 'should translate poly fks properly in toLocalStorageObject method', ->
object = {
name: 'PI:NAME:<NAME>END_PI'
from_id: Test.LocalStorage.tomId
from_type: 'Customer'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Customer.records[clientObject.from_id]).toBe(Test.LocalStorage.tom)
object = {
name: 'PI:NAME:<NAME>END_PI'
from_id: Test.LocalStorage.bcId
from_type: 'Store'
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(Test.LocalStorage.Store.records[clientObject.from_id]).toBe(Test.LocalStorage.bc)
it 'should translate non-poly fks in toLocalStorageObject when fk is null', ->
object = {
name: 'PI:NAME:<NAME>END_PI'
from_id: null
from_type: null
}
clientObject = Test.LocalStorage.Order.toLocalStorageClientObject(object)
expect(clientObject.from_id).toBeNull()
|
[
{
"context": "###\r\n\r\ngas-manager\r\nhttps://github.com/soundTricker/gas-manager\r\n\r\nCopyright (c) 2013 Keisuke Oohashi",
"end": 51,
"score": 0.9981634020805359,
"start": 39,
"tag": "USERNAME",
"value": "soundTricker"
},
{
"context": "com/soundTricker/gas-manager\r\n\r\nCopyrig... | src/lib/command.coffee | idobatter/gas-manager | 1 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 Keisuke Oohashi
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('./gas-manager').Manager
program = require 'commander'
util = require './commands/util'
pkg = require "../../package.json"
exports.run = ()->
program
.version(pkg.version)
.option('-f, --fileId <fileId>', "target gas project fileId")
.option('-c, --config <path>', "credential config file path", "#{path.resolve(util.getUserHome() , 'gas-config.json')}")
.option('-s, --setting <path>', "project setting file path", "./gas-project.json")
.option('-e, --env <env>', 'the environment of target sources', "src")
program
.command("download")
.description("download google apps script file")
.option('-p, --path <path>' , "download base path", process.cwd())
.option(
'-F, --force'
,"If a project source does not exist in project setting file, that is not downloaded."
)
.option(
'-S, --src "<from:to...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] = path : m[1]
return map
,{})
)
.action(require('./commands/download-command').download)
program
.command("upload")
.description("upload google apps script file")
.option(
'-e, --encoding <encoding>'
,"The encoding of reading file", "UTF-8"
)
.option(
'-S, --src "<to:from...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] =
path : m[1]
type : if path.extname(m[1]) == ".html" then "html" else "server_js"
return map
,{})
)
.option(
'-F, --force'
,"If does not exist source in config.json but exist on server,
server's file will be deleted"
)
.action(require('./commands/upload-command').upload)
program
.command("init")
.description("generate config file.")
.option(
'-P --only-project'
, "Creating only a project setting file"
)
.action require('./commands/init-command').init
program
.command("logo")
.action require('./commands/logo-command').logo
program.parse(process.argv)
| 156285 | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 <NAME>
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('./gas-manager').Manager
program = require 'commander'
util = require './commands/util'
pkg = require "../../package.json"
exports.run = ()->
program
.version(pkg.version)
.option('-f, --fileId <fileId>', "target gas project fileId")
.option('-c, --config <path>', "credential config file path", "#{path.resolve(util.getUserHome() , 'gas-config.json')}")
.option('-s, --setting <path>', "project setting file path", "./gas-project.json")
.option('-e, --env <env>', 'the environment of target sources', "src")
program
.command("download")
.description("download google apps script file")
.option('-p, --path <path>' , "download base path", process.cwd())
.option(
'-F, --force'
,"If a project source does not exist in project setting file, that is not downloaded."
)
.option(
'-S, --src "<from:to...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] = path : m[1]
return map
,{})
)
.action(require('./commands/download-command').download)
program
.command("upload")
.description("upload google apps script file")
.option(
'-e, --encoding <encoding>'
,"The encoding of reading file", "UTF-8"
)
.option(
'-S, --src "<to:from...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] =
path : m[1]
type : if path.extname(m[1]) == ".html" then "html" else "server_js"
return map
,{})
)
.option(
'-F, --force'
,"If does not exist source in config.json but exist on server,
server's file will be deleted"
)
.action(require('./commands/upload-command').upload)
program
.command("init")
.description("generate config file.")
.option(
'-P --only-project'
, "Creating only a project setting file"
)
.action require('./commands/init-command').init
program
.command("logo")
.action require('./commands/logo-command').logo
program.parse(process.argv)
| true | ###
gas-manager
https://github.com/soundTricker/gas-manager
Copyright (c) 2013 PI:NAME:<NAME>END_PI
Licensed under the MIT license.
###
'use strict'
fs = require 'fs'
path = require 'path'
async = require 'async'
Manager = require('./gas-manager').Manager
program = require 'commander'
util = require './commands/util'
pkg = require "../../package.json"
exports.run = ()->
program
.version(pkg.version)
.option('-f, --fileId <fileId>', "target gas project fileId")
.option('-c, --config <path>', "credential config file path", "#{path.resolve(util.getUserHome() , 'gas-config.json')}")
.option('-s, --setting <path>', "project setting file path", "./gas-project.json")
.option('-e, --env <env>', 'the environment of target sources', "src")
program
.command("download")
.description("download google apps script file")
.option('-p, --path <path>' , "download base path", process.cwd())
.option(
'-F, --force'
,"If a project source does not exist in project setting file, that is not downloaded."
)
.option(
'-S, --src "<from:to...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] = path : m[1]
return map
,{})
)
.action(require('./commands/download-command').download)
program
.command("upload")
.description("upload google apps script file")
.option(
'-e, --encoding <encoding>'
,"The encoding of reading file", "UTF-8"
)
.option(
'-S, --src "<to:from...>"'
,"""\n\tThe source mapping between project file and local file.
\tPlease set like below.
\t --src "code:./src/code.js index:./src/index.html"
\tThis option is preferred all other options and setting file.
"""
,(value)->
return value.split(" ").reduce((map, source)->
m = source.split(":")
map[m[0]] =
path : m[1]
type : if path.extname(m[1]) == ".html" then "html" else "server_js"
return map
,{})
)
.option(
'-F, --force'
,"If does not exist source in config.json but exist on server,
server's file will be deleted"
)
.action(require('./commands/upload-command').upload)
program
.command("init")
.description("generate config file.")
.option(
'-P --only-project'
, "Creating only a project setting file"
)
.action require('./commands/init-command').init
program
.command("logo")
.action require('./commands/logo-command').logo
program.parse(process.argv)
|
[
{
"context": " js function\n* @date 2015-12-01 22:01:25\n* @author pjg <iampjg@gmail.com>\n* @link http://pjg.pw\n* @versi",
"end": 79,
"score": 0.9996097087860107,
"start": 76,
"tag": "USERNAME",
"value": "pjg"
},
{
"context": "nction\n* @date 2015-12-01 22:01:25\n* @author pjg <iam... | node_modules/vbuilder/lib/tplCtl/index.coffee | duolaimi/v.builder.site | 0 | ###*
* html to AMD module js function
* @date 2015-12-01 22:01:25
* @author pjg <iampjg@gmail.com>
* @link http://pjg.pw
* @version $Id$
###
fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
class TplCtl
constructor:(@opts)->
@tplSrcPath = path.join @opts.srcPath , 'tpl/'
@tplOutPath = path.join @opts.srcPath , 'js/_tpl/'
convertHtmlToJs: (folder,cb)->
_this = @
_cb = cb or ->
return false if folder.indexOf('.') is 0 or folder is ""
tplPath = _this.tplSrcPath + folder
# console.log tplPath
tplData = {}
fs.readdirSync(tplPath).forEach (file)->
_filePath = path.join(tplPath, file)
if file.indexOf('.html') != -1 and file.indexOf('.') != 0
file_name = file.replace('.html', '')
_source = fs.readFileSync(_filePath, 'utf8')
# 给html中的图片链接加上Hash
_source = Utils.replaceImg(_source,'tpl')
# 压缩html
_source = Utils.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[file_name] = "<script id=\"tpl_#{folder}#{file_name}\" type=\"text/html\">#{_source}</script>"
else
tplData[file_name] = _source
tpl_soure = "define(function(){return #{JSON.stringify(tplData)};});"
_file = path.join(_this.tplOutPath, folder + '.js')
Utils.writeFile(_file, tpl_soure, !0)
gutil.log( "Convert",color.cyan("tpl/#{folder}/*.html"),"-->" + color.cyan("js/_tpl/#{folder}.js"), "success.")
_cb()
init: (cb)->
_cb = cb or ->
_this = @
_tplSrcPath = _this.tplSrcPath
gutil.log color.yellow "Convert html to js..."
fs.readdirSync(_tplSrcPath).forEach (v)->
_tplPath = path.join(_tplSrcPath, v)
if fs.statSync(_tplPath).isDirectory() and v.indexOf('.') != 0
_this.convertHtmlToJs(v)
gutil.log color.green "Convert html to js success!"
_cb()
module.exports = TplCtl | 64185 | ###*
* html to AMD module js function
* @date 2015-12-01 22:01:25
* @author pjg <<EMAIL>>
* @link http://pjg.pw
* @version $Id$
###
fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
class TplCtl
constructor:(@opts)->
@tplSrcPath = path.join @opts.srcPath , 'tpl/'
@tplOutPath = path.join @opts.srcPath , 'js/_tpl/'
convertHtmlToJs: (folder,cb)->
_this = @
_cb = cb or ->
return false if folder.indexOf('.') is 0 or folder is ""
tplPath = _this.tplSrcPath + folder
# console.log tplPath
tplData = {}
fs.readdirSync(tplPath).forEach (file)->
_filePath = path.join(tplPath, file)
if file.indexOf('.html') != -1 and file.indexOf('.') != 0
file_name = file.replace('.html', '')
_source = fs.readFileSync(_filePath, 'utf8')
# 给html中的图片链接加上Hash
_source = Utils.replaceImg(_source,'tpl')
# 压缩html
_source = Utils.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[file_name] = "<script id=\"tpl_#{folder}#{file_name}\" type=\"text/html\">#{_source}</script>"
else
tplData[file_name] = _source
tpl_soure = "define(function(){return #{JSON.stringify(tplData)};});"
_file = path.join(_this.tplOutPath, folder + '.js')
Utils.writeFile(_file, tpl_soure, !0)
gutil.log( "Convert",color.cyan("tpl/#{folder}/*.html"),"-->" + color.cyan("js/_tpl/#{folder}.js"), "success.")
_cb()
init: (cb)->
_cb = cb or ->
_this = @
_tplSrcPath = _this.tplSrcPath
gutil.log color.yellow "Convert html to js..."
fs.readdirSync(_tplSrcPath).forEach (v)->
_tplPath = path.join(_tplSrcPath, v)
if fs.statSync(_tplPath).isDirectory() and v.indexOf('.') != 0
_this.convertHtmlToJs(v)
gutil.log color.green "Convert html to js success!"
_cb()
module.exports = TplCtl | true | ###*
* html to AMD module js function
* @date 2015-12-01 22:01:25
* @author pjg <PI:EMAIL:<EMAIL>END_PI>
* @link http://pjg.pw
* @version $Id$
###
fs = require 'fs'
path = require 'path'
_ = require 'lodash'
gutil = require 'gulp-util'
color = gutil.colors
Utils = require '../utils'
class TplCtl
constructor:(@opts)->
@tplSrcPath = path.join @opts.srcPath , 'tpl/'
@tplOutPath = path.join @opts.srcPath , 'js/_tpl/'
convertHtmlToJs: (folder,cb)->
_this = @
_cb = cb or ->
return false if folder.indexOf('.') is 0 or folder is ""
tplPath = _this.tplSrcPath + folder
# console.log tplPath
tplData = {}
fs.readdirSync(tplPath).forEach (file)->
_filePath = path.join(tplPath, file)
if file.indexOf('.html') != -1 and file.indexOf('.') != 0
file_name = file.replace('.html', '')
_source = fs.readFileSync(_filePath, 'utf8')
# 给html中的图片链接加上Hash
_source = Utils.replaceImg(_source,'tpl')
# 压缩html
_source = Utils.htmlMinify(_source)
if file.indexOf('_') == 0
tplData[file_name] = "<script id=\"tpl_#{folder}#{file_name}\" type=\"text/html\">#{_source}</script>"
else
tplData[file_name] = _source
tpl_soure = "define(function(){return #{JSON.stringify(tplData)};});"
_file = path.join(_this.tplOutPath, folder + '.js')
Utils.writeFile(_file, tpl_soure, !0)
gutil.log( "Convert",color.cyan("tpl/#{folder}/*.html"),"-->" + color.cyan("js/_tpl/#{folder}.js"), "success.")
_cb()
init: (cb)->
_cb = cb or ->
_this = @
_tplSrcPath = _this.tplSrcPath
gutil.log color.yellow "Convert html to js..."
fs.readdirSync(_tplSrcPath).forEach (v)->
_tplPath = path.join(_tplSrcPath, v)
if fs.statSync(_tplPath).isDirectory() and v.indexOf('.') != 0
_this.convertHtmlToJs(v)
gutil.log color.green "Convert html to js success!"
_cb()
module.exports = TplCtl |
[
{
"context": "S_CHECK = uuid()\n\n# taken from https://github.com/manishsaraan/email-validator/blob/master/index.js\nEMAIL_RE = /",
"end": 263,
"score": 0.9996630549430847,
"start": 251,
"tag": "USERNAME",
"value": "manishsaraan"
},
{
"context": "0-9])+$/;\n\n# taken from - https://g... | lib/index.coffee | jhiver/validate-nosuck | 0 | _ = require 'lodash'
uuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random() * 16 | 0
v = if c == 'x' then r else r & 0x3 | 0x8
v.toString 16
IS_CHECK = uuid()
# taken from https://github.com/manishsaraan/email-validator/blob/master/index.js
EMAIL_RE = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
# taken from - https://gist.github.com/dperini/729294
RE_URL = new RegExp(
"^" +
# protocol identifier (optional)
# short syntax # still required
"(?:(?:(?:https?|ftp):)?\\/\\/)" +
# user:pass BasicAuth (optional)
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 224.0.0.0
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain names, may end with dot
# can be replaced by a shortest alternative
# (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
"(?:" +
"(?:" +
"[a-z0-9\\u00a1-\\uffff]" +
"[a-z0-9\\u00a1-\\uffff_-]{0,62}" +
")?" +
"[a-z0-9\\u00a1-\\uffff]\\." +
")+" +
# TLD identifier name, may end with dot
"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)" +
")" +
# port number (optional)
"(?::\\d{2,5})?" +
# resource path (optional)
"(?:[/?#]\\S*)?" +
"$", "i"
);
CHECKS =
sip: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(/^\+?(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))(:\d+)?$/)
return Promise.resolve()
else
return Promise.resolve('sip')
url: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(RE_URL)
return Promise.resolve()
else
return Promise.resolve('url')
phone: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /^\+?\d{4,15}$/ then return Promise.resolve()
return Promise.resolve('phone')
enum: (values...) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
for allowed in values
if obj[att] is allowed then return Promise.resolve()
return Promise.resolve('enum')
filter: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (k) -> allowed[k] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
boolean: ->
(att, obj, args...) ->
obj[att] = Boolean obj[att]
return Promise.resolve()
default: (val) ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = val
return Promise.resolve()
email: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
email = String obj[att]
if email.length > 254 then return Promise.resolve('email')
unless EMAIL_RE.test(email) then return Promise.resolve('email')
parts = email.split("@")
if(parts[0].length>64) then return Promise.resolve('email')
domainParts = parts[1].split(".");
if domainParts.some (part) -> part.length>63
return Promise.resolve('email')
return Promise.resolve()
equals: (val) ->
(att, obj, args...) ->
if obj[att] is val
return Promise.resolve()
else
return Promise.resolve 'equals'
notEquals: (val) ->
(att, obj, args...) ->
if obj[att] isnt val
return Promise.resolve()
else
return Promise.resolve 'notEquals'
hasDigit: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasDigit'
hasLowerCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[a-z]/
return Promise.resolve()
else
return Promise.resolve 'hasLowerCase'
hasSpecial: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[^A-Za-z0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasSpecial'
hasUpperCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[A-Z]/
return Promise.resolve()
else
return Promise.resolve 'hasUpperCase'
integer: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
if Math.floor(Number(obj[att])) is Number(obj[att])
return Promise.resolve()
else
return Promise.resolve 'integer'
like: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve()
else
return Promise.resolve 'like'
notLike: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve 'notLike'
else
return Promise.resolve()
maxLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length <= Number(len) then return Promise.resolve()
return Promise.resolve 'maxLen'
maxVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'maxVal'
if Number(obj[att]) <= Number(val) then return Promise.resolve()
return Promise.resolve 'maxVal'
minLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length >= Number(len) then return Promise.resolve()
return Promise.resolve 'minLen'
minVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'minVal'
if Number(obj[att]) >= Number(val) then return Promise.resolve()
return Promise.resolve 'minVal'
number: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('number')
obj[att] = Number obj[att]
return Promise.resolve()
required: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
return Promise.resolve()
optional: ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = null
return Promise.resolve null
else
return Promise.resolve()
overwrite: (val) ->
(att, obj, args...) ->
obj[att] = val
return Promise.resolve()
pick: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (att) -> allowed[att] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
round: (decimals) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
decimals or= 0
obj[att] = Number(Math.round(obj[att]+'e'+decimals)+'e-'+decimals);
return Promise.resolve()
string: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String obj[att]
return Promise.resolve()
trim: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String(obj[att]).replace(/^\s+/, '').replace(/\s+$/, '')
return Promise.resolve()
uuid: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /........-....-....-....-............/ then return Promise.resolve()
return Promise.resolve 'uuid'
array: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if _.isArray(obj[att]) then return Promise.resolve(undefined)
return Promise.resolve('array')
schema: (schema) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('schema')
model = obj[att]
return new Promise (resolve) ->
validate model, schema, {}
.then (err) ->
unless err then return resolve undefined
return resolve err
each: (check) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('each')
if _.size(obj[att]) is 0 then return Promise.resolve(undefined)
unless check[IS_CHECK] then check = CreateCheck().schema(check)
return new Promise (resolve) ->
if _.isArray(obj[att])
errors = []
else
errors = {}
todo = _.size(obj[att])
_.each obj[att], (item, item_name) ->
model = _: item
schema = _: check
validate model, schema, {}
.then (err) ->
if err then errors[item_name] = err._
todo--
if todo is 0
if _.size(errors) then return resolve(errors)
resolve(undefined)
CreateCheck = (args...) ->
self = todo: []
self[IS_CHECK] = true
self.add = (args...) -> self.todo.push args
_.each CHECKS, (check_generator, check_name) ->
self[check_name] = (args...) ->
self.add check_name, check_generator args...
return self
self._run = (index, att, model) ->
index or= 0
if self.todo.length is index then return Promise.resolve null
return new Promise (resolve, reject) ->
self.todo[index][1] att, model, args...
.then (status) ->
if status isnt undefined then return resolve status
self._run(index + 1, att, model).then(resolve)
self.run = (att, model) ->
return self._run 0, att, model
return self
validate = (model, constraints, errors) ->
constraints = _.clone constraints
constraint_names = _.keys constraints
if constraint_names.length is 0
if _.isEmpty(errors) then return Promise.resolve null
return Promise.resolve errors
constraint_name = constraint_names.shift()
constraint = constraints[constraint_name]
delete constraints[constraint_name]
return new Promise (resolve) ->
constraint.run constraint_name, model
.then (error) ->
if error isnt null then errors[constraint_name] = error
return validate(model, constraints, errors).then(resolve)
module.exports = CreateCheck
module.exports.check = CreateCheck
module.exports.register = (checkname, check) -> CHECKS[checkname] = check
module.exports.validate = (model) ->
with: (schema) ->
unless schema[IS_CHECK] then schema = CreateCheck().schema(schema)
schema.run '_', '_': model | 112084 | _ = require 'lodash'
uuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random() * 16 | 0
v = if c == 'x' then r else r & 0x3 | 0x8
v.toString 16
IS_CHECK = uuid()
# taken from https://github.com/manishsaraan/email-validator/blob/master/index.js
EMAIL_RE = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
# taken from - https://gist.github.com/dperini/729294
RE_URL = new RegExp(
"^" +
# protocol identifier (optional)
# short syntax # still required
"(?:(?:(?:https?|ftp):)?\\/\\/)" +
# user:pass BasicAuth (optional)
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= 192.168.3.11
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain names, may end with dot
# can be replaced by a shortest alternative
# (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
"(?:" +
"(?:" +
"[a-z0-9\\u00a1-\\uffff]" +
"[a-z0-9\\u00a1-\\uffff_-]{0,62}" +
")?" +
"[a-z0-9\\u00a1-\\uffff]\\." +
")+" +
# TLD identifier name, may end with dot
"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)" +
")" +
# port number (optional)
"(?::\\d{2,5})?" +
# resource path (optional)
"(?:[/?#]\\S*)?" +
"$", "i"
);
CHECKS =
sip: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(/^\+?(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))(:\d+)?$/)
return Promise.resolve()
else
return Promise.resolve('sip')
url: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(RE_URL)
return Promise.resolve()
else
return Promise.resolve('url')
phone: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /^\+?\d{4,15}$/ then return Promise.resolve()
return Promise.resolve('phone')
enum: (values...) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
for allowed in values
if obj[att] is allowed then return Promise.resolve()
return Promise.resolve('enum')
filter: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (k) -> allowed[k] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
boolean: ->
(att, obj, args...) ->
obj[att] = Boolean obj[att]
return Promise.resolve()
default: (val) ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = val
return Promise.resolve()
email: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
email = String obj[att]
if email.length > 254 then return Promise.resolve('email')
unless EMAIL_RE.test(email) then return Promise.resolve('email')
parts = email.split("@")
if(parts[0].length>64) then return Promise.resolve('email')
domainParts = parts[1].split(".");
if domainParts.some (part) -> part.length>63
return Promise.resolve('email')
return Promise.resolve()
equals: (val) ->
(att, obj, args...) ->
if obj[att] is val
return Promise.resolve()
else
return Promise.resolve 'equals'
notEquals: (val) ->
(att, obj, args...) ->
if obj[att] isnt val
return Promise.resolve()
else
return Promise.resolve 'notEquals'
hasDigit: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasDigit'
hasLowerCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[a-z]/
return Promise.resolve()
else
return Promise.resolve 'hasLowerCase'
hasSpecial: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[^A-Za-z0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasSpecial'
hasUpperCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[A-Z]/
return Promise.resolve()
else
return Promise.resolve 'hasUpperCase'
integer: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
if Math.floor(Number(obj[att])) is Number(obj[att])
return Promise.resolve()
else
return Promise.resolve 'integer'
like: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve()
else
return Promise.resolve 'like'
notLike: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve 'notLike'
else
return Promise.resolve()
maxLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length <= Number(len) then return Promise.resolve()
return Promise.resolve 'maxLen'
maxVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'maxVal'
if Number(obj[att]) <= Number(val) then return Promise.resolve()
return Promise.resolve 'maxVal'
minLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length >= Number(len) then return Promise.resolve()
return Promise.resolve 'minLen'
minVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'minVal'
if Number(obj[att]) >= Number(val) then return Promise.resolve()
return Promise.resolve 'minVal'
number: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('number')
obj[att] = Number obj[att]
return Promise.resolve()
required: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
return Promise.resolve()
optional: ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = null
return Promise.resolve null
else
return Promise.resolve()
overwrite: (val) ->
(att, obj, args...) ->
obj[att] = val
return Promise.resolve()
pick: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (att) -> allowed[att] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
round: (decimals) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
decimals or= 0
obj[att] = Number(Math.round(obj[att]+'e'+decimals)+'e-'+decimals);
return Promise.resolve()
string: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String obj[att]
return Promise.resolve()
trim: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String(obj[att]).replace(/^\s+/, '').replace(/\s+$/, '')
return Promise.resolve()
uuid: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /........-....-....-....-............/ then return Promise.resolve()
return Promise.resolve 'uuid'
array: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if _.isArray(obj[att]) then return Promise.resolve(undefined)
return Promise.resolve('array')
schema: (schema) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('schema')
model = obj[att]
return new Promise (resolve) ->
validate model, schema, {}
.then (err) ->
unless err then return resolve undefined
return resolve err
each: (check) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('each')
if _.size(obj[att]) is 0 then return Promise.resolve(undefined)
unless check[IS_CHECK] then check = CreateCheck().schema(check)
return new Promise (resolve) ->
if _.isArray(obj[att])
errors = []
else
errors = {}
todo = _.size(obj[att])
_.each obj[att], (item, item_name) ->
model = _: item
schema = _: check
validate model, schema, {}
.then (err) ->
if err then errors[item_name] = err._
todo--
if todo is 0
if _.size(errors) then return resolve(errors)
resolve(undefined)
CreateCheck = (args...) ->
self = todo: []
self[IS_CHECK] = true
self.add = (args...) -> self.todo.push args
_.each CHECKS, (check_generator, check_name) ->
self[check_name] = (args...) ->
self.add check_name, check_generator args...
return self
self._run = (index, att, model) ->
index or= 0
if self.todo.length is index then return Promise.resolve null
return new Promise (resolve, reject) ->
self.todo[index][1] att, model, args...
.then (status) ->
if status isnt undefined then return resolve status
self._run(index + 1, att, model).then(resolve)
self.run = (att, model) ->
return self._run 0, att, model
return self
validate = (model, constraints, errors) ->
constraints = _.clone constraints
constraint_names = _.keys constraints
if constraint_names.length is 0
if _.isEmpty(errors) then return Promise.resolve null
return Promise.resolve errors
constraint_name = constraint_names.shift()
constraint = constraints[constraint_name]
delete constraints[constraint_name]
return new Promise (resolve) ->
constraint.run constraint_name, model
.then (error) ->
if error isnt null then errors[constraint_name] = error
return validate(model, constraints, errors).then(resolve)
module.exports = CreateCheck
module.exports.check = CreateCheck
module.exports.register = (checkname, check) -> CHECKS[checkname] = check
module.exports.validate = (model) ->
with: (schema) ->
unless schema[IS_CHECK] then schema = CreateCheck().schema(schema)
schema.run '_', '_': model | true | _ = require 'lodash'
uuid = ->
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace /[xy]/g, (c) ->
r = Math.random() * 16 | 0
v = if c == 'x' then r else r & 0x3 | 0x8
v.toString 16
IS_CHECK = uuid()
# taken from https://github.com/manishsaraan/email-validator/blob/master/index.js
EMAIL_RE = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;
# taken from - https://gist.github.com/dperini/729294
RE_URL = new RegExp(
"^" +
# protocol identifier (optional)
# short syntax # still required
"(?:(?:(?:https?|ftp):)?\\/\\/)" +
# user:pass BasicAuth (optional)
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
# IP address dotted notation octets
# excludes loopback network 0.0.0.0
# excludes reserved space >= PI:IP_ADDRESS:192.168.3.11END_PI
# excludes network & broacast addresses
# (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
# host & domain names, may end with dot
# can be replaced by a shortest alternative
# (?![-_])(?:[-\\w\\u00a1-\\uffff]{0,63}[^-_]\\.)+
"(?:" +
"(?:" +
"[a-z0-9\\u00a1-\\uffff]" +
"[a-z0-9\\u00a1-\\uffff_-]{0,62}" +
")?" +
"[a-z0-9\\u00a1-\\uffff]\\." +
")+" +
# TLD identifier name, may end with dot
"(?:[a-z\\u00a1-\\uffff]{2,}\\.?)" +
")" +
# port number (optional)
"(?::\\d{2,5})?" +
# resource path (optional)
"(?:[/?#]\\S*)?" +
"$", "i"
);
CHECKS =
sip: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(/^\+?(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))(:\d+)?$/)
return Promise.resolve()
else
return Promise.resolve('sip')
url: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(RE_URL)
return Promise.resolve()
else
return Promise.resolve('url')
phone: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /^\+?\d{4,15}$/ then return Promise.resolve()
return Promise.resolve('phone')
enum: (values...) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
for allowed in values
if obj[att] is allowed then return Promise.resolve()
return Promise.resolve('enum')
filter: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (k) -> allowed[k] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
boolean: ->
(att, obj, args...) ->
obj[att] = Boolean obj[att]
return Promise.resolve()
default: (val) ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = val
return Promise.resolve()
email: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
email = String obj[att]
if email.length > 254 then return Promise.resolve('email')
unless EMAIL_RE.test(email) then return Promise.resolve('email')
parts = email.split("@")
if(parts[0].length>64) then return Promise.resolve('email')
domainParts = parts[1].split(".");
if domainParts.some (part) -> part.length>63
return Promise.resolve('email')
return Promise.resolve()
equals: (val) ->
(att, obj, args...) ->
if obj[att] is val
return Promise.resolve()
else
return Promise.resolve 'equals'
notEquals: (val) ->
(att, obj, args...) ->
if obj[att] isnt val
return Promise.resolve()
else
return Promise.resolve 'notEquals'
hasDigit: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasDigit'
hasLowerCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[a-z]/
return Promise.resolve()
else
return Promise.resolve 'hasLowerCase'
hasSpecial: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[^A-Za-z0-9]/
return Promise.resolve()
else
return Promise.resolve 'hasSpecial'
hasUpperCase: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].match /[A-Z]/
return Promise.resolve()
else
return Promise.resolve 'hasUpperCase'
integer: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
if Math.floor(Number(obj[att])) is Number(obj[att])
return Promise.resolve()
else
return Promise.resolve 'integer'
like: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve()
else
return Promise.resolve 'like'
notLike: (re) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match(re)
return Promise.resolve 'notLike'
else
return Promise.resolve()
maxLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length <= Number(len) then return Promise.resolve()
return Promise.resolve 'maxLen'
maxVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'maxVal'
if Number(obj[att]) <= Number(val) then return Promise.resolve()
return Promise.resolve 'maxVal'
minLen: (len) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if obj[att].length >= Number(len) then return Promise.resolve()
return Promise.resolve 'minLen'
minVal: (val) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(obj[att])) is 'NaN' then return Promise.resolve 'minVal'
if Number(obj[att]) >= Number(val) then return Promise.resolve()
return Promise.resolve 'minVal'
number: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('number')
obj[att] = Number obj[att]
return Promise.resolve()
required: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
return Promise.resolve()
optional: ->
(att, obj, args...) ->
if obj[att] is null or obj[att] is undefined
obj[att] = null
return Promise.resolve null
else
return Promise.resolve()
overwrite: (val) ->
(att, obj, args...) ->
obj[att] = val
return Promise.resolve()
pick: (attributes...) ->
(att, obj, args...) ->
allowed = {}
_.each attributes, (att) -> allowed[att] = true
_.each obj, (v, k) -> delete obj[k] unless allowed[k]
return Promise.resolve()
round: (decimals) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(Number(String(obj[att]))) is 'NaN' then return Promise.resolve('integer')
decimals or= 0
obj[att] = Number(Math.round(obj[att]+'e'+decimals)+'e-'+decimals);
return Promise.resolve()
string: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String obj[att]
return Promise.resolve()
trim: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
obj[att] = String(obj[att]).replace(/^\s+/, '').replace(/\s+$/, '')
return Promise.resolve()
uuid: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if String(obj[att]).match /........-....-....-....-............/ then return Promise.resolve()
return Promise.resolve 'uuid'
array: ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
if _.isArray(obj[att]) then return Promise.resolve(undefined)
return Promise.resolve('array')
schema: (schema) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('schema')
model = obj[att]
return new Promise (resolve) ->
validate model, schema, {}
.then (err) ->
unless err then return resolve undefined
return resolve err
each: (check) ->
(att, obj, args...) ->
if obj[att] is null then return Promise.resolve 'required'
if obj[att] is undefined then return Promise.resolve 'required'
unless _.isObject obj[att] then return Promise.resolve('each')
if _.size(obj[att]) is 0 then return Promise.resolve(undefined)
unless check[IS_CHECK] then check = CreateCheck().schema(check)
return new Promise (resolve) ->
if _.isArray(obj[att])
errors = []
else
errors = {}
todo = _.size(obj[att])
_.each obj[att], (item, item_name) ->
model = _: item
schema = _: check
validate model, schema, {}
.then (err) ->
if err then errors[item_name] = err._
todo--
if todo is 0
if _.size(errors) then return resolve(errors)
resolve(undefined)
CreateCheck = (args...) ->
self = todo: []
self[IS_CHECK] = true
self.add = (args...) -> self.todo.push args
_.each CHECKS, (check_generator, check_name) ->
self[check_name] = (args...) ->
self.add check_name, check_generator args...
return self
self._run = (index, att, model) ->
index or= 0
if self.todo.length is index then return Promise.resolve null
return new Promise (resolve, reject) ->
self.todo[index][1] att, model, args...
.then (status) ->
if status isnt undefined then return resolve status
self._run(index + 1, att, model).then(resolve)
self.run = (att, model) ->
return self._run 0, att, model
return self
validate = (model, constraints, errors) ->
constraints = _.clone constraints
constraint_names = _.keys constraints
if constraint_names.length is 0
if _.isEmpty(errors) then return Promise.resolve null
return Promise.resolve errors
constraint_name = constraint_names.shift()
constraint = constraints[constraint_name]
delete constraints[constraint_name]
return new Promise (resolve) ->
constraint.run constraint_name, model
.then (error) ->
if error isnt null then errors[constraint_name] = error
return validate(model, constraints, errors).then(resolve)
module.exports = CreateCheck
module.exports.check = CreateCheck
module.exports.register = (checkname, check) -> CHECKS[checkname] = check
module.exports.validate = (model) ->
with: (schema) ->
unless schema[IS_CHECK] then schema = CreateCheck().schema(schema)
schema.run '_', '_': model |
[
{
"context": "= null\n if users = ssh.users\n auth = 'multiUser'\n authTuples = (_.pairs(users).map ([k",
"end": 930,
"score": 0.4443959891796112,
"start": 925,
"tag": "USERNAME",
"value": "multi"
},
{
"context": "l\n if users = ssh.users\n auth = 'mult... | imports/server/ssh-container.coffee | ICTU/docker-dashboard | 33 | _ = require 'underscore'
module.exports =
buildComposeConfig: (project, instance, serviceName, serviceBigboatCompose) ->
config = (authMechanism, containerShell, authTuples) ->
image: 'ictu/docker-ssh'
container_name: "#{project}-#{instance}-#{serviceName}-ssh"
environment:
CONTAINER: "#{project}-#{instance}-#{serviceName}"
AUTH_MECHANISM: authMechanism
HTTP_ENABLED: 'false'
CONTAINER_SHELL: containerShell
AUTH_TUPLES: authTuples if authTuples
labels:
'bigboat.instance.name': instance
'bigboat.service.name': serviceName
'bigboat.service.type': 'ssh'
'bigboat.container.map_docker': 'true'
restart: 'unless-stopped'
if (ssh = serviceBigboatCompose?.ssh) and (typeof ssh is 'object')
shell = ssh.shell or 'bash'
auth = 'noAuth'
authTuples = null
if users = ssh.users
auth = 'multiUser'
authTuples = (_.pairs(users).map ([key, val]) -> "#{key}:#{val}").join ';'
config auth, shell, authTuples
else if serviceBigboatCompose?.enable_ssh or serviceBigboatCompose?.ssh is true
config 'noAuth', 'bash'
| 193129 | _ = require 'underscore'
module.exports =
buildComposeConfig: (project, instance, serviceName, serviceBigboatCompose) ->
config = (authMechanism, containerShell, authTuples) ->
image: 'ictu/docker-ssh'
container_name: "#{project}-#{instance}-#{serviceName}-ssh"
environment:
CONTAINER: "#{project}-#{instance}-#{serviceName}"
AUTH_MECHANISM: authMechanism
HTTP_ENABLED: 'false'
CONTAINER_SHELL: containerShell
AUTH_TUPLES: authTuples if authTuples
labels:
'bigboat.instance.name': instance
'bigboat.service.name': serviceName
'bigboat.service.type': 'ssh'
'bigboat.container.map_docker': 'true'
restart: 'unless-stopped'
if (ssh = serviceBigboatCompose?.ssh) and (typeof ssh is 'object')
shell = ssh.shell or 'bash'
auth = 'noAuth'
authTuples = null
if users = ssh.users
auth = 'multi<PASSWORD>'
authTuples = (_.pairs(users).map ([key, val]) -> "#{key}:#{val}").join ';'
config auth, shell, authTuples
else if serviceBigboatCompose?.enable_ssh or serviceBigboatCompose?.ssh is true
config 'noAuth', 'bash'
| true | _ = require 'underscore'
module.exports =
buildComposeConfig: (project, instance, serviceName, serviceBigboatCompose) ->
config = (authMechanism, containerShell, authTuples) ->
image: 'ictu/docker-ssh'
container_name: "#{project}-#{instance}-#{serviceName}-ssh"
environment:
CONTAINER: "#{project}-#{instance}-#{serviceName}"
AUTH_MECHANISM: authMechanism
HTTP_ENABLED: 'false'
CONTAINER_SHELL: containerShell
AUTH_TUPLES: authTuples if authTuples
labels:
'bigboat.instance.name': instance
'bigboat.service.name': serviceName
'bigboat.service.type': 'ssh'
'bigboat.container.map_docker': 'true'
restart: 'unless-stopped'
if (ssh = serviceBigboatCompose?.ssh) and (typeof ssh is 'object')
shell = ssh.shell or 'bash'
auth = 'noAuth'
authTuples = null
if users = ssh.users
auth = 'multiPI:PASSWORD:<PASSWORD>END_PI'
authTuples = (_.pairs(users).map ([key, val]) -> "#{key}:#{val}").join ';'
config auth, shell, authTuples
else if serviceBigboatCompose?.enable_ssh or serviceBigboatCompose?.ssh is true
config 'noAuth', 'bash'
|
[
{
"context": " (Darwin)\nComment: GPGTools - http://gpgtools.org\n\nhQEMA+bZw3a+syp5AQgAqqimwGjRe/m9d74f2Itu4rAs/BJUjgPprCSn1JTOBurK\nnneix4XLQM9slGNJANiOhjEmGR011+Dhk4PV2SNaJrgXI0RS43O3UAjI4gHUHpKF\nlHit1/UBwK24dTzl8G8LSBoI9g1p3QZTZqszsrsYOZfzpoObE1If0IlYvP6VTURC\nQUsHoOKaWXbVQFaUqW8tYqpCgiBZ3BLQbzdO8Wy20R3qRr... | dev/decrypt.iced | samkenxstream/kbpgp | 464 |
{parse} = require '../src/openpgp/parser'
armor = require '../src/openpgp/armor'
fs = require 'fs'
C = require '../src/const'
{KeyBlock} = require '../src/openpgp/processor'
util = require 'util'
{ASP} = require '../src/util'
{KeyManager} = require '../src/keymanager'
{import_key_pgp} = require '../src/symmetric'
{decrypt} = require '../src/openpgp/ocfb'
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
hQEMA+bZw3a+syp5AQgAqqimwGjRe/m9d74f2Itu4rAs/BJUjgPprCSn1JTOBurK
nneix4XLQM9slGNJANiOhjEmGR011+Dhk4PV2SNaJrgXI0RS43O3UAjI4gHUHpKF
lHit1/UBwK24dTzl8G8LSBoI9g1p3QZTZqszsrsYOZfzpoObE1If0IlYvP6VTURC
QUsHoOKaWXbVQFaUqW8tYqpCgiBZ3BLQbzdO8Wy20R3qRr/zEltvK62o4fitW1j/
t8vjzKXHxKCcE+Rqwdn+qb1/KLf+AOrqGJL8gDXytVeQlxMmiV3J/GDgaq/Ikjzk
whot7+b4kLwypxB8/fqNO2alFICwnXtlUMeqwtJFT9LqATfV9f85EEfr3Q4ejsB9
1eMHkubjSbj/SMIw+HlA/dYo4SFVxbej1ur3eY+VQFNA43IqSSsTKp2o9ZEvyXOt
zOHZSscVSPg1h7huqi9LWgAYUzPTqQHYkzRs7ckJ/jb+LBKesX4n6yUhuO0XZzNi
EC1qNueJjkNOy0T+NCSuTdMYq3P8De0hBu/5HnrUwgsujgWrrUMmSaTmCezyUkSo
4tBaPu8PtWaC97TPYefTCu5eI5L28NAAlrGVxtxkdWJs2IJZqGDR0O6X+xzxkFsH
jc1chiypfpEa4XsuvqfAkdU0I036ebwo+65lQwiVnbf0+XKxup3QspI9lmlMoKL3
A6Th+sqaLEv4GOca1YyI40on6ESg24TaC4WQK+SIVTuYqNdWvhb2lCcdK/WdzkIw
Jwiv2OGfAh5S8yg8c6r1k/WoWv1/hK6wj+MhBX7QSAtkde5BYX3P0ZpAUYXIBqZz
TscMwNiHdgS1FcQGk105wbfztfpBLAkIlVD3PmHxE8rIhvAcS+1GFn+TYSwbZE3M
kYyFvOKHjwnQEdQCSQuPc4YgfWChFYBtE6TNvp/e4rhcIf+7U6uRKLkXSS80jzDM
9sRp11/CxDXx4nZPF9zXd9sKBLXcsEs0QTpxwAzU0GCj9jc8AOZTQXFolzal40S9
C4HoctsmAb2ybX9+4E0SvcBGoMpmWDdXH3KB4MfJoSFLP2ErdGGuIIlDf94oqprv
sNOCls/STmI9L3RR1/g9AuwIElm0HKa3YIzJHE8hgMjsOAvDM1VQqRBLoYbKI74w
bLwXTajt2kN4gdJgHHZ0dZjZQZlf5D7DukY7qdghOOOOxrbPgrN1Qy8QLvdDcio7
lRe/HZUJkihmw4YfMaYfR5c0tVjfPVB/le14iz5E8gLFbWq0tANgEX5h8ylUepu/
N8eJSajVl+ybJtl+YmijM2viR03BJjnyWQLcTk+ZXqH30ti7cGFqtBrnLuIIn8sV
m1U9CgicfSMzg/ASflw6U6Zb290uheY1rFte1ZfrKoIBjGIV07s243VDR1I464zj
6xqr6dX7IuC0iP4BcdLEAUe2r99s5dVcuccHrgq7Me7tTYWSyxEbGfw2N1H00kGb
uOftACanYOkJT6j1m3k1c7XohZsOL43JK3yOkprGZczHRwrrQrbdHHXB27PhVq8e
YyjPQTmufZtWXgkdv1Q4f/oJks7NK9RATBfD/7qgOYpWNDDkmFX9qK23HA4shJu+
YnS6s8MBxyb+3HSkqL2z1Vv5JjEDpeuVFtUsJ4dr3BO0MzrqHVPRDJsjiIPqyb2A
bXX1zefINu0l1zgnDW0lggN/Fxqyrw7654yQGR1uRyEAVMO3QeoWaBSMIf39XiRN
YcDJo56SFcZQovBMuz6YzddJNal5/BFAdWhkEbwzkqJa3QEjm69YwQem9+ZB2n4I
RsLjWln6APXtNeTi4YAXgcb7KifnLSvprwGcna+H0b4UJVfs3IXYjvi1bggTGTj+
1rWAX2+f+fis8i40nH+zHQznZKtwZ/s7qb0KlwNui3moXSOd3YVSNwgmDMAPlPun
B5A13/wvLDwXP7j3gUZ2MJcm3x6VrX1LTcCRu/AqJFLyKHqovCeYSdGRotFRNDzv
NHw3ZbXgcyHyOtSoepHh+idb+F02oIDRkjQwezPRAiZk/vFbjAXGCcYQ9UBmScLM
QJlOr7Ua+tqT2rKmb1PwJYQz39SnUDdUD2+7VckUH/ioCL16k2x0XaK9KfSIpmzh
Qwe+4+nd17Jpj5jFfg2mYr5ccDIEugfCcplExI/VcgS+drlFSMgP871rzeJyIpCy
mqG0bSbMM3VJ307AWDqoiP2hSW5wZ9YweVeFh1DdH2I2Xwt5xYkQDx27M/H9LO1A
WYxrooYFv+qVvVMS
=euQN
-----END PGP MESSAGE-----"""
[err,msg] = armor.decode msg
throw err if err
switch msg.type
when C.openpgp.message_types.public_key then console.log "Got a public key..."
when C.openpgp.message_types.private_key then console.log "Got a private key..."
when C.openpgp.message_types.generic then console.log "Got a generic"
else throw new Error "unknown msg typ: #{msg.type}"
[err, packets] = parse msg.body
throw err if err
console.log util.inspect packets, { depth : null }
armored_key = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
lQO+BFJVxK0BCAC5JHmJ2MoDDUwzXWwnECMFbGF/6mGospOgLuQwGCjg0SMBRZ8j
SbtucJNZIKzCvk6se6wy+i1DH2+KzMSKDyINKgVjjA1rIpcvoFuDt1qBvDFNbQBZ
EiGSdnIYUn7cAJat+0SLIBmn6y7Mtz2ANt89/qwYV8dvMWyTcnR/FU9QhptaSF5Y
TyO8j54mwkoJqi47dm0L164u30uImObsJpRPxww/fwyxfbhFt3ptYIUhgxJjn3Ha
RIlVww/Z7Z7hROVdaPXDwTVjYrk406WtvFEewhigSP4ryf39kxhHPz4BOeD1wyJl
BiW1bWqwuj06VsZlaZXB1w/D+1A06yMZJfhTABEBAAH+AwMCelsOFYDjyITOymsx
MA7I2T+o8drgvaQi1Fv5t5VXjePJdo9KiqXNVVeQfU2o0DWN7Aau3vhFGA95EHbG
OOOPeikQDrbFWUoppeQSzExzcdwr/ySP/ETke3GKvaANzqBp8rVs4QkAD+EaPgm/
8MQxpMre8APRavxfI9ofkAEDMUrvBqJ2gzhmIY43ulFVrkUWBAZxfTC9AyiwkitP
UOau3Be9PUPcJvTJLNueB9KYdKn55gmAHwcMGPrKWFKnL9mhdFCfTotUpPLnu2G9
oOJLexcy+9CoClSkiZXJFg/uQaTKtZQEE/R6IafNL/hN0SiPz0WkcfTRIjDHOoQr
PuYnR1T+7twAKMWLq7EUwjnzov4UTOOS31+1cswaCSUduknJTDPaAMmm7+jwD+Av
nmLMNc7nmvQqr34vKRuq65nTLZgEUkj2hb8I4EmqH8W57aPIYkC/s9zCtRjf7y9G
tNpry48GupqVO92LpIzs6prr7lHsawy30MY50/dHWsxJ+xRUAQQJh1yoTQgOOBgf
0tL+ZKnMM58/eOhmj9+G4DCeJQPrkIONiXYlwSDU1ok6BfdFstKqvtX5Vib0ujLu
3pir+eOXTSqVM3lz+0PIEgNyT5Fq+0zA5usF99owUgYZJm1lTBpVJElOliM0zIJz
tvGZS6jS5X1qNfbL6hFbuTEfDHukRWnwn2ZQelGdCG3MRUpleFhbY8eQL4UtW2nR
HVQzXTRQfSo3PVwVak2gzItcS608gAPqLqKH+X9jPk3Ihn6XGyqwR7g/h8Ggq8ee
UMdbZzNUzdxGstyMwBEyXZA0Hxlojk1VyB20+xlcaLfFq11oTUAHeVNZxVTN/Yzz
ymgGu8yPU5CNRXxTMSg+MZfXqFJBAaWIdYJRw8r6MGzDCD6Erz+y6PUbLLi57zQv
qbQfQ2F0cyBNY0RvZyAobWVvdykgPGNhdEBkb2cuY29tPokBPgQTAQIAKAUCUlXE
rQIbAwUJEswDAAYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AACgkQJ2DcSvj/sywk
xAgAob/ZasZzj8iPNRtCXKGdUDvLu7x8CON3hhfvsa3qcBG0ETUUihaJ9gRonHQd
NuVoMKHMV81TqpIYJKyzaL3vkRx8cZk4etQ4HY+TVXboKKI40apFU4kTiZQMOs39
iVbnm+WuWWSg0OS+3ujAj1VaFQ0y5F9CLBlhYlDlssA/94gDLEPtpqmX19bqewcv
7alrBN2s257dn9wx26HZsE7w/OHaCWElbdcT+nX/SdtdXYsXj1ufjEbi8IPNtAKQ
xjFDNnLdv1qnzHWVdpz6q0ZBdNsCEuXgBI0U3ui/5UJl6mnm99gqTdcKZguySZ60
D1LkyzHJMeMSPdljI/sqfMjX3Z0DvgRSVcStAQgAu8VwtMvJ1D+HqFuLCd1S6pp8
0fYpPRlXMXvGL3W46XXv0WYer835wTtWrSHHpsmUdzto9Q6YaGmXvQi7+4Vt1apy
WbSwVGJpTkn0v76Sma/TmLq2u/FWpT11kB31ytYX2w6xzYZlRepSs9PFIxYg2ukf
XIjuSetps5O4juVFHNPylRYy41gDkj/40BPlaiMs7EOmd6COTO6ns/VfpOc1AYjG
tRG8vcCufPdf68xSHJNYq3SOpDtaAPIcCAeiUAUfdzSqbXSCQPZhvu/GnN8mokvt
LnRBPuCxxCBdAHqaEh9rjGSgievH6/XpzTtnR1A41Wap+CQp5uznGugTAGrIAQAR
AQAB/gMDAnpbDhWA48iEzuIn7APerKvybuDBuPV7MXmk/jhF6FuO/CEtzbX5i8nv
T5fkyxA/9q9brWhytS2/+2j6hLLyqgt5z2d6y5VeJlcXfPligTZfmbNTcH4KpIub
NYny9JGS7pGT1Ku3lc5PnKgOpAz9fLIB9xL1zFvWXn7wxcJSX7AY4HS6RiiSr9AV
RxTVKiF2T0DFA7erbk/aUPyMAio7IbonhWrV3d+3ajuXHF5mhqvdqFXncGXY7LpG
56ynLKFYMv+yorx0f3N3AwpNOLZWC1j8YstTzIefphuC+75mKyotuOJrGvzFtngi
AaRx64ecQBJhdDVhdUmapEK9y9gpAiILjrRLZMKEC1ZTsUZX5gFWh3wwxpaQmrMe
JSdkqmDXEY3LjlpwyCvQeZFnumMCrkTulEBh92ylHN0KN6rrOsnwBHEa6u277Q+s
/vDSN4ZQQ6jPvw1vXDtCf1v6+WUhpjab8/Wh8vTu4LPKYViOqD+LU9d/gzr5hGQa
KvqD3ut16yesLI8yjpLVSdQ8d3FpN/o96kLUnvX8+2q2mVdQoogeTFDnBmaYNeQ3
wFmCJ9cDd+GTqyhW+hBIt42DscSES/5AL1nzUFp2X0RFzVH1H9EyYlrMm+9j1JIQ
KdGi+f4vYvvtmI1LmUY8dOmhHYw/Q+4Z6F1skR4+Ufgn+gCR5JlM8JEDFNG7HejC
MqDeHdGRSHhwVwxx7X4vqf4DkhoEkPrO6//J8SHJMHrAYl3a+DB/B6YA/7ok1qpx
aGSZBKXzh+O9fXksuoRqWMZRdWCP7m26sLCnaH0HzrfxxPnaCcBfNbV2zE/yqEUc
VeJcdcyT1q7ysx2C3YT5y/katPgwl6f2TpAwsnVNlkjlgp3g4ww5iIaIDEb/Wjbp
oKjD0uOb3onQ/PHqrkNMkmg+pAKJASUEGAECAA8FAlJVxK0CGwwFCRLMAwAACgkQ
J2DcSvj/syxaOgf/e5e/4OMSKY8/+aIQ7i4DWj+VSncNfixrbNjX4NH//Bg/UYRS
8b+TKgpEuR8uTslF+/BGCHncv5SQRy7fgFTejMJSRkBPwb8CzirWoo5bTvjEs2tp
4rSLLg1gM5+SdY4NinKEo9pH3fKxszQIMzk/z0rSK9JDhVBzfpQXAEEd1pdMo+t3
JETDfjWhRAuFcE/6nFeVGTGwQn0dX/lQ9xxxhx+/K4PYAx1mYKsIFPtj9Y3C3uIg
Bl0yUJx3nJUTCBO4Wunn60UI/WRix9HcGhf/kbfF/IILuZoTSodvKYUxwcJ/iAAj
ObMKV7f7yqGEQNpyrXlHl4qGSzkvgxQ6IzTA1g==
=DRiu
-----END PGP PRIVATE KEY BLOCK-----"""
armored_verify_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
mQINBFJPT88BEADJWa60OpECivzsrEXx9Bx+X7h9HKdTjFS/QTdndv/CPuTjGeuk
5vlme5ePqXzRnB1hag7BDmvZjiVhzSWBlbzJKfSWGySe/to+mA4AjldZkzCnKeBt
GWsxJvu9+HWsfJp2/fNKyTMyL2VWThyhqJERrLtH/WK/CSA6ohV2f4/ZW/JN+mVp
ukUDIuNgHVcFV2c6AXNQLnHBB/xcAMdxRofbaw2anjDE+TM1C2aoIJY1aBtGPlZ1
wdcaIbrvzIW5xKA3Wv2ERPRYnJutZLb6fPLnrXJrOyvPocOwRNhcZs/s2g46y00B
1yPVvdntuvNuhIMSmEbd3NCxXykA+KgtZw7SXbYTwC68L9nfjR2CGYJDyyTQMHwq
dWEQcmETLqjtV2CDnuEspEg8pWZPHe/ImHhLP72unES6/oN/8xDlejd4tCJCAVE4
uY5UraTu4e4TN3B69x9j13hioFdfb7Jv9BNujB9axcZ7n63mkDQ2bBE7Y6KUtpr0
clTit8lxDqKAOJXgFxG+U/Y/xllxqNrY8+IJpVgzuFpU+O4Y6p1jaZMY5pweGLv4
ggE8MD//FDsQNwcxDLRQKCxqYUYGQCKl2U33W1+KR85S0v84Emc1PlfdjGO7aMft
vNladhBMjXRrUjL19NgMsLaFVNHKEP6lE+vQFejyqsXIXf4S1lHPfJT2dwARAQAB
tBxNYXggS3JvaG4gPHRoZW1heEBnbWFpbC5jb20+iQI+BBMBAgAoBQJST0/PAhsv
BQkHhh+ABgsJCAcDAgYVCAIJCgsEFgIDAQIeAQIXgAAKCRBjhHtLg5MPDEV6EADG
dMwseeQ9ie+zjRx9F8yAM9vMKMQXA36Tqb1CdgT35hVfGNxut2I87O0CkECbQ8xl
jicUt2GmGIDO/hw124yM6sui2FH8rxiiWHVfKEIq/rF3mZTzKJhs2Bv//+JFfWAE
vAmWfdhZPptHuRoN47VfK60KP49BwbFwTV3QOdoe99eFmuDJvW5KTlXEk+Ib9uZY
ipQL1R7zlh1ivjP+b7/WkptE1adbzyC/N3ghcgZUD5lWYh7kNibx5zA01gOMLBSX
umtIOoI4ksf6b+M0Os4ADeyO+BiGbEbPfpuigrFQvKIhUj7lYwe5BlwLwxIag8WL
D+Nlcot5x7EulonbjF5PzLKmC9mW2p1QnseSPS3rYTmYkpBzIQxvcBgfqcbuMEhR
kFCuMMS1esARRLhKcGe9GWwztMYAVJUFtFuwe9Th43gvK66lbrkaIh1gfRnFW5vx
rNjY0zddM39WFUo7WCfEr3bYbZAoSMEbayz1SDZu2noMRsETVaiVccknw1FNRLXx
0n+HVAb7pWqcHOgodrrwA3kuCA8QdgMYF1aJAgzmEH4q8NtggaRQNqfDsGcDToYw
AjGxzrQRJ/xIIct3PSamBTfiDVbFiY2y0LS0Jc2Uj0ptPfvlWRaxM6CHwxt7rcyi
ZPzW1cj9+z6eC3pmlJoNoxLx5jj3V1ZxYvIvA7tZ6bkCDQRST0/PARAA09+Bpd24
5vd46Dh+Qwro43f+3KQbjsZGJuWbMSmu8JTAePPclJtU6bFxbjbz1hahXJISRVu7
4FIN5grqytX7/RI6WbtSQ9vVftWZ2xzThK+RSz/nwxv4GzMpEUWAX7HJ6bqkogkO
7g4lV9H4r8lF21Tpcx5FfKYJIJZcix1Ac6LMZKuRJoT81jm057iWa8WQ/CWDxA9Y
2X/CeEAsjBQxwr59T2NR51DNpSri9OFjX44rpCIcdBHEzWODPDyDtyfp8p+UMUwv
Sd0ihaJ5ER9hbbU5Fm+n0GJSgcND3oyfeKOhlsr32yxYfQfVhQdlq30h/nAqso9Q
syy8/AY51srDfHGc6NXFcc8C7M9+vjWnjOlr+iWvaBWsNChPjXWLmeEKevcqs1br
pMmnkwhqhCT+B6z6hEAfXYjFaLVihqtraRikIAZUfUJSUmalvmtYpEHAcAGf7C0r
M6aQ9PwkFNbqTleC5OxYWG2hrNCPWgDY/M1/NxnB64+XTdbk+3hTAhgY6+QvkkFq
MQ9ReRcwv/t9ixHg2mjyPZmBOSCjdK23BKqUoT9C7mpQQ8ibM5XxC1rOS63QVuwM
tvFao0k9movsNdqcUhX+oouPYxfiNluZV6GLWP/DobqEYdmwOCOTjWkibNeg8JfO
89S1GZTtPs4kVEhZPOE8oqMpMDyi5i1D3+UAEQEAAYkERAQYAQIADwUCUk9PzwIb
LgUJB4YfgAIpCRBjhHtLg5MPDMFdIAQZAQIABgUCUk9PzwAKCRAv4BxFQ0jaOTmM
EACp8FZ+7f7C0knvVrx2O1u2NwYsUUcoE7XZIVZGgvlqFmSfEYMF5TPHettMetWh
wMQosIaORU3P+5qAelhT8lDHz1lhFTX8L2JMC/iPwwtYw3cKUJTHke8XSuwzlNqu
sqTfcc8/Qn49TSEymtl+tPciqKDDSnRPnUgNIiCN4WEcvTglx40LHQ00CuDj0Rao
KNNmVTupC8MGtzWPXb7ZtRlBYBCKJoBZzfKozmimXCHCqddRw76g6rAScPesNJxE
hvNe/3ZM3hL2vYI0s6zIy8n2hqI9Qn4312qJusSf6V6IMwkss/v8sTseGigMmH2R
1hX/as0ZO8S2y78Fy1OK9bZ2G5mTKI1ovKi7ba0xtudl5cbozpDM8GPwtkCAQ1ca
y/FyUwBH3CfATSdSbdx/nnZgSJyplU+xMEl/glMRY5iTvnLH1+oZnJN40lxvmVKZ
OHe3PDsB0ECBNa9kHY/LRGbnMAOwKUPKBGu42YiMeAAsVbNSgBb+smQj1qq1813c
B3FO+t4u7kuDcr0aM+ged5d8IiAbRrHP8gQduidCOe7/HRluW6FIZVs9TVxv41FY
HFj5c7/4D6zAYOZ77Pc8uT+HlXwZLcrXHOq1uiBalU5CEK0oIYxgP/IFitJZdDdL
TuKd2rsNuJnnrTn6qJyw0FIf8cxChTCTKFPCterCmhp3jo84EAC87mBws7GMAI9G
F9e9uBVTp7K5lskjBNq+vZMR0dpXBfLbci7dchqk5jPv9eChR5O+VsW8/CKY5OPJ
qYBjhqnxr3d65ywnNIs6j8Ty1P0UCCtjom6lnsipJ+BPoe1nyMyFkDCJxRiiE0nl
/qvQ3gmq/kTlkbd112denN0M3xReUryvmH1fH8QqTI6y2BlMRIJfDWShEUUqV3J4
jah5WR8mIgGv2UEBvK4OJrtHkIzEgKkLYJFijiHS1Jnc4S6aXHliKEaYPXXtU1Om
BzWxYSbkTDtZ98KoWs+OzNfT4+gu4wHbH98tPOUlq/ryEbeFeNv+29ngRIx9FNQx
QY4TiYD00vF2ifCwC/FVWQ0ybyiufago1h0hnvdu5x6pw3h811cWFuPcbN1M0opp
GajvutV2PEoXx7NIHsg8F+++eVwqmLKcw3EJw6AFNBzs7lFFiAzzV/PGoRRW/D/c
0QqTitcuFJ66xzueImZp+oKfjmO1gEsNg15P4iQjpWCFmpdi3Fzq4NsIDjzpBMWq
mNuq4W0HeVlK6RXv8IcySE+sFCCsqtDEhSBY68aepbCwlFz2kuAvr+jbuT0BTKA5
yh4J89ZwGA87CFabOeXtqeyS9z7ux5xKATv1bXoE9GuG5X5PsdNr3Awr1RAufdLH
nMd8vYZjDx7ro+5buf2cPmeiYlJdKQ==
=UGvW
-----END PGP PUBLIC KEY BLOCK-----
"""
passphrase = "catsdogs"
asp = new ASP {}
await KeyManager.import_from_armored_pgp { raw : armored_key, asp }, defer err, km
throw err if err?
await km.unlock_pgp { passphrase }, defer err
throw err if err?
await KeyManager.import_from_armored_pgp { raw : armored_verify_key, asp }, defer err, vkm
throw err if err?
km = km.find_pgp_key packets[0].key_id
console.log km
console.log packets[0].ekey.y.toString(16)
await km.key.decrypt_and_unpad packets[0].ekey.y, defer err, key
throw err if err?
cipher = import_key_pgp key
pt = decrypt { cipher, ciphertext : packets[1].ciphertext }
console.log util.inspect pt, { depth : null }
console.log pt.length
[err, packets] = parse pt
throw err if err?
console.log packets
await packets[0].inflate defer err, res
throw err if err?
[err, packets] = parse res
throw err if err?
console.log util.inspect packets, { depth : null }
console.log packets[1].toString()
vk = vkm.find_pgp_key packets[0].key_id
throw new Error "couldn't find vkey!" unless vk?
packets[2].key = vk.key
await packets[2].verify [ packets[1] ], defer err
throw err if err?
process.exit 0
| 4911 |
{parse} = require '../src/openpgp/parser'
armor = require '../src/openpgp/armor'
fs = require 'fs'
C = require '../src/const'
{KeyBlock} = require '../src/openpgp/processor'
util = require 'util'
{ASP} = require '../src/util'
{KeyManager} = require '../src/keymanager'
{import_key_pgp} = require '../src/symmetric'
{decrypt} = require '../src/openpgp/ocfb'
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
-----END PGP MESSAGE-----"""
[err,msg] = armor.decode msg
throw err if err
switch msg.type
when C.openpgp.message_types.public_key then console.log "Got a public key..."
when C.openpgp.message_types.private_key then console.log "Got a private key..."
when C.openpgp.message_types.generic then console.log "Got a generic"
else throw new Error "unknown msg typ: #{msg.type}"
[err, packets] = parse msg.body
throw err if err
console.log util.inspect packets, { depth : null }
armored_key = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
S<KEY>
-----END PGP PRIVATE KEY BLOCK-----"""
armored_verify_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
<KEY>
=UGv<KEY>
-----END PGP PUBLIC KEY BLOCK-----
"""
passphrase = "<PASSWORD>"
asp = new ASP {}
await KeyManager.import_from_armored_pgp { raw : armored_key, asp }, defer err, km
throw err if err?
await km.unlock_pgp { passphrase }, defer err
throw err if err?
await KeyManager.import_from_armored_pgp { raw : armored_verify_key, asp }, defer err, vkm
throw err if err?
km = km.find_pgp_key packets[0].key_id
console.log km
console.log packets[0].ekey.y.toString(16)
await km.key.decrypt_and_unpad packets[0].ekey.y, defer err, key
throw err if err?
cipher = import_key_pgp key
pt = decrypt { cipher, ciphertext : packets[1].ciphertext }
console.log util.inspect pt, { depth : null }
console.log pt.length
[err, packets] = parse pt
throw err if err?
console.log packets
await packets[0].inflate defer err, res
throw err if err?
[err, packets] = parse res
throw err if err?
console.log util.inspect packets, { depth : null }
console.log packets[1].toString()
vk = vkm.find_pgp_key packets[0].key_id
throw new Error "couldn't find vkey!" unless vk?
packets[2].key = vk.key
await packets[2].verify [ packets[1] ], defer err
throw err if err?
process.exit 0
| true |
{parse} = require '../src/openpgp/parser'
armor = require '../src/openpgp/armor'
fs = require 'fs'
C = require '../src/const'
{KeyBlock} = require '../src/openpgp/processor'
util = require 'util'
{ASP} = require '../src/util'
{KeyManager} = require '../src/keymanager'
{import_key_pgp} = require '../src/symmetric'
{decrypt} = require '../src/openpgp/ocfb'
msg = """-----BEGIN PGP MESSAGE-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
-----END PGP MESSAGE-----"""
[err,msg] = armor.decode msg
throw err if err
switch msg.type
when C.openpgp.message_types.public_key then console.log "Got a public key..."
when C.openpgp.message_types.private_key then console.log "Got a private key..."
when C.openpgp.message_types.generic then console.log "Got a generic"
else throw new Error "unknown msg typ: #{msg.type}"
[err, packets] = parse msg.body
throw err if err
console.log util.inspect packets, { depth : null }
armored_key = """-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.20 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
SPI:KEY:<KEY>END_PI
-----END PGP PRIVATE KEY BLOCK-----"""
armored_verify_key = """-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: GnuPG/MacGPG2 v2.0.22 (Darwin)
Comment: GPGTools - http://gpgtools.org
PI:KEY:<KEY>END_PI
=UGvPI:KEY:<KEY>END_PI
-----END PGP PUBLIC KEY BLOCK-----
"""
passphrase = "PI:PASSWORD:<PASSWORD>END_PI"
asp = new ASP {}
await KeyManager.import_from_armored_pgp { raw : armored_key, asp }, defer err, km
throw err if err?
await km.unlock_pgp { passphrase }, defer err
throw err if err?
await KeyManager.import_from_armored_pgp { raw : armored_verify_key, asp }, defer err, vkm
throw err if err?
km = km.find_pgp_key packets[0].key_id
console.log km
console.log packets[0].ekey.y.toString(16)
await km.key.decrypt_and_unpad packets[0].ekey.y, defer err, key
throw err if err?
cipher = import_key_pgp key
pt = decrypt { cipher, ciphertext : packets[1].ciphertext }
console.log util.inspect pt, { depth : null }
console.log pt.length
[err, packets] = parse pt
throw err if err?
console.log packets
await packets[0].inflate defer err, res
throw err if err?
[err, packets] = parse res
throw err if err?
console.log util.inspect packets, { depth : null }
console.log packets[1].toString()
vk = vkm.find_pgp_key packets[0].key_id
throw new Error "couldn't find vkey!" unless vk?
packets[2].key = vk.key
await packets[2].verify [ packets[1] ], defer err
throw err if err?
process.exit 0
|
[
{
"context": " alpha\n # \"Beta\"\n # \"Charlie\"\n # for x in delta\n # x",
"end": 2201,
"score": 0.9991902112960815,
"start": 2194,
"tag": "NAME",
"value": "Charlie"
}
] | node_modules/ion/src/test/ionCompilerES5.coffee | IanGlass/Budgetty | 14 | ion = require '../'
index = require '../compiler'
tests =
"""
let x = 10
""": """
'use strict';
var x = 10;
"""
"""
let x = 10
if foo
let y = 20
if bar
const y = 30
""": """
'use strict';
var x = 10;
if (foo) {
var y = 20;
}
if (bar) {
var y = 30;
}
"""
"""
export class StampFilter
stamp: (key, object) ->
for name, property of key.type.properties if property.stamp
log(name)
""": """
'use strict';
var ion = require('ion');
var StampFilter = ion.defineClass({
name: 'StampFilter',
stamp: function (key, object) {
{
var _ref = key.type.properties;
for (var name in _ref) {
var property = _ref[name];
if (property.stamp) {
log(name);
}
}
}
}
});
module.exports = exports = StampFilter;
"""
"""
let foo = bar(
1
2
)
.toString(
"12"
)
.split(' ')
""": """
'use strict';
var foo = bar(1, 2).toString('12').split(' ');
"""
# """
# template -> alpha ? beta
# """: null
"""
""
foo
bar #baz
""": """
'use strict';
'foo\\nbar #baz';
"""
"""
let object =
x: 10
property visible:
get: -> true
y: 20
""": """
'use strict';
var object = Object.defineProperties({
x: 10,
y: 20
}, {
visible: {
get: function () {
return true;
}
}
});
"""
# """
# template foo() ->
# """: null
"""
return {a:b ? c}
d
""": """
'use strict';
var ion = require('ion');
var _ref = { a: b != null ? b : c };
ion.add(_ref, d);
return _ref;
"""
# """
# template ->
# return []
# if alpha
# alpha
# "Beta"
# "Charlie"
# for x in delta
# x
# y
# z
# """: null
"""
template (model) ->
return (e) ->
let {listModel} = model
""": """
'use strict';
var ion = require('ion');
ion.template(function (model) {
return ion.createRuntime({
type: 'Template',
id: null,
body: [{
type: 'ReturnStatement',
argument: {
type: 'Function',
context: true,
value: function (_context) {
return function (e) {
var model = _context.get('model');
var _ref = model;
var listModel = _ref.listModel;
};
}
},
order: '0'
}],
bound: false
}, {
this: this,
model: model
}, null);
});
"""
# """
# JSON.stringify(deep object)
# """: null
"""
foo:
a: 1
""": {line:1, column:1}
"""
style.sheets:
[module.id]: ""
""": {line:1, column:1}
# TODO: Fix this bug in the parser.
# """
# for let i = 0; i < 100; i += 10
# i
# """: null
# """
# template -> {a:1,b:[2,3]}
# """: """
# 'use strict';
# var ion = require('ion');
# ion.template(function () {
# return ion.createRuntime({
# type: 'Template',
# id: null,
# body: [{
# type: 'ReturnStatement',
# argument: {
# type: 'Literal',
# value: {
# a: 1,
# b: [
# 2,
# 3
# ]
# }
# },
# order: '0'
# }],
# bound: false
# }, { this: this }, null);
# });
# """
# """
# let input = PaperInput()
# "iron-select"(e) ->
# console.log('select', e)
# """: null
if global.window?
return
exports.test = ->
for input, expected of tests
options = {target:'es5'}
if expected is null
index.compile input, ion.patch({loc:false,source:'ionCompilerES5.js', debug:true}, options)
else if typeof expected is 'object'
# expected to throw an error
error = null
try
index.compile input, options
catch e
error = e
# check equivalent fields
for key, value of expected
if value isnt e[key]
throw new Error "\n#{JSON.stringify e}\n!=\n#{JSON.stringify expected}"
if not error?
throw new Error "Expected an error: #{JSON.stringify expected}"
else
output = index.compile input, options
if output.trim() isnt expected.trim()
console.log '-Output---------------------------------------------'
console.log output
throw new Error "\n#{output}\n!=\n#{expected}"
return
| 43791 | ion = require '../'
index = require '../compiler'
tests =
"""
let x = 10
""": """
'use strict';
var x = 10;
"""
"""
let x = 10
if foo
let y = 20
if bar
const y = 30
""": """
'use strict';
var x = 10;
if (foo) {
var y = 20;
}
if (bar) {
var y = 30;
}
"""
"""
export class StampFilter
stamp: (key, object) ->
for name, property of key.type.properties if property.stamp
log(name)
""": """
'use strict';
var ion = require('ion');
var StampFilter = ion.defineClass({
name: 'StampFilter',
stamp: function (key, object) {
{
var _ref = key.type.properties;
for (var name in _ref) {
var property = _ref[name];
if (property.stamp) {
log(name);
}
}
}
}
});
module.exports = exports = StampFilter;
"""
"""
let foo = bar(
1
2
)
.toString(
"12"
)
.split(' ')
""": """
'use strict';
var foo = bar(1, 2).toString('12').split(' ');
"""
# """
# template -> alpha ? beta
# """: null
"""
""
foo
bar #baz
""": """
'use strict';
'foo\\nbar #baz';
"""
"""
let object =
x: 10
property visible:
get: -> true
y: 20
""": """
'use strict';
var object = Object.defineProperties({
x: 10,
y: 20
}, {
visible: {
get: function () {
return true;
}
}
});
"""
# """
# template foo() ->
# """: null
"""
return {a:b ? c}
d
""": """
'use strict';
var ion = require('ion');
var _ref = { a: b != null ? b : c };
ion.add(_ref, d);
return _ref;
"""
# """
# template ->
# return []
# if alpha
# alpha
# "Beta"
# "<NAME>"
# for x in delta
# x
# y
# z
# """: null
"""
template (model) ->
return (e) ->
let {listModel} = model
""": """
'use strict';
var ion = require('ion');
ion.template(function (model) {
return ion.createRuntime({
type: 'Template',
id: null,
body: [{
type: 'ReturnStatement',
argument: {
type: 'Function',
context: true,
value: function (_context) {
return function (e) {
var model = _context.get('model');
var _ref = model;
var listModel = _ref.listModel;
};
}
},
order: '0'
}],
bound: false
}, {
this: this,
model: model
}, null);
});
"""
# """
# JSON.stringify(deep object)
# """: null
"""
foo:
a: 1
""": {line:1, column:1}
"""
style.sheets:
[module.id]: ""
""": {line:1, column:1}
# TODO: Fix this bug in the parser.
# """
# for let i = 0; i < 100; i += 10
# i
# """: null
# """
# template -> {a:1,b:[2,3]}
# """: """
# 'use strict';
# var ion = require('ion');
# ion.template(function () {
# return ion.createRuntime({
# type: 'Template',
# id: null,
# body: [{
# type: 'ReturnStatement',
# argument: {
# type: 'Literal',
# value: {
# a: 1,
# b: [
# 2,
# 3
# ]
# }
# },
# order: '0'
# }],
# bound: false
# }, { this: this }, null);
# });
# """
# """
# let input = PaperInput()
# "iron-select"(e) ->
# console.log('select', e)
# """: null
if global.window?
return
exports.test = ->
for input, expected of tests
options = {target:'es5'}
if expected is null
index.compile input, ion.patch({loc:false,source:'ionCompilerES5.js', debug:true}, options)
else if typeof expected is 'object'
# expected to throw an error
error = null
try
index.compile input, options
catch e
error = e
# check equivalent fields
for key, value of expected
if value isnt e[key]
throw new Error "\n#{JSON.stringify e}\n!=\n#{JSON.stringify expected}"
if not error?
throw new Error "Expected an error: #{JSON.stringify expected}"
else
output = index.compile input, options
if output.trim() isnt expected.trim()
console.log '-Output---------------------------------------------'
console.log output
throw new Error "\n#{output}\n!=\n#{expected}"
return
| true | ion = require '../'
index = require '../compiler'
tests =
"""
let x = 10
""": """
'use strict';
var x = 10;
"""
"""
let x = 10
if foo
let y = 20
if bar
const y = 30
""": """
'use strict';
var x = 10;
if (foo) {
var y = 20;
}
if (bar) {
var y = 30;
}
"""
"""
export class StampFilter
stamp: (key, object) ->
for name, property of key.type.properties if property.stamp
log(name)
""": """
'use strict';
var ion = require('ion');
var StampFilter = ion.defineClass({
name: 'StampFilter',
stamp: function (key, object) {
{
var _ref = key.type.properties;
for (var name in _ref) {
var property = _ref[name];
if (property.stamp) {
log(name);
}
}
}
}
});
module.exports = exports = StampFilter;
"""
"""
let foo = bar(
1
2
)
.toString(
"12"
)
.split(' ')
""": """
'use strict';
var foo = bar(1, 2).toString('12').split(' ');
"""
# """
# template -> alpha ? beta
# """: null
"""
""
foo
bar #baz
""": """
'use strict';
'foo\\nbar #baz';
"""
"""
let object =
x: 10
property visible:
get: -> true
y: 20
""": """
'use strict';
var object = Object.defineProperties({
x: 10,
y: 20
}, {
visible: {
get: function () {
return true;
}
}
});
"""
# """
# template foo() ->
# """: null
"""
return {a:b ? c}
d
""": """
'use strict';
var ion = require('ion');
var _ref = { a: b != null ? b : c };
ion.add(_ref, d);
return _ref;
"""
# """
# template ->
# return []
# if alpha
# alpha
# "Beta"
# "PI:NAME:<NAME>END_PI"
# for x in delta
# x
# y
# z
# """: null
"""
template (model) ->
return (e) ->
let {listModel} = model
""": """
'use strict';
var ion = require('ion');
ion.template(function (model) {
return ion.createRuntime({
type: 'Template',
id: null,
body: [{
type: 'ReturnStatement',
argument: {
type: 'Function',
context: true,
value: function (_context) {
return function (e) {
var model = _context.get('model');
var _ref = model;
var listModel = _ref.listModel;
};
}
},
order: '0'
}],
bound: false
}, {
this: this,
model: model
}, null);
});
"""
# """
# JSON.stringify(deep object)
# """: null
"""
foo:
a: 1
""": {line:1, column:1}
"""
style.sheets:
[module.id]: ""
""": {line:1, column:1}
# TODO: Fix this bug in the parser.
# """
# for let i = 0; i < 100; i += 10
# i
# """: null
# """
# template -> {a:1,b:[2,3]}
# """: """
# 'use strict';
# var ion = require('ion');
# ion.template(function () {
# return ion.createRuntime({
# type: 'Template',
# id: null,
# body: [{
# type: 'ReturnStatement',
# argument: {
# type: 'Literal',
# value: {
# a: 1,
# b: [
# 2,
# 3
# ]
# }
# },
# order: '0'
# }],
# bound: false
# }, { this: this }, null);
# });
# """
# """
# let input = PaperInput()
# "iron-select"(e) ->
# console.log('select', e)
# """: null
if global.window?
return
exports.test = ->
for input, expected of tests
options = {target:'es5'}
if expected is null
index.compile input, ion.patch({loc:false,source:'ionCompilerES5.js', debug:true}, options)
else if typeof expected is 'object'
# expected to throw an error
error = null
try
index.compile input, options
catch e
error = e
# check equivalent fields
for key, value of expected
if value isnt e[key]
throw new Error "\n#{JSON.stringify e}\n!=\n#{JSON.stringify expected}"
if not error?
throw new Error "Expected an error: #{JSON.stringify expected}"
else
output = index.compile input, options
if output.trim() isnt expected.trim()
console.log '-Output---------------------------------------------'
console.log output
throw new Error "\n#{output}\n!=\n#{expected}"
return
|
[
{
"context": " list: ['1', '2', '3']\n person:\n name: 'Alexander Schilling'\n job: 'Developer'\n city:\n address:\n",
"end": 407,
"score": 0.9998038411140442,
"start": 388,
"tag": "NAME",
"value": "Alexander Schilling"
}
] | test/mocha/ini.coffee | alinex/node-formatter | 0 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "INI", ->
file = __dirname + '/../data/format.ini'
format = 'ini'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
list: ['1', '2', '3']
person:
name: 'Alexander Schilling'
job: 'Developer'
city:
address:
name: 'Stuttgart'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
it "should format without whitespace", (cb) ->
formatter.stringify data, format,
whitespace: false
, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
| 173553 | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "INI", ->
file = __dirname + '/../data/format.ini'
format = 'ini'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
list: ['1', '2', '3']
person:
name: '<NAME>'
job: 'Developer'
city:
address:
name: 'Stuttgart'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
it "should format without whitespace", (cb) ->
formatter.stringify data, format,
whitespace: false
, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
| true | chai = require 'chai'
expect = chai.expect
### eslint-env node, mocha ###
fs = require 'fs'
debug = require('debug') 'test'
chalk = require 'chalk'
formatter = require '../../src/index'
describe "INI", ->
file = __dirname + '/../data/format.ini'
format = 'ini'
example = fs.readFileSync file, 'UTF8'
data =
string: 'test'
list: ['1', '2', '3']
person:
name: 'PI:NAME:<NAME>END_PI'
job: 'Developer'
city:
address:
name: 'Stuttgart'
describe "parse preset file", ->
it "should get object", (cb) ->
formatter.parse example, format, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with autodetect", (cb) ->
formatter.parse example, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
it "should work with filename", (cb) ->
formatter.parse example, file, (err, obj) ->
expect(err, 'error').to.not.exist
expect(obj, 'object').to.deep.equal data
cb()
describe "format and parse", ->
it "should reread object", (cb) ->
formatter.stringify data, format, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
it "should format without whitespace", (cb) ->
formatter.stringify data, format,
whitespace: false
, (err, text) ->
expect(err, 'error').to.not.exist
expect(typeof text, 'type of result').to.equal 'string'
debug "result", chalk.grey text
formatter.parse text, format, (err, obj) ->
expect(obj, 'reread object').to.deep.equal data
cb()
|
[
{
"context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission",
"end": 18,
"score": 0.9994131922721863,
"start": 12,
"tag": "NAME",
"value": "Joyent"
}
] | test/simple/test-fs-read.coffee | lxe/io.coffee | 0 | # Copyright Joyent, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.fixturesDir, "x.txt")
fd = fs.openSync(filepath, "r")
expected = "xyz\n"
readCalled = 0
fs.read fd, expected.length, 0, "utf-8", (err, str, bytesRead) ->
readCalled++
assert.ok not err
assert.equal str, expected
assert.equal bytesRead, expected.length
return
r = fs.readSync(fd, expected.length, 0, "utf-8")
assert.equal r[0], expected
assert.equal r[1], expected.length
process.on "exit", ->
assert.equal readCalled, 1
return
| 48636 | # Copyright <NAME>, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.fixturesDir, "x.txt")
fd = fs.openSync(filepath, "r")
expected = "xyz\n"
readCalled = 0
fs.read fd, expected.length, 0, "utf-8", (err, str, bytesRead) ->
readCalled++
assert.ok not err
assert.equal str, expected
assert.equal bytesRead, expected.length
return
r = fs.readSync(fd, expected.length, 0, "utf-8")
assert.equal r[0], expected
assert.equal r[1], expected.length
process.on "exit", ->
assert.equal readCalled, 1
return
| true | # Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the
# following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
# USE OR OTHER DEALINGS IN THE SOFTWARE.
common = require("../common")
assert = require("assert")
path = require("path")
fs = require("fs")
filepath = path.join(common.fixturesDir, "x.txt")
fd = fs.openSync(filepath, "r")
expected = "xyz\n"
readCalled = 0
fs.read fd, expected.length, 0, "utf-8", (err, str, bytesRead) ->
readCalled++
assert.ok not err
assert.equal str, expected
assert.equal bytesRead, expected.length
return
r = fs.readSync(fd, expected.length, 0, "utf-8")
assert.equal r[0], expected
assert.equal r[1], expected.length
process.on "exit", ->
assert.equal readCalled, 1
return
|
[
{
"context": "ess) ->\n series = [\n Async.apply(@clone, \"git@github.com:#{@options.owner}/#{@options.repo}.git\"),\n @",
"end": 2047,
"score": 0.9938755035400391,
"start": 2033,
"tag": "EMAIL",
"value": "git@github.com"
}
] | src/deployer.coffee | erichmenge/deployer | 1 | Express = require 'express'
Router = require './router'
ChildProcess = require 'child_process'
HttpClient = require 'scoped-http-client'
QueryString = require 'querystring'
Async = require 'async'
class Deployer
constructor: ->
@express = new Express
@router = new Router(this)
@status = 'idle'
@options =
hubot_say: "#{process.env.HUBOT_URL}hubot/say"
hubot_room: process.env.HUBOT_ROOM
repo: process.env.GITHUB_REPO
owner: process.env.GITHUB_OWNER
url: process.env.HEROKU_URL
ChildProcess.exec 'mkdir -p .ssh && echo "$PRIVATE_KEY" > .ssh/id_rsa && echo "$KNOWN_HOSTS" > .ssh/known_hosts', @logger
port = process.env.PORT || 3000
@express.listen port
console.log "Listening on port #{port}"
@antiIdle(@options.url) if @options.url
success: ->
@message "Deployed to production"
@status = 'idle'
fail: ->
@status = 'idle'
@message 'Deploy Failed'
http: (url) ->
HttpClient.create(url)
message: (message) ->
data =
room: @options.hubot_room
message: message
@http(@options.hubot_say).header('Content-Type', 'application/x-www-form-urlencoded').post(QueryString.stringify(data))
logger: (error, stdout, stderr) =>
console.log "exec: stdout: #{stderr}"
console.log "exec: stderr: #{stdout}"
console.log('exec: error: ' + error) if error
getStatus: ->
@message "Deploy status is #{@status}"
deploy: ->
if @status == 'idle'
@message "Deploying to production"
else
@message "Deploy already in progress"
return false
@status = 'deploying'
@prepare => @capistrano('deploy')
true
rollback: ->
if @status == 'idle'
@message "Rolling back deploy"
else
@message "Can't rollback, deploy in progress."
return false
@status = 'deploying'
@prepare => @capistrano('rollback')
true
prepare: (success) ->
series = [
Async.apply(@clone, "git@github.com:#{@options.owner}/#{@options.repo}.git"),
@bundle
]
Async.series series, (error) => if error then @fail() else success()
clone: (url, callback) =>
child = ChildProcess.exec "cd tmp/repo && git pull || git clone #{url} tmp/repo", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('clone failed')
bundle: (callback) ->
child = ChildProcess.exec "cd tmp/repo && bundle install", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('bundle failed')
capistrano: (mode = 'deploy') =>
console.log "Calling capistrano"
if mode == "deploy"
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy", @logger
else
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy:rollback", @logger
child.on 'exit', (code) => if code == 0 then @success() else @fail()
antiIdle: (url) =>
setInterval =>
@http(url + 'ping').post() (err, response, body) =>
console.log "Self pinging"
, 1200000
module.exports = Deployer
| 187342 | Express = require 'express'
Router = require './router'
ChildProcess = require 'child_process'
HttpClient = require 'scoped-http-client'
QueryString = require 'querystring'
Async = require 'async'
class Deployer
constructor: ->
@express = new Express
@router = new Router(this)
@status = 'idle'
@options =
hubot_say: "#{process.env.HUBOT_URL}hubot/say"
hubot_room: process.env.HUBOT_ROOM
repo: process.env.GITHUB_REPO
owner: process.env.GITHUB_OWNER
url: process.env.HEROKU_URL
ChildProcess.exec 'mkdir -p .ssh && echo "$PRIVATE_KEY" > .ssh/id_rsa && echo "$KNOWN_HOSTS" > .ssh/known_hosts', @logger
port = process.env.PORT || 3000
@express.listen port
console.log "Listening on port #{port}"
@antiIdle(@options.url) if @options.url
success: ->
@message "Deployed to production"
@status = 'idle'
fail: ->
@status = 'idle'
@message 'Deploy Failed'
http: (url) ->
HttpClient.create(url)
message: (message) ->
data =
room: @options.hubot_room
message: message
@http(@options.hubot_say).header('Content-Type', 'application/x-www-form-urlencoded').post(QueryString.stringify(data))
logger: (error, stdout, stderr) =>
console.log "exec: stdout: #{stderr}"
console.log "exec: stderr: #{stdout}"
console.log('exec: error: ' + error) if error
getStatus: ->
@message "Deploy status is #{@status}"
deploy: ->
if @status == 'idle'
@message "Deploying to production"
else
@message "Deploy already in progress"
return false
@status = 'deploying'
@prepare => @capistrano('deploy')
true
rollback: ->
if @status == 'idle'
@message "Rolling back deploy"
else
@message "Can't rollback, deploy in progress."
return false
@status = 'deploying'
@prepare => @capistrano('rollback')
true
prepare: (success) ->
series = [
Async.apply(@clone, "<EMAIL>:#{@options.owner}/#{@options.repo}.git"),
@bundle
]
Async.series series, (error) => if error then @fail() else success()
clone: (url, callback) =>
child = ChildProcess.exec "cd tmp/repo && git pull || git clone #{url} tmp/repo", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('clone failed')
bundle: (callback) ->
child = ChildProcess.exec "cd tmp/repo && bundle install", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('bundle failed')
capistrano: (mode = 'deploy') =>
console.log "Calling capistrano"
if mode == "deploy"
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy", @logger
else
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy:rollback", @logger
child.on 'exit', (code) => if code == 0 then @success() else @fail()
antiIdle: (url) =>
setInterval =>
@http(url + 'ping').post() (err, response, body) =>
console.log "Self pinging"
, 1200000
module.exports = Deployer
| true | Express = require 'express'
Router = require './router'
ChildProcess = require 'child_process'
HttpClient = require 'scoped-http-client'
QueryString = require 'querystring'
Async = require 'async'
class Deployer
constructor: ->
@express = new Express
@router = new Router(this)
@status = 'idle'
@options =
hubot_say: "#{process.env.HUBOT_URL}hubot/say"
hubot_room: process.env.HUBOT_ROOM
repo: process.env.GITHUB_REPO
owner: process.env.GITHUB_OWNER
url: process.env.HEROKU_URL
ChildProcess.exec 'mkdir -p .ssh && echo "$PRIVATE_KEY" > .ssh/id_rsa && echo "$KNOWN_HOSTS" > .ssh/known_hosts', @logger
port = process.env.PORT || 3000
@express.listen port
console.log "Listening on port #{port}"
@antiIdle(@options.url) if @options.url
success: ->
@message "Deployed to production"
@status = 'idle'
fail: ->
@status = 'idle'
@message 'Deploy Failed'
http: (url) ->
HttpClient.create(url)
message: (message) ->
data =
room: @options.hubot_room
message: message
@http(@options.hubot_say).header('Content-Type', 'application/x-www-form-urlencoded').post(QueryString.stringify(data))
logger: (error, stdout, stderr) =>
console.log "exec: stdout: #{stderr}"
console.log "exec: stderr: #{stdout}"
console.log('exec: error: ' + error) if error
getStatus: ->
@message "Deploy status is #{@status}"
deploy: ->
if @status == 'idle'
@message "Deploying to production"
else
@message "Deploy already in progress"
return false
@status = 'deploying'
@prepare => @capistrano('deploy')
true
rollback: ->
if @status == 'idle'
@message "Rolling back deploy"
else
@message "Can't rollback, deploy in progress."
return false
@status = 'deploying'
@prepare => @capistrano('rollback')
true
prepare: (success) ->
series = [
Async.apply(@clone, "PI:EMAIL:<EMAIL>END_PI:#{@options.owner}/#{@options.repo}.git"),
@bundle
]
Async.series series, (error) => if error then @fail() else success()
clone: (url, callback) =>
child = ChildProcess.exec "cd tmp/repo && git pull || git clone #{url} tmp/repo", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('clone failed')
bundle: (callback) ->
child = ChildProcess.exec "cd tmp/repo && bundle install", @logger
child.on 'exit', (code) => if code == 0 then callback() else callback('bundle failed')
capistrano: (mode = 'deploy') =>
console.log "Calling capistrano"
if mode == "deploy"
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy", @logger
else
child = ChildProcess.exec "cd tmp/repo && bundle exec cap deploy:rollback", @logger
child.on 'exit', (code) => if code == 0 then @success() else @fail()
antiIdle: (url) =>
setInterval =>
@http(url + 'ping').post() (err, response, body) =>
console.log "Self pinging"
, 1200000
module.exports = Deployer
|
[
{
"context": "structor: (@origin, @context) ->\n for key in ['ID', 'fullID', 'board', 'thread', 'info', 'quotes', ",
"end": 82,
"score": 0.7427716255187988,
"start": 80,
"tag": "KEY",
"value": "ID"
},
{
"context": "(@origin, @context) ->\n for key in ['ID', 'fullID', 'board', '... | src/General/Clone.coffee | N3X15/4chan-x | 1 | class Clone extends Post
constructor: (@origin, @context) ->
for key in ['ID', 'fullID', 'board', 'thread', 'info', 'quotes', 'isReply']
# Copy or point to the origin's key value.
@[key] = origin[key]
{nodes} = origin
root = nodes.root.cloneNode true
post = $ '.post', root
info = $ '.postInfo', post
@nodes =
root: root
post: post
info: info
comment: $ '.postMessage', post
quotelinks: []
backlinks: info.getElementsByClassName 'backlink'
# Remove inlined posts inside of this post.
for inline in $$ '.inline', post
$.rm inline
for inlined in $$ '.inlined', post
$.rmClass inlined, 'inlined'
root.hidden = false # post hiding
$.rmClass root, 'forwarded' # quote inlining
$.rmClass post, 'highlight' # keybind navigation, ID highlighting
if nodes.subject
@nodes.subject = $ '.subject', info
if nodes.name
@nodes.name = $ '.name', info
if nodes.email
@nodes.email = $ '.useremail', info
if nodes.tripcode
@nodes.tripcode = $ '.postertrip', info
if nodes.uniqueID
@nodes.uniqueID = $ '.posteruid', info
if nodes.capcode
@nodes.capcode = $ '.capcode', info
if nodes.flag
@nodes.flag = $ '.countryFlag', info
if nodes.date
@nodes.date = $ '.dateTime', info
@parseQuotes()
if origin.file
# Copy values, point to relevant elements.
# See comments in Post's constructor.
@file = {}
for key, val of origin.file
@file[key] = val
file = $ '.file', post
@file.text = file.firstElementChild
@file.thumb = $ 'img[data-md5]', file
@file.fullImage = $ '.full-image', file
@isDead = true if origin.isDead
@isClone = true
index = origin.clones.push(@) - 1
root.dataset.clone = index
| 202968 | class Clone extends Post
constructor: (@origin, @context) ->
for key in ['<KEY>', 'full<KEY>', 'board', 'thread', 'info', 'quotes', 'isReply']
# Copy or point to the origin's key value.
@[key] = origin[key]
{nodes} = origin
root = nodes.root.cloneNode true
post = $ '.post', root
info = $ '.postInfo', post
@nodes =
root: root
post: post
info: info
comment: $ '.postMessage', post
quotelinks: []
backlinks: info.getElementsByClassName 'backlink'
# Remove inlined posts inside of this post.
for inline in $$ '.inline', post
$.rm inline
for inlined in $$ '.inlined', post
$.rmClass inlined, 'inlined'
root.hidden = false # post hiding
$.rmClass root, 'forwarded' # quote inlining
$.rmClass post, 'highlight' # keybind navigation, ID highlighting
if nodes.subject
@nodes.subject = $ '.subject', info
if nodes.name
@nodes.name = $ '.name', info
if nodes.email
@nodes.email = $ '.useremail', info
if nodes.tripcode
@nodes.tripcode = $ '.postertrip', info
if nodes.uniqueID
@nodes.uniqueID = $ '.posteruid', info
if nodes.capcode
@nodes.capcode = $ '.capcode', info
if nodes.flag
@nodes.flag = $ '.countryFlag', info
if nodes.date
@nodes.date = $ '.dateTime', info
@parseQuotes()
if origin.file
# Copy values, point to relevant elements.
# See comments in Post's constructor.
@file = {}
for key, val of origin.file
@file[key] = val
file = $ '.file', post
@file.text = file.firstElementChild
@file.thumb = $ 'img[data-md5]', file
@file.fullImage = $ '.full-image', file
@isDead = true if origin.isDead
@isClone = true
index = origin.clones.push(@) - 1
root.dataset.clone = index
| true | class Clone extends Post
constructor: (@origin, @context) ->
for key in ['PI:KEY:<KEY>END_PI', 'fullPI:KEY:<KEY>END_PI', 'board', 'thread', 'info', 'quotes', 'isReply']
# Copy or point to the origin's key value.
@[key] = origin[key]
{nodes} = origin
root = nodes.root.cloneNode true
post = $ '.post', root
info = $ '.postInfo', post
@nodes =
root: root
post: post
info: info
comment: $ '.postMessage', post
quotelinks: []
backlinks: info.getElementsByClassName 'backlink'
# Remove inlined posts inside of this post.
for inline in $$ '.inline', post
$.rm inline
for inlined in $$ '.inlined', post
$.rmClass inlined, 'inlined'
root.hidden = false # post hiding
$.rmClass root, 'forwarded' # quote inlining
$.rmClass post, 'highlight' # keybind navigation, ID highlighting
if nodes.subject
@nodes.subject = $ '.subject', info
if nodes.name
@nodes.name = $ '.name', info
if nodes.email
@nodes.email = $ '.useremail', info
if nodes.tripcode
@nodes.tripcode = $ '.postertrip', info
if nodes.uniqueID
@nodes.uniqueID = $ '.posteruid', info
if nodes.capcode
@nodes.capcode = $ '.capcode', info
if nodes.flag
@nodes.flag = $ '.countryFlag', info
if nodes.date
@nodes.date = $ '.dateTime', info
@parseQuotes()
if origin.file
# Copy values, point to relevant elements.
# See comments in Post's constructor.
@file = {}
for key, val of origin.file
@file[key] = val
file = $ '.file', post
@file.text = file.firstElementChild
@file.thumb = $ 'img[data-md5]', file
@file.fullImage = $ '.full-image', file
@isDead = true if origin.isDead
@isClone = true
index = origin.clones.push(@) - 1
root.dataset.clone = index
|
[
{
"context": "# Backbone.Include\n# https://github.com/anthonyshort/backbone.include\n#\n# Copyright (c) 2012 Anthony S",
"end": 52,
"score": 0.9992797374725342,
"start": 40,
"tag": "USERNAME",
"value": "anthonyshort"
},
{
"context": "thonyshort/backbone.include\n#\n# Copyright (c) 2... | src/backbone.include.coffee | anthonyshort/backbone.include | 2 | # Backbone.Include
# https://github.com/anthonyshort/backbone.include
#
# Copyright (c) 2012 Anthony Short
# Licensed under the MIT license.
Backbone.Model.include = Backbone.Collection.include = Backbone.View.include = Backbone.Router.include = (obj) ->
for key, value of obj when key not in ['included']
if not @::[key] then @::[key] = value
obj.included?.apply(this)
@
| 104989 | # Backbone.Include
# https://github.com/anthonyshort/backbone.include
#
# Copyright (c) 2012 <NAME>
# Licensed under the MIT license.
Backbone.Model.include = Backbone.Collection.include = Backbone.View.include = Backbone.Router.include = (obj) ->
for key, value of obj when key not in ['included']
if not @::[key] then @::[key] = value
obj.included?.apply(this)
@
| true | # Backbone.Include
# https://github.com/anthonyshort/backbone.include
#
# Copyright (c) 2012 PI:NAME:<NAME>END_PI
# Licensed under the MIT license.
Backbone.Model.include = Backbone.Collection.include = Backbone.View.include = Backbone.Router.include = (obj) ->
for key, value of obj when key not in ['included']
if not @::[key] then @::[key] = value
obj.included?.apply(this)
@
|
[
{
"context": "fset={3}>\n <Input\n label=\"Username\"\n id=\"userName\"\n type=\"",
"end": 1102,
"score": 0.9103083610534668,
"start": 1094,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "\n label=\"Username\"\n ... | webfe/src/components/cjsx/LoginForm.cjsx | pequalsnp/portroyal | 2 | React = require 'react'
Button = require 'react-bootstrap/lib/Button'
Col = require 'react-bootstrap/lib/Col'
Grid = require 'react-bootstrap/lib/Grid'
Input = require 'react-bootstrap/lib/Input'
Row = require 'react-bootstrap/lib/Row'
AuthService = require '../../services/AuthService.coffee'
LoginForm = React.createClass(
getInitialState: ->
userName: ""
password: ""
_valid: ->
if (!this.state.userName || !this.state.password)
return false
if (this.state.userName.length == 0 || this.state.password.length == 0)
return false
return true
_handleChange: (changeEvent) ->
if (changeEvent.target.id == "userName")
this.setState({userName: changeEvent.target.value})
else if (changeEvent.target.id == "password")
this.setState({password: changeEvent.target.value})
_handleSubmit: (submitEvent) ->
submitEvent.preventDefault()
AuthService.loginUser(this.state.userName, this.state.password)
render: ->
<Grid>
<form>
<Row>
<Col xs={6} xsOffset={3}>
<Input
label="Username"
id="userName"
type="text"
value={this.state.userName}
onChange={this._handleChange}
/>
<Input
label="Password"
id="password"
type="password"
value={this.state.password}
onChange={this._handleChange}
/>
<Button bsStyle="success" type="submit" disabled={!this._valid()} onClick={this._handleSubmit}>Login</Button>
</Col>
</Row>
</form>
</Grid>
)
module.exports = LoginForm
| 122186 | React = require 'react'
Button = require 'react-bootstrap/lib/Button'
Col = require 'react-bootstrap/lib/Col'
Grid = require 'react-bootstrap/lib/Grid'
Input = require 'react-bootstrap/lib/Input'
Row = require 'react-bootstrap/lib/Row'
AuthService = require '../../services/AuthService.coffee'
LoginForm = React.createClass(
getInitialState: ->
userName: ""
password: ""
_valid: ->
if (!this.state.userName || !this.state.password)
return false
if (this.state.userName.length == 0 || this.state.password.length == 0)
return false
return true
_handleChange: (changeEvent) ->
if (changeEvent.target.id == "userName")
this.setState({userName: changeEvent.target.value})
else if (changeEvent.target.id == "password")
this.setState({password: changeEvent.target.value})
_handleSubmit: (submitEvent) ->
submitEvent.preventDefault()
AuthService.loginUser(this.state.userName, this.state.password)
render: ->
<Grid>
<form>
<Row>
<Col xs={6} xsOffset={3}>
<Input
label="Username"
id="userName"
type="text"
value={this.state.userName}
onChange={this._handleChange}
/>
<Input
label="<PASSWORD>"
id="password"
type="password"
value={this.state.password}
onChange={this._handleChange}
/>
<Button bsStyle="success" type="submit" disabled={!this._valid()} onClick={this._handleSubmit}>Login</Button>
</Col>
</Row>
</form>
</Grid>
)
module.exports = LoginForm
| true | React = require 'react'
Button = require 'react-bootstrap/lib/Button'
Col = require 'react-bootstrap/lib/Col'
Grid = require 'react-bootstrap/lib/Grid'
Input = require 'react-bootstrap/lib/Input'
Row = require 'react-bootstrap/lib/Row'
AuthService = require '../../services/AuthService.coffee'
LoginForm = React.createClass(
getInitialState: ->
userName: ""
password: ""
_valid: ->
if (!this.state.userName || !this.state.password)
return false
if (this.state.userName.length == 0 || this.state.password.length == 0)
return false
return true
_handleChange: (changeEvent) ->
if (changeEvent.target.id == "userName")
this.setState({userName: changeEvent.target.value})
else if (changeEvent.target.id == "password")
this.setState({password: changeEvent.target.value})
_handleSubmit: (submitEvent) ->
submitEvent.preventDefault()
AuthService.loginUser(this.state.userName, this.state.password)
render: ->
<Grid>
<form>
<Row>
<Col xs={6} xsOffset={3}>
<Input
label="Username"
id="userName"
type="text"
value={this.state.userName}
onChange={this._handleChange}
/>
<Input
label="PI:PASSWORD:<PASSWORD>END_PI"
id="password"
type="password"
value={this.state.password}
onChange={this._handleChange}
/>
<Button bsStyle="success" type="submit" disabled={!this._valid()} onClick={this._handleSubmit}>Login</Button>
</Col>
</Row>
</form>
</Grid>
)
module.exports = LoginForm
|
[
{
"context": "#\n# batman.node.coffee\n# batman.js\n#\n# Created by Nick Small\n# Copyright 2011, Shopify\n#\n\n# Include this file ",
"end": 60,
"score": 0.9994186758995056,
"start": 50,
"tag": "NAME",
"value": "Nick Small"
},
{
"context": "}\n\n # Set auth if its given\n auth ... | src/batman.node.coffee | nickjs/batman | 1 | #
# batman.node.coffee
# batman.js
#
# Created by Nick Small
# Copyright 2011, Shopify
#
# Include this file if you plan to use batman
# with node.js.
url = require 'url'
querystring = require 'querystring'
{Batman} = require './batman'
Batman.Request::getModule = (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
else
throw "Unrecognized request protocol #{protocol}"
Batman.Request::send = (data) ->
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
path += querystring.stringify Batman.mixin({}, requestURL.query, @get 'data')
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: {}
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if options.method in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
# Join the array and set it as the response
data = data.join()
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@success data
else
request.request = @
@error request
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
request.setHeader("Authorization", new Buffer(auth).toString('base64'))
if @get 'method' is 'POST'
request.write JSON.stringify(@get 'data')
request.end()
request.on 'error', (e) ->
@set 'response', error
@error error
request
exports.Batman = Batman
| 28118 | #
# batman.node.coffee
# batman.js
#
# Created by <NAME>
# Copyright 2011, Shopify
#
# Include this file if you plan to use batman
# with node.js.
url = require 'url'
querystring = require 'querystring'
{Batman} = require './batman'
Batman.Request::getModule = (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
else
throw "Unrecognized request protocol #{protocol}"
Batman.Request::send = (data) ->
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
path += querystring.stringify Batman.mixin({}, requestURL.query, @get 'data')
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: {}
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if options.method in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
# Join the array and set it as the response
data = data.join()
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@success data
else
request.request = @
@error request
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
request.setHeader("Authorization", new Buffer(auth).toString('base64'))
if @get 'method' is 'POST'
request.write JSON.stringify(@get 'data')
request.end()
request.on 'error', (e) ->
@set 'response', error
@error error
request
exports.Batman = Batman
| true | #
# batman.node.coffee
# batman.js
#
# Created by PI:NAME:<NAME>END_PI
# Copyright 2011, Shopify
#
# Include this file if you plan to use batman
# with node.js.
url = require 'url'
querystring = require 'querystring'
{Batman} = require './batman'
Batman.Request::getModule = (protocol) ->
requestModule = switch protocol
when 'http:', 'https:'
require protocol.slice(0,-1)
else
throw "Unrecognized request protocol #{protocol}"
Batman.Request::send = (data) ->
requestURL = url.parse(@get 'url', true)
protocol = requestURL.protocol
# Figure out which module to use
requestModule = @getModule(protocol)
path = requestURL.pathname
if @get('method') is 'GET'
path += querystring.stringify Batman.mixin({}, requestURL.query, @get 'data')
# Make the request and grab the ClientRequest object
options =
path: path
method: @get 'method'
port: requestURL.port
host: requestURL.hostname
headers: {}
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
options.headers["Authorization"] = "Basic #{new Buffer(auth).toString('base64')}"
if options.method in ["PUT", "POST"]
options.headers["Content-type"] = @get 'contentType'
request = requestModule.request options, (response) =>
# Buffer all the chunks of data into an array
data = []
response.on 'data', (d) ->
data.push d
response.on 'end', () =>
# Join the array and set it as the response
data = data.join()
@set 'response', data
# Dispatch the appropriate event based on the status code
status = @set 'status', response.statusCode
if (status >= 200 and status < 300) or status is 304
@success data
else
request.request = @
@error request
# Set auth if its given
auth = if @get 'username'
"#{@get 'username'}:#{@get 'password'}"
else if requestURL.auth
requestURL.auth
if auth
request.setHeader("Authorization", new Buffer(auth).toString('base64'))
if @get 'method' is 'POST'
request.write JSON.stringify(@get 'data')
request.end()
request.on 'error', (e) ->
@set 'response', error
@error error
request
exports.Batman = Batman
|
[
{
"context": "testWrongPassword = \"Wrongkode12\"\n\nmodule.exports =\n tags: ['LoginPage']\n\n 'Re",
"end": 32,
"score": 0.9986826181411743,
"start": 21,
"tag": "PASSWORD",
"value": "Wrongkode12"
},
{
"context": "assword)\n .setValue(\".repeat-password\", testWrongPas... | Votiee/VotieeFrontend/tests/src/tests/LoginPageTests.coffee | Rotvig/Votiee | 0 | testWrongPassword = "Wrongkode12"
module.exports =
tags: ['LoginPage']
'Register New User with wrong password confirmation': (client) ->
client
.setup()
.click(".account-button")
.waitForElementPresent(".login-page")
.click(".toggle-buttons .register")
.waitForElementPresent(".register-part")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".write-password", client.globals.testPassword)
.setValue(".repeat-password", testWrongPassword)
.click(".register-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Register New User': (client) ->
client
.clearValue(".repeat-password")
.setValue(".repeat-password", client.globals.testPassword)
.click(".register-button")
.waitForStateReady()
.assert.urlContains("menu-page")
'Log in with wrong password (after loggin out)': (client) ->
client
.click(".logout-button")
.waitForElementPresent(".front-page")
.click(".account-button")
.waitForElementPresent(".login-page")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".password-input", testWrongPassword)
.click(".login-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Log in with existing user': (client) ->
client
.clearValue(".password-input")
.setValue(".password-input", client.globals.testPassword)
.click(".login-button")
.waitForStateReady()
.assert.urlContains("menu-page")
.end() | 48263 | testWrongPassword = "<PASSWORD>"
module.exports =
tags: ['LoginPage']
'Register New User with wrong password confirmation': (client) ->
client
.setup()
.click(".account-button")
.waitForElementPresent(".login-page")
.click(".toggle-buttons .register")
.waitForElementPresent(".register-part")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".write-password", client.globals.testPassword)
.setValue(".repeat-password", <PASSWORD>)
.click(".register-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Register New User': (client) ->
client
.clearValue(".repeat-password")
.setValue(".repeat-password", client.globals.testPassword)
.click(".register-button")
.waitForStateReady()
.assert.urlContains("menu-page")
'Log in with wrong password (after loggin out)': (client) ->
client
.click(".logout-button")
.waitForElementPresent(".front-page")
.click(".account-button")
.waitForElementPresent(".login-page")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".password-input", <PASSWORD>)
.click(".login-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Log in with existing user': (client) ->
client
.clearValue(".password-input")
.setValue(".password-input", client.globals.testPassword)
.click(".login-button")
.waitForStateReady()
.assert.urlContains("menu-page")
.end() | true | testWrongPassword = "PI:PASSWORD:<PASSWORD>END_PI"
module.exports =
tags: ['LoginPage']
'Register New User with wrong password confirmation': (client) ->
client
.setup()
.click(".account-button")
.waitForElementPresent(".login-page")
.click(".toggle-buttons .register")
.waitForElementPresent(".register-part")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".write-password", client.globals.testPassword)
.setValue(".repeat-password", PI:PASSWORD:<PASSWORD>END_PI)
.click(".register-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Register New User': (client) ->
client
.clearValue(".repeat-password")
.setValue(".repeat-password", client.globals.testPassword)
.click(".register-button")
.waitForStateReady()
.assert.urlContains("menu-page")
'Log in with wrong password (after loggin out)': (client) ->
client
.click(".logout-button")
.waitForElementPresent(".front-page")
.click(".account-button")
.waitForElementPresent(".login-page")
.assert.elementNotPresent(".error-message")
.setValue(".email-input", client.globals.loginTestMail)
.setValue(".password-input", PI:PASSWORD:<PASSWORD>END_PI)
.click(".login-button")
.waitForStateReady()
.assert.elementPresent(".error-message")
'Log in with existing user': (client) ->
client
.clearValue(".password-input")
.setValue(".password-input", client.globals.testPassword)
.click(".login-button")
.waitForStateReady()
.assert.urlContains("menu-page")
.end() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.