Web Dev Solutions

Catalin Mititiuc

aboutsummaryrefslogtreecommitdiff
blob: 13cca8be591384a558ebb13ebc25808211c0b4e6 (plain)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import * as esbuild from 'esbuild';
import * as fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import jsdom from 'jsdom';

const { JSDOM } = jsdom;
const __dirname = path.dirname(new URL(import.meta.url).pathname);

const colors = {
  reset: '\x1b[0m',
  dim: '\x1b[2m',
  bright: '\x1b[1m',
  normal: '\x1b[22m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
};

const mime = {
  '.svg': 'image/svg+xml; charset=utf-8',
  '.png': 'image/png',
  '.jpg': 'image/jpeg',
  '.css': 'text/css; charset=utf-8',
  '.html': 'text/html; charset=utf-8',
};

const importSvg = {
  name: 'importSvg',
  setup(build) {
    const regex = new RegExp(/\.svg$/);

    build.onResolve({ filter: /\*\.svg$/ }, args => {
      console.log('onresolve', args);

      return {
        path: path.join('public', 'assets', args.path),
        namespace: 'svg-stub'
      }
    });

    build.onLoad({ filter: /\.svg$/, namespace: 'svg-stub' }, async (args) => {
      console.log('onload', args);

      const svgs = fs.readdirSync(path.resolve(path.dirname(args.path))).filter(fn => regex.test(fn));;

      console.log(svgs);

      console.log('resolved path', path.join(path.dirname(args.path), 'mapsheets.svg'));
      console.log('cwd', process.cwd());

      // const contents = `import mapsheets from ./${path.join(path.dirname(args.path), 'mapsheets.svg')};
      //   console.log('mapsheets', mapsheets);
      //   export default mapsheets;`;

      // const contents = `
      //   import svg from '/usr/src/app/public/assets/images/scenario-side_show.svg';
      //   export default svg;
      // `;

      // const contents = `
      //   import svg from '/usr/src/app/public/assets/images/scenario-side_show.svg';
      //   export default svg;
      // `;

      // const contents = `
      //   export { default as scenario_sideShow } from '/usr/src/app/public/assets/images/scenario-side_show.svg';
      //   export { default as mapsheets } from '/usr/src/app/public/assets/images/mapsheets.svg';
      // `;

      const contents = `
        // export { default as countorLines } from './contour-lines.svg';
        export { default as mapsheets } from './mapsheets.svg';
      `;

      console.log('resolveDir', path.dirname(args.path));
      console.log('contents', contents);

      return {
        contents: contents,
        resolveDir: path.dirname(args.path) //'./public/assets/images'
      }
    });

    // build.onLoad({ filter: /.*/, namespace: 'svg-stub' }, async (args) => ({
    //   contents: `import svg from ${JSON.stringify(args.path)}
    //     export default (imports) =>
    //       WebAssembly.instantiate(wasm, imports).then(
    //         result => result.instance.exports)`,
    // }));
  }
};

const svgUseCacheBust = {
  name: 'svgUseCacheBust',
  setup(build) {
    const regex = new RegExp('mapsheets\..+\.svg');

    build.onStart(() => {
      console.log("BUILD START");

      // const version = Date.now();
      // const file = fs.readFileSync('./src/scenario-side_show.svg', { encoding: 'utf-8' });
      // const newFile = file.replaceAll('%%VERSION%%', version);
      // fs.writeFileSync('./public/assets/images/scenario-side_show.svg', newFile);
      // const files = fs.readdirSync('./public/assets/images').filter(fn => regex.test(fn));
      // files.forEach(fn => fs.unlinkSync(`./public/assets/images/${fn}`));
      // fs.copyFileSync('./public/assets/images/mapsheets.svg', `./public/assets/images/mapsheets.${version}.svg`);
    })
  }
};

