flux.js 2.1 KB

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