blogger-plugin 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/vite.cjs CHANGED
@@ -1,15 +1,78 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/vite.ts
2
- var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs);
3
- var _path = require('path'); var _path2 = _interopRequireDefault(_path);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }// src/vite.ts
2
+ var _fs = require('fs'); var fs2 = _interopRequireWildcard(_fs); var fs = _interopRequireWildcard(_fs);
3
+ var _path = require('path'); var path2 = _interopRequireWildcard(_path); var path = _interopRequireWildcard(_path);
4
4
  var _stream = require('stream');
5
5
 
6
- // src/schema.ts
7
- var _zod = require('zod');
8
- var BloggerPluginOptionsSchema = _zod.z.object({
9
- entry: _zod.z.string().optional(),
10
- template: _zod.z.string().optional(),
11
- proxyBlog: _zod.z.url()
12
- }).strict();
6
+
7
+ var _vite = require('vite');
8
+
9
+ // src/cache.ts
10
+
11
+
12
+ var _tailwindcssiso = require('tailwindcss-iso');
13
+ var TAILWIND_CACHE_FILE = ".tailwind-classes.json";
14
+ function readFileContent(file) {
15
+ if (!fs.existsSync(file)) {
16
+ return null;
17
+ }
18
+ return fs.readFileSync(file, "utf-8");
19
+ }
20
+ function writeFileContent(file, content) {
21
+ const dirname2 = path.dirname(file);
22
+ if (!fs.existsSync(dirname2)) {
23
+ fs.mkdirSync(dirname2, { recursive: true });
24
+ }
25
+ const current = readFileContent(file);
26
+ if (current === null || content !== current) {
27
+ fs.writeFileSync(file, content, "utf8");
28
+ return true;
29
+ }
30
+ return false;
31
+ }
32
+ function removeFile(file) {
33
+ if (!fs.existsSync(file)) {
34
+ return false;
35
+ }
36
+ fs.rmSync(file);
37
+ return true;
38
+ }
39
+ function getTailwindCacheFile(root) {
40
+ return path.resolve(root, TAILWIND_CACHE_FILE);
41
+ }
42
+ function readTailwindCache(root) {
43
+ const content = readFileContent(getTailwindCacheFile(root));
44
+ if (!content) {
45
+ return null;
46
+ }
47
+ try {
48
+ return JSON.parse(content);
49
+ } catch (e) {
50
+ return null;
51
+ }
52
+ }
53
+ function writeTailwindCache(root, classes) {
54
+ const file = getTailwindCacheFile(root);
55
+ const content = JSON.stringify(classes, null, 2);
56
+ const updated = writeFileContent(file, content);
57
+ return { updated, content };
58
+ }
59
+ function clearTailwindCache(root) {
60
+ writeTailwindCache(root, []);
61
+ }
62
+ function removeTailwindCache(root) {
63
+ removeFile(getTailwindCacheFile(root));
64
+ }
65
+ async function updateTailwindCache(root, content) {
66
+ var _a;
67
+ const classes = await _tailwindcssiso.getTailwindClasses.call(void 0, {
68
+ content
69
+ });
70
+ writeTailwindCache(root, [.../* @__PURE__ */ new Set([...(_a = readTailwindCache(root)) != null ? _a : [], ...classes])]);
71
+ }
72
+
73
+ // src/constants.ts
74
+ var DEFAULT_ENTRIES = ["index.tsx", "index.ts", "index.jsx", "index.js", "main.tsx", "main.ts", "main.jsx", "main.js"];
75
+ var DEFAULT_TEMPLATES = ["template.xml", "theme.xml"];
13
76
 
14
77
  // src/utils.ts
15
78
  function escapeHtml(str) {
@@ -49,24 +112,20 @@ function toWebHeaders(httpHeaders) {
49
112
  }
50
113
  return headers;
51
114
  }
115
+ var BLOGGER_PLUGIN_HEAD_COMMENT_REGEX = /(<!--blogger-plugin:head:begin-->)([\s\S]*?)(<!--blogger-plugin:head:end-->)/;
116
+ var BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX = /(<b:comment><!--blogger-plugin:head:begin--><\/b:comment>)([\s\S]*?)(<b:comment><!--blogger-plugin:head:end--><\/b:comment>)/;
52
117
  function replaceBloggerPluginHeadComment(input, replacement, bcomment = false) {
53
118
  if (bcomment) {
54
- return input.replace(
55
- /<b:comment><!--blogger-plugin:head:begin--><\/b:comment>[\s\S]*?<b:comment><!--blogger-plugin:head:end--><\/b:comment>/,
56
- `<b:comment><!--blogger-plugin:head:begin--></b:comment>${replacement}<b:comment><!--blogger-plugin:head:end--></b:comment>`
57
- );
119
+ return input.replace(BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX, (_, start, _content, end) => `${start}${replacement}${end}`);
58
120
  }
59
- return input.replace(
60
- /<!--blogger-plugin:head:begin-->[\s\S]*?<!--blogger-plugin:head:end-->/,
61
- `<!--blogger-plugin:head:begin-->${replacement}<!--blogger-plugin:head:end-->`
62
- );
121
+ return input.replace(BLOGGER_PLUGIN_HEAD_COMMENT_REGEX, (_, start, _content, end) => `${start}${replacement}${end}`);
63
122
  }
64
123
  function getBloggerPluginHeadComment(input, bcomment = false) {
65
124
  var _a, _b, _c, _d;
66
125
  if (bcomment) {
67
- return (_b = (_a = input.match(/<b:comment><!--blogger-plugin:head:begin--><\/b:comment>([\s\S]*?)<b:comment><!--blogger-plugin:head:end--><\/b:comment>/)) == null ? void 0 : _a[1]) != null ? _b : null;
126
+ return (_b = (_a = input.match(BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX)) == null ? void 0 : _a[2]) != null ? _b : null;
68
127
  }
69
- return (_d = (_c = input.match(/<!--blogger-plugin:head:begin-->([\s\S]*?)<!--blogger-plugin:head:end-->/)) == null ? void 0 : _c[1]) != null ? _d : null;
128
+ return (_d = (_c = input.match(BLOGGER_PLUGIN_HEAD_COMMENT_REGEX)) == null ? void 0 : _c[2]) != null ? _d : null;
70
129
  }
