tern.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. // Glue code between CodeMirror and Tern.
  2. //
  3. // Create a CodeMirror.TernServer to wrap an actual Tern server,
  4. // register open documents (CodeMirror.Doc instances) with it, and
  5. // call its methods to activate the assisting functions that Tern
  6. // provides.
  7. //
  8. // Options supported (all optional):
  9. // * defs: An array of JSON definition data structures.
  10. // * plugins: An object mapping plugin names to configuration
  11. // options.
  12. // * getFile: A function(name, c) that can be used to access files in
  13. // the project that haven't been loaded yet. Simply do c(null) to
  14. // indicate that a file is not available.
  15. // * fileFilter: A function(value, docName, doc) that will be applied
  16. // to documents before passing them on to Tern.
  17. // * switchToDoc: A function(name) that should, when providing a
  18. // multi-file view, switch the view or focus to the named file.
  19. // * showError: A function(editor, message) that can be used to
  20. // override the way errors are displayed.
  21. // * completionTip: Customize the content in tooltips for completions.
  22. // Is passed a single argument—the completion's data as returned by
  23. // Tern—and may return a string, DOM node, or null to indicate that
  24. // no tip should be shown. By default the docstring is shown.
  25. // * typeTip: Like completionTip, but for the tooltips shown for type
  26. // queries.
  27. // * responseFilter: A function(doc, query, request, error, data) that
  28. // will be applied to the Tern responses before treating them
  29. //
  30. //
  31. // It is possible to run the Tern server in a web worker by specifying
  32. // these additional options:
  33. // * useWorker: Set to true to enable web worker mode. You'll probably
  34. // want to feature detect the actual value you use here, for example
  35. // !!window.Worker.
  36. // * workerScript: The main script of the worker. Point this to
  37. // wherever you are hosting worker.js from this directory.
  38. // * workerDeps: An array of paths pointing (relative to workerScript)
  39. // to the Acorn and Tern libraries and any Tern plugins you want to
  40. // load. Or, if you minified those into a single script and included
  41. // them in the workerScript, simply leave this undefined.
  42. (function() {
  43. "use strict";
  44. // declare global: tern
  45. CodeMirror.TernServer = function(options) {
  46. var self = this;
  47. this.options = options || {};
  48. var plugins = this.options.plugins || (this.options.plugins = {});
  49. if (!plugins.doc_comment) plugins.doc_comment = true;
  50. if (this.options.useWorker) {
  51. this.server = new WorkerServer(this);
  52. } else {
  53. this.server = new tern.Server({
  54. getFile: function(name, c) { return getFile(self, name, c); },
  55. async: true,
  56. defs: this.options.defs || [],
  57. plugins: plugins
  58. });
  59. }
  60. this.docs = Object.create(null);
  61. this.trackChange = function(doc, change) { trackChange(self, doc, change); };
  62. this.cachedArgHints = null;
  63. this.activeArgHints = null;
  64. this.jumpStack = [];
  65. };
  66. CodeMirror.TernServer.prototype = {
  67. addDoc: function(name, doc) {
  68. var data = {doc: doc, name: name, changed: null};
  69. this.server.addFile(name, docValue(this, data));
  70. CodeMirror.on(doc, "change", this.trackChange);
  71. return this.docs[name] = data;
  72. },
  73. delDoc: function(name) {
  74. var found = this.docs[name];
  75. if (!found) return;
  76. CodeMirror.off(found.doc, "change", this.trackChange);
  77. delete this.docs[name];
  78. this.server.delFile(name);
  79. },
  80. hideDoc: function(name) {
  81. closeArgHints(this);
  82. var found = this.docs[name];
  83. if (found && found.changed) sendDoc(this, found);
  84. },
  85. complete: function(cm) {
  86. var self = this;
  87. CodeMirror.showHint(cm, function(cm, c) { return hint(self, cm, c); }, {async: true});
  88. },
  89. getHint: function(cm, c) { return hint(this, cm, c); },
  90. showType: function(cm) { showType(this, cm); },
  91. updateArgHints: function(cm) { updateArgHints(this, cm); },
  92. jumpToDef: function(cm) { jumpToDef(this, cm); },
  93. jumpBack: function(cm) { jumpBack(this, cm); },
  94. rename: function(cm) { rename(this, cm); },
  95. request: function (cm, query, c) {
  96. var self = this;
  97. var doc = findDoc(this, cm.getDoc());
  98. var request = buildRequest(this, doc, query);
  99. this.server.request(request, function (error, data) {
  100. if (!error && self.options.responseFilter)
  101. data = self.options.responseFilter(doc, query, request, error, data);
  102. c(error, data);
  103. });
  104. }
  105. };
  106. var Pos = CodeMirror.Pos;
  107. var cls = "CodeMirror-Tern-";
  108. var bigDoc = 250;
  109. function getFile(ts, name, c) {
  110. var buf = ts.docs[name];
  111. if (buf)
  112. c(docValue(ts, buf));
  113. else if (ts.options.getFile)
  114. ts.options.getFile(name, c);
  115. else
  116. c(null);
  117. }
  118. function findDoc(ts, doc, name) {
  119. for (var n in ts.docs) {
  120. var cur = ts.docs[n];
  121. if (cur.doc == doc) return cur;
  122. }
  123. if (!name) for (var i = 0;; ++i) {
  124. n = "[doc" + (i || "") + "]";
  125. if (!ts.docs[n]) { name = n; break; }
  126. }
  127. return ts.addDoc(name, doc);
  128. }
  129. function trackChange(ts, doc, change) {
  130. var data = findDoc(ts, doc);
  131. var argHints = ts.cachedArgHints;
  132. if (argHints && argHints.doc == doc && cmpPos(argHints.start, change.to) <= 0)
  133. ts.cachedArgHints = null;
  134. var changed = data.changed;
  135. if (changed == null)
  136. data.changed = changed = {from: change.from.line, to: change.from.line};
  137. var end = change.from.line + (change.text.length - 1);
  138. if (change.from.line < changed.to) changed.to = changed.to - (change.to.line - end);
  139. if (end >= changed.to) changed.to = end + 1;
  140. if (changed.from > change.from.line) changed.from = change.from.line;
  141. if (doc.lineCount() > bigDoc && change.to - changed.from > 100) setTimeout(function() {
  142. if (data.changed && data.changed.to - data.changed.from > 100) sendDoc(ts, data);
  143. }, 200);
  144. }
  145. function sendDoc(ts, doc) {
  146. ts.server.request({files: [{type: "full", name: doc.name, text: docValue(ts, doc)}]}, function(error) {
  147. if (error) console.error(error);
  148. else doc.changed = null;
  149. });
  150. }
  151. // Completion
  152. function hint(ts, cm, c) {
  153. ts.request(cm, {type: "completions", types: true, docs: true, urls: true}, function(error, data) {
  154. if (error) return showError(ts, cm, error);
  155. var completions = [], after = "";
  156. var from = data.start, to = data.end;
  157. if (cm.getRange(Pos(from.line, from.ch - 2), from) == "[\"" &&
  158. cm.getRange(to, Pos(to.line, to.ch + 2)) != "\"]")
  159. after = "\"]";
  160. for (var i = 0; i < data.completions.length; ++i) {
  161. var completion = data.completions[i], className = typeToIcon(completion.type);
  162. if (data.guess) className += " " + cls + "guess";
  163. completions.push({text: completion.name + after,
  164. displayText: completion.name,
  165. className: className,
  166. data: completion});
  167. }
  168. var obj = {from: from, to: to, list: completions};
  169. var tooltip = null;
  170. CodeMirror.on(obj, "close", function() { remove(tooltip); });
  171. CodeMirror.on(obj, "update", function() { remove(tooltip); });
  172. CodeMirror.on(obj, "select", function(cur, node) {
  173. remove(tooltip);
  174. var content = ts.options.completionTip ? ts.options.completionTip(cur.data) : cur.data.doc;
  175. if (content) {
  176. tooltip = makeTooltip(node.parentNode.getBoundingClientRect().right + window.pageXOffset,
  177. node.getBoundingClientRect().top + window.pageYOffset, content);
  178. tooltip.className += " " + cls + "hint-doc";
  179. }
  180. });
  181. c(obj);
  182. });
  183. }
  184. function typeToIcon(type) {
  185. var suffix;
  186. if (type == "?") suffix = "unknown";
  187. else if (type == "number" || type == "string" || type == "bool") suffix = type;
  188. else if (/^fn\(/.test(type)) suffix = "fn";
  189. else if (/^\[/.test(type)) suffix = "array";
  190. else suffix = "object";
  191. return cls + "completion " + cls + "completion-" + suffix;
  192. }
  193. // Type queries
  194. function showType(ts, cm) {
  195. ts.request(cm, "type", function(error, data) {
  196. if (error) return showError(ts, cm, error);
  197. if (ts.options.typeTip) {
  198. var tip = ts.options.typeTip(data);
  199. } else {
  200. var tip = elt("span", null, elt("strong", null, data.type || "not found"));
  201. if (data.doc)
  202. tip.appendChild(document.createTextNode(" — " + data.doc));
  203. if (data.url) {
  204. tip.appendChild(document.createTextNode(" "));
  205. tip.appendChild(elt("a", null, "[docs]")).href = data.url;
  206. }
  207. }
  208. tempTooltip(cm, tip);
  209. });
  210. }
  211. // Maintaining argument hints
  212. function updateArgHints(ts, cm) {
  213. closeArgHints(ts);
  214. if (cm.somethingSelected()) return;
  215. var state = cm.getTokenAt(cm.getCursor()).state;
  216. var inner = CodeMirror.innerMode(cm.getMode(), state);
  217. if (inner.mode.name != "javascript") return;
  218. var lex = inner.state.lexical;
  219. if (lex.info != "call") return;
  220. var ch, pos = lex.pos || 0, tabSize = cm.getOption("tabSize");
  221. for (var line = cm.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
  222. var str = cm.getLine(line), extra = 0;
  223. for (var pos = 0;;) {
  224. var tab = str.indexOf("\t", pos);
  225. if (tab == -1) break;
  226. extra += tabSize - (tab + extra) % tabSize - 1;
  227. pos = tab + 1;
  228. }
  229. ch = lex.column - extra;
  230. if (str.charAt(ch) == "(") {found = true; break;}
  231. }
  232. if (!found) return;
  233. var start = Pos(line, ch);
  234. var cache = ts.cachedArgHints;
  235. if (cache && cache.doc == cm.getDoc() && cmpPos(start, cache.start) == 0)
  236. return showArgHints(ts, cm, pos);
  237. ts.request(cm, {type: "type", preferFunction: true, end: start}, function(error, data) {
  238. if (error || !data.type || !(/^fn\(/).test(data.type)) return;
  239. ts.cachedArgHints = {
  240. start: pos,
  241. type: parseFnType(data.type),
  242. name: data.exprName || data.name || "fn",
  243. guess: data.guess,
  244. doc: cm.getDoc()
  245. };
  246. showArgHints(ts, cm, pos);
  247. });
  248. }
  249. function showArgHints(ts, cm, pos) {
  250. closeArgHints(ts);
  251. var cache = ts.cachedArgHints, tp = cache.type;
  252. var tip = elt("span", cache.guess ? cls + "fhint-guess" : null,
  253. elt("span", cls + "fname", cache.name), "(");
  254. for (var i = 0; i < tp.args.length; ++i) {
  255. if (i) tip.appendChild(document.createTextNode(", "));
  256. var arg = tp.args[i];
  257. tip.appendChild(elt("span", cls + "farg" + (i == pos ? " " + cls + "farg-current" : ""), arg.name || "?"));
  258. if (arg.type != "?") {
  259. tip.appendChild(document.createTextNode(":\u00a0"));
  260. tip.appendChild(elt("span", cls + "type", arg.type));
  261. }
  262. }
  263. tip.appendChild(document.createTextNode(tp.rettype ? ") ->\u00a0" : ")"));
  264. if (tp.rettype) tip.appendChild(elt("span", cls + "type", tp.rettype));
  265. var place = cm.cursorCoords(null, "page");
  266. ts.activeArgHints = makeTooltip(place.right + 1, place.bottom, tip);
  267. }
  268. function parseFnType(text) {
  269. var args = [], pos = 3;
  270. function skipMatching(upto) {
  271. var depth = 0, start = pos;
  272. for (;;) {
  273. var next = text.charAt(pos);
  274. if (upto.test(next) && !depth) return text.slice(start, pos);
  275. if (/[{\[\(]/.test(next)) ++depth;
  276. else if (/[}\]\)]/.test(next)) --depth;
  277. ++pos;
  278. }
  279. }
  280. // Parse arguments
  281. if (text.charAt(pos) != ")") for (;;) {
  282. var name = text.slice(pos).match(/^([^, \(\[\{]+): /);
  283. if (name) {
  284. pos += name[0].length;
  285. name = name[1];
  286. }
  287. args.push({name: name, type: skipMatching(/[\),]/)});
  288. if (text.charAt(pos) == ")") break;
  289. pos += 2;
  290. }
  291. var rettype = text.slice(pos).match(/^\) -> (.*)$/);
  292. return {args: args, rettype: rettype && rettype[1]};
  293. }
  294. // Moving to the definition of something
  295. function jumpToDef(ts, cm) {
  296. function inner(varName) {
  297. var req = {type: "definition", variable: varName || null};
  298. var doc = findDoc(ts, cm.getDoc());
  299. ts.server.request(buildRequest(ts, doc, req), function(error, data) {
  300. if (error) return showError(ts, cm, error);
  301. if (!data.file && data.url) { window.open(data.url); return; }
  302. if (data.file) {
  303. var localDoc = ts.docs[data.file], found;
  304. if (localDoc && (found = findContext(localDoc.doc, data))) {
  305. ts.jumpStack.push({file: doc.name,
  306. start: cm.getCursor("from"),
  307. end: cm.getCursor("to")});
  308. moveTo(ts, doc, localDoc, found.start, found.end);
  309. return;
  310. }
  311. }
  312. showError(ts, cm, "Could not find a definition.");
  313. });
  314. }
  315. if (!atInterestingExpression(cm))
  316. dialog(cm, "Jump to variable", function(name) { if (name) inner(name); });
  317. else
  318. inner();
  319. }
  320. function jumpBack(ts, cm) {
  321. var pos = ts.jumpStack.pop(), doc = pos && ts.docs[pos.file];
  322. if (!doc) return;
  323. moveTo(ts, findDoc(ts, cm.getDoc()), doc, pos.start, pos.end);
  324. }
  325. function moveTo(ts, curDoc, doc, start, end) {
  326. doc.doc.setSelection(end, start);
  327. if (curDoc != doc && ts.options.switchToDoc) {
  328. closeArgHints(ts);
  329. ts.options.switchToDoc(doc.name);
  330. }
  331. }
  332. // The {line,ch} representation of positions makes this rather awkward.
  333. function findContext(doc, data) {
  334. var before = data.context.slice(0, data.contextOffset).split("\n");
  335. var startLine = data.start.line - (before.length - 1);
  336. var start = Pos(startLine, (before.length == 1 ? data.start.ch : doc.getLine(startLine).length) - before[0].length);
  337. var text = doc.getLine(startLine).slice(start.ch);
  338. for (var cur = startLine + 1; cur < doc.lineCount() && text.length < data.context.length; ++cur)
  339. text += "\n" + doc.getLine(cur);
  340. if (text.slice(0, data.context.length) == data.context) return data;
  341. var cursor = doc.getSearchCursor(data.context, 0, false);
  342. var nearest, nearestDist = Infinity;
  343. while (cursor.findNext()) {
  344. var from = cursor.from(), dist = Math.abs(from.line - start.line) * 10000;
  345. if (!dist) dist = Math.abs(from.ch - start.ch);
  346. if (dist < nearestDist) { nearest = from; nearestDist = dist; }
  347. }
  348. if (!nearest) return null;
  349. if (before.length == 1)
  350. nearest.ch += before[0].length;
  351. else
  352. nearest = Pos(nearest.line + (before.length - 1), before[before.length - 1].length);
  353. if (data.start.line == data.end.line)
  354. var end = Pos(nearest.line, nearest.ch + (data.end.ch - data.start.ch));
  355. else
  356. var end = Pos(nearest.line + (data.end.line - data.start.line), data.end.ch);
  357. return {start: nearest, end: end};
  358. }
  359. function atInterestingExpression(cm) {
  360. var pos = cm.getCursor("end"), tok = cm.getTokenAt(pos);
  361. if (tok.start < pos.ch && (tok.type == "comment" || tok.type == "string")) return false;
  362. return /\w/.test(cm.getLine(pos.line).slice(Math.max(pos.ch - 1, 0), pos.ch + 1));
  363. }
  364. // Variable renaming
  365. function rename(ts, cm) {
  366. var token = cm.getTokenAt(cm.getCursor());
  367. if (!/\w/.test(token.string)) showError(ts, cm, "Not at a variable");
  368. dialog(cm, "New name for " + token.string, function(newName) {
  369. ts.request(cm, {type: "rename", newName: newName, fullDocs: true}, function(error, data) {
  370. if (error) return showError(ts, cm, error);
  371. applyChanges(ts, data.changes);
  372. });
  373. });
  374. }
  375. var nextChangeOrig = 0;
  376. function applyChanges(ts, changes) {
  377. var perFile = Object.create(null);
  378. for (var i = 0; i < changes.length; ++i) {
  379. var ch = changes[i];
  380. (perFile[ch.file] || (perFile[ch.file] = [])).push(ch);
  381. }
  382. for (var file in perFile) {
  383. var known = ts.docs[file], chs = perFile[file];;
  384. if (!known) continue;
  385. chs.sort(function(a, b) { return cmpPos(b, a); });
  386. var origin = "*rename" + (++nextChangeOrig);
  387. for (var i = 0; i < chs.length; ++i) {
  388. var ch = chs[i];
  389. known.doc.replaceRange(ch.text, ch.start, ch.end, origin);
  390. }
  391. }
  392. }
  393. // Generic request-building helper
  394. function buildRequest(ts, doc, query) {
  395. var files = [], offsetLines = 0, allowFragments = !query.fullDocs;
  396. if (!allowFragments) delete query.fullDocs;
  397. if (typeof query == "string") query = {type: query};
  398. query.lineCharPositions = true;
  399. if (query.end == null) {
  400. query.end = doc.doc.getCursor("end");
  401. if (doc.doc.somethingSelected())
  402. query.start = doc.doc.getCursor("start");
  403. }
  404. var startPos = query.start || query.end;
  405. if (doc.changed) {
  406. if (doc.doc.lineCount() > bigDoc && allowFragments !== false &&
  407. doc.changed.to - doc.changed.from < 100 &&
  408. doc.changed.from <= startPos.line && doc.changed.to > query.end.line) {
  409. files.push(getFragmentAround(doc, startPos, query.end));
  410. query.file = "#0";
  411. var offsetLines = files[0].offsetLines;
  412. if (query.start != null) query.start = Pos(query.start.line - -offsetLines, query.start.ch);
  413. query.end = Pos(query.end.line - offsetLines, query.end.ch);
  414. } else {
  415. files.push({type: "full",
  416. name: doc.name,
  417. text: docValue(ts, doc)});
  418. query.file = doc.name;
  419. doc.changed = null;
  420. }
  421. } else {
  422. query.file = doc.name;
  423. }
  424. for (var name in ts.docs) {
  425. var cur = ts.docs[name];
  426. if (cur.changed && cur != doc) {
  427. files.push({type: "full", name: cur.name, text: docValue(ts, cur)});
  428. cur.changed = null;
  429. }
  430. }
  431. return {query: query, files: files};
  432. }
  433. function getFragmentAround(data, start, end) {
  434. var doc = data.doc;
  435. var minIndent = null, minLine = null, endLine, tabSize = 4;
  436. for (var p = start.line - 1, min = Math.max(0, p - 50); p >= min; --p) {
  437. var line = doc.getLine(p), fn = line.search(/\bfunction\b/);
  438. if (fn < 0) continue;
  439. var indent = CodeMirror.countColumn(line, null, tabSize);
  440. if (minIndent != null && minIndent <= indent) continue;
  441. minIndent = indent;
  442. minLine = p;
  443. }
  444. if (minLine == null) minLine = min;
  445. var max = Math.min(doc.lastLine(), end.line + 20);
  446. if (minIndent == null || minIndent == CodeMirror.countColumn(doc.getLine(start.line), null, tabSize))
  447. endLine = max;
  448. else for (endLine = end.line + 1; endLine < max; ++endLine) {
  449. var indent = CodeMirror.countColumn(doc.getLine(endLine), null, tabSize);
  450. if (indent <= minIndent) break;
  451. }
  452. var from = Pos(minLine, 0);
  453. return {type: "part",
  454. name: data.name,
  455. offsetLines: from.line,
  456. text: doc.getRange(from, Pos(endLine, 0))};
  457. }
  458. // Generic utilities
  459. function cmpPos(a, b) { return a.line - b.line || a.ch - b.ch; }
  460. function elt(tagname, cls /*, ... elts*/) {
  461. var e = document.createElement(tagname);
  462. if (cls) e.className = cls;
  463. for (var i = 2; i < arguments.length; ++i) {
  464. var elt = arguments[i];
  465. if (typeof elt == "string") elt = document.createTextNode(elt);
  466. e.appendChild(elt);
  467. }
  468. return e;
  469. }
  470. function dialog(cm, text, f) {
  471. if (cm.openDialog)
  472. cm.openDialog(text + ": <input type=text>", f);
  473. else
  474. f(prompt(text, ""));
  475. }
  476. // Tooltips
  477. function tempTooltip(cm, content) {
  478. var where = cm.cursorCoords();
  479. var tip = makeTooltip(where.right + 1, where.bottom, content);
  480. function clear() {
  481. if (!tip.parentNode) return;
  482. cm.off("cursorActivity", clear);
  483. fadeOut(tip);
  484. }
  485. setTimeout(clear, 1700);
  486. cm.on("cursorActivity", clear);
  487. }
  488. function makeTooltip(x, y, content) {
  489. var node = elt("div", cls + "tooltip", content);
  490. node.style.left = x + "px";
  491. node.style.top = y + "px";
  492. document.body.appendChild(node);
  493. return node;
  494. }
  495. function remove(node) {
  496. var p = node && node.parentNode;
  497. if (p) p.removeChild(node);
  498. }
  499. function fadeOut(tooltip) {
  500. tooltip.style.opacity = "0";
  501. setTimeout(function() { remove(tooltip); }, 1100);
  502. }
  503. function showError(ts, cm, msg) {
  504. if (ts.options.showError)
  505. ts.options.showError(cm, msg);
  506. else
  507. tempTooltip(cm, String(msg));
  508. }
  509. function closeArgHints(ts) {
  510. if (ts.activeArgHints) { remove(ts.activeArgHints); ts.activeArgHints = null; }
  511. }
  512. function docValue(ts, doc) {
  513. var val = doc.doc.getValue();
  514. if (ts.options.fileFilter) val = ts.options.fileFilter(val, doc.name, doc.doc);
  515. return val;
  516. }
  517. // Worker wrapper
  518. function WorkerServer(ts) {
  519. var worker = new Worker(ts.options.workerScript);
  520. worker.postMessage({type: "init",
  521. defs: ts.options.defs,
  522. plugins: ts.options.plugins,
  523. scripts: ts.options.workerDeps});
  524. var msgId = 0, pending = {};
  525. function send(data, c) {
  526. if (c) {
  527. data.id = ++msgId;
  528. pending[msgId] = c;
  529. }
  530. worker.postMessage(data);
  531. }
  532. worker.onmessage = function(e) {
  533. var data = e.data;
  534. if (data.type == "getFile") {
  535. getFile(ts, data.name, function(err, text) {
  536. send({type: "getFile", err: String(err), text: text, id: data.id});
  537. });
  538. } else if (data.type == "debug") {
  539. console.log(data.message);
  540. } else if (data.id && pending[data.id]) {
  541. pending[data.id](data.err, data.body);
  542. delete pending[data.id];
  543. }
  544. };
  545. worker.onerror = function(e) {
  546. for (var id in pending) pending[id](e);
  547. pending = {};
  548. };
  549. this.addFile = function(name, text) { send({type: "add", name: name, text: text}); };
  550. this.delFile = function(name) { send({type: "del", name: name}); };
  551. this.request = function(body, c) { send({type: "req", body: body}, c); };
  552. }
  553. })();