flux.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Experimental
  2. const flux = {};
  3. flux.ModelFactory = class {
  4. match(context) {
  5. const identifier = context.identifier;
  6. const extension = identifier.split('.').pop().toLowerCase();
  7. const stream = context.stream;
  8. if (stream && extension === 'bson') {
  9. context.type = 'flux.bson';
  10. }
  11. }
  12. async open(context) {
  13. let root = null;
  14. try {
  15. root = context.read('bson');
  16. } catch (error) {
  17. const message = error && error.message ? error.message : error.toString();
  18. throw new flux.Error(`File format is not Flux BSON (${message.replace(/\.$/, '')}).`);
  19. }
  20. const metadata = context.metadata('flux-metadata.json');
  21. const backref = (obj, root) => {
  22. if (Array.isArray(obj)) {
  23. for (let i = 0; i < obj.length; i++) {
  24. obj[i] = backref(obj[i], root);
  25. }
  26. } else if (obj === Object(obj)) {
  27. if (obj.tag == 'backref' && obj.ref) {
  28. if (!root._backrefs[obj.ref - 1]) {
  29. throw new flux.Error(`Invalid backref '${obj.ref}'.`);
  30. }
  31. obj = root._backrefs[obj.ref - 1];
  32. }
  33. for (const key of Object.keys(obj)) {
  34. if (obj !== root || key !== '_backrefs') {
  35. obj[key] = backref(obj[key], root);
  36. }
  37. }
  38. }
  39. return obj;
  40. };
  41. const obj = backref(root, root);
  42. const model = obj.model;
  43. if (!model) {
  44. throw new flux.Error('File does not contain Flux model.');
  45. }
  46. return new flux.Model(metadata, model);
  47. }
  48. };
  49. flux.Model = class {
  50. constructor(/* root */) {
  51. this._format = 'Flux';
  52. this._graphs = [];
  53. }
  54. get format() {
  55. return this._format;
  56. }
  57. get graphs() {
  58. return this._graphs;
  59. }
  60. };
  61. flux.Error = class extends Error {
  62. constructor(message) {
  63. super(message);
  64. this.name = 'Flux Error';
  65. }
  66. };
  67. export const ModelFactory = flux.ModelFactory;