const resolveImportedSvg = {
  name: 'resolveImportedSvg',
  setup(build) {
    build.onStart(() => {
      console.log("BUILD STARTED");
    });

    build.onResolve({ filter: /\.svg$/ }, args => {
      return {
        path: path.resolve('public', args.path),
      };
    });

    build.onLoad({ filter: /\.svg$/ }, async (args) => {
      const document = (await JSDOM.fromFile(args.path)).window.document;
      const externalResourceUseEls = Array.from(document.querySelectorAll('use[href*=".svg"'));
      const readFiles = {};

      const files = [...new Set([...externalResourceUseEls.map(el =>
        el.getAttributeNS(null, 'href').match(/.+\.svg/).at(0)
      )])];

      await Promise.all(files.map((filename) =>
        JSDOM
          .fromFile(path.join(path.dirname(args.path), filename))
          .then(dom => readFiles[filename] = dom.window.document)
      ));

      const refs = {};

      externalResourceUseEls.forEach(el => {
        const href = el.getAttributeNS(null, 'href');
        const [filename] = href.match(/.+\.svg/);
        const fragId = href.split('.svg').pop();
        const frag = readFiles[filename].querySelector(fragId);

        if (frag) {
          frag.querySelectorAll('use').forEach(el =>
            (refs[filename] ??= []).push(el.getAttributeNS(null, 'href'))
          );

          (refs[filename] ??= []).push(fragId);
          el.setAttributeNS(null, 'href', fragId);
        }
      });

      Object.keys(refs).forEach(filename => {
        const refsQuery = [...new Set([...refs[filename]])].join(', ');
        const refNodes = readFiles[filename].querySelectorAll(refsQuery);
        const defs = document.querySelector('defs');
        refNodes.forEach(n => defs.appendChild(n));
      });

      return {
        contents: `<?xml version="1.0" standalone="no"?>\n${document.querySelector('svg').outerHTML}`,
        loader: 'file',
        watchFiles: Object.keys(readFiles).map(filename => path.join(path.dirname(args.path), filename))
      }
    });
  }
}

const ctx = await esbuild.context({
  entryPoints: ['src/index.js', 'src/soldier_record_block.js', 'src/map.js'],
  bundle: true,
  outdir: 'build',
  plugins: [resolveImportedSvg],
  loader: {
    '.svg': 'file'
  },
  assetNames: 'assets/images/[name]-[hash]',
});

await ctx.watch();

const { host, port } = await ctx.serve({
  servedir: 'build',
  port: 3000,
  // onRequest: function({ remoteAddress, method, path, status, timeInMS }) {
  //   let statusColor = colors.red;

  //   if (status >= 200 && status <= 299) {
  //     statusColor = colors.green;
  //   } else if (status >= 300 && status <= 399) {
  //     statusColor = colors.yellow;
  //   }

  //   console.log(`${colors.dim}${remoteAddress} - "${method} ${path}" ${colors.normal}${statusColor}${status}${colors.reset}${colors.dim} [${timeInMS}ms]${colors.reset}`);
  // },
});

http.createServer((req, res) => {
  const options = {
    hostname: host,
    port: port,
    path: req.url,
    method: req.method,
    headers: req.headers,
  }

  const filename = req.url && req.url !== '/' ? req.url : 'index.html';
  const filepath = path.join(__dirname, 'public', filename);

  if (fs.existsSync(filepath)) {
    const readStream = fs.createReadStream(filepath, { autoClose: true });

    readStream.on('ready', () => {
      const type = mime[path.parse(filepath).ext] || 'application/octet-stream';
      console.log(`${req.method} ${req.url} => 200 ${type}`);
      res.writeHead(200, { 'content-type': type });
      readStream.pipe(res, { end: true });
    });

    readStream.on('error', err => {
      console.log(`${req.method} ${req.url} => 500 ${filepath} ${err.name}`);
      res.writeHead(500, err.name);
      res.end(JSON.stringify(err));
    });
  } else {
    const proxyReq = http.request(options, proxyRes => {
      const type = proxyRes.headers['content-type'];
      console.log(`${req.method} ${req.url} => ${proxyRes.statusCode} ${type} via esbuild`);
      res.writeHead(proxyRes.statusCode, { 'content-type': type });
      proxyRes.pipe(res);
    });

    req.pipe(proxyReq, { end: true });
  }
}).listen(8080);