-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNar.coffee
88 lines (71 loc) · 2.15 KB
/
Nar.coffee
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
if this["process"]?
JSZip = require('jszip')
Encoding = require('encoding-japanese')
WMDescript = require('ikagaka.wmdescript.js')
XMLHttpRequest = require('uupaa.nodeproxy.js')
else
JSZip = @JSZip
Encoding = @Encoding
WMDescript = @WMDescript
XMLHttpRequest = @XHRProxy
class Loader
loadFromBuffer: (buffer, callback)->
try
nar = new Nar(Loader.unzip(buffer))
catch err
return callback(err, null)
setTimeout ->
callback(null, nar)
loadFromURL: (src, callback)->
Loader.wget src, "arraybuffer", (err, buffer)=>
if !!err then return callback(err, null)
@loadFromBuffer(buffer, callback)
loadFromBlob: (blob, callback)->
url = URL.createObjectURL(blob)
@loadFromURL url, (err, nar)->
URL.revokeObjectURL(url)
callback(err, nar)
@unzip = (buffer)->
zip = new JSZip()
zip.load(buffer)
dic = {}
for filePath of zip.files
path = filePath.split("\\").join("/")
dic[path] = zip.files[filePath]
dic
@wget = (url, type, callback)->
xhr = new XMLHttpRequest()
xhr.addEventListener "load", ->
if 200 <= xhr.status && xhr.status < 300
if !!xhr.response.error
then callback(new Error(xhr.response.error.message), null)
else callback(null, xhr.response)
else callback(new Error(xhr.status), null)
xhr.open("GET", url)
xhr.responseType = type
xhr.send()
undefined
class Nar
constructor: (@directory) ->
if !@directory["install.txt"]
throw new Error("install.txt not found")
@install = Nar.parseDescript(Nar.convert(@directory["install.txt"].asArrayBuffer()))
grep: (regexp)->
Object.keys(@directory).filter (path)-> regexp.test(path)
getDirectory: (regexp)->
@grep(regexp)
.reduce(((dir, path, zip)=>
dir[path.replace(regexp, "")] = @directory[path].asArrayBuffer()
dir
), {})
@convert = (buffer)->
Encoding.codeToString(Encoding.convert(new Uint8Array(buffer), 'UNICODE', 'AUTO'))
@parseDescript = (text)->
WMDescript.parse(text)
@Loader = Loader
if module?.exports?
module.exports = Nar
else if @Ikagaka?
@Ikagaka.Nar = Nar
else
@Nar = Nar