aboutsummaryrefslogtreecommitdiff
path: root/lib/util.js
blob: 5bd5f1145366da8c96f5c08fd14c826a01c0b242 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
var pull = require('pull-stream')
var cat = require('pull-cat')
var h = require('hyperscript')
var b64url = require('base64-url')
var u = exports

u.ssbRefRegex = /((?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+)/g
u.ssbRefRegexOnly = /^(?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+$/
u.ssbRefEncRegex = /((?:ssb:\/\/)?(?:[@%&]|%26|%40|%25)(?:[A-Za-z0-9\/+]|%2[fF]|%2[bB]){43}(?:=|%3[dD])\.[\w\d]+)/g

u.isRef = function (str) {
  if (!str) return false
  u.ssbRefRegexOnly.lastIndex = 0
  return u.ssbRefRegexOnly.test(str)
}

u.readNext = function (fn) {
  var next
  return function (end, cb) {
    if (next) return next(end, cb)
    fn(function (err, _next) {
      if (err) return cb(err)
      next = _next
      next(null, cb)
    })
  }
}

u.pullReverse = function () {
  return function (read) {
    return u.readNext(function (cb) {
      pull(read, pull.collect(function (err, items) {
        cb(err, items && pull.values(items.reverse()))
      }))
    })
  }
}

u.toHTML = function (el) {
  if (!el) return ''
  if (typeof el === 'string' || Array.isArray(el)) {
    return h('div', el).innerHTML
  }
  var html = el.outerHTML || String(el)
  if (el.nodeName === 'html') html = '<!doctype html>' + html + '\n'
  return html
}

u.hyperwrap = function (fn) {
  var token = '__HYPERWRAP_' + Math.random() + '__'
  return function (read) {
    return u.readNext(function (cb) {
      fn(token, function (err, el) {
        if (err) return cb(err)
        var parts = u.toHTML(el).split(token)
        switch (parts.length) {
          case 0: return cb(null, pull.empty())
          case 1: return cb(null, pull.once(parts[0]))
          case 2: return cb(null,
            cat([pull.once(parts[0]), read, pull.once(parts[1])]))
          default: return cb(new Error('duplicate wrap'))
        }
      })
    })
  }
}

u.ifString = function (str) {
  if (typeof str === 'string') return str
}

u.ifNumber = function (num) {
  if (!isNaN(num)) return num
}

u.toLink = function (link) {
  return typeof link === 'string' ? {link: link} : link || null
}

u.linkDest = function (link) {
  return link && (u.ifString(link) || u.ifString(link.link))
}

u.toArray = function (x) {
  return x == null ? [] : Array.isArray(x) ? x : [x]
}

u.fromArray = function (arr) {
  return Array.isArray(arr) && arr.length === 1 ? arr[0] : arr
}

u.toLinkArray = function (x) {
  return u.toArray(x).map(u.toLink).filter(u.linkDest)
}

u.renderError = function(err) {
  return h('div.error',
    h('h3', err.name),
    h('pre', err.stack))
}

u.pullLength = function (cb) {
  var len = 0
  return pull.through(function (data) {
    len += data.length
  }, function (err) {
    cb(err, len)
  })
}

u.tryDecodeJSON = function (json) {
  try {
    return JSON.parse(json)
  } catch(e) {
    return null
  }
}

u.extractRefs = function (str) {
  var ids = []
  String(str).replace(u.ssbRefRegex, function (id) {
    ids.push(id)
  })
  return ids
}

u.extractFeedIds = function (str) {
  return u.extractRefs(str).filter(function (ref) {
    return ref[0] === '@'
  })
}

u.extractBlobIds = function (str) {
  return u.extractRefs(str).filter(function (ref) {
    return ref[0] === '&'
  })
}

u.isMsgReadable = function (msg) {
  var c = msg && msg.value && msg.value.content
  return typeof c === 'object' && c !== null
}

u.isMsgEncrypted = function (msg) {
  var value = msg && msg.value
  return value && (value.private || typeof value.content === 'string')
}

u.pullConcat = function (cb) {
  return pull.collect(function (err, bufs) {
    if (err) return cb(err)
    cb(null, Buffer.concat(bufs))
  })
}

u.customError = function (name) {
  return function (message) {
    var error = new Error(message)
    error.name = name
    error.stack = error.stack.replace(/^    at .*\n/m, '')
    return error
  }
}

u.escapeHTML = function (html) {
  if (!html) return ''
  return html.toString('utf8')
    .replace(/&/g, '&amp;')
    .replace(/"/g, '&quot;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/\n/g, '&#x0a;')
}

u.unescapeHTML = function (text) {
  if (typeof text !== 'string') return text
  return text.replace(/&amp;/g, '&')
    .replace(/&quot;/g, '"')
    .replace(/&#39;/g, '\'')
    .replace(/&gt;/g, '>')
    .replace(/&lt;/g, '<')
}

u.pullSlice = function (start, end) {
  if (end == null) end = Infinity
  var offset = 0
  return function (read) {
    return function (abort, cb) {
      if (abort) read(abort, cb)
      else if (offset >= end) read(true, function (err) {
        cb(err || true)
      })
      else if (offset < start) read(null, function next(err, data) {
        if (err) return cb(err)
        offset += data.length
        if (offset <= start) read(null, next)
        else if (offset < end) cb(null,
          data.slice(data.length - (offset - start)))
        else cb(null, data.slice(data.length - (offset - start),
          data.length - (offset - end)))
      })
      else read(null, function (err, data) {
        if (err) return cb(err)
        offset += data.length
        if (offset <= end) cb(null, data)
          else cb(null, data.slice(0, data.length - (offset - end)))
      })
    }
  }
}

u.mergeOpts = function (a, b) {
  var obj = {}, k
  for (k in a) {
    obj[k] = a[k]
  }
  for (k in b) {
    if (b[k] != null) obj[k] = b[k]
    else delete obj[k]
  }
  return obj
}

u.escapeId = function (id) {
  return b64url.escape(id)
}

u.unescapeId = function (str) {
  var m = /^(.)(.*)(\..*)$/.exec(str)
  if (!m) return b64url.unescape(str)
  return m[1] + b64url.unescape(m[2]) + m[3]
}

u.rows = function (str) {
  return String(str).split(/[^\n]{150}|\n/).length
}

u.token = function () {
  return '__' + Math.random().toString(36).substr(2) + '__'
}

u.unwrapP = function(html) {
  return String(html).replace(/^<p>(.*)<\/p>\s*$/, function ($0, $1) {
    return $1
  })
}

u.estimateMessageSize = function (content) {
  var draftMsg = {
    key: '%0000000000000000000000000000000000000000000=.sha256',
    value: {
      previous: '%0000000000000000000000000000000000000000000=.sha256',
      author: '@0000000000000000000000000000000000000000000=.ed25519',
      sequence: 10000,
      timestamp: 1000000000000,
      hash: 'sha256',
      content: content,
      signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000==.sig.ed25519'
    }
  }

  return JSON.stringify(draftMsg, null, 2).length
}