UNPKG

3.45 kBJavaScriptView Raw
1System.register(['@babel/template'], (function (exports) {
2 'use strict';
3 var templateBuilder;
4 return {
5 setters: [function (module) {
6 templateBuilder = module["default"];
7 }],
8 execute: (function () {
9
10 exports('default', reactRefreshPlugin);
11
12 function isAtom(t, callee) {
13 if (t.isIdentifier(callee) && atomFunctionNames.includes(callee.name)) {
14 return true;
15 }
16 if (t.isMemberExpression(callee)) {
17 const { property } = callee;
18 if (t.isIdentifier(property) && atomFunctionNames.includes(property.name)) {
19 return true;
20 }
21 }
22 return false;
23 }
24 const atomFunctionNames = [
25 "atom",
26 "atomFamily",
27 "atomWithDefault",
28 "atomWithObservable",
29 "atomWithReducer",
30 "atomWithReset",
31 "atomWithStorage",
32 "freezeAtom",
33 "loadable",
34 "selectAtom",
35 "splitAtom"
36 ];
37
38 function reactRefreshPlugin({
39 types: t
40 }) {
41 return {
42 pre({ opts }) {
43 if (!opts.filename) {
44 throw new Error("Filename must be available");
45 }
46 },
47 visitor: {
48 Program: {
49 exit(path) {
50 const jotaiAtomCache = templateBuilder(`
51 globalThis.jotaiAtomCache = globalThis.jotaiAtomCache || {
52 cache: new Map(),
53 get(name, inst) {
54 if (this.cache.has(name)) {
55 return this.cache.get(name)
56 }
57 this.cache.set(name, inst)
58 return inst
59 },
60 }`)();
61 path.unshiftContainer("body", jotaiAtomCache);
62 }
63 },
64 ExportDefaultDeclaration(nodePath, state) {
65 const { node } = nodePath;
66 if (t.isCallExpression(node.declaration) && isAtom(t, node.declaration.callee)) {
67 const filename = state.filename || "unknown";
68 const atomKey = `${filename}/defaultExport`;
69 const buildExport = templateBuilder(`export default globalThis.jotaiAtomCache.get(%%atomKey%%, %%atom%%)`);
70 const ast = buildExport({
71 atomKey: t.stringLiteral(atomKey),
72 atom: node.declaration
73 });
74 nodePath.replaceWith(ast);
75 }
76 },
77 VariableDeclarator(nodePath, state) {
78 var _a, _b;
79 if (t.isIdentifier(nodePath.node.id) && t.isCallExpression(nodePath.node.init) && isAtom(t, nodePath.node.init.callee) && (((_a = nodePath.parentPath.parentPath) == null ? void 0 : _a.isProgram()) || ((_b = nodePath.parentPath.parentPath) == null ? void 0 : _b.isExportNamedDeclaration()))) {
80 const filename = state.filename || "unknown";
81 const atomKey = `${filename}/${nodePath.node.id.name}`;
82 const buildAtomDeclaration = templateBuilder(`const %%atomIdentifier%% = globalThis.jotaiAtomCache.get(%%atomKey%%, %%atom%%)`);
83 const ast = buildAtomDeclaration({
84 atomIdentifier: t.identifier(nodePath.node.id.name),
85 atomKey: t.stringLiteral(atomKey),
86 atom: nodePath.node.init
87 });
88 nodePath.parentPath.replaceWith(ast);
89 }
90 }
91 }
92 };
93 }
94
95 })
96 };
97}));