UNPKG

2.5 kBtext/coffeescriptView Raw
1Promise = require 'promiz'
2portal = require 'portal-gun'
3
4TRUSTED_DOMAIN = (process.env.TRUSTED_DOMAIN or 'clay.io')
5TWEET_LENGTH = 140
6VERSION = 'v1.0.2'
7
8config = new Promise (@resolve, @reject) -> null
9initHasBeenCalled = false
10
11Clay = (method, params, cb = -> null) ->
12 if typeof params is 'function'
13 cb = params
14 params = []
15
16 # Normalize params to an array if passed an object
17 if params? and Object::toString.call(params) is '[object Object]'
18 params = [params]
19
20 if params? and Object::toString.call(params) isnt '[object Array]'
21 return cb new Error 'Params must be an array'
22
23 methodRoot = method.split('.')[0]
24 method = method.slice method.indexOf('.') + 1
25
26 methods[methodRoot].apply 0, [method, params, cb]
27
28methods = {
29 version: (_, __, cb) ->
30 cb null, VERSION
31
32 init: (method, [options], cb) ->
33 (do ->
34 gameId = options.gameId
35 debug = Boolean options.debug
36
37 if debug
38 portal.up()
39 else
40 portal.up trusted: TRUSTED_DOMAIN, subdomains: true
41
42 unless typeof gameId is 'string' and /^[0-9]+$/.test gameId
43 return cb new Error 'Missing or invalid gameId'
44
45 initHasBeenCalled = true
46
47 portal.get 'auth.getStatus', {gameId}
48 .then (status) ->
49 # TODO: Token may be invalid
50 config.resolve
51 gameId: gameId
52 accessToken: status?.accessToken
53 .catch ->
54 config.resolve
55 gameId: gameId
56 accessToken: null
57 )
58 .then (x) ->
59 cb null, x
60 .catch cb
61
62 client: (method, params, cb) ->
63 if method is 'client'
64 return cb new Error 'Missing or invalid method'
65
66 (do ->
67 unless initHasBeenCalled
68 return Promise.reject new Error 'Must call Clay(\'init\') first'
69
70 return portal.get method, params
71 )
72 .then (x) -> cb null, x
73 .catch cb
74
75 register: (_, [{method, fn}]) ->
76 methods[method] = fn(config)
77
78}
79
80portal.register 'share.any', ({text} = {}) ->
81 unless typeof text is 'string'
82 throw new Error 'text parameter is missing or invalid'
83
84 if text.length > TWEET_LENGTH
85 throw new Error 'No valid share method available'
86
87 tweet = (text) ->
88 text = encodeURIComponent text.substr 0, TWEET_LENGTH
89 window.open "https://twitter.com/intent/tweet?text=#{text}"
90
91 return tweet(text)
92
93module.exports = Clay
94
95# Initialize, allowing time for synchronous registration of services
96window.setTimeout ->
97 q = window.Clay?.q or []
98
99 window.Clay = Clay
100 for call in q
101 Clay.apply 0, call