var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
  return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
    return __privateGet(this, extra);
  }, set [name](x) {
    return __privateSet(this, extra, x);
  } }, name));
  k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
  for (var i = decorators.length - 1; i >= 0; i--) {
    ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
    if (k) {
      ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
      if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
      if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
    }
    it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
    if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
    else if (typeof it !== "object" || it === null) __typeError("Object expected");
    else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
  }
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var font_manager_exports = {};
__export(font_manager_exports, {
  FontManager: () => FontManager
});
module.exports = __toCommonJS(font_manager_exports);
var import_node_path = __toESM(require("node:path"));
var import_server = require("@tego/server");
var import_renderer = require("@react-pdf/renderer");
var import_axios = __toESM(require("axios"));
var import_fs_extra = __toESM(require("fs-extra"));
var _logger_dec, _FontManager_decorators, _init;
_FontManager_decorators = [(0, import_server.Service)()], _logger_dec = [(0, import_server.InjectLog)()];
class FontManager {
  constructor() {
    this.logger = __runInitializers(_init, 8, this), __runInitializers(_init, 11, this);
  }
  async load() {
    import_renderer.Font.registerHyphenationCallback((word) => {
      if (word.length === 1) {
        return [word];
      }
      return Array.from(word).map((char) => [char, ""]).reduce((arr, current) => {
        arr.push(...current);
        return arr;
      }, []);
    });
    await this.loadFonts();
  }
  async loadFonts(flag = true) {
    this.logger.info("load fonts.");
    const fonts = [
      {
        family: "source-han-sans",
        weight: 200,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-ExtraLight.otf"
      },
      {
        family: "source-han-sans",
        weight: 300,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Light.otf"
      },
      {
        family: "source-han-sans",
        weight: 400,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Regular.otf"
      },
      {
        family: "source-han-sans",
        weight: 500,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Normal.otf"
      },
      {
        family: "source-han-sans",
        weight: 600,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Medium.otf"
      },
      {
        family: "source-han-sans",
        weight: 700,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Bold.otf"
      },
      {
        family: "source-han-sans",
        weight: 900,
        url: "https://assets.tachybase.com/fonts/SourceHanSansCN-Heavy.otf"
      }
    ];
    const fontsDir = import_node_path.default.join(process.env.TEGO_RUNTIME_HOME, "storage", "fonts");
    const isExists = await import_fs_extra.default.exists(fontsDir);
    if (!isExists) {
      import_fs_extra.default.mkdir(fontsDir);
    }
    if (flag) {
      await Promise.all(
        fonts.map((font) => {
          const doAsync = async () => {
            const filename = font.url.split("/").slice(-1)[0];
            const filepath = import_node_path.default.join(fontsDir, filename);
            const isExists2 = await import_fs_extra.default.exists(filepath);
            if (!isExists2) {
              this.logger.info("download " + filepath);
              const response = await (0, import_axios.default)({
                method: "GET",
                url: font.url,
                responseType: "stream"
              });
              try {
                const writer = import_fs_extra.default.createWriteStream(filepath);
                await new Promise((resolve, reject) => {
                  response.data.pipe(writer);
                  writer.on("finish", () => {
                    this.logger.info("download " + filepath + " done.");
                    resolve("done");
                  });
                  writer.on("error", () => {
                    reject();
                  });
                });
              } catch (err) {
                this.logger.error("download error.", { err });
                await import_fs_extra.default.remove(filepath);
              }
            }
          };
          return doAsync();
        })
      );
    }
    fonts.forEach((font) => {
      const filename = font.url.split("/").slice(-1)[0];
      const filepath = import_node_path.default.join(fontsDir, filename);
      import_renderer.Font.register({
        family: font.family,
        fontWeight: font.weight,
        src: filepath
      });
    });
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 5, "logger", _logger_dec, FontManager);
FontManager = __decorateElement(_init, 0, "FontManager", _FontManager_decorators, FontManager);
__runInitializers(_init, 1, FontManager);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  FontManager
});