71
130
  function replaceHost(input, oldHost, newHost, newProtocol) {
72
131
  return input.replace(
@@ -74,6 +133,21 @@ function replaceHost(input, oldHost, newHost, newProtocol) {
74
133
  (_, protocol, slash) => `${protocol ? newProtocol != null ? newProtocol : protocol : ""}${slash != null ? slash : ""}${newHost}`
75
134
  );
76
135
  }
136
+ function getRequestUrl(req) {
137
+ const xForwardedProtoHeader = req.headers["x-forwarded-proto"];
138
+ const xForwardedHostHeader = req.headers["x-forwarded-host"];
139
+ const hostHeader = req.headers.host;
140
+ const protocol = Array.isArray(xForwardedProtoHeader) ? xForwardedProtoHeader[0] : xForwardedProtoHeader != null ? xForwardedProtoHeader : req.socket && "encrypted" in req.socket && req.socket.encrypted ? "https" : "http";
141
+ const host = Array.isArray(xForwardedHostHeader) ? xForwardedHostHeader[0] : xForwardedHostHeader != null ? xForwardedHostHeader : hostHeader;
142
+ if (host && req.url) {
143
+ return new URL(`${protocol}://${host}${req.url}`);
144
+ }
145
+ return null;
146
+ }
147
+ var TAILWIND_PLUGIN_NAMES = /* @__PURE__ */ new Set(["@tailwindcss/vite:scan"]);
148
+ function isTailwindPlugin(plugin) {
149
+ return TAILWIND_PLUGIN_NAMES.has(plugin.name);
150
+ }
77
151
  function errorHtml(reqUrl) {
78
152
  return `<!DOCTYPE html>
79
153
  <html>
@@ -179,14 +253,94 @@ function errorHtml(reqUrl) {
179
253
  }
180
254
 
181
255
  // src/vite.ts
182
- var DEFAULT_ENTRIES = ["index.tsx", "index.ts", "index.jsx", "index.js", "main.tsx", "main.ts", "main.jsx", "main.js"];
183
- var DEFAULT_TEMPLATES = ["template.xml", "theme.xml"];
184
- function createPluginContext(userOptions) {
256
+ function createBloggerPluginContext(userOptions) {
257
+ if (typeof userOptions.entry !== "undefined" && typeof userOptions.entry !== "string") {
258
+ throw new Error("Option 'entry' must be a string");
259
+ }
260
+ if (typeof userOptions.template !== "undefined" && typeof userOptions.template !== "string") {
261
+ throw new Error("Option 'template' must be a string");
262
+ }
263
+ if (typeof userOptions.proxyBlog !== "string") {
264
+ throw new Error("Option 'proxyBlog' must be a string");
265
+ }
266
+ let proxyBlog;
267
+ try {
268
+ proxyBlog = new URL(userOptions.proxyBlog);
269
+ } catch (e) {
270
+ throw new Error("Option 'proxyBlog' must be a valid url");
271
+ }
185
272
  return {
186
- viteConfig: void 0,
273
+ root: process.cwd(),
187
274
  entry: void 0,
188
275
  template: void 0,
189
- options: BloggerPluginOptionsSchema.parse(userOptions)
276
+ proxyBlog,
277
+ viteConfig: void 0,
278
+ tailwind: false,
279
+ input: void 0,
280
+ html: void 0,
281
+ resolve(config) {
282
+ this.root = config.root ? path2.resolve(config.root) : this.root;
283
+ if (userOptions.entry) {
284
+ const providedPath = path2.resolve(this.root, userOptions.entry);
285
+ if (fs2.existsSync(providedPath)) {
286
+ this.entry = providedPath;
287
+ } else {
288
+ throw new Error(`Provided entry file does not exist: ${providedPath}`);
289
+ }
290
+ } else {
291
+ for (const file of DEFAULT_ENTRIES) {
292
+ const fullPath = path2.resolve(this.root, "src", file);
293
+ if (fs2.existsSync(fullPath)) {
294
+ this.entry = fullPath;
295
+ break;
296
+ }
297
+ }
298
+ if (!this.entry) {
299
+ throw new Error(
300
+ `No entry file found in "src".
301
+ Tried: ${DEFAULT_ENTRIES.map((c) => path2.join("src", c)).join(", ")}
302
+ \u{1F449} Tip: You can pass a custom entry like:
303
+ blogger({ entry: "src/my-entry.ts" })`
304
+ );
305
+ }
306
+ }
307
+ if (userOptions.template) {
308
+ const providedPath = path2.resolve(this.root, userOptions.template);
309
+ if (fs2.existsSync(providedPath)) {
310
+ this.template = providedPath;
311
+ } else {
312
+ throw new Error(`Provided template file does not exist: ${providedPath}`);
313
+ }
314
+ } else {
315
+ for (const file of DEFAULT_TEMPLATES) {
316
+ const fullPath = path2.resolve(this.root, "src", file);
317
+ if (fs2.existsSync(fullPath)) {
318
+ this.template = fullPath;
319
+ break;
320
+ }
321
+ }
322
+ if (!this.template) {
323
+ throw new Error(
324
+ `No template file found in "src".
325
+ Tried: ${DEFAULT_TEMPLATES.map((c) => path2.join("src", c)).join(", ")}
326
+ \u{1F449} Tip: You can pass a custom template like:
327
+ blogger({ template: "src/my-template.xml" })`
328
+ );
329
+ }
330
+ }
331
+ const name = path2.basename(this.entry, path2.extname(this.entry));
332
+ this.input = `virtual:blogger-plugin/${name}.html`;
333
+ this.html = `<!DOCTYPE html>
334
+ <html lang="en">
335
+ <head>
336
+ <!--head-->
337
+ <script type="module" src="/${path2.relative(this.root, this.entry).replace("\\", "/")}"></script>
338
+ </head>
339
+ <body>
340
+ <!--body-->
341
+ </body>
342
+ </html>`;
343
+ }
190
344
  };
191
345
  }
192
346
  function isViteDevServer(server) {
@@ -197,17 +351,18 @@ function useServerMiddleware(server, ctx, _this) {
197
351
  var _a;
198
352
  (_a = server.httpServer) == null ? void 0 : _a.once("listening", () => {
199
353
  setTimeout(() => {
200
- _this.info(`Unhandled requests will be proxied to ${ctx.options.proxyBlog}`);
354
+ _this.info(`Unhandled requests will be proxied to ${ctx.proxyBlog.origin}`);
201
355
  }, 0);
202
356
  });
203
357
  server.middlewares.use(async (req, res, next) => {
204
358
  var _a2;
205
- if (!req.url || !req.originalUrl) {
359
+ const url = getRequestUrl(req);
360
+ if (!req.url || !req.originalUrl || !url) {
206
361
  next();
207
362
  return;
208
363
  }
209
364
  const start = Date.now();
210
- const proxyUrl = new URL(req.originalUrl, ctx.options.proxyBlog);
365
+ const proxyUrl = new URL(`${ctx.proxyBlog.origin}${req.originalUrl}`);
211
366
  const viewParam = proxyUrl.searchParams.get("view");
212
367
  proxyUrl.searchParams.set("view", `${isViteDevServer(server) ? "-DevServer" : "-PreviewServer"}${(viewParam == null ? void 0 : viewParam.startsWith("-")) ? viewParam : ""}`);
213
368
  const proxyRequest = new Request(proxyUrl, {
@@ -229,28 +384,24 @@ function useServerMiddleware(server, ctx, _this) {
229
384
  return null;
230
385
  });
231
386
  if (proxyResponse) {
232
- const requestProtocol = `${req.headers["x-forwarded-proto"] || (req.socket && "encrypted" in req.socket && req.socket.encrypted ? "https" : "http")}:`;
233
- const requestHost = req.headers["x-forwarded-host"] || req.headers.host;
234
387
  res.statusCode = proxyResponse.status;
235
388
  res.statusMessage = proxyResponse.statusText;
236
389
  proxyResponse.headers.forEach((value, key) => {
237
390
  var _a3;
238
391
  if (key === "location") {
239
- const redirectUrl = new URL(value, requestHost ? `${requestProtocol}//${requestHost}${req.originalUrl}` : proxyUrl.href);
240
- if (requestHost && redirectUrl.host === requestHost || redirectUrl.host === proxyUrl.host) {
241
- if (requestHost && requestProtocol) {
242
- redirectUrl.host = requestHost;
243
- redirectUrl.protocol = requestProtocol;
244
- }
392
+ const redirectUrl = new URL(value, proxyUrl);
393
+ if (redirectUrl.host === url.host || redirectUrl.host === proxyUrl.host) {
394
+ redirectUrl.host = url.host;
395
+ redirectUrl.protocol = url.protocol;
245
396
  const viewParam2 = (_a3 = redirectUrl.searchParams.get("view")) == null ? void 0 : _a3.replaceAll("-DevServer", "").replaceAll("-PreviewServer", "");
246
397
  if (viewParam2) {
247
398
  redirectUrl.searchParams.set("view", viewParam2);
248
399
  } else {
249
400
  redirectUrl.searchParams.delete("view");
250
401
  }
251
- res.setHeader(key, redirectUrl.pathname + redirectUrl.search + redirectUrl.hash);
402
+ res.setHeader("location", redirectUrl.pathname + redirectUrl.search + redirectUrl.hash);
252
403
  } else {
253
- res.setHeader(key, redirectUrl.href);
404
+ res.setHeader("location", redirectUrl.href);
254
405
  }
255
406
  } else if (["content-type", "x-robots-tag", "date", "location"].includes(key)) {
256
407
  res.setHeader(key, value);
@@ -259,12 +410,13 @@ function useServerMiddleware(server, ctx, _this) {
259
410
  const contentType = proxyResponse.headers.get("content-type");
260
411
  if (contentType == null ? void 0 : contentType.startsWith("text/html")) {
261
412
  let htmlTemplateContent = await proxyResponse.text();
262
- if (requestHost && requestProtocol) {
263
- htmlTemplateContent = replaceHost(htmlTemplateContent, proxyUrl.host, requestHost, requestProtocol);
413
+ if (ctx.tailwind && isViteDevServer(server)) {
414
+ await updateTailwindCache(ctx.root, htmlTemplateContent);
264
415
  }
416
+ htmlTemplateContent = replaceHost(htmlTemplateContent, proxyUrl.host, url.host, url.protocol);
265
417
  if (isViteDevServer(server)) {
266
418
  const htmlTags = [];
267
- htmlTags.push(`<script src='/${escapeHtml(_path2.default.relative(ctx.viteConfig.root, ctx.entry))}' type='module'></script>`);
419
+ htmlTags.push(`<script type='module' src='/${escapeHtml(path2.relative(ctx.root, ctx.entry).replace("\\", "/"))}'></script>`);
268
420
  const template = await server.transformIndexHtml(
269
421
  req.url,
270
422
  replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTags.join("")),
@@ -272,14 +424,14 @@ function useServerMiddleware(server, ctx, _this) {
272
424
  );
273
425
  res.end(template);
274
426
  } else {
275
- const xmlTemplateContent = _fs2.default.readFileSync(_path2.default.resolve(ctx.viteConfig.build.outDir, "template.xml"), "utf8");
427
+ const xmlTemplateContent = fs2.readFileSync(path2.resolve(ctx.viteConfig.build.outDir, "template.xml"), "utf8");
276
428
  const htmlTagsStr = getBloggerPluginHeadComment(xmlTemplateContent, true);
277
429
  const template = replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTagsStr != null ? htmlTagsStr : "");
278
430
  res.end(template);
279
431
  }
280
- } else if (requestHost && requestProtocol && contentType && /^(text\/)|(application\/(.*\+)?(xml|json))/.test(contentType)) {
432
+ } else if (contentType && /^(text\/)|(application\/(.*\+)?(xml|json))/.test(contentType)) {
281
433
  const content = await proxyResponse.text();
282
- res.end(replaceHost(content, proxyUrl.host, requestHost, requestProtocol));
434
+ res.end(replaceHost(content, proxyUrl.host, url.host, url.protocol));
283
435
  } else {
284
436
  res.end(new Uint8Array(await proxyResponse.arrayBuffer()));
285
437
  }
@@ -295,94 +447,78 @@ function useServerMiddleware(server, ctx, _this) {
295
447
  };
296
448
  }
297
449
  function blogger(userOptions) {
298
- const ctx = createPluginContext(userOptions);
450
+ const ctx = createBloggerPluginContext(userOptions);
299
451
  return {
300
452
  name: "vite-plugin-blogger",
301
453
  config(config) {
302
- var _a, _b, _c;
303
- const root = config.root || process.cwd();
304
- let entry;
305
- let template;
306
- if (ctx.options.entry) {
307
- const providedPath = _path2.default.resolve(root, ctx.options.entry);
308
- if (_fs2.default.existsSync(providedPath)) {
309
- entry = providedPath;
310
- } else {
311
- this.error(`Provided entry file does not exist: ${providedPath}`);
312
- }
454
+ var _a;
455
+ ctx.resolve(config);
456
+ config.build || (config.build = {});
457
+ const major = Number(_vite.version.split(".")[0]);
458
+ const bundlerKey = major >= 8 ? "rolldownOptions" : "rollupOptions";
459
+ (_a = config.build)[bundlerKey] || (_a[bundlerKey] = {});
460
+ const bundlerOptions = config.build[bundlerKey];
461
+ if (Array.isArray(bundlerOptions.input)) {
462
+ bundlerOptions.input = [...bundlerOptions.input, ctx.input];
463
+ } else if (typeof bundlerOptions.input === "object" && bundlerOptions.input !== null) {
464
+ bundlerOptions.input[ctx.input] = ctx.input;
313
465
  } else {
314
- for (const file of DEFAULT_ENTRIES) {
315
- const fullPath = _path2.default.resolve(root, "src", file);
316
- if (_fs2.default.existsSync(fullPath)) {
317
- entry = fullPath;
318
- break;
319
- }
320
- }
321
- if (!entry) {
322
- this.error(
323
- `No entry file found in "src".
324
- Tried: ${DEFAULT_ENTRIES.map((c) => _path2.default.join("src", c)).join(", ")}
325
- \u{1F449} Tip: You can pass a custom entry like:
326
- blogger({ entry: "src/my-entry.ts" })`
327
- );
328
- }
466
+ bundlerOptions.input = ctx.input;
329
467
  }
330
- if (ctx.options.template) {
331
- const providedPath = _path2.default.resolve(root, ctx.options.template);
332
- if (_fs2.default.existsSync(providedPath)) {
333
- template = providedPath;
334
- } else {
335
- this.error(`Provided template file does not exist: ${providedPath}`);
468
+ const originalTemplateXmlContent = fs2.readFileSync(ctx.template, "utf8");
469
+ const modifiedTemplateXmlContent = replaceBloggerPluginHeadComment(replaceBloggerPluginHeadComment(originalTemplateXmlContent, ""), "", true);
470
+ fs2.writeFileSync(ctx.template, modifiedTemplateXmlContent, "utf-8");
471
+ },
472
+ configResolved(config) {
473
+ ctx.viteConfig = config;
474
+ ctx.tailwind = config.plugins.flat(Number.POSITIVE_INFINITY).some((plugin) => isTailwindPlugin(plugin));
475
+ if (ctx.tailwind) {
476
+ clearTailwindCache(ctx.root);
477
+ if (config.command === "build") {
478
+ updateTailwindCache(ctx.root, fs2.readFileSync(ctx.template, "utf-8"));
336
479
  }
337
480
  } else {
338
- for (const file of DEFAULT_TEMPLATES) {
339
- const fullPath = _path2.default.resolve(root, "src", file);
340
- if (_fs2.default.existsSync(fullPath)) {
341
- template = fullPath;
342
- break;
343
- }
344
- }
345
- if (!template) {
346
- this.error(
347
- `No template file found in "src".
348
- Tried: ${DEFAULT_TEMPLATES.map((c) => _path2.default.join("src", c)).join(", ")}
349
- \u{1F449} Tip: You can pass a custom template like:
350
- blogger({ template: "src/my-template.xml" })`
351
- );
352
- }
481
+ removeTailwindCache(ctx.root);
353
482
  }
354
- ctx.entry = entry;
355
- ctx.template = template;
356
- (_a = config.build) != null ? _a : config.build = {};
357
- (_c = (_b = config.build).rollupOptions) != null ? _c : _b.rollupOptions = {};
358
- config.build.rollupOptions.input = entry;
359
- const xmlTemplateContent = _fs2.default.readFileSync(ctx.template, "utf8");
360
- _fs2.default.writeFileSync(ctx.template, replaceBloggerPluginHeadComment(replaceBloggerPluginHeadComment(xmlTemplateContent, ""), "", true), {
361
- encoding: "utf8"
362
- });
363
483
  },
364
- configResolved(config) {
365
- ctx.viteConfig = config;
484
+ resolveId(source) {
485
+ if (source === ctx.input) {
486
+ return ctx.input;
487
+ }
366
488
  },
367
- generateBundle(_options, bundle) {
368
- var _a;
369
- for (const output of Object.values(bundle)) {
370
- if (output.type !== "chunk" || !output.isEntry) {
371
- continue;
372
- }
373
- const xmlTemplateContent = _fs2.default.readFileSync(ctx.template, "utf8");
374
- const htmlTags = [];
375
- (_a = output.viteMetadata) == null ? void 0 : _a.importedCss.forEach((value) => {
376
- htmlTags.push(`<link crossorigin='anonymous' href='${escapeHtml(ctx.viteConfig.base + value)}' rel='stylesheet'/>`);
377
- });
378
- htmlTags.push(`<script crossorigin='anonymous' src='${escapeHtml(ctx.viteConfig.base + output.fileName)}' type='module'></script>`);
379
- const template = replaceBloggerPluginHeadComment(xmlTemplateContent, htmlTags.join(""), true);
380
- this.emitFile({
381
- type: "asset",
382
- fileName: "template.xml",
383
- source: template
384
- });
385
- break;
489
+ load(id) {
490
+ if (id === ctx.input) {
491
+ return ctx.html;
492
+ }
493
+ },
494
+ writeBundle(_, bundle) {
495
+ if (!(ctx.input in bundle)) {
496
+ return;
497
+ }
498
+ const asset = bundle[ctx.input];
499
+ delete bundle[ctx.input];
500
+ if (asset.type !== "asset" || typeof asset.source !== "string") {
501
+ return;
502
+ }
503
+ const regex = /<!DOCTYPE html>\s*<html[^>]*>\s*<head>([\s\S]*?)<!--head-->([\s\S]*?)<\/head>\s*<body>([\s\S]*?)<!--body-->([\s\S]*?)<\/body>\s*<\/html>/i;
504
+ const match = asset.source.match(regex);
505
+ if (!match) {
506
+ return;
507
+ }
508
+ const afterHeadBegin = match[2];
509
+ const beforeHeadEnd = match[3];
510
+ const headContent = (afterHeadBegin + beforeHeadEnd).replace(/\b(crossorigin|defer|async|disabled|checked)\b(?!=)/g, (_2, $1) => `${$1}=""`).replace(/(\w+)=(".*?"|'.*?')/g, (_2, $1, $2) => {
511
+ const v = $2.slice(1, -1).replace(/&/g, "&amp;").replace(/'/g, "&apos;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
512
+ return `${$1}='${v}'`;
513
+ }).replace(/<(link|meta|img|br|hr|input)([^>]*?)>/gi, (_2, $1, $2) => `<${$1}${$2} />`).replace(/>\s+</g, "><").trim();
514
+ const originalTemplateXmlContent = fs2.readFileSync(ctx.template, "utf8");
515
+ const modifiedTemplateXmlContent = replaceBloggerPluginHeadComment(originalTemplateXmlContent, headContent, true);
516
+ fs2.writeFileSync(path2.resolve(ctx.viteConfig.build.outDir, "template.xml"), modifiedTemplateXmlContent);
517
+ },
518
+ closeBundle() {
519
+ const htmlDir = path2.resolve(ctx.viteConfig.build.outDir, "virtual:blogger-plugin");
520
+ if (fs2.existsSync(htmlDir)) {
521
+ fs2.rmSync(htmlDir, { recursive: true });
386
522
  }
387
523
  },
388
524
  configureServer(server) {
package/dist/vite.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/blogger-plugin/blogger-plugin/packages/blogger-plugin/dist/vite.cjs","../src/vite.ts","../src/schema.ts","../src/utils.ts"],"names":["_a"],"mappings":"AAAA;ACAA,gEAAe;AACf,wEAAiB;AACjB,gCAAyB;ADEzB;AACA;AELA,0BAAkB;AAEX,IAAM,2BAAA,EAA6B,MAAA,CACvC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC3B,QAAA,EAAU,MAAA,CAAE,MAAA,CAAO,CAAA,CAAE,QAAA,CAAS,CAAA;AAAA,EAC9B,SAAA,EAAW,MAAA,CAAE,GAAA,CAAI;AACnB,CAAC,CAAA,CACA,MAAA,CAAO,CAAA;AFIV;AACA;AGXO,SAAS,UAAA,CAAW,GAAA,EAAa;AACtC,EAAA,GAAA,CAAI,IAAA,IAAQ,EAAA,EAAI,OAAO,EAAA;AACvB,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,WAAA,EAAa,CAAC,EAAA,EAAA,GAAO;AACtC,IAAA,OAAA,CAAQ,EAAA,EAAI;AAAA,MACV,KAAK,GAAA;AACH,QAAA,OAAO,OAAA;AAAA,MACT,KAAK,GAAA;AACH,QAAA,OAAO,MAAA;AAAA,MACT,KAAK,GAAA;AACH,QAAA,OAAO,MAAA;AAAA,MACT,KAAK,GAAA;AACH,QAAA,OAAO,QAAA;AAAA,MACT,KAAK,GAAA;AACH,QAAA,OAAO,OAAA;AAAA,MACT,KAAK,GAAA;AACH,QAAA,OAAO,OAAA;AAAA,MACT,OAAA;AACE,QAAA,OAAO,EAAA;AAAA,IACX;AAAA,EACF,CAAC,CAAA;AACH;AAEO,SAAS,WAAA,CAAY,GAAA,EAAa;AACvC,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,qBAAA,EAA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B,IAAA;AACe,MAAA;AAC9C,IAAA;AACF,EAAA;AACF;ADgIoE;AACA;AACA","file":"/home/runner/work/blogger-plugin/blogger-plugin/packages/blogger-plugin/dist/vite.cjs","sourcesContent":[null,"import fs from 'node:fs';\nimport path from 'node:path';\nimport { Readable } from 'node:stream';\nimport type { MinimalPluginContextWithoutEnvironment, Plugin, PreviewServer, ResolvedConfig, ViteDevServer } from 'vite';\nimport { type BloggerPluginOptions, BloggerPluginOptionsSchema } from './schema';\nimport { errorHtml, escapeHtml, getBloggerPluginHeadComment, replaceBloggerPluginHeadComment, replaceHost, toWebHeaders } from './utils';\n\nconst DEFAULT_ENTRIES = ['index.tsx', 'index.ts', 'index.jsx', 'index.js', 'main.tsx', 'main.ts', 'main.jsx', 'main.js'];\nconst DEFAULT_TEMPLATES = ['template.xml', 'theme.xml'];\n\ninterface PluginContext {\n viteConfig: ResolvedConfig;\n entry: string;\n template: string;\n options: BloggerPluginOptions;\n}\n\nfunction createPluginContext(userOptions: BloggerPluginOptions): PluginContext {\n return {\n viteConfig: undefined as unknown as ResolvedConfig,\n entry: undefined as unknown as string,\n template: undefined as unknown as string,\n options: BloggerPluginOptionsSchema.parse(userOptions),\n };\n}\n\nfunction isViteDevServer(server: ViteDevServer | PreviewServer): server is ViteDevServer {\n return 'hot' in server && 'transformRequest' in server && 'transformIndexHtml' in server;\n}\n\nfunction useServerMiddleware(server: ViteDevServer | PreviewServer, ctx: PluginContext, _this: MinimalPluginContextWithoutEnvironment) {\n return () => {\n server.httpServer?.once('listening', () => {\n setTimeout(() => {\n _this.info(`Unhandled requests will be proxied to ${ctx.options.proxyBlog}`);\n }, 0);\n });\n\n server.middlewares.use(async (req, res, next) => {\n if (!req.url || !req.originalUrl) {\n next();\n return;\n }\n\n const start = Date.now();\n\n const proxyUrl = new URL(req.originalUrl, ctx.options.proxyBlog);\n\n const viewParam = proxyUrl.searchParams.get('view');\n proxyUrl.searchParams.set('view', `${isViteDevServer(server) ? '-DevServer' : '-PreviewServer'}${viewParam?.startsWith('-') ? viewParam : ''}`);\n\n const proxyRequest = new Request(proxyUrl, {\n method: req.method,\n headers: toWebHeaders(req.headers),\n body: ['GET', 'HEAD'].includes(req.method ?? '') ? undefined : Readable.toWeb(req),\n redirect: 'manual',\n });\n\n const proxyResponse = await fetch(proxyRequest).catch((error) => {\n if (error instanceof Error) {\n _this.warn({\n message: `${error.name}: ${error.message}`,\n cause: error.cause,\n stack: error.stack,\n });\n } else {\n _this.warn('Fetch failed');\n }\n return null;\n });\n\n if (proxyResponse) {\n const requestProtocol = `${(req.headers['x-forwarded-proto'] as string) || (req.socket && 'encrypted' in req.socket && req.socket.encrypted ? 'https' : 'http')}:`;\n const requestHost = (req.headers['x-forwarded-host'] as string) || req.headers.host;\n\n res.statusCode = proxyResponse.status;\n res.statusMessage = proxyResponse.statusText;\n\n proxyResponse.headers.forEach((value, key) => {\n if (key === 'location') {\n const redirectUrl = new URL(value, requestHost ? `${requestProtocol}//${requestHost}${req.originalUrl}` : proxyUrl.href);\n if ((requestHost && redirectUrl.host === requestHost) || redirectUrl.host === proxyUrl.host) {\n if (requestHost && requestProtocol) {\n redirectUrl.host = requestHost;\n redirectUrl.protocol = requestProtocol;\n }\n const viewParam = redirectUrl.searchParams.get('view')?.replaceAll('-DevServer', '').replaceAll('-PreviewServer', '');\n if (viewParam) {\n redirectUrl.searchParams.set('view', viewParam);\n } else {\n redirectUrl.searchParams.delete('view');\n }\n res.setHeader(key, redirectUrl.pathname + redirectUrl.search + redirectUrl.hash);\n } else {\n res.setHeader(key, redirectUrl.href);\n }\n } else if (['content-type', 'x-robots-tag', 'date', 'location'].includes(key)) {\n res.setHeader(key, value);\n }\n });\n\n const contentType = proxyResponse.headers.get('content-type');\n\n if (contentType?.startsWith('text/html')) {\n let htmlTemplateContent = await proxyResponse.text();\n\n if (requestHost && requestProtocol) {\n htmlTemplateContent = replaceHost(htmlTemplateContent, proxyUrl.host, requestHost, requestProtocol);\n }\n\n if (isViteDevServer(server)) {\n const htmlTags: string[] = [];\n\n htmlTags.push(`<script src='/${escapeHtml(path.relative(ctx.viteConfig.root, ctx.entry))}' type='module'></script>`);\n\n const template = await server.transformIndexHtml(\n req.url,\n replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTags.join('')),\n req.originalUrl,\n );\n\n res.end(template);\n } else {\n const xmlTemplateContent = fs.readFileSync(path.resolve(ctx.viteConfig.build.outDir, 'template.xml'), 'utf8');\n\n const htmlTagsStr = getBloggerPluginHeadComment(xmlTemplateContent, true);\n\n const template = replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTagsStr ?? '');\n\n res.end(template);\n }\n } else if (requestHost && requestProtocol && contentType && /^(text\\/)|(application\\/(.*\\+)?(xml|json))/.test(contentType)) {\n const content = await proxyResponse.text();\n\n res.end(replaceHost(content, proxyUrl.host, requestHost, requestProtocol));\n } else {\n res.end(new Uint8Array(await proxyResponse.arrayBuffer()));\n }\n } else {\n res.statusCode = 500;\n res.statusMessage = 'Internal Server Error';\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(errorHtml(proxyUrl.href));\n }\n\n const duration = Date.now() - start;\n\n _this.info(`${req.method} ${req.originalUrl} -> ${res.statusCode} ${res.statusMessage} (${duration}ms)`);\n });\n };\n}\n\nexport default function blogger(userOptions: BloggerPluginOptions): Plugin {\n const ctx = createPluginContext(userOptions);\n\n return {\n name: 'vite-plugin-blogger',\n config(config) {\n const root = config.root || process.cwd();\n\n let entry: string | undefined;\n let template: string | undefined;\n\n if (ctx.options.entry) {\n const providedPath = path.resolve(root, ctx.options.entry);\n if (fs.existsSync(providedPath)) {\n entry = providedPath;\n } else {\n this.error(`Provided entry file does not exist: ${providedPath}`);\n }\n } else {\n for (const file of DEFAULT_ENTRIES) {\n const fullPath = path.resolve(root, 'src', file);\n if (fs.existsSync(fullPath)) {\n entry = fullPath;\n break;\n }\n }\n\n if (!entry) {\n this.error(\n 'No entry file found in \"src\".\\n' +\n `Tried: ${DEFAULT_ENTRIES.map((c) => path.join('src', c)).join(', ')}\\n` +\n '👉 Tip: You can pass a custom entry like:\\n' +\n ' blogger({ entry: \"src/my-entry.ts\" })',\n );\n }\n }\n\n if (ctx.options.template) {\n const providedPath = path.resolve(root, ctx.options.template);\n if (fs.existsSync(providedPath)) {\n template = providedPath;\n } else {\n this.error(`Provided template file does not exist: ${providedPath}`);\n }\n } else {\n for (const file of DEFAULT_TEMPLATES) {\n const fullPath = path.resolve(root, 'src', file);\n if (fs.existsSync(fullPath)) {\n template = fullPath;\n break;\n }\n }\n\n if (!template) {\n this.error(\n 'No template file found in \"src\".\\n' +\n `Tried: ${DEFAULT_TEMPLATES.map((c) => path.join('src', c)).join(', ')}\\n` +\n '👉 Tip: You can pass a custom template like:\\n' +\n ' blogger({ template: \"src/my-template.xml\" })',\n );\n }\n }\n\n // populate plugin context\n ctx.entry = entry as string;\n ctx.template = template as string;\n\n // override vite config\n config.build ??= {};\n config.build.rollupOptions ??= {};\n config.build.rollupOptions.input = entry;\n\n // remove contents between comments from template\n const xmlTemplateContent = fs.readFileSync(ctx.template, 'utf8');\n fs.writeFileSync(ctx.template, replaceBloggerPluginHeadComment(replaceBloggerPluginHeadComment(xmlTemplateContent, ''), '', true), {\n encoding: 'utf8',\n });\n },\n configResolved(config) {\n ctx.viteConfig = config;\n },\n generateBundle(_options, bundle) {\n for (const output of Object.values(bundle)) {\n if (output.type !== 'chunk' || !output.isEntry) {\n continue;\n }\n\n const xmlTemplateContent = fs.readFileSync(ctx.template, 'utf8');\n\n const htmlTags: string[] = [];\n output.viteMetadata?.importedCss.forEach((value) => {\n htmlTags.push(`<link crossorigin='anonymous' href='${escapeHtml(ctx.viteConfig.base + value)}' rel='stylesheet'/>`);\n });\n htmlTags.push(`<script crossorigin='anonymous' src='${escapeHtml(ctx.viteConfig.base + output.fileName)}' type='module'></script>`);\n\n const template = replaceBloggerPluginHeadComment(xmlTemplateContent, htmlTags.join(''), true);\n\n this.emitFile({\n type: 'asset',\n fileName: 'template.xml',\n source: template,\n });\n\n break;\n }\n },\n configureServer(server) {\n return useServerMiddleware(server, ctx, this);\n },\n configurePreviewServer(server) {\n return useServerMiddleware(server, ctx, this);\n },\n };\n}\n\nexport type { BloggerPluginOptions } from './schema';\n","import { z } from 'zod';\n\nexport const BloggerPluginOptionsSchema = z\n .object({\n entry: z.string().optional(),\n template: z.string().optional(),\n proxyBlog: z.url(),\n })\n .strict();\n\nexport type BloggerPluginOptions = z.infer<typeof BloggerPluginOptionsSchema>;\n","import type { IncomingHttpHeaders, OutgoingHttpHeaders } from 'node:http';\n\nexport function escapeHtml(str: string) {\n if (str === '') return '';\n return str.replace(/[&<>\"'`]/g, (ch) => {\n switch (ch) {\n case '&':\n return '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n case \"'\":\n return '&#39;';\n case '`':\n return '&#96;';\n default:\n return ch;\n }\n });\n}\n\nexport function escapeRegex(str: string) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function toWebHeaders(httpHeaders: IncomingHttpHeaders | OutgoingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(httpHeaders)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, String(value ?? ''));\n }\n }\n return headers;\n}\n\nexport function replaceBloggerPluginHeadComment(input: string, replacement: string, bcomment = false) {\n if (bcomment) {\n return input.replace(\n /<b:comment><!--blogger-plugin:head:begin--><\\/b:comment>[\\s\\S]*?<b:comment><!--blogger-plugin:head:end--><\\/b:comment>/,\n `<b:comment><!--blogger-plugin:head:begin--></b:comment>${replacement}<b:comment><!--blogger-plugin:head:end--></b:comment>`,\n );\n }\n return input.replace(\n /<!--blogger-plugin:head:begin-->[\\s\\S]*?<!--blogger-plugin:head:end-->/,\n `<!--blogger-plugin:head:begin-->${replacement}<!--blogger-plugin:head:end-->`,\n );\n}\n\nexport function getBloggerPluginHeadComment(input: string, bcomment = false) {\n if (bcomment) {\n return (\n input.match(/<b:comment><!--blogger-plugin:head:begin--><\\/b:comment>([\\s\\S]*?)<b:comment><!--blogger-plugin:head:end--><\\/b:comment>/)?.[1] ??\n null\n );\n }\n return input.match(/<!--blogger-plugin:head:begin-->([\\s\\S]*?)<!--blogger-plugin:head:end-->/)?.[1] ?? null;\n}\n\nexport function replaceHost(input: string, oldHost: string, newHost: string, newProtocol?: string) {\n return input.replace(\n new RegExp(`(https?:)?(\\\\/\\\\/|\\\\\\\\/\\\\\\\\/)${escapeRegex(oldHost)}`, 'g'),\n (_, protocol, slash) => `${protocol ? (newProtocol ?? protocol) : ''}${slash ?? ''}${newHost}`,\n );\n}\n\nexport function errorHtml(reqUrl: string) {\n return `<!DOCTYPE html>\n<html>\n\n<head>\n <meta charset='UTF-8'/>\n <meta content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=5, user-scalable=yes' name='viewport'/>\n <title>500 Internal Server Error</title>\n <link rel='icon' href='data:,' />\n <style>\n *, ::before, ::after {\n box-sizing: border-box;\n }\n body {\n min-height: 100svh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n margin: 0;\n padding: 20px;\n background-color: #f5f5f5;\n font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", Segoe UI Symbol, \"Noto Color Emoji\";\n }\n .card {\n padding: 24px;\n background-color: #ffffff;\n border: 1px solid #e5e5e5;\n max-width: 448px;\n border-radius: 14px;\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);\n display: flex;\n flex-direction: column;\n gap: 24px;\n }\n .card-content {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .card-title {\n font-weight: 600;\n }\n .card-description {\n font-size: 14px;\n opacity: 0.85;\n }\n .card-footer {\n display: flex;\n align-items: center;\n }\n .button {\n display: inline-flex;\n white-space: nowrap;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 8px 16px;\n font-weight: 500;\n background-color: #171717;\n outline: none;\n border: none;\n color: #ffffff;\n border-radius: 8px;\n min-height: 36px;\n }\n .button:hover {\n opacity: 0.9;\n }\n .button svg {\n wiheadersdth: 16px;\n height: 16px;\n flex-shrink: 0;\n }\n .card-footer .button {\n flex-grow: 1;\n }\n </style>\n</head>\n\n<body>\n <div class='card'>\n <div class='card-content'>\n <div class='card-title'>500 Internal Server Error</div>\n <div class='card-description'>Failed to fetch: ${escapeHtml(reqUrl)}</div>\n </div>\n <div class='card-footer'>\n <button class='button' type='button'>\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-refresh-ccw\" aria-hidden=\"true\"><path d=\"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\"></path><path d=\"M3 3v5h5\"></path><path d=\"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16\"></path><path d=\"M16 16h5v5\"></path></svg>\n Reload\n </button>\n </div>\n </div>\n <script>\n const button = document.getElementsByTagName('button')[0];\n button.addEventListener('click', () => {\n window.location.reload();\n });\n </script>\n</body>\n\n</html>`;\n}\n"]}
1
+ {"version":3,"sources":["/home/runner/work/blogger-plugin/blogger-plugin/packages/blogger-plugin/dist/vite.cjs","../src/vite.ts","../src/cache.ts","../src/constants.ts","../src/utils.ts"],"names":["dirname","_a"],"mappings":"AAAA;ACAA,uGAAoB;AACpB,mHAAsB;AACtB,gCAAyB;AACzB;AAOE;AAAA,4BACK;ADJP;AACA;AERA;AACA;AACA,iDAAmC;AAEnC,IAAM,oBAAA,EAAsB,wBAAA;AAE5B,SAAS,eAAA,CAAgB,IAAA,EAA6B;AACpD,EAAA,GAAA,CAAI,CAAI,EAAA,CAAA,UAAA,CAAW,I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A,MAAA;AACwB,MAAA;AACW,MAAA;AACvB,MAAA;AACgB,MAAA;AACL,MAAA;AACmB,QAAA;AACoB,MAAA;AACxC,QAAA;AACjC,MAAA;AACsB,QAAA;AAC7B,MAAA;AAEuE,MAAA;AAEJ,MAAA;AAED,MAAA;AACpE,IAAA;AACuB,IAAA;AACJ,MAAA;AAC6D,MAAA;AAE5D,MAAA;AACW,QAAA;AAEK,QAAA;AACsC,UAAA;AACtE,QAAA;AACK,MAAA;AACuB,QAAA;AAC9B,MAAA;AACF,IAAA;AACkB,IAAA;AACU,MAAA;AACb,QAAA;AACb,MAAA;AACF,IAAA;AACS,IAAA;AACe,MAAA;AACT,QAAA;AACb,MAAA;AACF,IAAA;AACuB,IAAA;AACO,MAAA;AAC1B,QAAA;AACF,MAAA;AAC8B,MAAA;AACP,MAAA;AAEyC,MAAA;AAC9D,QAAA;AACF,MAAA;AAEE,MAAA;AACoC,MAAA;AAC1B,MAAA;AACV,QAAA;AACF,MAAA;AAE8B,MAAA;AACD,MAAA;AAMlB,MAAA;AASI,QAAA;AAGO,QAAA;AAG0E,MAAA;AAMzB,MAAA;AACJ,MAAA;AAES,MAAA;AAC9E,IAAA;AACc,IAAA;AACsE,MAAA;AACtD,MAAA;AACY,QAAA;AACxC,MAAA;AACF,IAAA;AACwB,IAAA;AACsB,MAAA;AAC9C,IAAA;AAC+B,IAAA;AACe,MAAA;AAC9C,IAAA;AACF,EAAA;AACF;ADqJ2F;AACA;AACA","file":"/home/runner/work/blogger-plugin/blogger-plugin/packages/blogger-plugin/dist/vite.cjs","sourcesContent":[null,"import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { Readable } from 'node:stream';\nimport {\n type MinimalPluginContextWithoutEnvironment,\n type Plugin,\n type PreviewServer,\n type ResolvedConfig,\n type UserConfig,\n type ViteDevServer,\n version,\n} from 'vite';\nimport { clearTailwindCache, removeTailwindCache, updateTailwindCache } from './cache';\nimport { DEFAULT_ENTRIES, DEFAULT_TEMPLATES } from './constants';\nimport {\n errorHtml,\n escapeHtml,\n getBloggerPluginHeadComment,\n getRequestUrl,\n isTailwindPlugin,\n replaceBloggerPluginHeadComment,\n replaceHost,\n toWebHeaders,\n} from './utils';\n\ninterface BloggerPluginContext {\n root: string;\n entry: string;\n template: string;\n proxyBlog: URL;\n viteConfig: ResolvedConfig;\n tailwind: boolean;\n input: string;\n html: string;\n resolve(root: UserConfig): void;\n}\n\nfunction createBloggerPluginContext(userOptions: BloggerPluginOptions): BloggerPluginContext {\n if (typeof userOptions.entry !== 'undefined' && typeof userOptions.entry !== 'string') {\n throw new Error(\"Option 'entry' must be a string\");\n }\n if (typeof userOptions.template !== 'undefined' && typeof userOptions.template !== 'string') {\n throw new Error(\"Option 'template' must be a string\");\n }\n if (typeof userOptions.proxyBlog !== 'string') {\n throw new Error(\"Option 'proxyBlog' must be a string\");\n }\n let proxyBlog: URL;\n try {\n proxyBlog = new URL(userOptions.proxyBlog);\n } catch {\n throw new Error(\"Option 'proxyBlog' must be a valid url\");\n }\n return {\n root: process.cwd(),\n entry: undefined as unknown as string,\n template: undefined as unknown as string,\n proxyBlog,\n viteConfig: undefined as unknown as ResolvedConfig,\n tailwind: false,\n input: undefined as unknown as string,\n html: undefined as unknown as string,\n resolve(config: UserConfig) {\n this.root = config.root ? path.resolve(config.root) : this.root;\n\n if (userOptions.entry) {\n const providedPath = path.resolve(this.root, userOptions.entry);\n if (fs.existsSync(providedPath)) {\n this.entry = providedPath;\n } else {\n throw new Error(`Provided entry file does not exist: ${providedPath}`);\n }\n } else {\n for (const file of DEFAULT_ENTRIES) {\n const fullPath = path.resolve(this.root, 'src', file);\n if (fs.existsSync(fullPath)) {\n this.entry = fullPath;\n break;\n }\n }\n\n if (!this.entry) {\n throw new Error(\n 'No entry file found in \"src\".\\n' +\n `Tried: ${DEFAULT_ENTRIES.map((c) => path.join('src', c)).join(', ')}\\n` +\n '👉 Tip: You can pass a custom entry like:\\n' +\n ' blogger({ entry: \"src/my-entry.ts\" })',\n );\n }\n }\n\n if (userOptions.template) {\n const providedPath = path.resolve(this.root, userOptions.template);\n if (fs.existsSync(providedPath)) {\n this.template = providedPath;\n } else {\n throw new Error(`Provided template file does not exist: ${providedPath}`);\n }\n } else {\n for (const file of DEFAULT_TEMPLATES) {\n const fullPath = path.resolve(this.root, 'src', file);\n if (fs.existsSync(fullPath)) {\n this.template = fullPath;\n break;\n }\n }\n\n if (!this.template) {\n throw new Error(\n 'No template file found in \"src\".\\n' +\n `Tried: ${DEFAULT_TEMPLATES.map((c) => path.join('src', c)).join(', ')}\\n` +\n '👉 Tip: You can pass a custom template like:\\n' +\n ' blogger({ template: \"src/my-template.xml\" })',\n );\n }\n }\n\n const name = path.basename(this.entry, path.extname(this.entry));\n this.input = `virtual:blogger-plugin/${name}.html`;\n this.html = `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <!--head-->\n <script type=\"module\" src=\"/${path.relative(this.root, this.entry).replace('\\\\', '/')}\"></script>\n</head>\n<body>\n <!--body-->\n</body>\n</html>`;\n },\n };\n}\n\nfunction isViteDevServer(server: ViteDevServer | PreviewServer): server is ViteDevServer {\n return 'hot' in server && 'transformRequest' in server && 'transformIndexHtml' in server;\n}\n\nfunction useServerMiddleware(server: ViteDevServer | PreviewServer, ctx: BloggerPluginContext, _this: MinimalPluginContextWithoutEnvironment) {\n return () => {\n server.httpServer?.once('listening', () => {\n setTimeout(() => {\n _this.info(`Unhandled requests will be proxied to ${ctx.proxyBlog.origin}`);\n }, 0);\n });\n\n server.middlewares.use(async (req, res, next) => {\n const url = getRequestUrl(req);\n\n if (!req.url || !req.originalUrl || !url) {\n next();\n return;\n }\n\n const start = Date.now();\n\n const proxyUrl = new URL(`${ctx.proxyBlog.origin}${req.originalUrl}`);\n\n const viewParam = proxyUrl.searchParams.get('view');\n proxyUrl.searchParams.set('view', `${isViteDevServer(server) ? '-DevServer' : '-PreviewServer'}${viewParam?.startsWith('-') ? viewParam : ''}`);\n\n const proxyRequest = new Request(proxyUrl, {\n method: req.method,\n headers: toWebHeaders(req.headers),\n body: ['GET', 'HEAD'].includes(req.method ?? '') ? undefined : Readable.toWeb(req),\n redirect: 'manual',\n });\n\n const proxyResponse = await fetch(proxyRequest).catch((error) => {\n if (error instanceof Error) {\n _this.warn({\n message: `${error.name}: ${error.message}`,\n cause: error.cause,\n stack: error.stack,\n });\n } else {\n _this.warn('Fetch failed');\n }\n return null;\n });\n\n if (proxyResponse) {\n res.statusCode = proxyResponse.status;\n res.statusMessage = proxyResponse.statusText;\n\n proxyResponse.headers.forEach((value, key) => {\n if (key === 'location') {\n const redirectUrl = new URL(value, proxyUrl);\n if (redirectUrl.host === url.host || redirectUrl.host === proxyUrl.host) {\n redirectUrl.host = url.host;\n redirectUrl.protocol = url.protocol;\n const viewParam = redirectUrl.searchParams.get('view')?.replaceAll('-DevServer', '').replaceAll('-PreviewServer', '');\n if (viewParam) {\n redirectUrl.searchParams.set('view', viewParam);\n } else {\n redirectUrl.searchParams.delete('view');\n }\n res.setHeader('location', redirectUrl.pathname + redirectUrl.search + redirectUrl.hash);\n } else {\n res.setHeader('location', redirectUrl.href);\n }\n } else if (['content-type', 'x-robots-tag', 'date', 'location'].includes(key)) {\n res.setHeader(key, value);\n }\n });\n\n const contentType = proxyResponse.headers.get('content-type');\n\n if (contentType?.startsWith('text/html')) {\n let htmlTemplateContent = await proxyResponse.text();\n\n if (ctx.tailwind && isViteDevServer(server)) {\n await updateTailwindCache(ctx.root, htmlTemplateContent);\n }\n\n htmlTemplateContent = replaceHost(htmlTemplateContent, proxyUrl.host, url.host, url.protocol);\n\n if (isViteDevServer(server)) {\n const htmlTags: string[] = [];\n\n htmlTags.push(`<script type='module' src='/${escapeHtml(path.relative(ctx.root, ctx.entry).replace('\\\\', '/'))}'></script>`);\n\n const template = await server.transformIndexHtml(\n req.url,\n replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTags.join('')),\n req.originalUrl,\n );\n\n res.end(template);\n } else {\n const xmlTemplateContent = fs.readFileSync(path.resolve(ctx.viteConfig.build.outDir, 'template.xml'), 'utf8');\n\n const htmlTagsStr = getBloggerPluginHeadComment(xmlTemplateContent, true);\n\n const template = replaceBloggerPluginHeadComment(htmlTemplateContent, htmlTagsStr ?? '');\n\n res.end(template);\n }\n } else if (contentType && /^(text\\/)|(application\\/(.*\\+)?(xml|json))/.test(contentType)) {\n const content = await proxyResponse.text();\n\n res.end(replaceHost(content, proxyUrl.host, url.host, url.protocol));\n } else {\n res.end(new Uint8Array(await proxyResponse.arrayBuffer()));\n }\n } else {\n res.statusCode = 500;\n res.statusMessage = 'Internal Server Error';\n\n res.setHeader('Content-Type', 'text/html');\n\n res.end(errorHtml(proxyUrl.href));\n }\n\n const duration = Date.now() - start;\n\n _this.info(`${req.method} ${req.originalUrl} -> ${res.statusCode} ${res.statusMessage} (${duration}ms)`);\n });\n };\n}\n\nexport interface BloggerPluginOptions {\n entry?: string;\n template?: string;\n proxyBlog: string;\n}\n\nexport default function blogger(userOptions: BloggerPluginOptions): Plugin {\n const ctx = createBloggerPluginContext(userOptions);\n\n return {\n name: 'vite-plugin-blogger',\n config(config) {\n // resolve plugin context\n ctx.resolve(config);\n\n // modify vite config\n config.build ||= {};\n const major = Number(version.split('.')[0]);\n const bundlerKey = (major >= 8 ? 'rolldownOptions' : 'rollupOptions') as 'rollupOptions';\n config.build[bundlerKey] ||= {};\n const bundlerOptions = config.build[bundlerKey];\n if (Array.isArray(bundlerOptions.input)) {\n bundlerOptions.input = [...bundlerOptions.input, ctx.input];\n } else if (typeof bundlerOptions.input === 'object' && bundlerOptions.input !== null) {\n bundlerOptions.input[ctx.input] = ctx.input;\n } else {\n bundlerOptions.input = ctx.input;\n }\n\n const originalTemplateXmlContent = fs.readFileSync(ctx.template, 'utf8');\n // remove contents between comments from template\n const modifiedTemplateXmlContent = replaceBloggerPluginHeadComment(replaceBloggerPluginHeadComment(originalTemplateXmlContent, ''), '', true);\n\n fs.writeFileSync(ctx.template, modifiedTemplateXmlContent, 'utf-8');\n },\n configResolved(config) {\n ctx.viteConfig = config;\n ctx.tailwind = config.plugins.flat(Number.POSITIVE_INFINITY).some((plugin) => isTailwindPlugin(plugin));\n\n if (ctx.tailwind) {\n clearTailwindCache(ctx.root);\n\n if (config.command === 'build') {\n updateTailwindCache(ctx.root, fs.readFileSync(ctx.template, 'utf-8'));\n }\n } else {\n removeTailwindCache(ctx.root);\n }\n },\n resolveId(source) {\n if (source === ctx.input) {\n return ctx.input;\n }\n },\n load(id) {\n if (id === ctx.input) {\n return ctx.html;\n }\n },\n writeBundle(_, bundle) {\n if (!(ctx.input in bundle)) {\n return;\n }\n const asset = bundle[ctx.input];\n delete bundle[ctx.input];\n\n if (asset.type !== 'asset' || typeof asset.source !== 'string') {\n return;\n }\n const regex =\n /<!DOCTYPE html>\\s*<html[^>]*>\\s*<head>([\\s\\S]*?)<!--head-->([\\s\\S]*?)<\\/head>\\s*<body>([\\s\\S]*?)<!--body-->([\\s\\S]*?)<\\/body>\\s*<\\/html>/i;\n const match = asset.source.match(regex);\n if (!match) {\n return;\n }\n\n const afterHeadBegin = match[2];\n const beforeHeadEnd = match[3];\n // const afterBodyBegin = match[4];\n // const beforeBodyEnd = match[5];\n\n const headContent = (afterHeadBegin + beforeHeadEnd)\n // boolean attributes to empty string\n .replace(/\\b(crossorigin|defer|async|disabled|checked)\\b(?!=)/g, (_, $1: string) => `${$1}=\"\"`)\n // convert attributes to single quotes safely\n .replace(/(\\w+)=(\".*?\"|'.*?')/g, (_, $1: string, $2: string) => {\n const v = $2\n // remove quotes\n .slice(1, -1)\n // escape special XML chars\n .replace(/&/g, '&amp;')\n .replace(/'/g, '&apos;')\n .replace(/\"/g, '&quot;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;');\n return `${$1}='${v}'`;\n })\n // self-close void tags\n .replace(/<(link|meta|img|br|hr|input)([^>]*?)>/gi, (_, $1: string, $2: string) => `<${$1}${$2} />`)\n // remove whitespace between tags\n .replace(/>\\s+</g, '><')\n // trim overall\n .trim();\n\n const originalTemplateXmlContent = fs.readFileSync(ctx.template, 'utf8');\n const modifiedTemplateXmlContent = replaceBloggerPluginHeadComment(originalTemplateXmlContent, headContent, true);\n\n fs.writeFileSync(path.resolve(ctx.viteConfig.build.outDir, 'template.xml'), modifiedTemplateXmlContent);\n },\n closeBundle() {\n const htmlDir = path.resolve(ctx.viteConfig.build.outDir, 'virtual:blogger-plugin');\n if (fs.existsSync(htmlDir)) {\n fs.rmSync(htmlDir, { recursive: true });\n }\n },\n configureServer(server) {\n return useServerMiddleware(server, ctx, this);\n },\n configurePreviewServer(server) {\n return useServerMiddleware(server, ctx, this);\n },\n };\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { getTailwindClasses } from 'tailwindcss-iso';\n\nconst TAILWIND_CACHE_FILE = '.tailwind-classes.json';\n\nfunction readFileContent(file: string): string | null {\n if (!fs.existsSync(file)) {\n return null;\n }\n return fs.readFileSync(file, 'utf-8');\n}\n\nfunction writeFileContent(file: string, content: string): boolean {\n const dirname = path.dirname(file);\n\n if (!fs.existsSync(dirname)) {\n fs.mkdirSync(dirname, { recursive: true });\n }\n\n const current = readFileContent(file);\n if (current === null || content !== current) {\n fs.writeFileSync(file, content, 'utf8');\n return true;\n }\n\n return false;\n}\n\nfunction removeFile(file: string): boolean {\n if (!fs.existsSync(file)) {\n return false;\n }\n fs.rmSync(file);\n return true;\n}\n\nfunction getTailwindCacheFile(root: string): string {\n return path.resolve(root, TAILWIND_CACHE_FILE);\n}\n\nexport function readTailwindCache(root: string): string[] | null {\n const content = readFileContent(getTailwindCacheFile(root));\n if (!content) {\n return null;\n }\n try {\n return JSON.parse(content);\n } catch {\n return null;\n }\n}\n\nexport function writeTailwindCache(root: string, classes: string[]): { updated: boolean; content: string } {\n const file = getTailwindCacheFile(root);\n const content = JSON.stringify(classes, null, 2);\n const updated = writeFileContent(file, content);\n return { updated, content };\n}\n\nexport function clearTailwindCache(root: string): void {\n writeTailwindCache(root, []);\n}\n\nexport function removeTailwindCache(root: string): void {\n removeFile(getTailwindCacheFile(root));\n}\n\nexport async function updateTailwindCache(root: string, content: string): Promise<void> {\n const classes = (await getTailwindClasses({\n content,\n })) as string[];\n\n writeTailwindCache(root, [...new Set([...(readTailwindCache(root) ?? []), ...classes])]);\n}\n","export const DEFAULT_ENTRIES = ['index.tsx', 'index.ts', 'index.jsx', 'index.js', 'main.tsx', 'main.ts', 'main.jsx', 'main.js'];\n\nexport const DEFAULT_TEMPLATES = ['template.xml', 'theme.xml'];\n","import type { IncomingHttpHeaders, IncomingMessage, OutgoingHttpHeaders } from 'node:http';\n\nexport function escapeHtml(str: string) {\n if (str === '') return '';\n return str.replace(/[&<>\"'`]/g, (ch) => {\n switch (ch) {\n case '&':\n return '&amp;';\n case '<':\n return '&lt;';\n case '>':\n return '&gt;';\n case '\"':\n return '&quot;';\n case \"'\":\n return '&#39;';\n case '`':\n return '&#96;';\n default:\n return ch;\n }\n });\n}\n\nexport function escapeRegex(str: string) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function toWebHeaders(httpHeaders: IncomingHttpHeaders | OutgoingHttpHeaders): Headers {\n const headers = new Headers();\n for (const [name, value] of Object.entries(httpHeaders)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n headers.append(name, item);\n }\n } else {\n headers.set(name, String(value ?? ''));\n }\n }\n return headers;\n}\n\nexport const BLOGGER_PLUGIN_HEAD_COMMENT_REGEX = /(<!--blogger-plugin:head:begin-->)([\\s\\S]*?)(<!--blogger-plugin:head:end-->)/;\n\nexport const BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX =\n /(<b:comment><!--blogger-plugin:head:begin--><\\/b:comment>)([\\s\\S]*?)(<b:comment><!--blogger-plugin:head:end--><\\/b:comment>)/;\n\nexport function replaceBloggerPluginHeadComment(input: string, replacement: string, bcomment = false) {\n if (bcomment) {\n return input.replace(BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX, (_, start: string, _content: string, end: string) => `${start}${replacement}${end}`);\n }\n return input.replace(BLOGGER_PLUGIN_HEAD_COMMENT_REGEX, (_, start: string, _content: string, end: string) => `${start}${replacement}${end}`);\n}\n\nexport function getBloggerPluginHeadComment(input: string, bcomment = false) {\n if (bcomment) {\n return input.match(BLOGGER_PLUGIN_HEAD_BCOMMENT_REGEX)?.[2] ?? null;\n }\n return input.match(BLOGGER_PLUGIN_HEAD_COMMENT_REGEX)?.[2] ?? null;\n}\n\nexport function replaceHost(input: string, oldHost: string, newHost: string, newProtocol?: string) {\n return input.replace(\n new RegExp(`(https?:)?(\\\\/\\\\/|\\\\\\\\/\\\\\\\\/)${escapeRegex(oldHost)}`, 'g'),\n (_, protocol, slash) => `${protocol ? (newProtocol ?? protocol) : ''}${slash ?? ''}${newHost}`,\n );\n}\n\nexport function getRequestUrl(req: IncomingMessage): URL | null {\n const xForwardedProtoHeader = req.headers['x-forwarded-proto'];\n const xForwardedHostHeader = req.headers['x-forwarded-host'];\n const hostHeader = req.headers.host;\n\n const protocol = Array.isArray(xForwardedProtoHeader)\n ? xForwardedProtoHeader[0]\n : (xForwardedProtoHeader ?? (req.socket && 'encrypted' in req.socket && req.socket.encrypted ? 'https' : 'http'));\n const host = Array.isArray(xForwardedHostHeader) ? xForwardedHostHeader[0] : (xForwardedHostHeader ?? hostHeader);\n\n if (host && req.url) {\n return new URL(`${protocol}://${host}${req.url}`);\n }\n\n return null;\n}\n\nexport function isBloggerPath(path: string) {\n return (\n path === '/' ||\n path === '/search' ||\n /^\\/search\\/label(\\/[^/]+)?\\/?$/.test(path) ||\n /^p\\/.+\\.html$/.test(path) ||\n /^\\/\\d{4}\\/\\d{2}(\\/?|\\/[^/\\s]+\\.html)$/.test(path)\n );\n}\n\nconst TAILWIND_PLUGIN_NAMES = new Set(['@tailwindcss/vite:scan']);\n\nexport function isTailwindPlugin(plugin: { name: string }): boolean {\n return TAILWIND_PLUGIN_NAMES.has(plugin.name);\n}\n\nexport function errorHtml(reqUrl: string) {\n return `<!DOCTYPE html>\n<html>\n\n<head>\n <meta charset='UTF-8'/>\n <meta content='width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=5, user-scalable=yes' name='viewport'/>\n <title>500 Internal Server Error</title>\n <link rel='icon' href='data:,' />\n <style>\n *, ::before, ::after {\n box-sizing: border-box;\n }\n body {\n min-height: 100svh;\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n margin: 0;\n padding: 20px;\n background-color: #f5f5f5;\n font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Helvetica Neue, Arial, Noto Sans, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", Segoe UI Symbol, \"Noto Color Emoji\";\n }\n .card {\n padding: 24px;\n background-color: #ffffff;\n border: 1px solid #e5e5e5;\n max-width: 448px;\n border-radius: 14px;\n box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);\n display: flex;\n flex-direction: column;\n gap: 24px;\n }\n .card-content {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n .card-title {\n font-weight: 600;\n }\n .card-description {\n font-size: 14px;\n opacity: 0.85;\n }\n .card-footer {\n display: flex;\n align-items: center;\n }\n .button {\n display: inline-flex;\n white-space: nowrap;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 8px 16px;\n font-weight: 500;\n background-color: #171717;\n outline: none;\n border: none;\n color: #ffffff;\n border-radius: 8px;\n min-height: 36px;\n }\n .button:hover {\n opacity: 0.9;\n }\n .button svg {\n wiheadersdth: 16px;\n height: 16px;\n flex-shrink: 0;\n }\n .card-footer .button {\n flex-grow: 1;\n }\n </style>\n</head>\n\n<body>\n <div class='card'>\n <div class='card-content'>\n <div class='card-title'>500 Internal Server Error</div>\n <div class='card-description'>Failed to fetch: ${escapeHtml(reqUrl)}</div>\n </div>\n <div class='card-footer'>\n <button class='button' type='button'>\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"lucide lucide-refresh-ccw\" aria-hidden=\"true\"><path d=\"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8\"></path><path d=\"M3 3v5h5\"></path><path d=\"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16\"></path><path d=\"M16 16h5v5\"></path></svg>\n Reload\n </button>\n </div>\n </div>\n <script>\n const button = document.getElementsByTagName('button')[0];\n button.addEventListener('click', () => {\n window.location.reload();\n });\n </script>\n</body>\n\n</html>`;\n}\n"]}
package/dist/vite.d.cts CHANGED
@@ -1,13 +1,10 @@
1
1
  import { Plugin } from 'vite';
2
- import { z } from 'zod';
3
-
4
- declare const BloggerPluginOptionsSchema: z.ZodObject<{
5
- entry: z.ZodOptional<z.ZodString>;
6
- template: z.ZodOptional<z.ZodString>;
7
- proxyBlog: z.ZodURL;
8
- }, z.core.$strict>;
9
- type BloggerPluginOptions = z.infer<typeof BloggerPluginOptionsSchema>;
10
2
 
3
+ interface BloggerPluginOptions {
4
+ entry?: string;
5
+ template?: string;
6
+ proxyBlog: string;
7
+ }
11
8
  declare function blogger(userOptions: BloggerPluginOptions): Plugin;
12
9
 
13
10
  export { type BloggerPluginOptions, blogger as default };