/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i = decorators.length - 1, decorator; i >= 0; i--)
if (decorator = decorators[i])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result)
__defProp(target, key, result);
return result;
};
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
// main.ts
var main_exports = {};
__export(main_exports, {
default: () => MetaTitlePlugin
});
module.exports = __toCommonJS(main_exports);
// node_modules/reflect-metadata/Reflect.js
var Reflect2;
(function(Reflect3) {
(function(factory) {
var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : Function("return this;")();
var exporter = makeExporter(Reflect3);
if (typeof root.Reflect === "undefined") {
root.Reflect = Reflect3;
} else {
exporter = makeExporter(root.Reflect, exporter);
}
factory(exporter);
function makeExporter(target, previous) {
return function(key, value) {
if (typeof target[key] !== "function") {
Object.defineProperty(target, key, { configurable: true, writable: true, value });
}
if (previous)
previous(key, value);
};
}
})(function(exporter) {
var hasOwn = Object.prototype.hasOwnProperty;
var supportsSymbol = typeof Symbol === "function";
var toPrimitiveSymbol = supportsSymbol && typeof Symbol.toPrimitive !== "undefined" ? Symbol.toPrimitive : "@@toPrimitive";
var iteratorSymbol = supportsSymbol && typeof Symbol.iterator !== "undefined" ? Symbol.iterator : "@@iterator";
var supportsCreate = typeof Object.create === "function";
var supportsProto = { __proto__: [] } instanceof Array;
var downLevel = !supportsCreate && !supportsProto;
var HashMap = {
// create an object in dictionary mode (a.k.a. "slow" mode in v8)
create: supportsCreate ? function() {
return MakeDictionary(/* @__PURE__ */ Object.create(null));
} : supportsProto ? function() {
return MakeDictionary({ __proto__: null });
} : function() {
return MakeDictionary({});
},
has: downLevel ? function(map, key) {
return hasOwn.call(map, key);
} : function(map, key) {
return key in map;
},
get: downLevel ? function(map, key) {
return hasOwn.call(map, key) ? map[key] : void 0;
} : function(map, key) {
return map[key];
}
};
var functionPrototype = Object.getPrototypeOf(Function);
var usePolyfill = typeof process === "object" && process.env && process.env["REFLECT_METADATA_USE_MAP_POLYFILL"] === "true";
var _Map = !usePolyfill && typeof Map === "function" && typeof Map.prototype.entries === "function" ? Map : CreateMapPolyfill();
var _Set = !usePolyfill && typeof Set === "function" && typeof Set.prototype.entries === "function" ? Set : CreateSetPolyfill();
var _WeakMap = !usePolyfill && typeof WeakMap === "function" ? WeakMap : CreateWeakMapPolyfill();
var Metadata2 = new _WeakMap();
function decorate(decorators, target, propertyKey, attributes) {
if (!IsUndefined(propertyKey)) {
if (!IsArray(decorators))
throw new TypeError();
if (!IsObject(target))
throw new TypeError();
if (!IsObject(attributes) && !IsUndefined(attributes) && !IsNull(attributes))
throw new TypeError();
if (IsNull(attributes))
attributes = void 0;
propertyKey = ToPropertyKey(propertyKey);
return DecorateProperty(decorators, target, propertyKey, attributes);
} else {
if (!IsArray(decorators))
throw new TypeError();
if (!IsConstructor(target))
throw new TypeError();
return DecorateConstructor(decorators, target);
}
}
exporter("decorate", decorate);
function metadata(metadataKey, metadataValue) {
function decorator(target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey) && !IsPropertyKey(propertyKey))
throw new TypeError();
OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
}
return decorator;
}
exporter("metadata", metadata);
function defineMetadata(metadataKey, metadataValue, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryDefineOwnMetadata(metadataKey, metadataValue, target, propertyKey);
}
exporter("defineMetadata", defineMetadata);
function hasMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryHasMetadata(metadataKey, target, propertyKey);
}
exporter("hasMetadata", hasMetadata);
function hasOwnMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryHasOwnMetadata(metadataKey, target, propertyKey);
}
exporter("hasOwnMetadata", hasOwnMetadata);
function getMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryGetMetadata(metadataKey, target, propertyKey);
}
exporter("getMetadata", getMetadata);
function getOwnMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryGetOwnMetadata(metadataKey, target, propertyKey);
}
exporter("getOwnMetadata", getOwnMetadata);
function getMetadataKeys(target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryMetadataKeys(target, propertyKey);
}
exporter("getMetadataKeys", getMetadataKeys);
function getOwnMetadataKeys(target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
return OrdinaryOwnMetadataKeys(target, propertyKey);
}
exporter("getOwnMetadataKeys", getOwnMetadataKeys);
function deleteMetadata(metadataKey, target, propertyKey) {
if (!IsObject(target))
throw new TypeError();
if (!IsUndefined(propertyKey))
propertyKey = ToPropertyKey(propertyKey);
var metadataMap = GetOrCreateMetadataMap(
target,
propertyKey,
/*Create*/
false
);
if (IsUndefined(metadataMap))
return false;
if (!metadataMap.delete(metadataKey))
return false;
if (metadataMap.size > 0)
return true;
var targetMetadata = Metadata2.get(target);
targetMetadata.delete(propertyKey);
if (targetMetadata.size > 0)
return true;
Metadata2.delete(target);
return true;
}
exporter("deleteMetadata", deleteMetadata);
function DecorateConstructor(decorators, target) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target);
if (!IsUndefined(decorated) && !IsNull(decorated)) {
if (!IsConstructor(decorated))
throw new TypeError();
target = decorated;
}
}
return target;
}
function DecorateProperty(decorators, target, propertyKey, descriptor) {
for (var i = decorators.length - 1; i >= 0; --i) {
var decorator = decorators[i];
var decorated = decorator(target, propertyKey, descriptor);
if (!IsUndefined(decorated) && !IsNull(decorated)) {
if (!IsObject(decorated))
throw new TypeError();
descriptor = decorated;
}
}
return descriptor;
}
function GetOrCreateMetadataMap(O, P, Create) {
var targetMetadata = Metadata2.get(O);
if (IsUndefined(targetMetadata)) {
if (!Create)
return void 0;
targetMetadata = new _Map();
Metadata2.set(O, targetMetadata);
}
var metadataMap = targetMetadata.get(P);
if (IsUndefined(metadataMap)) {
if (!Create)
return void 0;
metadataMap = new _Map();
targetMetadata.set(P, metadataMap);
}
return metadataMap;
}
function OrdinaryHasMetadata(MetadataKey, O, P) {
var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn2)
return true;
var parent = OrdinaryGetPrototypeOf(O);
if (!IsNull(parent))
return OrdinaryHasMetadata(MetadataKey, parent, P);
return false;
}
function OrdinaryHasOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(
O,
P,
/*Create*/
false
);
if (IsUndefined(metadataMap))
return false;
return ToBoolean(metadataMap.has(MetadataKey));
}
function OrdinaryGetMetadata(MetadataKey, O, P) {
var hasOwn2 = OrdinaryHasOwnMetadata(MetadataKey, O, P);
if (hasOwn2)
return OrdinaryGetOwnMetadata(MetadataKey, O, P);
var parent = OrdinaryGetPrototypeOf(O);
if (!IsNull(parent))
return OrdinaryGetMetadata(MetadataKey, parent, P);
return void 0;
}
function OrdinaryGetOwnMetadata(MetadataKey, O, P) {
var metadataMap = GetOrCreateMetadataMap(
O,
P,
/*Create*/
false
);
if (IsUndefined(metadataMap))
return void 0;
return metadataMap.get(MetadataKey);
}
function OrdinaryDefineOwnMetadata(MetadataKey, MetadataValue, O, P) {
var metadataMap = GetOrCreateMetadataMap(
O,
P,
/*Create*/
true
);
metadataMap.set(MetadataKey, MetadataValue);
}
function OrdinaryMetadataKeys(O, P) {
var ownKeys = OrdinaryOwnMetadataKeys(O, P);
var parent = OrdinaryGetPrototypeOf(O);
if (parent === null)
return ownKeys;
var parentKeys = OrdinaryMetadataKeys(parent, P);
if (parentKeys.length <= 0)
return ownKeys;
if (ownKeys.length <= 0)
return parentKeys;
var set = new _Set();
var keys = [];
for (var _i = 0, ownKeys_1 = ownKeys; _i < ownKeys_1.length; _i++) {
var key = ownKeys_1[_i];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
for (var _a = 0, parentKeys_1 = parentKeys; _a < parentKeys_1.length; _a++) {
var key = parentKeys_1[_a];
var hasKey = set.has(key);
if (!hasKey) {
set.add(key);
keys.push(key);
}
}
return keys;
}
function OrdinaryOwnMetadataKeys(O, P) {
var keys = [];
var metadataMap = GetOrCreateMetadataMap(
O,
P,
/*Create*/
false
);
if (IsUndefined(metadataMap))
return keys;
var keysObj = metadataMap.keys();
var iterator = GetIterator(keysObj);
var k = 0;
while (true) {
var next = IteratorStep(iterator);
if (!next) {
keys.length = k;
return keys;
}
var nextValue = IteratorValue(next);
try {
keys[k] = nextValue;
} catch (e) {
try {
IteratorClose(iterator);
} finally {
throw e;
}
}
k++;
}
}
function Type(x) {
if (x === null)
return 1;
switch (typeof x) {
case "undefined":
return 0;
case "boolean":
return 2;
case "string":
return 3;
case "symbol":
return 4;
case "number":
return 5;
case "object":
return x === null ? 1 : 6;
default:
return 6;
}
}
function IsUndefined(x) {
return x === void 0;
}
function IsNull(x) {
return x === null;
}
function IsSymbol(x) {
return typeof x === "symbol";
}
function IsObject(x) {
return typeof x === "object" ? x !== null : typeof x === "function";
}
function ToPrimitive(input, PreferredType) {
switch (Type(input)) {
case 0:
return input;
case 1:
return input;
case 2:
return input;
case 3:
return input;
case 4:
return input;
case 5:
return input;
}
var hint = PreferredType === 3 ? "string" : PreferredType === 5 ? "number" : "default";
var exoticToPrim = GetMethod(input, toPrimitiveSymbol);
if (exoticToPrim !== void 0) {
var result = exoticToPrim.call(input, hint);
if (IsObject(result))
throw new TypeError();
return result;
}
return OrdinaryToPrimitive(input, hint === "default" ? "number" : hint);
}
function OrdinaryToPrimitive(O, hint) {
if (hint === "string") {
var toString_1 = O.toString;
if (IsCallable(toString_1)) {
var result = toString_1.call(O);
if (!IsObject(result))
return result;
}
var valueOf = O.valueOf;
if (IsCallable(valueOf)) {
var result = valueOf.call(O);
if (!IsObject(result))
return result;
}
} else {
var valueOf = O.valueOf;
if (IsCallable(valueOf)) {
var result = valueOf.call(O);
if (!IsObject(result))
return result;
}
var toString_2 = O.toString;
if (IsCallable(toString_2)) {
var result = toString_2.call(O);
if (!IsObject(result))
return result;
}
}
throw new TypeError();
}
function ToBoolean(argument) {
return !!argument;
}
function ToString(argument) {
return "" + argument;
}
function ToPropertyKey(argument) {
var key = ToPrimitive(
argument,
3
/* String */
);
if (IsSymbol(key))
return key;
return ToString(key);
}
function IsArray(argument) {
return Array.isArray ? Array.isArray(argument) : argument instanceof Object ? argument instanceof Array : Object.prototype.toString.call(argument) === "[object Array]";
}
function IsCallable(argument) {
return typeof argument === "function";
}
function IsConstructor(argument) {
return typeof argument === "function";
}
function IsPropertyKey(argument) {
switch (Type(argument)) {
case 3:
return true;
case 4:
return true;
default:
return false;
}
}
function GetMethod(V, P) {
var func = V[P];
if (func === void 0 || func === null)
return void 0;
if (!IsCallable(func))
throw new TypeError();
return func;
}
function GetIterator(obj) {
var method = GetMethod(obj, iteratorSymbol);
if (!IsCallable(method))
throw new TypeError();
var iterator = method.call(obj);
if (!IsObject(iterator))
throw new TypeError();
return iterator;
}
function IteratorValue(iterResult) {
return iterResult.value;
}
function IteratorStep(iterator) {
var result = iterator.next();
return result.done ? false : result;
}
function IteratorClose(iterator) {
var f = iterator["return"];
if (f)
f.call(iterator);
}
function OrdinaryGetPrototypeOf(O) {
var proto = Object.getPrototypeOf(O);
if (typeof O !== "function" || O === functionPrototype)
return proto;
if (proto !== functionPrototype)
return proto;
var prototype = O.prototype;
var prototypeProto = prototype && Object.getPrototypeOf(prototype);
if (prototypeProto == null || prototypeProto === Object.prototype)
return proto;
var constructor = prototypeProto.constructor;
if (typeof constructor !== "function")
return proto;
if (constructor === O)
return proto;
return constructor;
}
function CreateMapPolyfill() {
var cacheSentinel = {};
var arraySentinel = [];
var MapIterator = (
/** @class */
function() {
function MapIterator2(keys, values, selector) {
this._index = 0;
this._keys = keys;
this._values = values;
this._selector = selector;
}
MapIterator2.prototype["@@iterator"] = function() {
return this;
};
MapIterator2.prototype[iteratorSymbol] = function() {
return this;
};
MapIterator2.prototype.next = function() {
var index = this._index;
if (index >= 0 && index < this._keys.length) {
var result = this._selector(this._keys[index], this._values[index]);
if (index + 1 >= this._keys.length) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
} else {
this._index++;
}
return { value: result, done: false };
}
return { value: void 0, done: true };
};
MapIterator2.prototype.throw = function(error) {
if (this._index >= 0) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
}
throw error;
};
MapIterator2.prototype.return = function(value) {
if (this._index >= 0) {
this._index = -1;
this._keys = arraySentinel;
this._values = arraySentinel;
}
return { value, done: true };
};
return MapIterator2;
}()
);
return (
/** @class */
function() {
function Map2() {
this._keys = [];
this._values = [];
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
}
Object.defineProperty(Map2.prototype, "size", {
get: function() {
return this._keys.length;
},
enumerable: true,
configurable: true
});
Map2.prototype.has = function(key) {
return this._find(
key,
/*insert*/
false
) >= 0;
};
Map2.prototype.get = function(key) {
var index = this._find(
key,
/*insert*/
false
);
return index >= 0 ? this._values[index] : void 0;
};
Map2.prototype.set = function(key, value) {
var index = this._find(
key,
/*insert*/
true
);
this._values[index] = value;
return this;
};
Map2.prototype.delete = function(key) {
var index = this._find(
key,
/*insert*/
false
);
if (index >= 0) {
var size = this._keys.length;
for (var i = index + 1; i < size; i++) {
this._keys[i - 1] = this._keys[i];
this._values[i - 1] = this._values[i];
}
this._keys.length--;
this._values.length--;
if (key === this._cacheKey) {
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
}
return true;
}
return false;
};
Map2.prototype.clear = function() {
this._keys.length = 0;
this._values.length = 0;
this._cacheKey = cacheSentinel;
this._cacheIndex = -2;
};
Map2.prototype.keys = function() {
return new MapIterator(this._keys, this._values, getKey);
};
Map2.prototype.values = function() {
return new MapIterator(this._keys, this._values, getValue);
};
Map2.prototype.entries = function() {
return new MapIterator(this._keys, this._values, getEntry);
};
Map2.prototype["@@iterator"] = function() {
return this.entries();
};
Map2.prototype[iteratorSymbol] = function() {
return this.entries();
};
Map2.prototype._find = function(key, insert) {
if (this._cacheKey !== key) {
this._cacheIndex = this._keys.indexOf(this._cacheKey = key);
}
if (this._cacheIndex < 0 && insert) {
this._cacheIndex = this._keys.length;
this._keys.push(key);
this._values.push(void 0);
}
return this._cacheIndex;
};
return Map2;
}()
);
function getKey(key, _) {
return key;
}
function getValue(_, value) {
return value;
}
function getEntry(key, value) {
return [key, value];
}
}
function CreateSetPolyfill() {
return (
/** @class */
function() {
function Set2() {
this._map = new _Map();
}
Object.defineProperty(Set2.prototype, "size", {
get: function() {
return this._map.size;
},
enumerable: true,
configurable: true
});
Set2.prototype.has = function(value) {
return this._map.has(value);
};
Set2.prototype.add = function(value) {
return this._map.set(value, value), this;
};
Set2.prototype.delete = function(value) {
return this._map.delete(value);
};
Set2.prototype.clear = function() {
this._map.clear();
};
Set2.prototype.keys = function() {
return this._map.keys();
};
Set2.prototype.values = function() {
return this._map.values();
};
Set2.prototype.entries = function() {
return this._map.entries();
};
Set2.prototype["@@iterator"] = function() {
return this.keys();
};
Set2.prototype[iteratorSymbol] = function() {
return this.keys();
};
return Set2;
}()
);
}
function CreateWeakMapPolyfill() {
var UUID_SIZE = 16;
var keys = HashMap.create();
var rootKey = CreateUniqueKey();
return (
/** @class */
function() {
function WeakMap2() {
this._key = CreateUniqueKey();
}
WeakMap2.prototype.has = function(target) {
var table = GetOrCreateWeakMapTable(
target,
/*create*/
false
);
return table !== void 0 ? HashMap.has(table, this._key) : false;
};
WeakMap2.prototype.get = function(target) {
var table = GetOrCreateWeakMapTable(
target,
/*create*/
false
);
return table !== void 0 ? HashMap.get(table, this._key) : void 0;
};
WeakMap2.prototype.set = function(target, value) {
var table = GetOrCreateWeakMapTable(
target,
/*create*/
true
);
table[this._key] = value;
return this;
};
WeakMap2.prototype.delete = function(target) {
var table = GetOrCreateWeakMapTable(
target,
/*create*/
false
);
return table !== void 0 ? delete table[this._key] : false;
};
WeakMap2.prototype.clear = function() {
this._key = CreateUniqueKey();
};
return WeakMap2;
}()
);
function CreateUniqueKey() {
var key;
do
key = "@@WeakMap@@" + CreateUUID();
while (HashMap.has(keys, key));
keys[key] = true;
return key;
}
function GetOrCreateWeakMapTable(target, create2) {
if (!hasOwn.call(target, rootKey)) {
if (!create2)
return void 0;
Object.defineProperty(target, rootKey, { value: HashMap.create() });
}
return target[rootKey];
}
function FillRandomBytes(buffer, size) {
for (var i = 0; i < size; ++i)
buffer[i] = Math.random() * 255 | 0;
return buffer;
}
function GenRandomBytes(size) {
if (typeof Uint8Array === "function") {
if (typeof crypto !== "undefined")
return crypto.getRandomValues(new Uint8Array(size));
if (typeof msCrypto !== "undefined")
return msCrypto.getRandomValues(new Uint8Array(size));
return FillRandomBytes(new Uint8Array(size), size);
}
return FillRandomBytes(new Array(size), size);
}
function CreateUUID() {
var data = GenRandomBytes(UUID_SIZE);
data[6] = data[6] & 79 | 64;
data[8] = data[8] & 191 | 128;
var result = "";
for (var offset = 0; offset < UUID_SIZE; ++offset) {
var byte = data[offset];
if (offset === 4 || offset === 6 || offset === 8)
result += "-";
if (byte < 16)
result += "0";
result += byte.toString(16).toLowerCase();
}
return result;
}
}
function MakeDictionary(obj) {
obj.__ = void 0;
delete obj.__;
return obj;
}
});
})(Reflect2 || (Reflect2 = {}));
// main.ts
var import_obsidian17 = require("obsidian");
// src/Settings/SettingsTab.ts
var import_obsidian2 = require("obsidian");
// src/Components/EventDispatcher/Event.ts
var Event = class {
constructor(data) {
this.data = data;
}
get() {
return this.data;
}
stop() {
return;
}
};
// src/Utils/ObjectHelper.ts
var ObjectHelper = class _ObjectHelper {
static compare(old = {}, actual = {}) {
const changed = {};
const keys = [...Object.keys(old), ...Object.keys(actual)].filter((e, i, s) => s.indexOf(e) === i);
for (const k of keys) {
const first = old[k];
const second = actual[k];
const type = typeof (first !== void 0 ? first : second);
const thereIsNull = first === null || second === null;
if (type === "object" && !thereIsNull) {
if (Array.isArray(first)) {
const hasDiff = first.some((x) => !second.includes(x));
const isChanged = hasDiff ? true : second.some((x) => !first.includes(x));
if (isChanged) {
changed[k] = true;
}
} else {
const c = _ObjectHelper.compare(first, second);
if (Object.values(c).some((e) => e !== false)) {
changed[k] = c;
}
}
} else {
if (first !== second) {
changed[k] = true;
}
}
}
return changed;
}
static fillFrom(to, from) {
for (const [k, v] of Object.entries(to)) {
const fv = from[k];
if (fv === void 0) {
continue;
}
const type = typeof v;
if (type === "object" && !Array.isArray(fv) && v !== null) {
if (fv !== null) {
_ObjectHelper.fillFrom(v, fv);
}
continue;
}
to[k] = fv;
}
return to;
}
static entries(object) {
return Object.entries(object);
}
static values(object) {
return Object.values(object);
}
};
// node_modules/inversify/es/constants/metadata_keys.js
var NAMED_TAG = "named";
var NAME_TAG = "name";
var UNMANAGED_TAG = "unmanaged";
var OPTIONAL_TAG = "optional";
var INJECT_TAG = "inject";
var MULTI_INJECT_TAG = "multi_inject";
var TAGGED = "inversify:tagged";
var TAGGED_PROP = "inversify:tagged_props";
var PARAM_TYPES = "inversify:paramtypes";
var DESIGN_PARAM_TYPES = "design:paramtypes";
var POST_CONSTRUCT = "post_construct";
var PRE_DESTROY = "pre_destroy";
function getNonCustomTagKeys() {
return [
INJECT_TAG,
MULTI_INJECT_TAG,
NAME_TAG,
UNMANAGED_TAG,
NAMED_TAG,
OPTIONAL_TAG
];
}
var NON_CUSTOM_TAG_KEYS = getNonCustomTagKeys();
// node_modules/inversify/es/constants/literal_types.js
var BindingScopeEnum = {
Request: "Request",
Singleton: "Singleton",
Transient: "Transient"
};
var BindingTypeEnum = {
ConstantValue: "ConstantValue",
Constructor: "Constructor",
DynamicValue: "DynamicValue",
Factory: "Factory",
Function: "Function",
Instance: "Instance",
Invalid: "Invalid",
Provider: "Provider"
};
var TargetTypeEnum = {
ClassProperty: "ClassProperty",
ConstructorArgument: "ConstructorArgument",
Variable: "Variable"
};
// node_modules/inversify/es/utils/id.js
var idCounter = 0;
function id() {
return idCounter++;
}
// node_modules/inversify/es/bindings/binding.js
var Binding = function() {
function Binding2(serviceIdentifier, scope) {
this.id = id();
this.activated = false;
this.serviceIdentifier = serviceIdentifier;
this.scope = scope;
this.type = BindingTypeEnum.Invalid;
this.constraint = function(request) {
return true;
};
this.implementationType = null;
this.cache = null;
this.factory = null;
this.provider = null;
this.onActivation = null;
this.onDeactivation = null;
this.dynamicValue = null;
}
Binding2.prototype.clone = function() {
var clone = new Binding2(this.serviceIdentifier, this.scope);
clone.activated = clone.scope === BindingScopeEnum.Singleton ? this.activated : false;
clone.implementationType = this.implementationType;
clone.dynamicValue = this.dynamicValue;
clone.scope = this.scope;
clone.type = this.type;
clone.factory = this.factory;
clone.provider = this.provider;
clone.constraint = this.constraint;
clone.onActivation = this.onActivation;
clone.onDeactivation = this.onDeactivation;
clone.cache = this.cache;
return clone;
};
return Binding2;
}();
// node_modules/inversify/es/constants/error_msgs.js
var DUPLICATED_INJECTABLE_DECORATOR = "Cannot apply @injectable decorator multiple times.";
var DUPLICATED_METADATA = "Metadata key was used more than once in a parameter:";
var NULL_ARGUMENT = "NULL argument";
var KEY_NOT_FOUND = "Key Not Found";
var AMBIGUOUS_MATCH = "Ambiguous match found for serviceIdentifier:";
var CANNOT_UNBIND = "Could not unbind serviceIdentifier:";
var NOT_REGISTERED = "No matching bindings found for serviceIdentifier:";
var MISSING_INJECTABLE_ANNOTATION = "Missing required @injectable annotation in:";
var MISSING_INJECT_ANNOTATION = "Missing required @inject or @multiInject annotation in:";
var UNDEFINED_INJECT_ANNOTATION = function(name) {
return "@inject called with undefined this could mean that the class " + name + " has a circular dependency problem. You can use a LazyServiceIdentifer to overcome this limitation.";
};
var CIRCULAR_DEPENDENCY = "Circular dependency found:";
var INVALID_BINDING_TYPE = "Invalid binding type:";
var NO_MORE_SNAPSHOTS_AVAILABLE = "No snapshot available to restore.";
var INVALID_MIDDLEWARE_RETURN = "Invalid return type in middleware. Middleware must return!";
var INVALID_FUNCTION_BINDING = "Value provided to function binding must be a function!";
var LAZY_IN_SYNC = function(key) {
return "You are attempting to construct '" + key + "' in a synchronous way\n but it has asynchronous dependencies.";
};
var INVALID_TO_SELF_VALUE = "The toSelf function can only be applied when a constructor is used as service identifier";
var INVALID_DECORATOR_OPERATION = "The @inject @multiInject @tagged and @named decorators must be applied to the parameters of a class constructor or a class property.";
var ARGUMENTS_LENGTH_MISMATCH = function() {
var values = [];
for (var _i = 0; _i < arguments.length; _i++) {
values[_i] = arguments[_i];
}
return "The number of constructor arguments in the derived class " + (values[0] + " must be >= than the number of constructor arguments of its base class.");
};
var CONTAINER_OPTIONS_MUST_BE_AN_OBJECT = "Invalid Container constructor argument. Container options must be an object.";
var CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE = "Invalid Container option. Default scope must be a string ('singleton' or 'transient').";
var CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE = "Invalid Container option. Auto bind injectable must be a boolean";
var CONTAINER_OPTIONS_INVALID_SKIP_BASE_CHECK = "Invalid Container option. Skip base check must be a boolean";
var ASYNC_UNBIND_REQUIRED = "Attempting to unbind dependency with asynchronous destruction (@preDestroy or onDeactivation)";
var POST_CONSTRUCT_ERROR = function(clazz, errorMessage) {
return "@postConstruct error in class " + clazz + ": " + errorMessage;
};
var PRE_DESTROY_ERROR = function(clazz, errorMessage) {
return "@preDestroy error in class " + clazz + ": " + errorMessage;
};
var ON_DEACTIVATION_ERROR = function(clazz, errorMessage) {
return "onDeactivation() error in class " + clazz + ": " + errorMessage;
};
var CIRCULAR_DEPENDENCY_IN_FACTORY = function(factoryType, serviceIdentifier) {
return "It looks like there is a circular dependency in one of the '" + factoryType + "' bindings. Please investigate bindings with" + ("service identifier '" + serviceIdentifier + "'.");
};
var STACK_OVERFLOW = "Maximum call stack size exceeded";
// node_modules/inversify/es/planning/metadata_reader.js
var MetadataReader = function() {
function MetadataReader2() {
}
MetadataReader2.prototype.getConstructorMetadata = function(constructorFunc) {
var compilerGeneratedMetadata = Reflect.getMetadata(PARAM_TYPES, constructorFunc);
var userGeneratedMetadata = Reflect.getMetadata(TAGGED, constructorFunc);
return {
compilerGeneratedMetadata,
userGeneratedMetadata: userGeneratedMetadata || {}
};
};
MetadataReader2.prototype.getPropertiesMetadata = function(constructorFunc) {
var userGeneratedMetadata = Reflect.getMetadata(TAGGED_PROP, constructorFunc) || [];
return userGeneratedMetadata;
};
return MetadataReader2;
}();
// node_modules/inversify/es/bindings/binding_count.js
var BindingCount = {
MultipleBindingsAvailable: 2,
NoBindingsAvailable: 0,
OnlyOneBindingAvailable: 1
};
// node_modules/inversify/es/utils/exceptions.js
function isStackOverflowExeption(error) {
return error instanceof RangeError || error.message === STACK_OVERFLOW;
}
var tryAndThrowErrorIfStackOverflow = function(fn, errorCallback) {
try {
return fn();
} catch (error) {
if (isStackOverflowExeption(error)) {
error = errorCallback();
}
throw error;
}
};
// node_modules/inversify/es/utils/serialization.js
function getServiceIdentifierAsString(serviceIdentifier) {
if (typeof serviceIdentifier === "function") {
var _serviceIdentifier = serviceIdentifier;
return _serviceIdentifier.name;
} else if (typeof serviceIdentifier === "symbol") {
return serviceIdentifier.toString();
} else {
var _serviceIdentifier = serviceIdentifier;
return _serviceIdentifier;
}
}
function listRegisteredBindingsForServiceIdentifier(container, serviceIdentifier, getBindings2) {
var registeredBindingsList = "";
var registeredBindings = getBindings2(container, serviceIdentifier);
if (registeredBindings.length !== 0) {
registeredBindingsList = "\nRegistered bindings:";
registeredBindings.forEach(function(binding) {
var name = "Object";
if (binding.implementationType !== null) {
name = getFunctionName(binding.implementationType);
}
registeredBindingsList = registeredBindingsList + "\n " + name;
if (binding.constraint.metaData) {
registeredBindingsList = registeredBindingsList + " - " + binding.constraint.metaData;
}
});
}
return registeredBindingsList;
}
function alreadyDependencyChain(request, serviceIdentifier) {
if (request.parentRequest === null) {
return false;
} else if (request.parentRequest.serviceIdentifier === serviceIdentifier) {
return true;
} else {
return alreadyDependencyChain(request.parentRequest, serviceIdentifier);
}
}
function dependencyChainToString(request) {
function _createStringArr(req, result) {
if (result === void 0) {
result = [];
}
var serviceIdentifier = getServiceIdentifierAsString(req.serviceIdentifier);
result.push(serviceIdentifier);
if (req.parentRequest !== null) {
return _createStringArr(req.parentRequest, result);
}
return result;
}
var stringArr = _createStringArr(request);
return stringArr.reverse().join(" --> ");
}
function circularDependencyToException(request) {
request.childRequests.forEach(function(childRequest) {
if (alreadyDependencyChain(childRequest, childRequest.serviceIdentifier)) {
var services = dependencyChainToString(childRequest);
throw new Error(CIRCULAR_DEPENDENCY + " " + services);
} else {
circularDependencyToException(childRequest);
}
});
}
function listMetadataForTarget(serviceIdentifierString, target) {
if (target.isTagged() || target.isNamed()) {
var m_1 = "";
var namedTag = target.getNamedTag();
var otherTags = target.getCustomTags();
if (namedTag !== null) {
m_1 += namedTag.toString() + "\n";
}
if (otherTags !== null) {
otherTags.forEach(function(tag) {
m_1 += tag.toString() + "\n";
});
}
return " " + serviceIdentifierString + "\n " + serviceIdentifierString + " - " + m_1;
} else {
return " " + serviceIdentifierString;
}
}
function getFunctionName(func) {
if (func.name) {
return func.name;
} else {
var name_1 = func.toString();
var match = name_1.match(/^function\s*([^\s(]+)/);
return match ? match[1] : "Anonymous function: " + name_1;
}
}
function getSymbolDescription(symbol) {
return symbol.toString().slice(7, -1);
}
// node_modules/inversify/es/planning/context.js
var Context = function() {
function Context2(container) {
this.id = id();
this.container = container;
}
Context2.prototype.addPlan = function(plan2) {
this.plan = plan2;
};
Context2.prototype.setCurrentRequest = function(currentRequest) {
this.currentRequest = currentRequest;
};
return Context2;
}();
// node_modules/inversify/es/planning/metadata.js
var Metadata = function() {
function Metadata2(key, value) {
this.key = key;
this.value = value;
}
Metadata2.prototype.toString = function() {
if (this.key === NAMED_TAG) {
return "named: " + String(this.value).toString() + " ";
} else {
return "tagged: { key:" + this.key.toString() + ", value: " + String(this.value) + " }";
}
};
return Metadata2;
}();
// node_modules/inversify/es/planning/plan.js
var Plan = function() {
function Plan2(parentContext, rootRequest) {
this.parentContext = parentContext;
this.rootRequest = rootRequest;
}
return Plan2;
}();
// node_modules/inversify/es/annotation/lazy_service_identifier.js
var LazyServiceIdentifer = function() {
function LazyServiceIdentifer2(cb) {
this._cb = cb;
}
LazyServiceIdentifer2.prototype.unwrap = function() {
return this._cb();
};
return LazyServiceIdentifer2;
}();
// node_modules/inversify/es/planning/queryable_string.js
var QueryableString = function() {
function QueryableString2(str) {
this.str = str;
}
QueryableString2.prototype.startsWith = function(searchString) {
return this.str.indexOf(searchString) === 0;
};
QueryableString2.prototype.endsWith = function(searchString) {
var reverseString = "";
var reverseSearchString = searchString.split("").reverse().join("");
reverseString = this.str.split("").reverse().join("");
return this.startsWith.call({ str: reverseString }, reverseSearchString);
};
QueryableString2.prototype.contains = function(searchString) {
return this.str.indexOf(searchString) !== -1;
};
QueryableString2.prototype.equals = function(compareString) {
return this.str === compareString;
};
QueryableString2.prototype.value = function() {
return this.str;
};
return QueryableString2;
}();
// node_modules/inversify/es/planning/target.js
var Target = function() {
function Target2(type, identifier, serviceIdentifier, namedOrTagged) {
this.id = id();
this.type = type;
this.serviceIdentifier = serviceIdentifier;
var queryableName = typeof identifier === "symbol" ? getSymbolDescription(identifier) : identifier;
this.name = new QueryableString(queryableName || "");
this.identifier = identifier;
this.metadata = new Array();
var metadataItem = null;
if (typeof namedOrTagged === "string") {
metadataItem = new Metadata(NAMED_TAG, namedOrTagged);
} else if (namedOrTagged instanceof Metadata) {
metadataItem = namedOrTagged;
}
if (metadataItem !== null) {
this.metadata.push(metadataItem);
}
}
Target2.prototype.hasTag = function(key) {
for (var _i = 0, _a = this.metadata; _i < _a.length; _i++) {
var m = _a[_i];
if (m.key === key) {
return true;
}
}
return false;
};
Target2.prototype.isArray = function() {
return this.hasTag(MULTI_INJECT_TAG);
};
Target2.prototype.matchesArray = function(name) {
return this.matchesTag(MULTI_INJECT_TAG)(name);
};
Target2.prototype.isNamed = function() {
return this.hasTag(NAMED_TAG);
};
Target2.prototype.isTagged = function() {
return this.metadata.some(function(metadata) {
return NON_CUSTOM_TAG_KEYS.every(function(key) {
return metadata.key !== key;
});
});
};
Target2.prototype.isOptional = function() {
return this.matchesTag(OPTIONAL_TAG)(true);
};
Target2.prototype.getNamedTag = function() {
if (this.isNamed()) {
return this.metadata.filter(function(m) {
return m.key === NAMED_TAG;
})[0];
}
return null;
};
Target2.prototype.getCustomTags = function() {
if (this.isTagged()) {
return this.metadata.filter(function(metadata) {
return NON_CUSTOM_TAG_KEYS.every(function(key) {
return metadata.key !== key;
});
});
} else {
return null;
}
};
Target2.prototype.matchesNamedTag = function(name) {
return this.matchesTag(NAMED_TAG)(name);
};
Target2.prototype.matchesTag = function(key) {
var _this = this;
return function(value) {
for (var _i = 0, _a = _this.metadata; _i < _a.length; _i++) {
var m = _a[_i];
if (m.key === key && m.value === value) {
return true;
}
}
return false;
};
};
return Target2;
}();
// node_modules/inversify/es/planning/reflection_utils.js
var __spreadArray = function(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
function getDependencies(metadataReader, func) {
var constructorName = getFunctionName(func);
return getTargets(metadataReader, constructorName, func, false);
}
function getTargets(metadataReader, constructorName, func, isBaseClass) {
var metadata = metadataReader.getConstructorMetadata(func);
var serviceIdentifiers = metadata.compilerGeneratedMetadata;
if (serviceIdentifiers === void 0) {
var msg = MISSING_INJECTABLE_ANNOTATION + " " + constructorName + ".";
throw new Error(msg);
}
var constructorArgsMetadata = metadata.userGeneratedMetadata;
var keys = Object.keys(constructorArgsMetadata);
var hasUserDeclaredUnknownInjections = func.length === 0 && keys.length > 0;
var hasOptionalParameters = keys.length > func.length;
var iterations = hasUserDeclaredUnknownInjections || hasOptionalParameters ? keys.length : func.length;
var constructorTargets = getConstructorArgsAsTargets(isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata, iterations);
var propertyTargets = getClassPropsAsTargets(metadataReader, func, constructorName);
var targets = __spreadArray(__spreadArray([], constructorTargets, true), propertyTargets, true);
return targets;
}
function getConstructorArgsAsTarget(index, isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata) {
var targetMetadata = constructorArgsMetadata[index.toString()] || [];
var metadata = formatTargetMetadata(targetMetadata);
var isManaged = metadata.unmanaged !== true;
var serviceIdentifier = serviceIdentifiers[index];
var injectIdentifier = metadata.inject || metadata.multiInject;
serviceIdentifier = injectIdentifier ? injectIdentifier : serviceIdentifier;
if (serviceIdentifier instanceof LazyServiceIdentifer) {
serviceIdentifier = serviceIdentifier.unwrap();
}
if (isManaged) {
var isObject = serviceIdentifier === Object;
var isFunction = serviceIdentifier === Function;
var isUndefined = serviceIdentifier === void 0;
var isUnknownType = isObject || isFunction || isUndefined;
if (!isBaseClass && isUnknownType) {
var msg = MISSING_INJECT_ANNOTATION + " argument " + index + " in class " + constructorName + ".";
throw new Error(msg);
}
var target = new Target(TargetTypeEnum.ConstructorArgument, metadata.targetName, serviceIdentifier);
target.metadata = targetMetadata;
return target;
}
return null;
}
function getConstructorArgsAsTargets(isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata, iterations) {
var targets = [];
for (var i = 0; i < iterations; i++) {
var index = i;
var target = getConstructorArgsAsTarget(index, isBaseClass, constructorName, serviceIdentifiers, constructorArgsMetadata);
if (target !== null) {
targets.push(target);
}
}
return targets;
}
function _getServiceIdentifierForProperty(inject2, multiInject2, propertyName, className) {
var serviceIdentifier = inject2 || multiInject2;
if (serviceIdentifier === void 0) {
var msg = MISSING_INJECTABLE_ANNOTATION + " for property " + String(propertyName) + " in class " + className + ".";
throw new Error(msg);
}
return serviceIdentifier;
}
function getClassPropsAsTargets(metadataReader, constructorFunc, constructorName) {
var classPropsMetadata = metadataReader.getPropertiesMetadata(constructorFunc);
var targets = [];
var symbolKeys = Object.getOwnPropertySymbols(classPropsMetadata);
var stringKeys = Object.keys(classPropsMetadata);
var keys = stringKeys.concat(symbolKeys);
for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
var key = keys_1[_i];
var targetMetadata = classPropsMetadata[key];
var metadata = formatTargetMetadata(targetMetadata);
var identifier = metadata.targetName || key;
var serviceIdentifier = _getServiceIdentifierForProperty(metadata.inject, metadata.multiInject, key, constructorName);
var target = new Target(TargetTypeEnum.ClassProperty, identifier, serviceIdentifier);
target.metadata = targetMetadata;
targets.push(target);
}
var baseConstructor = Object.getPrototypeOf(constructorFunc.prototype).constructor;
if (baseConstructor !== Object) {
var baseTargets = getClassPropsAsTargets(metadataReader, baseConstructor, constructorName);
targets = __spreadArray(__spreadArray([], targets, true), baseTargets, true);
}
return targets;
}
function getBaseClassDependencyCount(metadataReader, func) {
var baseConstructor = Object.getPrototypeOf(func.prototype).constructor;
if (baseConstructor !== Object) {
var baseConstructorName = getFunctionName(baseConstructor);
var targets = getTargets(metadataReader, baseConstructorName, baseConstructor, true);
var metadata = targets.map(function(t3) {
return t3.metadata.filter(function(m) {
return m.key === UNMANAGED_TAG;
});
});
var unmanagedCount = [].concat.apply([], metadata).length;
var dependencyCount = targets.length - unmanagedCount;
if (dependencyCount > 0) {
return dependencyCount;
} else {
return getBaseClassDependencyCount(metadataReader, baseConstructor);
}
} else {
return 0;
}
}
function formatTargetMetadata(targetMetadata) {
var targetMetadataMap = {};
targetMetadata.forEach(function(m) {
targetMetadataMap[m.key.toString()] = m.value;
});
return {
inject: targetMetadataMap[INJECT_TAG],
multiInject: targetMetadataMap[MULTI_INJECT_TAG],
targetName: targetMetadataMap[NAME_TAG],
unmanaged: targetMetadataMap[UNMANAGED_TAG]
};
}
// node_modules/inversify/es/planning/request.js
var Request = function() {
function Request2(serviceIdentifier, parentContext, parentRequest, bindings, target) {
this.id = id();
this.serviceIdentifier = serviceIdentifier;
this.parentContext = parentContext;
this.parentRequest = parentRequest;
this.target = target;
this.childRequests = [];
this.bindings = Array.isArray(bindings) ? bindings : [bindings];
this.requestScope = parentRequest === null ? /* @__PURE__ */ new Map() : null;
}
Request2.prototype.addChildRequest = function(serviceIdentifier, bindings, target) {
var child = new Request2(serviceIdentifier, this.parentContext, this, bindings, target);
this.childRequests.push(child);
return child;
};
return Request2;
}();
// node_modules/inversify/es/planning/planner.js
function getBindingDictionary(cntnr) {
return cntnr._bindingDictionary;
}
function _createTarget(isMultiInject, targetType, serviceIdentifier, name, key, value) {
var metadataKey = isMultiInject ? MULTI_INJECT_TAG : INJECT_TAG;
var injectMetadata = new Metadata(metadataKey, serviceIdentifier);
var target = new Target(targetType, name, serviceIdentifier, injectMetadata);
if (key !== void 0) {
var tagMetadata = new Metadata(key, value);
target.metadata.push(tagMetadata);
}
return target;
}
function _getActiveBindings(metadataReader, avoidConstraints, context, parentRequest, target) {
var bindings = getBindings(context.container, target.serviceIdentifier);
var activeBindings = [];
if (bindings.length === BindingCount.NoBindingsAvailable && context.container.options.autoBindInjectable && typeof target.serviceIdentifier === "function" && metadataReader.getConstructorMetadata(target.serviceIdentifier).compilerGeneratedMetadata) {
context.container.bind(target.serviceIdentifier).toSelf();
bindings = getBindings(context.container, target.serviceIdentifier);
}
if (!avoidConstraints) {
activeBindings = bindings.filter(function(binding) {
var request = new Request(binding.serviceIdentifier, context, parentRequest, binding, target);
return binding.constraint(request);
});
} else {
activeBindings = bindings;
}
_validateActiveBindingCount(target.serviceIdentifier, activeBindings, target, context.container);
return activeBindings;
}
function _validateActiveBindingCount(serviceIdentifier, bindings, target, container) {
switch (bindings.length) {
case BindingCount.NoBindingsAvailable:
if (target.isOptional()) {
return bindings;
} else {
var serviceIdentifierString = getServiceIdentifierAsString(serviceIdentifier);
var msg = NOT_REGISTERED;
msg += listMetadataForTarget(serviceIdentifierString, target);
msg += listRegisteredBindingsForServiceIdentifier(container, serviceIdentifierString, getBindings);
throw new Error(msg);
}
case BindingCount.OnlyOneBindingAvailable:
return bindings;
case BindingCount.MultipleBindingsAvailable:
default:
if (!target.isArray()) {
var serviceIdentifierString = getServiceIdentifierAsString(serviceIdentifier);
var msg = AMBIGUOUS_MATCH + " " + serviceIdentifierString;
msg += listRegisteredBindingsForServiceIdentifier(container, serviceIdentifierString, getBindings);
throw new Error(msg);
} else {
return bindings;
}
}
}
function _createSubRequests(metadataReader, avoidConstraints, serviceIdentifier, context, parentRequest, target) {
var activeBindings;
var childRequest;
if (parentRequest === null) {
activeBindings = _getActiveBindings(metadataReader, avoidConstraints, context, null, target);
childRequest = new Request(serviceIdentifier, context, null, activeBindings, target);
var thePlan = new Plan(context, childRequest);
context.addPlan(thePlan);
} else {
activeBindings = _getActiveBindings(metadataReader, avoidConstraints, context, parentRequest, target);
childRequest = parentRequest.addChildRequest(target.serviceIdentifier, activeBindings, target);
}
activeBindings.forEach(function(binding) {
var subChildRequest = null;
if (target.isArray()) {
subChildRequest = childRequest.addChildRequest(binding.serviceIdentifier, binding, target);
} else {
if (binding.cache) {
return;
}
subChildRequest = childRequest;
}
if (binding.type === BindingTypeEnum.Instance && binding.implementationType !== null) {
var dependencies = getDependencies(metadataReader, binding.implementationType);
if (!context.container.options.skipBaseClassChecks) {
var baseClassDependencyCount = getBaseClassDependencyCount(metadataReader, binding.implementationType);
if (dependencies.length < baseClassDependencyCount) {
var error = ARGUMENTS_LENGTH_MISMATCH(getFunctionName(binding.implementationType));
throw new Error(error);
}
}
dependencies.forEach(function(dependency) {
_createSubRequests(metadataReader, false, dependency.serviceIdentifier, context, subChildRequest, dependency);
});
}
});
}
function getBindings(container, serviceIdentifier) {
var bindings = [];
var bindingDictionary = getBindingDictionary(container);
if (bindingDictionary.hasKey(serviceIdentifier)) {
bindings = bindingDictionary.get(serviceIdentifier);
} else if (container.parent !== null) {
bindings = getBindings(container.parent, serviceIdentifier);
}
return bindings;
}
function plan(metadataReader, container, isMultiInject, targetType, serviceIdentifier, key, value, avoidConstraints) {
if (avoidConstraints === void 0) {
avoidConstraints = false;
}
var context = new Context(container);
var target = _createTarget(isMultiInject, targetType, serviceIdentifier, "", key, value);
try {
_createSubRequests(metadataReader, avoidConstraints, serviceIdentifier, context, null, target);
return context;
} catch (error) {
if (isStackOverflowExeption(error)) {
circularDependencyToException(context.plan.rootRequest);
}
throw error;
}
}
function createMockRequest(container, serviceIdentifier, key, value) {
var target = new Target(TargetTypeEnum.Variable, "", serviceIdentifier, new Metadata(key, value));
var context = new Context(container);
var request = new Request(serviceIdentifier, context, null, [], target);
return request;
}
// node_modules/inversify/es/utils/async.js
function isPromise(object) {
var isObjectOrFunction = typeof object === "object" && object !== null || typeof object === "function";
return isObjectOrFunction && typeof object.then === "function";
}
function isPromiseOrContainsPromise(object) {
if (isPromise(object)) {
return true;
}
return Array.isArray(object) && object.some(isPromise);
}
// node_modules/inversify/es/scope/scope.js
var __awaiter = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t3[0] & 1)
throw t3[1];
return t3[1];
}, trys: [], ops: [] }, f, y, t3, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t3 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t3 = y["return"]) && t3.call(y), 0) : y.next) && !(t3 = t3.call(y, op[1])).done)
return t3;
if (y = 0, t3)
op = [op[0] & 2, t3.value];
switch (op[0]) {
case 0:
case 1:
t3 = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t3 = _.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t3[1]) {
_.label = t3[1];
t3 = op;
break;
}
if (t3 && _.label < t3[2]) {
_.label = t3[2];
_.ops.push(op);
break;
}
if (t3[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t3 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
var tryGetFromScope = function(requestScope, binding) {
if (binding.scope === BindingScopeEnum.Singleton && binding.activated) {
return binding.cache;
}
if (binding.scope === BindingScopeEnum.Request && requestScope.has(binding.id)) {
return requestScope.get(binding.id);
}
return null;
};
var saveToScope = function(requestScope, binding, result) {
if (binding.scope === BindingScopeEnum.Singleton) {
_saveToSingletonScope(binding, result);
}
if (binding.scope === BindingScopeEnum.Request) {
_saveToRequestScope(requestScope, binding, result);
}
};
var _saveToRequestScope = function(requestScope, binding, result) {
if (!requestScope.has(binding.id)) {
requestScope.set(binding.id, result);
}
};
var _saveToSingletonScope = function(binding, result) {
binding.cache = result;
binding.activated = true;
if (isPromise(result)) {
void _saveAsyncResultToSingletonScope(binding, result);
}
};
var _saveAsyncResultToSingletonScope = function(binding, asyncResult) {
return __awaiter(void 0, void 0, void 0, function() {
var result, ex_1;
return __generator(this, function(_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4, asyncResult];
case 1:
result = _a.sent();
binding.cache = result;
return [3, 3];
case 2:
ex_1 = _a.sent();
binding.cache = null;
binding.activated = false;
throw ex_1;
case 3:
return [2];
}
});
});
};
// node_modules/inversify/es/utils/factory_type.js
var FactoryType;
(function(FactoryType2) {
FactoryType2["DynamicValue"] = "toDynamicValue";
FactoryType2["Factory"] = "toFactory";
FactoryType2["Provider"] = "toProvider";
})(FactoryType || (FactoryType = {}));
// node_modules/inversify/es/utils/binding_utils.js
var ensureFullyBound = function(binding) {
var boundValue = null;
switch (binding.type) {
case BindingTypeEnum.ConstantValue:
case BindingTypeEnum.Function:
boundValue = binding.cache;
break;
case BindingTypeEnum.Constructor:
case BindingTypeEnum.Instance:
boundValue = binding.implementationType;
break;
case BindingTypeEnum.DynamicValue:
boundValue = binding.dynamicValue;
break;
case BindingTypeEnum.Provider:
boundValue = binding.provider;
break;
case BindingTypeEnum.Factory:
boundValue = binding.factory;
break;
}
if (boundValue === null) {
var serviceIdentifierAsString = getServiceIdentifierAsString(binding.serviceIdentifier);
throw new Error(INVALID_BINDING_TYPE + " " + serviceIdentifierAsString);
}
};
var getFactoryDetails = function(binding) {
switch (binding.type) {
case BindingTypeEnum.Factory:
return { factory: binding.factory, factoryType: FactoryType.Factory };
case BindingTypeEnum.Provider:
return { factory: binding.provider, factoryType: FactoryType.Provider };
case BindingTypeEnum.DynamicValue:
return { factory: binding.dynamicValue, factoryType: FactoryType.DynamicValue };
default:
throw new Error("Unexpected factory type " + binding.type);
}
};
// node_modules/inversify/es/resolution/instantiation.js
var __assign = function() {
__assign = Object.assign || function(t3) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t3[p] = s[p];
}
return t3;
};
return __assign.apply(this, arguments);
};
var __awaiter2 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator2 = function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t3[0] & 1)
throw t3[1];
return t3[1];
}, trys: [], ops: [] }, f, y, t3, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t3 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t3 = y["return"]) && t3.call(y), 0) : y.next) && !(t3 = t3.call(y, op[1])).done)
return t3;
if (y = 0, t3)
op = [op[0] & 2, t3.value];
switch (op[0]) {
case 0:
case 1:
t3 = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t3 = _.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t3[1]) {
_.label = t3[1];
t3 = op;
break;
}
if (t3 && _.label < t3[2]) {
_.label = t3[2];
_.ops.push(op);
break;
}
if (t3[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t3 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray2 = function(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
function _resolveRequests(childRequests, resolveRequest) {
return childRequests.reduce(function(resolvedRequests, childRequest) {
var injection = resolveRequest(childRequest);
var targetType = childRequest.target.type;
if (targetType === TargetTypeEnum.ConstructorArgument) {
resolvedRequests.constructorInjections.push(injection);
} else {
resolvedRequests.propertyRequests.push(childRequest);
resolvedRequests.propertyInjections.push(injection);
}
if (!resolvedRequests.isAsync) {
resolvedRequests.isAsync = isPromiseOrContainsPromise(injection);
}
return resolvedRequests;
}, { constructorInjections: [], propertyInjections: [], propertyRequests: [], isAsync: false });
}
function _createInstance(constr, childRequests, resolveRequest) {
var result;
if (childRequests.length > 0) {
var resolved2 = _resolveRequests(childRequests, resolveRequest);
var createInstanceWithInjectionsArg = __assign(__assign({}, resolved2), { constr });
if (resolved2.isAsync) {
result = createInstanceWithInjectionsAsync(createInstanceWithInjectionsArg);
} else {
result = createInstanceWithInjections(createInstanceWithInjectionsArg);
}
} else {
result = new constr();
}
return result;
}
function createInstanceWithInjections(args) {
var _a;
var instance2 = new ((_a = args.constr).bind.apply(_a, __spreadArray2([void 0], args.constructorInjections, false)))();
args.propertyRequests.forEach(function(r, index) {
var property = r.target.identifier;
var injection = args.propertyInjections[index];
instance2[property] = injection;
});
return instance2;
}
function createInstanceWithInjectionsAsync(args) {
return __awaiter2(this, void 0, void 0, function() {
var constructorInjections, propertyInjections;
return __generator2(this, function(_a) {
switch (_a.label) {
case 0:
return [4, possiblyWaitInjections(args.constructorInjections)];
case 1:
constructorInjections = _a.sent();
return [4, possiblyWaitInjections(args.propertyInjections)];
case 2:
propertyInjections = _a.sent();
return [2, createInstanceWithInjections(__assign(__assign({}, args), { constructorInjections, propertyInjections }))];
}
});
});
}
function possiblyWaitInjections(possiblePromiseinjections) {
return __awaiter2(this, void 0, void 0, function() {
var injections, _i, possiblePromiseinjections_1, injection;
return __generator2(this, function(_a) {
injections = [];
for (_i = 0, possiblePromiseinjections_1 = possiblePromiseinjections; _i < possiblePromiseinjections_1.length; _i++) {
injection = possiblePromiseinjections_1[_i];
if (Array.isArray(injection)) {
injections.push(Promise.all(injection));
} else {
injections.push(injection);
}
}
return [2, Promise.all(injections)];
});
});
}
function _getInstanceAfterPostConstruct(constr, result) {
var postConstructResult = _postConstruct(constr, result);
if (isPromise(postConstructResult)) {
return postConstructResult.then(function() {
return result;
});
} else {
return result;
}
}
function _postConstruct(constr, instance2) {
var _a, _b;
if (Reflect.hasMetadata(POST_CONSTRUCT, constr)) {
var data = Reflect.getMetadata(POST_CONSTRUCT, constr);
try {
return (_b = (_a = instance2)[data.value]) === null || _b === void 0 ? void 0 : _b.call(_a);
} catch (e) {
throw new Error(POST_CONSTRUCT_ERROR(constr.name, e.message));
}
}
}
function _validateInstanceResolution(binding, constr) {
if (binding.scope !== BindingScopeEnum.Singleton) {
_throwIfHandlingDeactivation(binding, constr);
}
}
function _throwIfHandlingDeactivation(binding, constr) {
var scopeErrorMessage = "Class cannot be instantiated in " + (binding.scope === BindingScopeEnum.Request ? "request" : "transient") + " scope.";
if (typeof binding.onDeactivation === "function") {
throw new Error(ON_DEACTIVATION_ERROR(constr.name, scopeErrorMessage));
}
if (Reflect.hasMetadata(PRE_DESTROY, constr)) {
throw new Error(PRE_DESTROY_ERROR(constr.name, scopeErrorMessage));
}
}
function resolveInstance(binding, constr, childRequests, resolveRequest) {
_validateInstanceResolution(binding, constr);
var result = _createInstance(constr, childRequests, resolveRequest);
if (isPromise(result)) {
return result.then(function(resolvedResult) {
return _getInstanceAfterPostConstruct(constr, resolvedResult);
});
} else {
return _getInstanceAfterPostConstruct(constr, result);
}
}
// node_modules/inversify/es/resolution/resolver.js
var __awaiter3 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator3 = function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t3[0] & 1)
throw t3[1];
return t3[1];
}, trys: [], ops: [] }, f, y, t3, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t3 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t3 = y["return"]) && t3.call(y), 0) : y.next) && !(t3 = t3.call(y, op[1])).done)
return t3;
if (y = 0, t3)
op = [op[0] & 2, t3.value];
switch (op[0]) {
case 0:
case 1:
t3 = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t3 = _.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t3[1]) {
_.label = t3[1];
t3 = op;
break;
}
if (t3 && _.label < t3[2]) {
_.label = t3[2];
_.ops.push(op);
break;
}
if (t3[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t3 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
var _resolveRequest = function(requestScope) {
return function(request) {
request.parentContext.setCurrentRequest(request);
var bindings = request.bindings;
var childRequests = request.childRequests;
var targetIsAnArray = request.target && request.target.isArray();
var targetParentIsNotAnArray = !request.parentRequest || !request.parentRequest.target || !request.target || !request.parentRequest.target.matchesArray(request.target.serviceIdentifier);
if (targetIsAnArray && targetParentIsNotAnArray) {
return childRequests.map(function(childRequest) {
var _f = _resolveRequest(requestScope);
return _f(childRequest);
});
} else {
if (request.target.isOptional() && bindings.length === 0) {
return void 0;
}
var binding = bindings[0];
return _resolveBinding(requestScope, request, binding);
}
};
};
var _resolveFactoryFromBinding = function(binding, context) {
var factoryDetails = getFactoryDetails(binding);
return tryAndThrowErrorIfStackOverflow(function() {
return factoryDetails.factory.bind(binding)(context);
}, function() {
return new Error(CIRCULAR_DEPENDENCY_IN_FACTORY(factoryDetails.factoryType, context.currentRequest.serviceIdentifier.toString()));
});
};
var _getResolvedFromBinding = function(requestScope, request, binding) {
var result;
var childRequests = request.childRequests;
ensureFullyBound(binding);
switch (binding.type) {
case BindingTypeEnum.ConstantValue:
case BindingTypeEnum.Function:
result = binding.cache;
break;
case BindingTypeEnum.Constructor:
result = binding.implementationType;
break;
case BindingTypeEnum.Instance:
result = resolveInstance(binding, binding.implementationType, childRequests, _resolveRequest(requestScope));
break;
default:
result = _resolveFactoryFromBinding(binding, request.parentContext);
}
return result;
};
var _resolveInScope = function(requestScope, binding, resolveFromBinding) {
var result = tryGetFromScope(requestScope, binding);
if (result !== null) {
return result;
}
result = resolveFromBinding();
saveToScope(requestScope, binding, result);
return result;
};
var _resolveBinding = function(requestScope, request, binding) {
return _resolveInScope(requestScope, binding, function() {
var result = _getResolvedFromBinding(requestScope, request, binding);
if (isPromise(result)) {
result = result.then(function(resolved2) {
return _onActivation(request, binding, resolved2);
});
} else {
result = _onActivation(request, binding, result);
}
return result;
});
};
function _onActivation(request, binding, resolved2) {
var result = _bindingActivation(request.parentContext, binding, resolved2);
var containersIterator = _getContainersIterator(request.parentContext.container);
var container;
var containersIteratorResult = containersIterator.next();
do {
container = containersIteratorResult.value;
var context_1 = request.parentContext;
var serviceIdentifier = request.serviceIdentifier;
var activationsIterator = _getContainerActivationsForService(container, serviceIdentifier);
if (isPromise(result)) {
result = _activateContainerAsync(activationsIterator, context_1, result);
} else {
result = _activateContainer(activationsIterator, context_1, result);
}
containersIteratorResult = containersIterator.next();
} while (containersIteratorResult.done !== true && !getBindingDictionary(container).hasKey(request.serviceIdentifier));
return result;
}
var _bindingActivation = function(context, binding, previousResult) {
var result;
if (typeof binding.onActivation === "function") {
result = binding.onActivation(context, previousResult);
} else {
result = previousResult;
}
return result;
};
var _activateContainer = function(activationsIterator, context, result) {
var activation = activationsIterator.next();
while (!activation.done) {
result = activation.value(context, result);
if (isPromise(result)) {
return _activateContainerAsync(activationsIterator, context, result);
}
activation = activationsIterator.next();
}
return result;
};
var _activateContainerAsync = function(activationsIterator, context, resultPromise) {
return __awaiter3(void 0, void 0, void 0, function() {
var result, activation;
return __generator3(this, function(_a) {
switch (_a.label) {
case 0:
return [4, resultPromise];
case 1:
result = _a.sent();
activation = activationsIterator.next();
_a.label = 2;
case 2:
if (!!activation.done)
return [3, 4];
return [4, activation.value(context, result)];
case 3:
result = _a.sent();
activation = activationsIterator.next();
return [3, 2];
case 4:
return [2, result];
}
});
});
};
var _getContainerActivationsForService = function(container, serviceIdentifier) {
var activations = container._activations;
return activations.hasKey(serviceIdentifier) ? activations.get(serviceIdentifier).values() : [].values();
};
var _getContainersIterator = function(container) {
var containersStack = [container];
var parent = container.parent;
while (parent !== null) {
containersStack.push(parent);
parent = parent.parent;
}
var getNextContainer = function() {
var nextContainer = containersStack.pop();
if (nextContainer !== void 0) {
return { done: false, value: nextContainer };
} else {
return { done: true, value: void 0 };
}
};
var containersIterator = {
next: getNextContainer
};
return containersIterator;
};
function resolve(context) {
var _f = _resolveRequest(context.plan.rootRequest.requestScope);
return _f(context.plan.rootRequest);
}
// node_modules/inversify/es/syntax/constraint_helpers.js
var traverseAncerstors = function(request, constraint) {
var parent = request.parentRequest;
if (parent !== null) {
return constraint(parent) ? true : traverseAncerstors(parent, constraint);
} else {
return false;
}
};
var taggedConstraint = function(key) {
return function(value) {
var constraint = function(request) {
return request !== null && request.target !== null && request.target.matchesTag(key)(value);
};
constraint.metaData = new Metadata(key, value);
return constraint;
};
};
var namedConstraint = taggedConstraint(NAMED_TAG);
var typeConstraint = function(type) {
return function(request) {
var binding = null;
if (request !== null) {
binding = request.bindings[0];
if (typeof type === "string") {
var serviceIdentifier = binding.serviceIdentifier;
return serviceIdentifier === type;
} else {
var constructor = request.bindings[0].implementationType;
return type === constructor;
}
}
return false;
};
};
// node_modules/inversify/es/syntax/binding_when_syntax.js
var BindingWhenSyntax = function() {
function BindingWhenSyntax2(binding) {
this._binding = binding;
}
BindingWhenSyntax2.prototype.when = function(constraint) {
this._binding.constraint = constraint;
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenTargetNamed = function(name) {
this._binding.constraint = namedConstraint(name);
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenTargetIsDefault = function() {
this._binding.constraint = function(request) {
if (request === null) {
return false;
}
var targetIsDefault = request.target !== null && !request.target.isNamed() && !request.target.isTagged();
return targetIsDefault;
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenTargetTagged = function(tag, value) {
this._binding.constraint = taggedConstraint(tag)(value);
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenInjectedInto = function(parent) {
this._binding.constraint = function(request) {
return request !== null && typeConstraint(parent)(request.parentRequest);
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenParentNamed = function(name) {
this._binding.constraint = function(request) {
return request !== null && namedConstraint(name)(request.parentRequest);
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenParentTagged = function(tag, value) {
this._binding.constraint = function(request) {
return request !== null && taggedConstraint(tag)(value)(request.parentRequest);
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenAnyAncestorIs = function(ancestor) {
this._binding.constraint = function(request) {
return request !== null && traverseAncerstors(request, typeConstraint(ancestor));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenNoAncestorIs = function(ancestor) {
this._binding.constraint = function(request) {
return request !== null && !traverseAncerstors(request, typeConstraint(ancestor));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenAnyAncestorNamed = function(name) {
this._binding.constraint = function(request) {
return request !== null && traverseAncerstors(request, namedConstraint(name));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenNoAncestorNamed = function(name) {
this._binding.constraint = function(request) {
return request !== null && !traverseAncerstors(request, namedConstraint(name));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenAnyAncestorTagged = function(tag, value) {
this._binding.constraint = function(request) {
return request !== null && traverseAncerstors(request, taggedConstraint(tag)(value));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenNoAncestorTagged = function(tag, value) {
this._binding.constraint = function(request) {
return request !== null && !traverseAncerstors(request, taggedConstraint(tag)(value));
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenAnyAncestorMatches = function(constraint) {
this._binding.constraint = function(request) {
return request !== null && traverseAncerstors(request, constraint);
};
return new BindingOnSyntax(this._binding);
};
BindingWhenSyntax2.prototype.whenNoAncestorMatches = function(constraint) {
this._binding.constraint = function(request) {
return request !== null && !traverseAncerstors(request, constraint);
};
return new BindingOnSyntax(this._binding);
};
return BindingWhenSyntax2;
}();
// node_modules/inversify/es/syntax/binding_on_syntax.js
var BindingOnSyntax = function() {
function BindingOnSyntax2(binding) {
this._binding = binding;
}
BindingOnSyntax2.prototype.onActivation = function(handler) {
this._binding.onActivation = handler;
return new BindingWhenSyntax(this._binding);
};
BindingOnSyntax2.prototype.onDeactivation = function(handler) {
this._binding.onDeactivation = handler;
return new BindingWhenSyntax(this._binding);
};
return BindingOnSyntax2;
}();
// node_modules/inversify/es/syntax/binding_when_on_syntax.js
var BindingWhenOnSyntax = function() {
function BindingWhenOnSyntax2(binding) {
this._binding = binding;
this._bindingWhenSyntax = new BindingWhenSyntax(this._binding);
this._bindingOnSyntax = new BindingOnSyntax(this._binding);
}
BindingWhenOnSyntax2.prototype.when = function(constraint) {
return this._bindingWhenSyntax.when(constraint);
};
BindingWhenOnSyntax2.prototype.whenTargetNamed = function(name) {
return this._bindingWhenSyntax.whenTargetNamed(name);
};
BindingWhenOnSyntax2.prototype.whenTargetIsDefault = function() {
return this._bindingWhenSyntax.whenTargetIsDefault();
};
BindingWhenOnSyntax2.prototype.whenTargetTagged = function(tag, value) {
return this._bindingWhenSyntax.whenTargetTagged(tag, value);
};
BindingWhenOnSyntax2.prototype.whenInjectedInto = function(parent) {
return this._bindingWhenSyntax.whenInjectedInto(parent);
};
BindingWhenOnSyntax2.prototype.whenParentNamed = function(name) {
return this._bindingWhenSyntax.whenParentNamed(name);
};
BindingWhenOnSyntax2.prototype.whenParentTagged = function(tag, value) {
return this._bindingWhenSyntax.whenParentTagged(tag, value);
};
BindingWhenOnSyntax2.prototype.whenAnyAncestorIs = function(ancestor) {
return this._bindingWhenSyntax.whenAnyAncestorIs(ancestor);
};
BindingWhenOnSyntax2.prototype.whenNoAncestorIs = function(ancestor) {
return this._bindingWhenSyntax.whenNoAncestorIs(ancestor);
};
BindingWhenOnSyntax2.prototype.whenAnyAncestorNamed = function(name) {
return this._bindingWhenSyntax.whenAnyAncestorNamed(name);
};
BindingWhenOnSyntax2.prototype.whenAnyAncestorTagged = function(tag, value) {
return this._bindingWhenSyntax.whenAnyAncestorTagged(tag, value);
};
BindingWhenOnSyntax2.prototype.whenNoAncestorNamed = function(name) {
return this._bindingWhenSyntax.whenNoAncestorNamed(name);
};
BindingWhenOnSyntax2.prototype.whenNoAncestorTagged = function(tag, value) {
return this._bindingWhenSyntax.whenNoAncestorTagged(tag, value);
};
BindingWhenOnSyntax2.prototype.whenAnyAncestorMatches = function(constraint) {
return this._bindingWhenSyntax.whenAnyAncestorMatches(constraint);
};
BindingWhenOnSyntax2.prototype.whenNoAncestorMatches = function(constraint) {
return this._bindingWhenSyntax.whenNoAncestorMatches(constraint);
};
BindingWhenOnSyntax2.prototype.onActivation = function(handler) {
return this._bindingOnSyntax.onActivation(handler);
};
BindingWhenOnSyntax2.prototype.onDeactivation = function(handler) {
return this._bindingOnSyntax.onDeactivation(handler);
};
return BindingWhenOnSyntax2;
}();
// node_modules/inversify/es/syntax/binding_in_syntax.js
var BindingInSyntax = function() {
function BindingInSyntax2(binding) {
this._binding = binding;
}
BindingInSyntax2.prototype.inRequestScope = function() {
this._binding.scope = BindingScopeEnum.Request;
return new BindingWhenOnSyntax(this._binding);
};
BindingInSyntax2.prototype.inSingletonScope = function() {
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingInSyntax2.prototype.inTransientScope = function() {
this._binding.scope = BindingScopeEnum.Transient;
return new BindingWhenOnSyntax(this._binding);
};
return BindingInSyntax2;
}();
// node_modules/inversify/es/syntax/binding_in_when_on_syntax.js
var BindingInWhenOnSyntax = function() {
function BindingInWhenOnSyntax2(binding) {
this._binding = binding;
this._bindingWhenSyntax = new BindingWhenSyntax(this._binding);
this._bindingOnSyntax = new BindingOnSyntax(this._binding);
this._bindingInSyntax = new BindingInSyntax(binding);
}
BindingInWhenOnSyntax2.prototype.inRequestScope = function() {
return this._bindingInSyntax.inRequestScope();
};
BindingInWhenOnSyntax2.prototype.inSingletonScope = function() {
return this._bindingInSyntax.inSingletonScope();
};
BindingInWhenOnSyntax2.prototype.inTransientScope = function() {
return this._bindingInSyntax.inTransientScope();
};
BindingInWhenOnSyntax2.prototype.when = function(constraint) {
return this._bindingWhenSyntax.when(constraint);
};
BindingInWhenOnSyntax2.prototype.whenTargetNamed = function(name) {
return this._bindingWhenSyntax.whenTargetNamed(name);
};
BindingInWhenOnSyntax2.prototype.whenTargetIsDefault = function() {
return this._bindingWhenSyntax.whenTargetIsDefault();
};
BindingInWhenOnSyntax2.prototype.whenTargetTagged = function(tag, value) {
return this._bindingWhenSyntax.whenTargetTagged(tag, value);
};
BindingInWhenOnSyntax2.prototype.whenInjectedInto = function(parent) {
return this._bindingWhenSyntax.whenInjectedInto(parent);
};
BindingInWhenOnSyntax2.prototype.whenParentNamed = function(name) {
return this._bindingWhenSyntax.whenParentNamed(name);
};
BindingInWhenOnSyntax2.prototype.whenParentTagged = function(tag, value) {
return this._bindingWhenSyntax.whenParentTagged(tag, value);
};
BindingInWhenOnSyntax2.prototype.whenAnyAncestorIs = function(ancestor) {
return this._bindingWhenSyntax.whenAnyAncestorIs(ancestor);
};
BindingInWhenOnSyntax2.prototype.whenNoAncestorIs = function(ancestor) {
return this._bindingWhenSyntax.whenNoAncestorIs(ancestor);
};
BindingInWhenOnSyntax2.prototype.whenAnyAncestorNamed = function(name) {
return this._bindingWhenSyntax.whenAnyAncestorNamed(name);
};
BindingInWhenOnSyntax2.prototype.whenAnyAncestorTagged = function(tag, value) {
return this._bindingWhenSyntax.whenAnyAncestorTagged(tag, value);
};
BindingInWhenOnSyntax2.prototype.whenNoAncestorNamed = function(name) {
return this._bindingWhenSyntax.whenNoAncestorNamed(name);
};
BindingInWhenOnSyntax2.prototype.whenNoAncestorTagged = function(tag, value) {
return this._bindingWhenSyntax.whenNoAncestorTagged(tag, value);
};
BindingInWhenOnSyntax2.prototype.whenAnyAncestorMatches = function(constraint) {
return this._bindingWhenSyntax.whenAnyAncestorMatches(constraint);
};
BindingInWhenOnSyntax2.prototype.whenNoAncestorMatches = function(constraint) {
return this._bindingWhenSyntax.whenNoAncestorMatches(constraint);
};
BindingInWhenOnSyntax2.prototype.onActivation = function(handler) {
return this._bindingOnSyntax.onActivation(handler);
};
BindingInWhenOnSyntax2.prototype.onDeactivation = function(handler) {
return this._bindingOnSyntax.onDeactivation(handler);
};
return BindingInWhenOnSyntax2;
}();
// node_modules/inversify/es/syntax/binding_to_syntax.js
var BindingToSyntax = function() {
function BindingToSyntax2(binding) {
this._binding = binding;
}
BindingToSyntax2.prototype.to = function(constructor) {
this._binding.type = BindingTypeEnum.Instance;
this._binding.implementationType = constructor;
return new BindingInWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toSelf = function() {
if (typeof this._binding.serviceIdentifier !== "function") {
throw new Error("" + INVALID_TO_SELF_VALUE);
}
var self2 = this._binding.serviceIdentifier;
return this.to(self2);
};
BindingToSyntax2.prototype.toConstantValue = function(value) {
this._binding.type = BindingTypeEnum.ConstantValue;
this._binding.cache = value;
this._binding.dynamicValue = null;
this._binding.implementationType = null;
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toDynamicValue = function(func) {
this._binding.type = BindingTypeEnum.DynamicValue;
this._binding.cache = null;
this._binding.dynamicValue = func;
this._binding.implementationType = null;
return new BindingInWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toConstructor = function(constructor) {
this._binding.type = BindingTypeEnum.Constructor;
this._binding.implementationType = constructor;
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toFactory = function(factory) {
this._binding.type = BindingTypeEnum.Factory;
this._binding.factory = factory;
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toFunction = function(func) {
if (typeof func !== "function") {
throw new Error(INVALID_FUNCTION_BINDING);
}
var bindingWhenOnSyntax = this.toConstantValue(func);
this._binding.type = BindingTypeEnum.Function;
this._binding.scope = BindingScopeEnum.Singleton;
return bindingWhenOnSyntax;
};
BindingToSyntax2.prototype.toAutoFactory = function(serviceIdentifier) {
this._binding.type = BindingTypeEnum.Factory;
this._binding.factory = function(context) {
var autofactory = function() {
return context.container.get(serviceIdentifier);
};
return autofactory;
};
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toAutoNamedFactory = function(serviceIdentifier) {
this._binding.type = BindingTypeEnum.Factory;
this._binding.factory = function(context) {
return function(named2) {
return context.container.getNamed(serviceIdentifier, named2);
};
};
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toProvider = function(provider) {
this._binding.type = BindingTypeEnum.Provider;
this._binding.provider = provider;
this._binding.scope = BindingScopeEnum.Singleton;
return new BindingWhenOnSyntax(this._binding);
};
BindingToSyntax2.prototype.toService = function(service) {
this.toDynamicValue(function(context) {
return context.container.get(service);
});
};
return BindingToSyntax2;
}();
// node_modules/inversify/es/container/container_snapshot.js
var ContainerSnapshot = function() {
function ContainerSnapshot2() {
}
ContainerSnapshot2.of = function(bindings, middleware, activations, deactivations, moduleActivationStore) {
var snapshot = new ContainerSnapshot2();
snapshot.bindings = bindings;
snapshot.middleware = middleware;
snapshot.deactivations = deactivations;
snapshot.activations = activations;
snapshot.moduleActivationStore = moduleActivationStore;
return snapshot;
};
return ContainerSnapshot2;
}();
// node_modules/inversify/es/utils/clonable.js
function isClonable(obj) {
return typeof obj === "object" && obj !== null && "clone" in obj && typeof obj.clone === "function";
}
// node_modules/inversify/es/container/lookup.js
var Lookup = function() {
function Lookup2() {
this._map = /* @__PURE__ */ new Map();
}
Lookup2.prototype.getMap = function() {
return this._map;
};
Lookup2.prototype.add = function(serviceIdentifier, value) {
if (serviceIdentifier === null || serviceIdentifier === void 0) {
throw new Error(NULL_ARGUMENT);
}
if (value === null || value === void 0) {
throw new Error(NULL_ARGUMENT);
}
var entry = this._map.get(serviceIdentifier);
if (entry !== void 0) {
entry.push(value);
} else {
this._map.set(serviceIdentifier, [value]);
}
};
Lookup2.prototype.get = function(serviceIdentifier) {
if (serviceIdentifier === null || serviceIdentifier === void 0) {
throw new Error(NULL_ARGUMENT);
}
var entry = this._map.get(serviceIdentifier);
if (entry !== void 0) {
return entry;
} else {
throw new Error(KEY_NOT_FOUND);
}
};
Lookup2.prototype.remove = function(serviceIdentifier) {
if (serviceIdentifier === null || serviceIdentifier === void 0) {
throw new Error(NULL_ARGUMENT);
}
if (!this._map.delete(serviceIdentifier)) {
throw new Error(KEY_NOT_FOUND);
}
};
Lookup2.prototype.removeIntersection = function(lookup) {
var _this = this;
this.traverse(function(serviceIdentifier, value) {
var lookupActivations = lookup.hasKey(serviceIdentifier) ? lookup.get(serviceIdentifier) : void 0;
if (lookupActivations !== void 0) {
var filteredValues = value.filter(function(lookupValue) {
return !lookupActivations.some(function(moduleActivation) {
return lookupValue === moduleActivation;
});
});
_this._setValue(serviceIdentifier, filteredValues);
}
});
};
Lookup2.prototype.removeByCondition = function(condition) {
var _this = this;
var removals = [];
this._map.forEach(function(entries, key) {
var updatedEntries = [];
for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
var entry = entries_1[_i];
var remove = condition(entry);
if (remove) {
removals.push(entry);
} else {
updatedEntries.push(entry);
}
}
_this._setValue(key, updatedEntries);
});
return removals;
};
Lookup2.prototype.hasKey = function(serviceIdentifier) {
if (serviceIdentifier === null || serviceIdentifier === void 0) {
throw new Error(NULL_ARGUMENT);
}
return this._map.has(serviceIdentifier);
};
Lookup2.prototype.clone = function() {
var copy2 = new Lookup2();
this._map.forEach(function(value, key) {
value.forEach(function(b) {
return copy2.add(key, isClonable(b) ? b.clone() : b);
});
});
return copy2;
};
Lookup2.prototype.traverse = function(func) {
this._map.forEach(function(value, key) {
func(key, value);
});
};
Lookup2.prototype._setValue = function(serviceIdentifier, value) {
if (value.length > 0) {
this._map.set(serviceIdentifier, value);
} else {
this._map.delete(serviceIdentifier);
}
};
return Lookup2;
}();
// node_modules/inversify/es/container/module_activation_store.js
var ModuleActivationStore = function() {
function ModuleActivationStore2() {
this._map = /* @__PURE__ */ new Map();
}
ModuleActivationStore2.prototype.remove = function(moduleId) {
if (this._map.has(moduleId)) {
var handlers = this._map.get(moduleId);
this._map.delete(moduleId);
return handlers;
}
return this._getEmptyHandlersStore();
};
ModuleActivationStore2.prototype.addDeactivation = function(moduleId, serviceIdentifier, onDeactivation) {
this._getModuleActivationHandlers(moduleId).onDeactivations.add(serviceIdentifier, onDeactivation);
};
ModuleActivationStore2.prototype.addActivation = function(moduleId, serviceIdentifier, onActivation) {
this._getModuleActivationHandlers(moduleId).onActivations.add(serviceIdentifier, onActivation);
};
ModuleActivationStore2.prototype.clone = function() {
var clone = new ModuleActivationStore2();
this._map.forEach(function(handlersStore, moduleId) {
clone._map.set(moduleId, {
onActivations: handlersStore.onActivations.clone(),
onDeactivations: handlersStore.onDeactivations.clone()
});
});
return clone;
};
ModuleActivationStore2.prototype._getModuleActivationHandlers = function(moduleId) {
var moduleActivationHandlers = this._map.get(moduleId);
if (moduleActivationHandlers === void 0) {
moduleActivationHandlers = this._getEmptyHandlersStore();
this._map.set(moduleId, moduleActivationHandlers);
}
return moduleActivationHandlers;
};
ModuleActivationStore2.prototype._getEmptyHandlersStore = function() {
var handlersStore = {
onActivations: new Lookup(),
onDeactivations: new Lookup()
};
return handlersStore;
};
return ModuleActivationStore2;
}();
// node_modules/inversify/es/container/container.js
var __assign2 = function() {
__assign2 = Object.assign || function(t3) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t3[p] = s[p];
}
return t3;
};
return __assign2.apply(this, arguments);
};
var __awaiter4 = function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve2) {
resolve2(value);
});
}
return new (P || (P = Promise))(function(resolve2, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve2(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator4 = function(thisArg, body) {
var _ = { label: 0, sent: function() {
if (t3[0] & 1)
throw t3[1];
return t3[1];
}, trys: [], ops: [] }, f, y, t3, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
return this;
}), g;
function verb(n) {
return function(v) {
return step([n, v]);
};
}
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t3 = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t3 = y["return"]) && t3.call(y), 0) : y.next) && !(t3 = t3.call(y, op[1])).done)
return t3;
if (y = 0, t3)
op = [op[0] & 2, t3.value];
switch (op[0]) {
case 0:
case 1:
t3 = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t3 = _.trys, t3 = t3.length > 0 && t3[t3.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t3 || op[1] > t3[0] && op[1] < t3[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t3[1]) {
_.label = t3[1];
t3 = op;
break;
}
if (t3 && _.label < t3[2]) {
_.label = t3[2];
_.ops.push(op);
break;
}
if (t3[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [6, e];
y = 0;
} finally {
f = t3 = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __spreadArray3 = function(to, from, pack) {
if (pack || arguments.length === 2)
for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar)
ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var Container = function() {
function Container3(containerOptions) {
var options = containerOptions || {};
if (typeof options !== "object") {
throw new Error("" + CONTAINER_OPTIONS_MUST_BE_AN_OBJECT);
}
if (options.defaultScope === void 0) {
options.defaultScope = BindingScopeEnum.Transient;
} else if (options.defaultScope !== BindingScopeEnum.Singleton && options.defaultScope !== BindingScopeEnum.Transient && options.defaultScope !== BindingScopeEnum.Request) {
throw new Error("" + CONTAINER_OPTIONS_INVALID_DEFAULT_SCOPE);
}
if (options.autoBindInjectable === void 0) {
options.autoBindInjectable = false;
} else if (typeof options.autoBindInjectable !== "boolean") {
throw new Error("" + CONTAINER_OPTIONS_INVALID_AUTO_BIND_INJECTABLE);
}
if (options.skipBaseClassChecks === void 0) {
options.skipBaseClassChecks = false;
} else if (typeof options.skipBaseClassChecks !== "boolean") {
throw new Error("" + CONTAINER_OPTIONS_INVALID_SKIP_BASE_CHECK);
}
this.options = {
autoBindInjectable: options.autoBindInjectable,
defaultScope: options.defaultScope,
skipBaseClassChecks: options.skipBaseClassChecks
};
this.id = id();
this._bindingDictionary = new Lookup();
this._snapshots = [];
this._middleware = null;
this._activations = new Lookup();
this._deactivations = new Lookup();
this.parent = null;
this._metadataReader = new MetadataReader();
this._moduleActivationStore = new ModuleActivationStore();
}
Container3.merge = function(container1, container2) {
var containers = [];
for (var _i = 2; _i < arguments.length; _i++) {
containers[_i - 2] = arguments[_i];
}
var container = new Container3();
var targetContainers = __spreadArray3([container1, container2], containers, true).map(function(targetContainer) {
return getBindingDictionary(targetContainer);
});
var bindingDictionary = getBindingDictionary(container);
function copyDictionary(origin, destination) {
origin.traverse(function(_key, value) {
value.forEach(function(binding) {
destination.add(binding.serviceIdentifier, binding.clone());
});
});
}
targetContainers.forEach(function(targetBindingDictionary) {
copyDictionary(targetBindingDictionary, bindingDictionary);
});
return container;
};
Container3.prototype.load = function() {
var modules = [];
for (var _i = 0; _i < arguments.length; _i++) {
modules[_i] = arguments[_i];
}
var getHelpers = this._getContainerModuleHelpersFactory();
for (var _a = 0, modules_1 = modules; _a < modules_1.length; _a++) {
var currentModule = modules_1[_a];
var containerModuleHelpers = getHelpers(currentModule.id);
currentModule.registry(containerModuleHelpers.bindFunction, containerModuleHelpers.unbindFunction, containerModuleHelpers.isboundFunction, containerModuleHelpers.rebindFunction, containerModuleHelpers.unbindAsyncFunction, containerModuleHelpers.onActivationFunction, containerModuleHelpers.onDeactivationFunction);
}
};
Container3.prototype.loadAsync = function() {
var modules = [];
for (var _i = 0; _i < arguments.length; _i++) {
modules[_i] = arguments[_i];
}
return __awaiter4(this, void 0, void 0, function() {
var getHelpers, _a, modules_2, currentModule, containerModuleHelpers;
return __generator4(this, function(_b) {
switch (_b.label) {
case 0:
getHelpers = this._getContainerModuleHelpersFactory();
_a = 0, modules_2 = modules;
_b.label = 1;
case 1:
if (!(_a < modules_2.length))
return [3, 4];
currentModule = modules_2[_a];
containerModuleHelpers = getHelpers(currentModule.id);
return [4, currentModule.registry(containerModuleHelpers.bindFunction, containerModuleHelpers.unbindFunction, containerModuleHelpers.isboundFunction, containerModuleHelpers.rebindFunction, containerModuleHelpers.unbindAsyncFunction, containerModuleHelpers.onActivationFunction, containerModuleHelpers.onDeactivationFunction)];
case 2:
_b.sent();
_b.label = 3;
case 3:
_a++;
return [3, 1];
case 4:
return [2];
}
});
});
};
Container3.prototype.unload = function() {
var _this = this;
var modules = [];
for (var _i = 0; _i < arguments.length; _i++) {
modules[_i] = arguments[_i];
}
modules.forEach(function(module2) {
var deactivations = _this._removeModuleBindings(module2.id);
_this._deactivateSingletons(deactivations);
_this._removeModuleHandlers(module2.id);
});
};
Container3.prototype.unloadAsync = function() {
var modules = [];
for (var _i = 0; _i < arguments.length; _i++) {
modules[_i] = arguments[_i];
}
return __awaiter4(this, void 0, void 0, function() {
var _a, modules_3, module_1, deactivations;
return __generator4(this, function(_b) {
switch (_b.label) {
case 0:
_a = 0, modules_3 = modules;
_b.label = 1;
case 1:
if (!(_a < modules_3.length))
return [3, 4];
module_1 = modules_3[_a];
deactivations = this._removeModuleBindings(module_1.id);
return [4, this._deactivateSingletonsAsync(deactivations)];
case 2:
_b.sent();
this._removeModuleHandlers(module_1.id);
_b.label = 3;
case 3:
_a++;
return [3, 1];
case 4:
return [2];
}
});
});
};
Container3.prototype.bind = function(serviceIdentifier) {
var scope = this.options.defaultScope || BindingScopeEnum.Transient;
var binding = new Binding(serviceIdentifier, scope);
this._bindingDictionary.add(serviceIdentifier, binding);
return new BindingToSyntax(binding);
};
Container3.prototype.rebind = function(serviceIdentifier) {
this.unbind(serviceIdentifier);
return this.bind(serviceIdentifier);
};
Container3.prototype.rebindAsync = function(serviceIdentifier) {
return __awaiter4(this, void 0, void 0, function() {
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
return [4, this.unbindAsync(serviceIdentifier)];
case 1:
_a.sent();
return [2, this.bind(serviceIdentifier)];
}
});
});
};
Container3.prototype.unbind = function(serviceIdentifier) {
if (this._bindingDictionary.hasKey(serviceIdentifier)) {
var bindings = this._bindingDictionary.get(serviceIdentifier);
this._deactivateSingletons(bindings);
}
this._removeServiceFromDictionary(serviceIdentifier);
};
Container3.prototype.unbindAsync = function(serviceIdentifier) {
return __awaiter4(this, void 0, void 0, function() {
var bindings;
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
if (!this._bindingDictionary.hasKey(serviceIdentifier))
return [3, 2];
bindings = this._bindingDictionary.get(serviceIdentifier);
return [4, this._deactivateSingletonsAsync(bindings)];
case 1:
_a.sent();
_a.label = 2;
case 2:
this._removeServiceFromDictionary(serviceIdentifier);
return [2];
}
});
});
};
Container3.prototype.unbindAll = function() {
var _this = this;
this._bindingDictionary.traverse(function(_key, value) {
_this._deactivateSingletons(value);
});
this._bindingDictionary = new Lookup();
};
Container3.prototype.unbindAllAsync = function() {
return __awaiter4(this, void 0, void 0, function() {
var promises;
var _this = this;
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
promises = [];
this._bindingDictionary.traverse(function(_key, value) {
promises.push(_this._deactivateSingletonsAsync(value));
});
return [4, Promise.all(promises)];
case 1:
_a.sent();
this._bindingDictionary = new Lookup();
return [2];
}
});
});
};
Container3.prototype.onActivation = function(serviceIdentifier, onActivation) {
this._activations.add(serviceIdentifier, onActivation);
};
Container3.prototype.onDeactivation = function(serviceIdentifier, onDeactivation) {
this._deactivations.add(serviceIdentifier, onDeactivation);
};
Container3.prototype.isBound = function(serviceIdentifier) {
var bound = this._bindingDictionary.hasKey(serviceIdentifier);
if (!bound && this.parent) {
bound = this.parent.isBound(serviceIdentifier);
}
return bound;
};
Container3.prototype.isCurrentBound = function(serviceIdentifier) {
return this._bindingDictionary.hasKey(serviceIdentifier);
};
Container3.prototype.isBoundNamed = function(serviceIdentifier, named2) {
return this.isBoundTagged(serviceIdentifier, NAMED_TAG, named2);
};
Container3.prototype.isBoundTagged = function(serviceIdentifier, key, value) {
var bound = false;
if (this._bindingDictionary.hasKey(serviceIdentifier)) {
var bindings = this._bindingDictionary.get(serviceIdentifier);
var request_1 = createMockRequest(this, serviceIdentifier, key, value);
bound = bindings.some(function(b) {
return b.constraint(request_1);
});
}
if (!bound && this.parent) {
bound = this.parent.isBoundTagged(serviceIdentifier, key, value);
}
return bound;
};
Container3.prototype.snapshot = function() {
this._snapshots.push(ContainerSnapshot.of(this._bindingDictionary.clone(), this._middleware, this._activations.clone(), this._deactivations.clone(), this._moduleActivationStore.clone()));
};
Container3.prototype.restore = function() {
var snapshot = this._snapshots.pop();
if (snapshot === void 0) {
throw new Error(NO_MORE_SNAPSHOTS_AVAILABLE);
}
this._bindingDictionary = snapshot.bindings;
this._activations = snapshot.activations;
this._deactivations = snapshot.deactivations;
this._middleware = snapshot.middleware;
this._moduleActivationStore = snapshot.moduleActivationStore;
};
Container3.prototype.createChild = function(containerOptions) {
var child = new Container3(containerOptions || this.options);
child.parent = this;
return child;
};
Container3.prototype.applyMiddleware = function() {
var middlewares = [];
for (var _i = 0; _i < arguments.length; _i++) {
middlewares[_i] = arguments[_i];
}
var initial = this._middleware ? this._middleware : this._planAndResolve();
this._middleware = middlewares.reduce(function(prev, curr) {
return curr(prev);
}, initial);
};
Container3.prototype.applyCustomMetadataReader = function(metadataReader) {
this._metadataReader = metadataReader;
};
Container3.prototype.get = function(serviceIdentifier) {
var getArgs = this._getNotAllArgs(serviceIdentifier, false);
return this._getButThrowIfAsync(getArgs);
};
Container3.prototype.getAsync = function(serviceIdentifier) {
return __awaiter4(this, void 0, void 0, function() {
var getArgs;
return __generator4(this, function(_a) {
getArgs = this._getNotAllArgs(serviceIdentifier, false);
return [2, this._get(getArgs)];
});
});
};
Container3.prototype.getTagged = function(serviceIdentifier, key, value) {
var getArgs = this._getNotAllArgs(serviceIdentifier, false, key, value);
return this._getButThrowIfAsync(getArgs);
};
Container3.prototype.getTaggedAsync = function(serviceIdentifier, key, value) {
return __awaiter4(this, void 0, void 0, function() {
var getArgs;
return __generator4(this, function(_a) {
getArgs = this._getNotAllArgs(serviceIdentifier, false, key, value);
return [2, this._get(getArgs)];
});
});
};
Container3.prototype.getNamed = function(serviceIdentifier, named2) {
return this.getTagged(serviceIdentifier, NAMED_TAG, named2);
};
Container3.prototype.getNamedAsync = function(serviceIdentifier, named2) {
return this.getTaggedAsync(serviceIdentifier, NAMED_TAG, named2);
};
Container3.prototype.getAll = function(serviceIdentifier) {
var getArgs = this._getAllArgs(serviceIdentifier);
return this._getButThrowIfAsync(getArgs);
};
Container3.prototype.getAllAsync = function(serviceIdentifier) {
var getArgs = this._getAllArgs(serviceIdentifier);
return this._getAll(getArgs);
};
Container3.prototype.getAllTagged = function(serviceIdentifier, key, value) {
var getArgs = this._getNotAllArgs(serviceIdentifier, true, key, value);
return this._getButThrowIfAsync(getArgs);
};
Container3.prototype.getAllTaggedAsync = function(serviceIdentifier, key, value) {
var getArgs = this._getNotAllArgs(serviceIdentifier, true, key, value);
return this._getAll(getArgs);
};
Container3.prototype.getAllNamed = function(serviceIdentifier, named2) {
return this.getAllTagged(serviceIdentifier, NAMED_TAG, named2);
};
Container3.prototype.getAllNamedAsync = function(serviceIdentifier, named2) {
return this.getAllTaggedAsync(serviceIdentifier, NAMED_TAG, named2);
};
Container3.prototype.resolve = function(constructorFunction) {
var isBound = this.isBound(constructorFunction);
if (!isBound) {
this.bind(constructorFunction).toSelf();
}
var resolved2 = this.get(constructorFunction);
if (!isBound) {
this.unbind(constructorFunction);
}
return resolved2;
};
Container3.prototype._preDestroy = function(constructor, instance2) {
if (Reflect.hasMetadata(PRE_DESTROY, constructor)) {
var data = Reflect.getMetadata(PRE_DESTROY, constructor);
return instance2[data.value]();
}
};
Container3.prototype._removeModuleHandlers = function(moduleId) {
var moduleActivationsHandlers = this._moduleActivationStore.remove(moduleId);
this._activations.removeIntersection(moduleActivationsHandlers.onActivations);
this._deactivations.removeIntersection(moduleActivationsHandlers.onDeactivations);
};
Container3.prototype._removeModuleBindings = function(moduleId) {
return this._bindingDictionary.removeByCondition(function(binding) {
return binding.moduleId === moduleId;
});
};
Container3.prototype._deactivate = function(binding, instance2) {
var _this = this;
var constructor = Object.getPrototypeOf(instance2).constructor;
try {
if (this._deactivations.hasKey(binding.serviceIdentifier)) {
var result = this._deactivateContainer(instance2, this._deactivations.get(binding.serviceIdentifier).values());
if (isPromise(result)) {
return this._handleDeactivationError(result.then(function() {
return _this._propagateContainerDeactivationThenBindingAndPreDestroyAsync(binding, instance2, constructor);
}), constructor);
}
}
var propagateDeactivationResult = this._propagateContainerDeactivationThenBindingAndPreDestroy(binding, instance2, constructor);
if (isPromise(propagateDeactivationResult)) {
return this._handleDeactivationError(propagateDeactivationResult, constructor);
}
} catch (ex) {
throw new Error(ON_DEACTIVATION_ERROR(constructor.name, ex.message));
}
};
Container3.prototype._handleDeactivationError = function(asyncResult, constructor) {
return __awaiter4(this, void 0, void 0, function() {
var ex_1;
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4, asyncResult];
case 1:
_a.sent();
return [3, 3];
case 2:
ex_1 = _a.sent();
throw new Error(ON_DEACTIVATION_ERROR(constructor.name, ex_1.message));
case 3:
return [2];
}
});
});
};
Container3.prototype._deactivateContainer = function(instance2, deactivationsIterator) {
var _this = this;
var deactivation = deactivationsIterator.next();
while (deactivation.value) {
var result = deactivation.value(instance2);
if (isPromise(result)) {
return result.then(function() {
return _this._deactivateContainerAsync(instance2, deactivationsIterator);
});
}
deactivation = deactivationsIterator.next();
}
};
Container3.prototype._deactivateContainerAsync = function(instance2, deactivationsIterator) {
return __awaiter4(this, void 0, void 0, function() {
var deactivation;
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
deactivation = deactivationsIterator.next();
_a.label = 1;
case 1:
if (!deactivation.value)
return [3, 3];
return [4, deactivation.value(instance2)];
case 2:
_a.sent();
deactivation = deactivationsIterator.next();
return [3, 1];
case 3:
return [2];
}
});
});
};
Container3.prototype._getContainerModuleHelpersFactory = function() {
var _this = this;
var setModuleId = function(bindingToSyntax, moduleId) {
bindingToSyntax._binding.moduleId = moduleId;
};
var getBindFunction = function(moduleId) {
return function(serviceIdentifier) {
var bindingToSyntax = _this.bind(serviceIdentifier);
setModuleId(bindingToSyntax, moduleId);
return bindingToSyntax;
};
};
var getUnbindFunction = function() {
return function(serviceIdentifier) {
return _this.unbind(serviceIdentifier);
};
};
var getUnbindAsyncFunction = function() {
return function(serviceIdentifier) {
return _this.unbindAsync(serviceIdentifier);
};
};
var getIsboundFunction = function() {
return function(serviceIdentifier) {
return _this.isBound(serviceIdentifier);
};
};
var getRebindFunction = function(moduleId) {
return function(serviceIdentifier) {
var bindingToSyntax = _this.rebind(serviceIdentifier);
setModuleId(bindingToSyntax, moduleId);
return bindingToSyntax;
};
};
var getOnActivationFunction = function(moduleId) {
return function(serviceIdentifier, onActivation) {
_this._moduleActivationStore.addActivation(moduleId, serviceIdentifier, onActivation);
_this.onActivation(serviceIdentifier, onActivation);
};
};
var getOnDeactivationFunction = function(moduleId) {
return function(serviceIdentifier, onDeactivation) {
_this._moduleActivationStore.addDeactivation(moduleId, serviceIdentifier, onDeactivation);
_this.onDeactivation(serviceIdentifier, onDeactivation);
};
};
return function(mId) {
return {
bindFunction: getBindFunction(mId),
isboundFunction: getIsboundFunction(),
onActivationFunction: getOnActivationFunction(mId),
onDeactivationFunction: getOnDeactivationFunction(mId),
rebindFunction: getRebindFunction(mId),
unbindFunction: getUnbindFunction(),
unbindAsyncFunction: getUnbindAsyncFunction()
};
};
};
Container3.prototype._getAll = function(getArgs) {
return Promise.all(this._get(getArgs));
};
Container3.prototype._get = function(getArgs) {
var planAndResolveArgs = __assign2(__assign2({}, getArgs), { contextInterceptor: function(context) {
return context;
}, targetType: TargetTypeEnum.Variable });
if (this._middleware) {
var middlewareResult = this._middleware(planAndResolveArgs);
if (middlewareResult === void 0 || middlewareResult === null) {
throw new Error(INVALID_MIDDLEWARE_RETURN);
}
return middlewareResult;
}
return this._planAndResolve()(planAndResolveArgs);
};
Container3.prototype._getButThrowIfAsync = function(getArgs) {
var result = this._get(getArgs);
if (isPromiseOrContainsPromise(result)) {
throw new Error(LAZY_IN_SYNC(getArgs.serviceIdentifier));
}
return result;
};
Container3.prototype._getAllArgs = function(serviceIdentifier) {
var getAllArgs = {
avoidConstraints: true,
isMultiInject: true,
serviceIdentifier
};
return getAllArgs;
};
Container3.prototype._getNotAllArgs = function(serviceIdentifier, isMultiInject, key, value) {
var getNotAllArgs = {
avoidConstraints: false,
isMultiInject,
serviceIdentifier,
key,
value
};
return getNotAllArgs;
};
Container3.prototype._planAndResolve = function() {
var _this = this;
return function(args) {
var context = plan(_this._metadataReader, _this, args.isMultiInject, args.targetType, args.serviceIdentifier, args.key, args.value, args.avoidConstraints);
context = args.contextInterceptor(context);
var result = resolve(context);
return result;
};
};
Container3.prototype._deactivateIfSingleton = function(binding) {
var _this = this;
if (!binding.activated) {
return;
}
if (isPromise(binding.cache)) {
return binding.cache.then(function(resolved2) {
return _this._deactivate(binding, resolved2);
});
}
return this._deactivate(binding, binding.cache);
};
Container3.prototype._deactivateSingletons = function(bindings) {
for (var _i = 0, bindings_1 = bindings; _i < bindings_1.length; _i++) {
var binding = bindings_1[_i];
var result = this._deactivateIfSingleton(binding);
if (isPromise(result)) {
throw new Error(ASYNC_UNBIND_REQUIRED);
}
}
};
Container3.prototype._deactivateSingletonsAsync = function(bindings) {
return __awaiter4(this, void 0, void 0, function() {
var _this = this;
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
return [4, Promise.all(bindings.map(function(b) {
return _this._deactivateIfSingleton(b);
}))];
case 1:
_a.sent();
return [2];
}
});
});
};
Container3.prototype._propagateContainerDeactivationThenBindingAndPreDestroy = function(binding, instance2, constructor) {
if (this.parent) {
return this._deactivate.bind(this.parent)(binding, instance2);
} else {
return this._bindingDeactivationAndPreDestroy(binding, instance2, constructor);
}
};
Container3.prototype._propagateContainerDeactivationThenBindingAndPreDestroyAsync = function(binding, instance2, constructor) {
return __awaiter4(this, void 0, void 0, function() {
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
if (!this.parent)
return [3, 2];
return [4, this._deactivate.bind(this.parent)(binding, instance2)];
case 1:
_a.sent();
return [3, 4];
case 2:
return [4, this._bindingDeactivationAndPreDestroyAsync(binding, instance2, constructor)];
case 3:
_a.sent();
_a.label = 4;
case 4:
return [2];
}
});
});
};
Container3.prototype._removeServiceFromDictionary = function(serviceIdentifier) {
try {
this._bindingDictionary.remove(serviceIdentifier);
} catch (e) {
throw new Error(CANNOT_UNBIND + " " + getServiceIdentifierAsString(serviceIdentifier));
}
};
Container3.prototype._bindingDeactivationAndPreDestroy = function(binding, instance2, constructor) {
var _this = this;
if (typeof binding.onDeactivation === "function") {
var result = binding.onDeactivation(instance2);
if (isPromise(result)) {
return result.then(function() {
return _this._preDestroy(constructor, instance2);
});
}
}
return this._preDestroy(constructor, instance2);
};
Container3.prototype._bindingDeactivationAndPreDestroyAsync = function(binding, instance2, constructor) {
return __awaiter4(this, void 0, void 0, function() {
return __generator4(this, function(_a) {
switch (_a.label) {
case 0:
if (!(typeof binding.onDeactivation === "function"))
return [3, 2];
return [4, binding.onDeactivation(instance2)];
case 1:
_a.sent();
_a.label = 2;
case 2:
return [4, this._preDestroy(constructor, instance2)];
case 3:
_a.sent();
return [2];
}
});
});
};
return Container3;
}();
// node_modules/inversify/es/container/container_module.js
var ContainerModule = function() {
function ContainerModule2(registry) {
this.id = id();
this.registry = registry;
}
return ContainerModule2;
}();
var AsyncContainerModule = function() {
function AsyncContainerModule2(registry) {
this.id = id();
this.registry = registry;
}
return AsyncContainerModule2;
}();
// node_modules/inversify/es/utils/js.js
function getFirstArrayDuplicate(array) {
var seenValues = /* @__PURE__ */ new Set();
for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
var entry = array_1[_i];
if (seenValues.has(entry)) {
return entry;
} else {
seenValues.add(entry);
}
}
return void 0;
}
// node_modules/inversify/es/annotation/decorator_utils.js
function targetIsConstructorFunction(target) {
return target.prototype !== void 0;
}
function _throwIfMethodParameter(parameterName) {
if (parameterName !== void 0) {
throw new Error(INVALID_DECORATOR_OPERATION);
}
}
function tagParameter(annotationTarget, parameterName, parameterIndex, metadata) {
_throwIfMethodParameter(parameterName);
_tagParameterOrProperty(TAGGED, annotationTarget, parameterIndex.toString(), metadata);
}
function tagProperty(annotationTarget, propertyName, metadata) {
if (targetIsConstructorFunction(annotationTarget)) {
throw new Error(INVALID_DECORATOR_OPERATION);
}
_tagParameterOrProperty(TAGGED_PROP, annotationTarget.constructor, propertyName, metadata);
}
function _ensureNoMetadataKeyDuplicates(metadata) {
var metadatas = [];
if (Array.isArray(metadata)) {
metadatas = metadata;
var duplicate = getFirstArrayDuplicate(metadatas.map(function(md) {
return md.key;
}));
if (duplicate !== void 0) {
throw new Error(DUPLICATED_METADATA + " " + duplicate.toString());
}
} else {
metadatas = [metadata];
}
return metadatas;
}
function _tagParameterOrProperty(metadataKey, annotationTarget, key, metadata) {
var metadatas = _ensureNoMetadataKeyDuplicates(metadata);
var paramsOrPropertiesMetadata = {};
if (Reflect.hasOwnMetadata(metadataKey, annotationTarget)) {
paramsOrPropertiesMetadata = Reflect.getMetadata(metadataKey, annotationTarget);
}
var paramOrPropertyMetadata = paramsOrPropertiesMetadata[key];
if (paramOrPropertyMetadata === void 0) {
paramOrPropertyMetadata = [];
} else {
var _loop_1 = function(m2) {
if (metadatas.some(function(md) {
return md.key === m2.key;
})) {
throw new Error(DUPLICATED_METADATA + " " + m2.key.toString());
}
};
for (var _i = 0, paramOrPropertyMetadata_1 = paramOrPropertyMetadata; _i < paramOrPropertyMetadata_1.length; _i++) {
var m = paramOrPropertyMetadata_1[_i];
_loop_1(m);
}
}
paramOrPropertyMetadata.push.apply(paramOrPropertyMetadata, metadatas);
paramsOrPropertiesMetadata[key] = paramOrPropertyMetadata;
Reflect.defineMetadata(metadataKey, paramsOrPropertiesMetadata, annotationTarget);
}
function createTaggedDecorator(metadata) {
return function(target, targetKey, indexOrPropertyDescriptor) {
if (typeof indexOrPropertyDescriptor === "number") {
tagParameter(target, targetKey, indexOrPropertyDescriptor, metadata);
} else {
tagProperty(target, targetKey, metadata);
}
};
}
// node_modules/inversify/es/annotation/injectable.js
function injectable() {
return function(target) {
if (Reflect.hasOwnMetadata(PARAM_TYPES, target)) {
throw new Error(DUPLICATED_INJECTABLE_DECORATOR);
}
var types = Reflect.getMetadata(DESIGN_PARAM_TYPES, target) || [];
Reflect.defineMetadata(PARAM_TYPES, types, target);
return target;
};
}
// node_modules/inversify/es/annotation/named.js
function named(name) {
return createTaggedDecorator(new Metadata(NAMED_TAG, name));
}
// node_modules/inversify/es/annotation/inject_base.js
function injectBase(metadataKey) {
return function(serviceIdentifier) {
return function(target, targetKey, indexOrPropertyDescriptor) {
if (serviceIdentifier === void 0) {
var className = typeof target === "function" ? target.name : target.constructor.name;
throw new Error(UNDEFINED_INJECT_ANNOTATION(className));
}
return createTaggedDecorator(new Metadata(metadataKey, serviceIdentifier))(target, targetKey, indexOrPropertyDescriptor);
};
};
}
// node_modules/inversify/es/annotation/inject.js
var inject = injectBase(INJECT_TAG);
// node_modules/inversify/es/annotation/multi_inject.js
var multiInject = injectBase(MULTI_INJECT_TAG);
// config/inversify.types.ts
var SI = {
"factory:replacer": "",
"event:dispatcher": "",
"alias:modifier": "",
"alias:modifier:strategy": "",
"alias:modifier:validator": "",
cache: "",
"component:black_white_list": "",
"component:extractor": "",
"component:extractor:strategy": "",
"creator:creator": "",
"creator:fallback": "",
"creator:template": "",
delimiter: "",
"facade:obsidian": "",
"factory:alias:modifier:strategy": "",
"factory:alias:modifier:validator": "",
"factory:feature": "",
"factory:metadata:cache": "",
"factory:obsidian:active:file": "",
"factory:obsidian:modal": "",
"factory:obsidian:file": "",
"factory:obsidian:file_modifiable": "",
"factory:obsidian:meta": "",
"factory:placeholder": "",
"factory:placeholder:resolver": "",
"factory:creator:template": "",
"factory:template:resolver": "",
"newable:obsidian:chooser": "",
feature: "",
"feature:composer": "",
"feature:service": "",
"feature:alias:config": "",
"feature:notelink:approve": "",
"feature:config": "",
filter: "",
"getter:delimiter": "",
listener: "",
logger: "",
"feature:helper": "",
"logger:composer": "",
"manager:composer": "",
"obsidian:app": "",
"obsidian:plugin": "",
placeholder: "",
"placeholder:brackets": "",
"placeholder:meta": "",
resolver: "",
"resolver:service": "",
"factory:resolver:template": "",
"factory:resolver:resolver": "",
"service:note:link": "",
"service:fake_title_element": "",
"service:search:dom:wrapper": "",
"settings:feature:builder": "",
"settings:builder": "",
"factory:settings:feature:builder": "",
"factory:settings:builder": "",
"settings:storage": "",
"template:pattern": "",
api: "",
defer: "",
"factory:api": "",
"factory:processor": "",
processor: "",
"processor:args": ""
};
for (const key of Object.keys(SI)) {
SI[key] = Symbol.for(key);
}
var inversify_types_default = SI;
// src/i18n/Locale.ts
var import_obsidian = require("obsidian");
// src/Enum.ts
var Feature = /* @__PURE__ */ ((Feature4) => {
Feature4["Explorer"] = "explorer";
Feature4["ExplorerSort"] = "explorer:sort";
Feature4["Graph"] = "graph";
Feature4["Header"] = "header";
Feature4["Starred"] = "starred";
Feature4["Search"] = "search" /* S */;
Feature4["Tab"] = "tab";
Feature4["Alias"] = "alias";
Feature4["Suggest"] = "suggest";
Feature4["InlineTitle"] = "inlineTitle";
Feature4["Canvas"] = "canvas";
Feature4["Backlink"] = "backlink" /* BL */;
Feature4["NoteLink"] = "noteLink";
return Feature4;
})(Feature || {});
var Managers = [
"explorer" /* Explorer */,
"graph" /* Graph */,
"header" /* Header */,
"starred" /* Starred */,
"tab" /* Tab */,
"inlineTitle" /* InlineTitle */,
"canvas" /* Canvas */
];
var GITHUB_DOCS = "https://github.com/snezhig/obsidian-front-matter-title/blob/master/docs/";
// src/i18n/en/index.ts
var en = {
validator: "Validator",
strategy: "Strategy",
cancel: "Cancel",
apply: "Apply",
feature: {
["alias" /* Alias */]: {
name: "Alias",
desc: "Modify alias in metadata cache. The real alias will not be affected",
validator: {
auto: {
name: "Frontmatter Auto",
desc: "If frontmatter does not exist, it will be created in cache. Side-effects may occur."
},
required: {
name: "Frontmatter Required",
desc: "Only files with frontmatter will be processed."
}
},
strategy: {
ensure: {
name: "Ensure",
desc: "Set title as an alias only if the one does not exist"
},
adjust: {
name: "Adjust",
desc: "Add title to alias and without affect on existing alias"
},
replace: {
name: "Replace",
desc: "Replace current alias with title"
}
}
},
["explorer" /* Explorer */]: {
name: "Explorer",
desc: "Replace shown titles in the file explorer"
},
["explorer:sort" /* ExplorerSort */]: {
name: "Explorer sort",
desc: "Sort files in explorer by titles from Explorer feature"
},
["graph" /* Graph */]: {
name: "Graph",
desc: "Replace shown titles in the graph/local-graph"
},
["header" /* Header */]: {
name: "Header",
desc: "Replace titles in header of leaves and update them"
},
["starred" /* Starred */]: {
name: "Starred",
desc: "Replace shown titles in built-in starred plugin"
},
["search" /* Search */]: {
name: "Search",
desc: "Replace shown titles in search leaf"
},
["suggest" /* Suggest */]: {
name: "Suggest",
desc: "Replace shown titles in suggest modals"
},
["tab" /* Tab */]: {
name: "Tabs",
desc: "Replace shown titles in tabs"
},
["inlineTitle" /* InlineTitle */]: {
name: "Inline",
desc: "Replace shown titles in Inline Title"
},
["canvas" /* Canvas */]: {
name: "Canvas",
desc: "Replace shown titles in Canvas"
},
["backlink" /* Backlink */]: {
name: "Backlink",
desc: "Replace shown titles in Backlink(Linked mentions)"
},
["noteLink" /* NoteLink */]: {
name: "Note Link",
desc: "Replace internal links in files",
strategy: {
all: "Repalce all links",
onlyEmpty: "Replace only links without alias"
},
approval: {
showModal: "Show approve modal",
auto: "Use auto approve"
}
}
},
manage: "Manage",
template: {
features: {
name: "Features' templates",
desc: "Manage templates for each feature individually"
},
main: "Main",
fallback: "Fallback",
placeholder: "Type a template",
commmon: {
main: {
name: "Common main template",
desc: `Set a yaml path, which value will be used as a file title. Value must be string or numeric. Also you can use template-like path using "{{ }}".
Also you can use #heading to use first Heading from a file or _basename and another reserved words.
See Readme to find out more`
},
fallback: {
name: "Common fallback template",
desc: "This template will be used as a fallback option if the main template is not resolved"
}
},
used: "Common template will be used. It's value is {{value}}",
specific: "Current template will be used for this feature"
},
settings: "Settings for plugin",
rule: {
name: "Rules",
path: {
name: "File path rule",
black: {
name: "Black list mode",
desc: "Files that are located by paths will be ignored by plugin. Each path must be written with new line."
},
white: {
name: "White list mode",
desc: "Files that are located by paths will be processed by plugin. Each path must be written with new line."
}
},
delimiter: {
name: "List values",
desc: "Set the rule about how to process list values",
first: "Use first value",
join: "Join all by delimiter",
placeholder: {
first: "First value will be used",
join: "Type a delimiter"
}
}
},
features: "Features",
util: "Util",
coffee: "If you like this plugin and you would like to help support continued development, you can use the buttons below:",
debug_info: {
title: "Debug info",
desc: "Show debug info and caught errors in console"
},
boot_delay: {
title: "Boot delay",
desc: "Plugin will be loaded with specified delay in ms"
},
disabled: "Disabled",
processor: {
name: "Processor",
desc: "Modifies resolved title",
replace: {
name: "Replace",
desc: "What will be executed",
pattern: {
name: "Pattern",
desc: "Will be used as a first argument of RegExp first, and then as a first argument of replace()"
},
flags: {
name: "Flags",
desc: "Will be used as a second argument of new RegExp"
},
replacement: {
name: "Replacement",
desc: "Will be used as a second argument of replace()"
}
},
function: {
name: "Function",
desc: "How it will work:",
valueDesc: "Your value of text area"
}
},
command: {
features: {
reload: "Reload features",
disable: "Disable features"
}
}
};
var en_default = en;
// src/i18n/ru/index.ts
var ru = {};
var ru_default = ru;
// node_modules/i18next/dist/esm/i18next.js
var consoleLogger = {
type: "logger",
log(args) {
this.output("log", args);
},
warn(args) {
this.output("warn", args);
},
error(args) {
this.output("error", args);
},
output(type, args) {
if (console && console[type])
console[type].apply(console, args);
}
};
var Logger = class _Logger {
constructor(concreteLogger) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.init(concreteLogger, options);
}
init(concreteLogger) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.prefix = options.prefix || "i18next:";
this.logger = concreteLogger || consoleLogger;
this.options = options;
this.debug = options.debug;
}
log() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return this.forward(args, "log", "", true);
}
warn() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this.forward(args, "warn", "", true);
}
error() {
for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
return this.forward(args, "error", "");
}
deprecate() {
for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
args[_key4] = arguments[_key4];
}
return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
}
forward(args, lvl, prefix, debugOnly) {
if (debugOnly && !this.debug)
return null;
if (typeof args[0] === "string")
args[0] = `${prefix}${this.prefix} ${args[0]}`;
return this.logger[lvl](args);
}
create(moduleName) {
return new _Logger(this.logger, {
...{
prefix: `${this.prefix}:${moduleName}:`
},
...this.options
});
}
clone(options) {
options = options || this.options;
options.prefix = options.prefix || this.prefix;
return new _Logger(this.logger, options);
}
};
var baseLogger = new Logger();
var EventEmitter = class {
constructor() {
this.observers = {};
}
on(events, listener) {
events.split(" ").forEach((event) => {
this.observers[event] = this.observers[event] || [];
this.observers[event].push(listener);
});
return this;
}
off(event, listener) {
if (!this.observers[event])
return;
if (!listener) {
delete this.observers[event];
return;
}
this.observers[event] = this.observers[event].filter((l) => l !== listener);
}
emit(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (this.observers[event]) {
const cloned = [].concat(this.observers[event]);
cloned.forEach((observer) => {
observer(...args);
});
}
if (this.observers["*"]) {
const cloned = [].concat(this.observers["*"]);
cloned.forEach((observer) => {
observer.apply(observer, [event, ...args]);
});
}
}
};
function defer() {
let res;
let rej;
const promise = new Promise((resolve2, reject) => {
res = resolve2;
rej = reject;
});
promise.resolve = res;
promise.reject = rej;
return promise;
}
function makeString(object) {
if (object == null)
return "";
return "" + object;
}
function copy(a, s, t3) {
a.forEach((m) => {
if (s[m])
t3[m] = s[m];
});
}
function getLastOfPath(object, path, Empty) {
function cleanKey(key) {
return key && key.indexOf("###") > -1 ? key.replace(/###/g, ".") : key;
}
function canNotTraverseDeeper() {
return !object || typeof object === "string";
}
const stack = typeof path !== "string" ? [].concat(path) : path.split(".");
while (stack.length > 1) {
if (canNotTraverseDeeper())
return {};
const key = cleanKey(stack.shift());
if (!object[key] && Empty)
object[key] = new Empty();
if (Object.prototype.hasOwnProperty.call(object, key)) {
object = object[key];
} else {
object = {};
}
}
if (canNotTraverseDeeper())
return {};
return {
obj: object,
k: cleanKey(stack.shift())
};
}
function setPath(object, path, newValue) {
const {
obj,
k
} = getLastOfPath(object, path, Object);
obj[k] = newValue;
}
function pushPath(object, path, newValue, concat) {
const {
obj,
k
} = getLastOfPath(object, path, Object);
obj[k] = obj[k] || [];
if (concat)
obj[k] = obj[k].concat(newValue);
if (!concat)
obj[k].push(newValue);
}
function getPath(object, path) {
const {
obj,
k
} = getLastOfPath(object, path);
if (!obj)
return void 0;
return obj[k];
}
function getPathWithDefaults(data, defaultData, key) {
const value = getPath(data, key);
if (value !== void 0) {
return value;
}
return getPath(defaultData, key);
}
function deepExtend(target, source, overwrite) {
for (const prop in source) {
if (prop !== "__proto__" && prop !== "constructor") {
if (prop in target) {
if (typeof target[prop] === "string" || target[prop] instanceof String || typeof source[prop] === "string" || source[prop] instanceof String) {
if (overwrite)
target[prop] = source[prop];
} else {
deepExtend(target[prop], source[prop], overwrite);
}
} else {
target[prop] = source[prop];
}
}
}
return target;
}
function regexEscape(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
var _entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/"
};
function escape(data) {
if (typeof data === "string") {
return data.replace(/[&<>"'\/]/g, (s) => _entityMap[s]);
}
return data;
}
var chars = [" ", ",", "?", "!", ";"];
function looksLikeObjectPath(key, nsSeparator, keySeparator) {
nsSeparator = nsSeparator || "";
keySeparator = keySeparator || "";
const possibleChars = chars.filter((c) => nsSeparator.indexOf(c) < 0 && keySeparator.indexOf(c) < 0);
if (possibleChars.length === 0)
return true;
const r = new RegExp(`(${possibleChars.map((c) => c === "?" ? "\\?" : c).join("|")})`);
let matched = !r.test(key);
if (!matched) {
const ki = key.indexOf(keySeparator);
if (ki > 0 && !r.test(key.substring(0, ki))) {
matched = true;
}
}
return matched;
}
function deepFind(obj, path) {
let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
if (!obj)
return void 0;
if (obj[path])
return obj[path];
const paths = path.split(keySeparator);
let current = obj;
for (let i = 0; i < paths.length; ++i) {
if (!current)
return void 0;
if (typeof current[paths[i]] === "string" && i + 1 < paths.length) {
return void 0;
}
if (current[paths[i]] === void 0) {
let j = 2;
let p = paths.slice(i, i + j).join(keySeparator);
let mix = current[p];
while (mix === void 0 && paths.length > i + j) {
j++;
p = paths.slice(i, i + j).join(keySeparator);
mix = current[p];
}
if (mix === void 0)
return void 0;
if (mix === null)
return null;
if (path.endsWith(p)) {
if (typeof mix === "string")
return mix;
if (p && typeof mix[p] === "string")
return mix[p];
}
const joinedPath = paths.slice(i + j).join(keySeparator);
if (joinedPath)
return deepFind(mix, joinedPath, keySeparator);
return void 0;
}
current = current[paths[i]];
}
return current;
}
function getCleanedCode(code) {
if (code && code.indexOf("_") > 0)
return code.replace("_", "-");
return code;
}
var ResourceStore = class extends EventEmitter {
constructor(data) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
ns: ["translation"],
defaultNS: "translation"
};
super();
this.data = data || {};
this.options = options;
if (this.options.keySeparator === void 0) {
this.options.keySeparator = ".";
}
if (this.options.ignoreJSONStructure === void 0) {
this.options.ignoreJSONStructure = true;
}
}
addNamespaces(ns) {
if (this.options.ns.indexOf(ns) < 0) {
this.options.ns.push(ns);
}
}
removeNamespaces(ns) {
const index = this.options.ns.indexOf(ns);
if (index > -1) {
this.options.ns.splice(index, 1);
}
}
getResource(lng, ns, key) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
let path = [lng, ns];
if (key && typeof key !== "string")
path = path.concat(key);
if (key && typeof key === "string")
path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf(".") > -1) {
path = lng.split(".");
}
const result = getPath(this.data, path);
if (result || !ignoreJSONStructure || typeof key !== "string")
return result;
return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
}
addResource(lng, ns, key, value) {
let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
silent: false
};
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
let path = [lng, ns];
if (key)
path = path.concat(keySeparator ? key.split(keySeparator) : key);
if (lng.indexOf(".") > -1) {
path = lng.split(".");
value = ns;
ns = path[1];
}
this.addNamespaces(ns);
setPath(this.data, path, value);
if (!options.silent)
this.emit("added", lng, ns, key, value);
}
addResources(lng, ns, resources) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
silent: false
};
for (const m in resources) {
if (typeof resources[m] === "string" || Object.prototype.toString.apply(resources[m]) === "[object Array]")
this.addResource(lng, ns, m, resources[m], {
silent: true
});
}
if (!options.silent)
this.emit("added", lng, ns, resources);
}
addResourceBundle(lng, ns, resources, deep, overwrite) {
let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
silent: false
};
let path = [lng, ns];
if (lng.indexOf(".") > -1) {
path = lng.split(".");
deep = resources;
resources = ns;
ns = path[1];
}
this.addNamespaces(ns);
let pack = getPath(this.data, path) || {};
if (deep) {
deepExtend(pack, resources, overwrite);
} else {
pack = {
...pack,
...resources
};
}
setPath(this.data, path, pack);
if (!options.silent)
this.emit("added", lng, ns, resources);
}
removeResourceBundle(lng, ns) {
if (this.hasResourceBundle(lng, ns)) {
delete this.data[lng][ns];
}
this.removeNamespaces(ns);
this.emit("removed", lng, ns);
}
hasResourceBundle(lng, ns) {
return this.getResource(lng, ns) !== void 0;
}
getResourceBundle(lng, ns) {
if (!ns)
ns = this.options.defaultNS;
if (this.options.compatibilityAPI === "v1")
return {
...{},
...this.getResource(lng, ns)
};
return this.getResource(lng, ns);
}
getDataByLanguage(lng) {
return this.data[lng];
}
hasLanguageSomeTranslations(lng) {
const data = this.getDataByLanguage(lng);
const n = data && Object.keys(data) || [];
return !!n.find((v) => data[v] && Object.keys(data[v]).length > 0);
}
toJSON() {
return this.data;
}
};
var postProcessor = {
processors: {},
addPostProcessor(module2) {
this.processors[module2.name] = module2;
},
handle(processors, value, key, options, translator) {
processors.forEach((processor) => {
if (this.processors[processor])
value = this.processors[processor].process(value, key, options, translator);
});
return value;
}
};
var checkedLoadedFor = {};
var Translator = class _Translator extends EventEmitter {
constructor(services) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
super();
copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
this.options = options;
if (this.options.keySeparator === void 0) {
this.options.keySeparator = ".";
}
this.logger = baseLogger.create("translator");
}
changeLanguage(lng) {
if (lng)
this.language = lng;
}
exists(key) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
interpolation: {}
};
if (key === void 0 || key === null) {
return false;
}
const resolved2 = this.resolve(key, options);
return resolved2 && resolved2.res !== void 0;
}
extractFromKey(key, options) {
let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
if (nsSeparator === void 0)
nsSeparator = ":";
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
let namespaces = options.ns || this.options.defaultNS || [];
const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
const m = key.match(this.interpolator.nestingRegexp);
if (m && m.length > 0) {
return {
key,
namespaces
};
}
const parts = key.split(nsSeparator);
if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1)
namespaces = parts.shift();
key = parts.join(keySeparator);
}
if (typeof namespaces === "string")
namespaces = [namespaces];
return {
key,
namespaces
};
}
translate(keys, options, lastKey) {
if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
options = this.options.overloadTranslationOptionHandler(arguments);
}
if (typeof options === "object")
options = {
...options
};
if (!options)
options = {};
if (keys === void 0 || keys === null)
return "";
if (!Array.isArray(keys))
keys = [String(keys)];
const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
const {
key,
namespaces
} = this.extractFromKey(keys[keys.length - 1], options);
const namespace = namespaces[namespaces.length - 1];
const lng = options.lng || this.language;
const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
if (lng && lng.toLowerCase() === "cimode") {
if (appendNamespaceToCIMode) {
const nsSeparator = options.nsSeparator || this.options.nsSeparator;
if (returnDetails) {
return {
res: `${namespace}${nsSeparator}${key}`,
usedKey: key,
exactUsedKey: key,
usedLng: lng,
usedNS: namespace
};
}
return `${namespace}${nsSeparator}${key}`;
}
if (returnDetails) {
return {
res: key,
usedKey: key,
exactUsedKey: key,
usedLng: lng,
usedNS: namespace
};
}
return key;
}
const resolved2 = this.resolve(keys, options);
let res = resolved2 && resolved2.res;
const resUsedKey = resolved2 && resolved2.usedKey || key;
const resExactUsedKey = resolved2 && resolved2.exactUsedKey || key;
const resType = Object.prototype.toString.apply(res);
const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
const handleAsObject = typeof res !== "string" && typeof res !== "boolean" && typeof res !== "number";
if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === "string" && resType === "[object Array]")) {
if (!options.returnObjects && !this.options.returnObjects) {
if (!this.options.returnedObjectHandler) {
this.logger.warn("accessing an object - but returnObjects options is not enabled!");
}
const r = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
...options,
ns: namespaces
}) : `key '${key} (${this.language})' returned an object instead of string.`;
if (returnDetails) {
resolved2.res = r;
return resolved2;
}
return r;
}
if (keySeparator) {
const resTypeIsArray = resType === "[object Array]";
const copy2 = resTypeIsArray ? [] : {};
const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
for (const m in res) {
if (Object.prototype.hasOwnProperty.call(res, m)) {
const deepKey = `${newKeyToUse}${keySeparator}${m}`;
copy2[m] = this.translate(deepKey, {
...options,
...{
joinArrays: false,
ns: namespaces
}
});
if (copy2[m] === deepKey)
copy2[m] = res[m];
}
}
res = copy2;
}
} else if (handleAsObjectInI18nFormat && typeof joinArrays === "string" && resType === "[object Array]") {
res = res.join(joinArrays);
if (res)
res = this.extendTranslation(res, keys, options, lastKey);
} else {
let usedDefault = false;
let usedKey = false;
const needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
const hasDefaultValue = _Translator.hasDefaultValue(options);
const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
ordinal: false
}) : "";
const defaultValue = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
if (!this.isValidLookup(res) && hasDefaultValue) {
usedDefault = true;
res = defaultValue;
}
if (!this.isValidLookup(res)) {
usedKey = true;
res = key;
}
const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
const updateMissing = hasDefaultValue && defaultValue !== res && this.options.updateMissing;
if (usedKey || usedDefault || updateMissing) {
this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue : res);
if (keySeparator) {
const fk = this.resolve(key, {
...options,
keySeparator: false
});
if (fk && fk.res)
this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
}
let lngs = [];
const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
for (let i = 0; i < fallbackLngs.length; i++) {
lngs.push(fallbackLngs[i]);
}
} else if (this.options.saveMissingTo === "all") {
lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
} else {
lngs.push(options.lng || this.language);
}
const send = (l, k, specificDefaultValue) => {
const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
if (this.options.missingKeyHandler) {
this.options.missingKeyHandler(l, namespace, k, defaultForMissing, updateMissing, options);
} else if (this.backendConnector && this.backendConnector.saveMissing) {
this.backendConnector.saveMissing(l, namespace, k, defaultForMissing, updateMissing, options);
}
this.emit("missingKey", l, namespace, k, res);
};
if (this.options.saveMissing) {
if (this.options.saveMissingPlurals && needsPluralHandling) {
lngs.forEach((language) => {
this.pluralResolver.getSuffixes(language, options).forEach((suffix) => {
send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue);
});
});
} else {
send(lngs, key, defaultValue);
}
}
}
res = this.extendTranslation(res, keys, options, resolved2, lastKey);
if (usedKey && res === key && this.options.appendNamespaceToMissingKey)
res = `${namespace}:${key}`;
if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
if (this.options.compatibilityAPI !== "v1") {
res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
} else {
res = this.options.parseMissingKeyHandler(res);
}
}
}
if (returnDetails) {
resolved2.res = res;
return resolved2;
}
return res;
}
extendTranslation(res, key, options, resolved2, lastKey) {
var _this = this;
if (this.i18nFormat && this.i18nFormat.parse) {
res = this.i18nFormat.parse(res, {
...this.options.interpolation.defaultVariables,
...options
}, resolved2.usedLng, resolved2.usedNS, resolved2.usedKey, {
resolved: resolved2
});
} else if (!options.skipInterpolation) {
if (options.interpolation)
this.interpolator.init({
...options,
...{
interpolation: {
...this.options.interpolation,
...options.interpolation
}
}
});
const skipOnVariables = typeof res === "string" && (options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
let nestBef;
if (skipOnVariables) {
const nb = res.match(this.interpolator.nestingRegexp);
nestBef = nb && nb.length;
}
let data = options.replace && typeof options.replace !== "string" ? options.replace : options;
if (this.options.interpolation.defaultVariables)
data = {
...this.options.interpolation.defaultVariables,
...data
};
res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
if (skipOnVariables) {
const na = res.match(this.interpolator.nestingRegexp);
const nestAft = na && na.length;
if (nestBef < nestAft)
options.nest = false;
}
if (!options.lng && this.options.compatibilityAPI !== "v1" && resolved2 && resolved2.res)
options.lng = resolved2.usedLng;
if (options.nest !== false)
res = this.interpolator.nest(res, function() {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
if (lastKey && lastKey[0] === args[0] && !options.context) {
_this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
return null;
}
return _this.translate(...args, key);
}, options);
if (options.interpolation)
this.interpolator.reset();
}
const postProcess = options.postProcess || this.options.postProcess;
const postProcessorNames = typeof postProcess === "string" ? [postProcess] : postProcess;
if (res !== void 0 && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
i18nResolved: resolved2,
...options
} : options, this);
}
return res;
}
resolve(keys) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
let found;
let usedKey;
let exactUsedKey;
let usedLng;
let usedNS;
if (typeof keys === "string")
keys = [keys];
keys.forEach((k) => {
if (this.isValidLookup(found))
return;
const extracted = this.extractFromKey(k, options);
const key = extracted.key;
usedKey = key;
let namespaces = extracted.namespaces;
if (this.options.fallbackNS)
namespaces = namespaces.concat(this.options.fallbackNS);
const needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
const needsContextHandling = options.context !== void 0 && (typeof options.context === "string" || typeof options.context === "number") && options.context !== "";
const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
namespaces.forEach((ns) => {
if (this.isValidLookup(found))
return;
usedNS = ns;
if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
checkedLoadedFor[`${codes[0]}-${ns}`] = true;
this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
}
codes.forEach((code) => {
if (this.isValidLookup(found))
return;
usedLng = code;
const finalKeys = [key];
if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
} else {
let pluralSuffix;
if (needsPluralHandling)
pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
const zeroSuffix = `${this.options.pluralSeparator}zero`;
const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
if (needsPluralHandling) {
finalKeys.push(key + pluralSuffix);
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
}
if (needsZeroSuffixLookup) {
finalKeys.push(key + zeroSuffix);
}
}
if (needsContextHandling) {
const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
finalKeys.push(contextKey);
if (needsPluralHandling) {
finalKeys.push(contextKey + pluralSuffix);
if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
}
if (needsZeroSuffixLookup) {
finalKeys.push(contextKey + zeroSuffix);
}
}
}
}
let possibleKey;
while (possibleKey = finalKeys.pop()) {
if (!this.isValidLookup(found)) {
exactUsedKey = possibleKey;
found = this.getResource(code, ns, possibleKey, options);
}
}
});
});
});
return {
res: found,
usedKey,
exactUsedKey,
usedLng,
usedNS
};
}
isValidLookup(res) {
return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
}
getResource(code, ns, key) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
if (this.i18nFormat && this.i18nFormat.getResource)
return this.i18nFormat.getResource(code, ns, key, options);
return this.resourceStore.getResource(code, ns, key, options);
}
static hasDefaultValue(options) {
const prefix = "defaultValue";
for (const option in options) {
if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
return true;
}
}
return false;
}
};
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
var LanguageUtil = class {
constructor(options) {
this.options = options;
this.supportedLngs = this.options.supportedLngs || false;
this.logger = baseLogger.create("languageUtils");
}
getScriptPartFromCode(code) {
code = getCleanedCode(code);
if (!code || code.indexOf("-") < 0)
return null;
const p = code.split("-");
if (p.length === 2)
return null;
p.pop();
if (p[p.length - 1].toLowerCase() === "x")
return null;
return this.formatLanguageCode(p.join("-"));
}
getLanguagePartFromCode(code) {
code = getCleanedCode(code);
if (!code || code.indexOf("-") < 0)
return code;
const p = code.split("-");
return this.formatLanguageCode(p[0]);
}
formatLanguageCode(code) {
if (typeof code === "string" && code.indexOf("-") > -1) {
const specialCases = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"];
let p = code.split("-");
if (this.options.lowerCaseLng) {
p = p.map((part) => part.toLowerCase());
} else if (p.length === 2) {
p[0] = p[0].toLowerCase();
p[1] = p[1].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1)
p[1] = capitalize(p[1].toLowerCase());
} else if (p.length === 3) {
p[0] = p[0].toLowerCase();
if (p[1].length === 2)
p[1] = p[1].toUpperCase();
if (p[0] !== "sgn" && p[2].length === 2)
p[2] = p[2].toUpperCase();
if (specialCases.indexOf(p[1].toLowerCase()) > -1)
p[1] = capitalize(p[1].toLowerCase());
if (specialCases.indexOf(p[2].toLowerCase()) > -1)
p[2] = capitalize(p[2].toLowerCase());
}
return p.join("-");
}
return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
}
isSupportedCode(code) {
if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
code = this.getLanguagePartFromCode(code);
}
return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
}
getBestMatchFromCodes(codes) {
if (!codes)
return null;
let found;
codes.forEach((code) => {
if (found)
return;
const cleanedLng = this.formatLanguageCode(code);
if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng))
found = cleanedLng;
});
if (!found && this.options.supportedLngs) {
codes.forEach((code) => {
if (found)
return;
const lngOnly = this.getLanguagePartFromCode(code);
if (this.isSupportedCode(lngOnly))
return found = lngOnly;
found = this.options.supportedLngs.find((supportedLng) => {
if (supportedLng === lngOnly)
return supportedLng;
if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0)
return;
if (supportedLng.indexOf(lngOnly) === 0)
return supportedLng;
});
});
}
if (!found)
found = this.getFallbackCodes(this.options.fallbackLng)[0];
return found;
}
getFallbackCodes(fallbacks, code) {
if (!fallbacks)
return [];
if (typeof fallbacks === "function")
fallbacks = fallbacks(code);
if (typeof fallbacks === "string")
fallbacks = [fallbacks];
if (Object.prototype.toString.apply(fallbacks) === "[object Array]")
return fallbacks;
if (!code)
return fallbacks.default || [];
let found = fallbacks[code];
if (!found)
found = fallbacks[this.getScriptPartFromCode(code)];
if (!found)
found = fallbacks[this.formatLanguageCode(code)];
if (!found)
found = fallbacks[this.getLanguagePartFromCode(code)];
if (!found)
found = fallbacks.default;
return found || [];
}
toResolveHierarchy(code, fallbackCode) {
const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
const codes = [];
const addCode = (c) => {
if (!c)
return;
if (this.isSupportedCode(c)) {
codes.push(c);
} else {
this.logger.warn(`rejecting language code not found in supportedLngs: ${c}`);
}
};
if (typeof code === "string" && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
if (this.options.load !== "languageOnly")
addCode(this.formatLanguageCode(code));
if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly")
addCode(this.getScriptPartFromCode(code));
if (this.options.load !== "currentOnly")
addCode(this.getLanguagePartFromCode(code));
} else if (typeof code === "string") {
addCode(this.formatLanguageCode(code));
}
fallbackCodes.forEach((fc) => {
if (codes.indexOf(fc) < 0)
addCode(this.formatLanguageCode(fc));
});
return codes;
}
};
var sets = [{
lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"],
nr: [1, 2],
fc: 1
}, {
lngs: ["af", "an", "ast", "az", "bg", "bn", "ca", "da", "de", "dev", "el", "en", "eo", "es", "et", "eu", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "hi", "hu", "hy", "ia", "it", "kk", "kn", "ku", "lb", "mai", "ml", "mn", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "pa", "pap", "pms", "ps", "pt-PT", "rm", "sco", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"],
nr: [1, 2],
fc: 2
}, {
lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"],
nr: [1],
fc: 3
}, {
lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"],
nr: [1, 2, 5],
fc: 4
}, {
lngs: ["ar"],
nr: [0, 1, 2, 3, 11, 100],
fc: 5
}, {
lngs: ["cs", "sk"],
nr: [1, 2, 5],
fc: 6
}, {
lngs: ["csb", "pl"],
nr: [1, 2, 5],
fc: 7
}, {
lngs: ["cy"],
nr: [1, 2, 3, 8],
fc: 8
}, {
lngs: ["fr"],
nr: [1, 2],
fc: 9
}, {
lngs: ["ga"],
nr: [1, 2, 3, 7, 11],
fc: 10
}, {
lngs: ["gd"],
nr: [1, 2, 3, 20],
fc: 11
}, {
lngs: ["is"],
nr: [1, 2],
fc: 12
}, {
lngs: ["jv"],
nr: [0, 1],
fc: 13
}, {
lngs: ["kw"],
nr: [1, 2, 3, 4],
fc: 14
}, {
lngs: ["lt"],
nr: [1, 2, 10],
fc: 15
}, {
lngs: ["lv"],
nr: [1, 2, 0],
fc: 16
}, {
lngs: ["mk"],
nr: [1, 2],
fc: 17
}, {
lngs: ["mnk"],
nr: [0, 1, 2],
fc: 18
}, {
lngs: ["mt"],
nr: [1, 2, 11, 20],
fc: 19
}, {
lngs: ["or"],
nr: [2, 1],
fc: 2
}, {
lngs: ["ro"],
nr: [1, 2, 20],
fc: 20
}, {
lngs: ["sl"],
nr: [5, 1, 2, 3],
fc: 21
}, {
lngs: ["he", "iw"],
nr: [1, 2, 20, 21],
fc: 22
}];
var _rulesPluralsTypes = {
1: function(n) {
return Number(n > 1);
},
2: function(n) {
return Number(n != 1);
},
3: function(n) {
return 0;
},
4: function(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
5: function(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : n == 2 ? 2 : n % 100 >= 3 && n % 100 <= 10 ? 3 : n % 100 >= 11 ? 4 : 5);
},
6: function(n) {
return Number(n == 1 ? 0 : n >= 2 && n <= 4 ? 1 : 2);
},
7: function(n) {
return Number(n == 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
8: function(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n != 8 && n != 11 ? 2 : 3);
},
9: function(n) {
return Number(n >= 2);
},
10: function(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n < 7 ? 2 : n < 11 ? 3 : 4);
},
11: function(n) {
return Number(n == 1 || n == 11 ? 0 : n == 2 || n == 12 ? 1 : n > 2 && n < 20 ? 2 : 3);
},
12: function(n) {
return Number(n % 10 != 1 || n % 100 == 11);
},
13: function(n) {
return Number(n !== 0);
},
14: function(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : n == 3 ? 2 : 3);
},
15: function(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
},
16: function(n) {
return Number(n % 10 == 1 && n % 100 != 11 ? 0 : n !== 0 ? 1 : 2);
},
17: function(n) {
return Number(n == 1 || n % 10 == 1 && n % 100 != 11 ? 0 : 1);
},
18: function(n) {
return Number(n == 0 ? 0 : n == 1 ? 1 : 2);
},
19: function(n) {
return Number(n == 1 ? 0 : n == 0 || n % 100 > 1 && n % 100 < 11 ? 1 : n % 100 > 10 && n % 100 < 20 ? 2 : 3);
},
20: function(n) {
return Number(n == 1 ? 0 : n == 0 || n % 100 > 0 && n % 100 < 20 ? 1 : 2);
},
21: function(n) {
return Number(n % 100 == 1 ? 1 : n % 100 == 2 ? 2 : n % 100 == 3 || n % 100 == 4 ? 3 : 0);
},
22: function(n) {
return Number(n == 1 ? 0 : n == 2 ? 1 : (n < 0 || n > 10) && n % 10 == 0 ? 2 : 3);
}
};
var nonIntlVersions = ["v1", "v2", "v3"];
var intlVersions = ["v4"];
var suffixesOrder = {
zero: 0,
one: 1,
two: 2,
few: 3,
many: 4,
other: 5
};
function createRules() {
const rules = {};
sets.forEach((set) => {
set.lngs.forEach((l) => {
rules[l] = {
numbers: set.nr,
plurals: _rulesPluralsTypes[set.fc]
};
});
});
return rules;
}
var PluralResolver = class {
constructor(languageUtils) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
this.languageUtils = languageUtils;
this.options = options;
this.logger = baseLogger.create("pluralResolver");
if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === "undefined" || !Intl.PluralRules)) {
this.options.compatibilityJSON = "v3";
this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.");
}
this.rules = createRules();
}
addRule(lng, obj) {
this.rules[lng] = obj;
}
getRule(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
if (this.shouldUseIntlApi()) {
try {
return new Intl.PluralRules(getCleanedCode(code), {
type: options.ordinal ? "ordinal" : "cardinal"
});
} catch (e) {
return;
}
}
return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
}
needsPlural(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
const rule = this.getRule(code, options);
if (this.shouldUseIntlApi()) {
return rule && rule.resolvedOptions().pluralCategories.length > 1;
}
return rule && rule.numbers.length > 1;
}
getPluralFormsOfKey(code, key) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
}
getSuffixes(code) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
const rule = this.getRule(code, options);
if (!rule) {
return [];
}
if (this.shouldUseIntlApi()) {
return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
}
return rule.numbers.map((number) => this.getSuffix(code, number, options));
}
getSuffix(code, count) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
const rule = this.getRule(code, options);
if (rule) {
if (this.shouldUseIntlApi()) {
return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
}
return this.getSuffixRetroCompatible(rule, count);
}
this.logger.warn(`no plural rule found for: ${code}`);
return "";
}
getSuffixRetroCompatible(rule, count) {
const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
let suffix = rule.numbers[idx];
if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
if (suffix === 2) {
suffix = "plural";
} else if (suffix === 1) {
suffix = "";
}
}
const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
if (this.options.compatibilityJSON === "v1") {
if (suffix === 1)
return "";
if (typeof suffix === "number")
return `_plural_${suffix.toString()}`;
return returnSuffix();
} else if (this.options.compatibilityJSON === "v2") {
return returnSuffix();
} else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
return returnSuffix();
}
return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
}
shouldUseIntlApi() {
return !nonIntlVersions.includes(this.options.compatibilityJSON);
}
};
function deepFindWithDefaults(data, defaultData, key) {
let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
let path = getPathWithDefaults(data, defaultData, key);
if (!path && ignoreJSONStructure && typeof key === "string") {
path = deepFind(data, key, keySeparator);
if (path === void 0)
path = deepFind(defaultData, key, keySeparator);
}
return path;
}
var Interpolator = class {
constructor() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
this.logger = baseLogger.create("interpolator");
this.options = options;
this.format = options.interpolation && options.interpolation.format || ((value) => value);
this.init(options);
}
init() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
if (!options.interpolation)
options.interpolation = {
escapeValue: true
};
const iOpts = options.interpolation;
this.escape = iOpts.escape !== void 0 ? iOpts.escape : escape;
this.escapeValue = iOpts.escapeValue !== void 0 ? iOpts.escapeValue : true;
this.useRawValueToEscape = iOpts.useRawValueToEscape !== void 0 ? iOpts.useRawValueToEscape : false;
this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || "{{";
this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || "}}";
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
this.unescapePrefix = iOpts.unescapeSuffix ? "" : iOpts.unescapePrefix || "-";
this.unescapeSuffix = this.unescapePrefix ? "" : iOpts.unescapeSuffix || "";
this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape("$t(");
this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(")");
this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ",";
this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1e3;
this.alwaysFormat = iOpts.alwaysFormat !== void 0 ? iOpts.alwaysFormat : false;
this.resetRegExp();
}
reset() {
if (this.options)
this.init(this.options);
}
resetRegExp() {
const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
this.regexp = new RegExp(regexpStr, "g");
const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
this.regexpUnescape = new RegExp(regexpUnescapeStr, "g");
const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
this.nestingRegexp = new RegExp(nestingRegexpStr, "g");
}
interpolate(str, data, lng, options) {
let match;
let value;
let replaces;
const defaultData = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
function regexSafe(val) {
return val.replace(/\$/g, "$$$$");
}
const handleFormat = (key) => {
if (key.indexOf(this.formatSeparator) < 0) {
const path = deepFindWithDefaults(data, defaultData, key, this.options.keySeparator, this.options.ignoreJSONStructure);
return this.alwaysFormat ? this.format(path, void 0, lng, {
...options,
...data,
interpolationkey: key
}) : path;
}
const p = key.split(this.formatSeparator);
const k = p.shift().trim();
const f = p.join(this.formatSeparator).trim();
return this.format(deepFindWithDefaults(data, defaultData, k, this.options.keySeparator, this.options.ignoreJSONStructure), f, lng, {
...options,
...data,
interpolationkey: k
});
};
this.resetRegExp();
const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
const todos = [{
regex: this.regexpUnescape,
safeValue: (val) => regexSafe(val)
}, {
regex: this.regexp,
safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
}];
todos.forEach((todo) => {
replaces = 0;
while (match = todo.regex.exec(str)) {
const matchedVar = match[1].trim();
value = handleFormat(matchedVar);
if (value === void 0) {
if (typeof missingInterpolationHandler === "function") {
const temp = missingInterpolationHandler(str, match, options);
value = typeof temp === "string" ? temp : "";
} else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
value = "";
} else if (skipOnVariables) {
value = match[0];
continue;
} else {
this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
value = "";
}
} else if (typeof value !== "string" && !this.useRawValueToEscape) {
value = makeString(value);
}
const safeValue = todo.safeValue(value);
str = str.replace(match[0], safeValue);
if (skipOnVariables) {
todo.regex.lastIndex += value.length;
todo.regex.lastIndex -= match[0].length;
} else {
todo.regex.lastIndex = 0;
}
replaces++;
if (replaces >= this.maxReplaces) {
break;
}
}
});
return str;
}
nest(str, fc) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
let match;
let value;
let clonedOptions;
function handleHasOptions(key, inheritedOptions) {
const sep = this.nestingOptionsSeparator;
if (key.indexOf(sep) < 0)
return key;
const c = key.split(new RegExp(`${sep}[ ]*{`));
let optionsString = `{${c[1]}`;
key = c[0];
optionsString = this.interpolate(optionsString, clonedOptions);
const matchedSingleQuotes = optionsString.match(/'/g);
const matchedDoubleQuotes = optionsString.match(/"/g);
if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
optionsString = optionsString.replace(/'/g, '"');
}
try {
clonedOptions = JSON.parse(optionsString);
if (inheritedOptions)
clonedOptions = {
...inheritedOptions,
...clonedOptions
};
} catch (e) {
this.logger.warn(`failed parsing options string in nesting for key ${key}`, e);
return `${key}${sep}${optionsString}`;
}
delete clonedOptions.defaultValue;
return key;
}
while (match = this.nestingRegexp.exec(str)) {
let formatters = [];
clonedOptions = {
...options
};
clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== "string" ? clonedOptions.replace : clonedOptions;
clonedOptions.applyPostProcessor = false;
delete clonedOptions.defaultValue;
let doReduce = false;
if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
const r = match[1].split(this.formatSeparator).map((elem) => elem.trim());
match[1] = r.shift();
formatters = r;
doReduce = true;
}
value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
if (value && match[0] === str && typeof value !== "string")
return value;
if (typeof value !== "string")
value = makeString(value);
if (!value) {
this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
value = "";
}
if (doReduce) {
value = formatters.reduce((v, f) => this.format(v, f, options.lng, {
...options,
interpolationkey: match[1].trim()
}), value.trim());
}
str = str.replace(match[0], value);
this.regexp.lastIndex = 0;
}
return str;
}
};
function parseFormatStr(formatStr) {
let formatName = formatStr.toLowerCase().trim();
const formatOptions = {};
if (formatStr.indexOf("(") > -1) {
const p = formatStr.split("(");
formatName = p[0].toLowerCase().trim();
const optStr = p[1].substring(0, p[1].length - 1);
if (formatName === "currency" && optStr.indexOf(":") < 0) {
if (!formatOptions.currency)
formatOptions.currency = optStr.trim();
} else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
if (!formatOptions.range)
formatOptions.range = optStr.trim();
} else {
const opts = optStr.split(";");
opts.forEach((opt) => {
if (!opt)
return;
const [key, ...rest] = opt.split(":");
const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
if (!formatOptions[key.trim()])
formatOptions[key.trim()] = val;
if (val === "false")
formatOptions[key.trim()] = false;
if (val === "true")
formatOptions[key.trim()] = true;
if (!isNaN(val))
formatOptions[key.trim()] = parseInt(val, 10);
});
}
}
return {
formatName,
formatOptions
};
}
function createCachedFormatter(fn) {
const cache = {};
return function invokeFormatter(val, lng, options) {
const key = lng + JSON.stringify(options);
let formatter = cache[key];
if (!formatter) {
formatter = fn(getCleanedCode(lng), options);
cache[key] = formatter;
}
return formatter(val);
};
}
var Formatter = class {
constructor() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
this.logger = baseLogger.create("formatter");
this.options = options;
this.formats = {
number: createCachedFormatter((lng, opt) => {
const formatter = new Intl.NumberFormat(lng, {
...opt
});
return (val) => formatter.format(val);
}),
currency: createCachedFormatter((lng, opt) => {
const formatter = new Intl.NumberFormat(lng, {
...opt,
style: "currency"
});
return (val) => formatter.format(val);
}),
datetime: createCachedFormatter((lng, opt) => {
const formatter = new Intl.DateTimeFormat(lng, {
...opt
});
return (val) => formatter.format(val);
}),
relativetime: createCachedFormatter((lng, opt) => {
const formatter = new Intl.RelativeTimeFormat(lng, {
...opt
});
return (val) => formatter.format(val, opt.range || "day");
}),
list: createCachedFormatter((lng, opt) => {
const formatter = new Intl.ListFormat(lng, {
...opt
});
return (val) => formatter.format(val);
})
};
this.init(options);
}
init(services) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
interpolation: {}
};
const iOpts = options.interpolation;
this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
}
add(name, fc) {
this.formats[name.toLowerCase().trim()] = fc;
}
addCached(name, fc) {
this.formats[name.toLowerCase().trim()] = createCachedFormatter(fc);
}
format(value, format, lng) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
const formats = format.split(this.formatSeparator);
const result = formats.reduce((mem, f) => {
const {
formatName,
formatOptions
} = parseFormatStr(f);
if (this.formats[formatName]) {
let formatted = mem;
try {
const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
const l = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
formatted = this.formats[formatName](mem, l, {
...formatOptions,
...options,
...valOptions
});
} catch (error) {
this.logger.warn(error);
}
return formatted;
} else {
this.logger.warn(`there was no format function for ${formatName}`);
}
return mem;
}, value);
return result;
}
};
function removePending(q, name) {
if (q.pending[name] !== void 0) {
delete q.pending[name];
q.pendingCount--;
}
}
var Connector = class extends EventEmitter {
constructor(backend, store, services) {
let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
super();
this.backend = backend;
this.store = store;
this.services = services;
this.languageUtils = services.languageUtils;
this.options = options;
this.logger = baseLogger.create("backendConnector");
this.waitingReads = [];
this.maxParallelReads = options.maxParallelReads || 10;
this.readingCalls = 0;
this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
this.state = {};
this.queue = [];
if (this.backend && this.backend.init) {
this.backend.init(services, options.backend, options);
}
}
queueLoad(languages, namespaces, options, callback) {
const toLoad = {};
const pending = {};
const toLoadLanguages = {};
const toLoadNamespaces = {};
languages.forEach((lng) => {
let hasAllNamespaces = true;
namespaces.forEach((ns) => {
const name = `${lng}|${ns}`;
if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
this.state[name] = 2;
} else if (this.state[name] < 0)
;
else if (this.state[name] === 1) {
if (pending[name] === void 0)
pending[name] = true;
} else {
this.state[name] = 1;
hasAllNamespaces = false;
if (pending[name] === void 0)
pending[name] = true;
if (toLoad[name] === void 0)
toLoad[name] = true;
if (toLoadNamespaces[ns] === void 0)
toLoadNamespaces[ns] = true;
}
});
if (!hasAllNamespaces)
toLoadLanguages[lng] = true;
});
if (Object.keys(toLoad).length || Object.keys(pending).length) {
this.queue.push({
pending,
pendingCount: Object.keys(pending).length,
loaded: {},
errors: [],
callback
});
}
return {
toLoad: Object.keys(toLoad),
pending: Object.keys(pending),
toLoadLanguages: Object.keys(toLoadLanguages),
toLoadNamespaces: Object.keys(toLoadNamespaces)
};
}
loaded(name, err, data) {
const s = name.split("|");
const lng = s[0];
const ns = s[1];
if (err)
this.emit("failedLoading", lng, ns, err);
if (data) {
this.store.addResourceBundle(lng, ns, data);
}
this.state[name] = err ? -1 : 2;
const loaded = {};
this.queue.forEach((q) => {
pushPath(q.loaded, [lng], ns);
removePending(q, name);
if (err)
q.errors.push(err);
if (q.pendingCount === 0 && !q.done) {
Object.keys(q.loaded).forEach((l) => {
if (!loaded[l])
loaded[l] = {};
const loadedKeys = q.loaded[l];
if (loadedKeys.length) {
loadedKeys.forEach((n) => {
if (loaded[l][n] === void 0)
loaded[l][n] = true;
});
}
});
q.done = true;
if (q.errors.length) {
q.callback(q.errors);
} else {
q.callback();
}
}
});
this.emit("loaded", loaded);
this.queue = this.queue.filter((q) => !q.done);
}
read(lng, ns, fcName) {
let tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
let wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout;
let callback = arguments.length > 5 ? arguments[5] : void 0;
if (!lng.length)
return callback(null, {});
if (this.readingCalls >= this.maxParallelReads) {
this.waitingReads.push({
lng,
ns,
fcName,
tried,
wait,
callback
});
return;
}
this.readingCalls++;
const resolver = (err, data) => {
this.readingCalls--;
if (this.waitingReads.length > 0) {
const next = this.waitingReads.shift();
this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
}
if (err && data && tried < this.maxRetries) {
setTimeout(() => {
this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
}, wait);
return;
}
callback(err, data);
};
const fc = this.backend[fcName].bind(this.backend);
if (fc.length === 2) {
try {
const r = fc(lng, ns);
if (r && typeof r.then === "function") {
r.then((data) => resolver(null, data)).catch(resolver);
} else {
resolver(null, r);
}
} catch (err) {
resolver(err);
}
return;
}
return fc(lng, ns, resolver);
}
prepareLoading(languages, namespaces) {
let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
let callback = arguments.length > 3 ? arguments[3] : void 0;
if (!this.backend) {
this.logger.warn("No backend was added via i18next.use. Will not load resources.");
return callback && callback();
}
if (typeof languages === "string")
languages = this.languageUtils.toResolveHierarchy(languages);
if (typeof namespaces === "string")
namespaces = [namespaces];
const toLoad = this.queueLoad(languages, namespaces, options, callback);
if (!toLoad.toLoad.length) {
if (!toLoad.pending.length)
callback();
return null;
}
toLoad.toLoad.forEach((name) => {
this.loadOne(name);
});
}
load(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {}, callback);
}
reload(languages, namespaces, callback) {
this.prepareLoading(languages, namespaces, {
reload: true
}, callback);
}
loadOne(name) {
let prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
const s = name.split("|");
const lng = s[0];
const ns = s[1];
this.read(lng, ns, "read", void 0, void 0, (err, data) => {
if (err)
this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
if (!err && data)
this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
this.loaded(name, err, data);
});
}
saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
let clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : () => {
};
if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
return;
}
if (key === void 0 || key === null || key === "")
return;
if (this.backend && this.backend.create) {
const opts = {
...options,
isUpdate
};
const fc = this.backend.create.bind(this.backend);
if (fc.length < 6) {
try {
let r;
if (fc.length === 5) {
r = fc(languages, namespace, key, fallbackValue, opts);
} else {
r = fc(languages, namespace, key, fallbackValue);
}
if (r && typeof r.then === "function") {
r.then((data) => clb(null, data)).catch(clb);
} else {
clb(null, r);
}
} catch (err) {
clb(err);
}
} else {
fc(languages, namespace, key, fallbackValue, clb, opts);
}
}
if (!languages || !languages[0])
return;
this.store.addResource(languages[0], namespace, key, fallbackValue);
}
};
function get() {
return {
debug: false,
initImmediate: true,
ns: ["translation"],
defaultNS: ["translation"],
fallbackLng: ["dev"],
fallbackNS: false,
supportedLngs: false,
nonExplicitSupportedLngs: false,
load: "all",
preload: false,
simplifyPluralSuffix: true,
keySeparator: ".",
nsSeparator: ":",
pluralSeparator: "_",
contextSeparator: "_",
partialBundledLanguages: false,
saveMissing: false,
updateMissing: false,
saveMissingTo: "fallback",
saveMissingPlurals: true,
missingKeyHandler: false,
missingInterpolationHandler: false,
postProcess: false,
postProcessPassResolved: false,
returnNull: false,
returnEmptyString: true,
returnObjects: false,
joinArrays: false,
returnedObjectHandler: false,
parseMissingKeyHandler: false,
appendNamespaceToMissingKey: false,
appendNamespaceToCIMode: false,
overloadTranslationOptionHandler: function handle(args) {
let ret = {};
if (typeof args[1] === "object")
ret = args[1];
if (typeof args[1] === "string")
ret.defaultValue = args[1];
if (typeof args[2] === "string")
ret.tDescription = args[2];
if (typeof args[2] === "object" || typeof args[3] === "object") {
const options = args[3] || args[2];
Object.keys(options).forEach((key) => {
ret[key] = options[key];
});
}
return ret;
},
interpolation: {
escapeValue: true,
format: (value, format, lng, options) => value,
prefix: "{{",
suffix: "}}",
formatSeparator: ",",
unescapePrefix: "-",
nestingPrefix: "$t(",
nestingSuffix: ")",
nestingOptionsSeparator: ",",
maxReplaces: 1e3,
skipOnVariables: true
}
};
}
function transformOptions(options) {
if (typeof options.ns === "string")
options.ns = [options.ns];
if (typeof options.fallbackLng === "string")
options.fallbackLng = [options.fallbackLng];
if (typeof options.fallbackNS === "string")
options.fallbackNS = [options.fallbackNS];
if (options.supportedLngs && options.supportedLngs.indexOf("cimode") < 0) {
options.supportedLngs = options.supportedLngs.concat(["cimode"]);
}
return options;
}
function noop() {
}
function bindMemberFunctions(inst) {
const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
mems.forEach((mem) => {
if (typeof inst[mem] === "function") {
inst[mem] = inst[mem].bind(inst);
}
});
}
var I18n = class _I18n extends EventEmitter {
constructor() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
let callback = arguments.length > 1 ? arguments[1] : void 0;
super();
this.options = transformOptions(options);
this.services = {};
this.logger = baseLogger;
this.modules = {
external: []
};
bindMemberFunctions(this);
if (callback && !this.isInitialized && !options.isClone) {
if (!this.options.initImmediate) {
this.init(options, callback);
return this;
}
setTimeout(() => {
this.init(options, callback);
}, 0);
}
}
init() {
var _this = this;
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
let callback = arguments.length > 1 ? arguments[1] : void 0;
if (typeof options === "function") {
callback = options;
options = {};
}
if (!options.defaultNS && options.defaultNS !== false && options.ns) {
if (typeof options.ns === "string") {
options.defaultNS = options.ns;
} else if (options.ns.indexOf("translation") < 0) {
options.defaultNS = options.ns[0];
}
}
const defOpts = get();
this.options = {
...defOpts,
...this.options,
...transformOptions(options)
};
if (this.options.compatibilityAPI !== "v1") {
this.options.interpolation = {
...defOpts.interpolation,
...this.options.interpolation
};
}
if (options.keySeparator !== void 0) {
this.options.userDefinedKeySeparator = options.keySeparator;
}
if (options.nsSeparator !== void 0) {
this.options.userDefinedNsSeparator = options.nsSeparator;
}
function createClassOnDemand(ClassOrObject) {
if (!ClassOrObject)
return null;
if (typeof ClassOrObject === "function")
return new ClassOrObject();
return ClassOrObject;
}
if (!this.options.isClone) {
if (this.modules.logger) {
baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
} else {
baseLogger.init(null, this.options);
}
let formatter;
if (this.modules.formatter) {
formatter = this.modules.formatter;
} else if (typeof Intl !== "undefined") {
formatter = Formatter;
}
const lu = new LanguageUtil(this.options);
this.store = new ResourceStore(this.options.resources, this.options);
const s = this.services;
s.logger = baseLogger;
s.resourceStore = this.store;
s.languageUtils = lu;
s.pluralResolver = new PluralResolver(lu, {
prepend: this.options.pluralSeparator,
compatibilityJSON: this.options.compatibilityJSON,
simplifyPluralSuffix: this.options.simplifyPluralSuffix
});
if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
s.formatter = createClassOnDemand(formatter);
s.formatter.init(s, this.options);
this.options.interpolation.format = s.formatter.format.bind(s.formatter);
}
s.interpolator = new Interpolator(this.options);
s.utils = {
hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
};
s.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s.resourceStore, s, this.options);
s.backendConnector.on("*", function(event) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
_this.emit(event, ...args);
});
if (this.modules.languageDetector) {
s.languageDetector = createClassOnDemand(this.modules.languageDetector);
if (s.languageDetector.init)
s.languageDetector.init(s, this.options.detection, this.options);
}
if (this.modules.i18nFormat) {
s.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
if (s.i18nFormat.init)
s.i18nFormat.init(this);
}
this.translator = new Translator(this.services, this.options);
this.translator.on("*", function(event) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
_this.emit(event, ...args);
});
this.modules.external.forEach((m) => {
if (m.init)
m.init(this);
});
}
this.format = this.options.interpolation.format;
if (!callback)
callback = noop;
if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
if (codes.length > 0 && codes[0] !== "dev")
this.options.lng = codes[0];
}
if (!this.services.languageDetector && !this.options.lng) {
this.logger.warn("init: no languageDetector is used and no lng is defined");
}
const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
storeApi.forEach((fcName) => {
this[fcName] = function() {
return _this.store[fcName](...arguments);
};
});
const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
storeApiChained.forEach((fcName) => {
this[fcName] = function() {
_this.store[fcName](...arguments);
return _this;
};
});
const deferred = defer();
const load = () => {
const finish = (err, t3) => {
if (this.isInitialized && !this.initializedStoreOnce)
this.logger.warn("init: i18next is already initialized. You should call init just once!");
this.isInitialized = true;
if (!this.options.isClone)
this.logger.log("initialized", this.options);
this.emit("initialized", this.options);
deferred.resolve(t3);
callback(err, t3);
};
if (this.languages && this.options.compatibilityAPI !== "v1" && !this.isInitialized)
return finish(null, this.t.bind(this));
this.changeLanguage(this.options.lng, finish);
};
if (this.options.resources || !this.options.initImmediate) {
load();
} else {
setTimeout(load, 0);
}
return deferred;
}
loadResources(language) {
let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
let usedCallback = callback;
const usedLng = typeof language === "string" ? language : this.language;
if (typeof language === "function")
usedCallback = language;
if (!this.options.resources || this.options.partialBundledLanguages) {
if (usedLng && usedLng.toLowerCase() === "cimode")
return usedCallback();
const toLoad = [];
const append = (lng) => {
if (!lng)
return;
const lngs = this.services.languageUtils.toResolveHierarchy(lng);
lngs.forEach((l) => {
if (toLoad.indexOf(l) < 0)
toLoad.push(l);
});
};
if (!usedLng) {
const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
fallbacks.forEach((l) => append(l));
} else {
append(usedLng);
}
if (this.options.preload) {
this.options.preload.forEach((l) => append(l));
}
this.services.backendConnector.load(toLoad, this.options.ns, (e) => {
if (!e && !this.resolvedLanguage && this.language)
this.setResolvedLanguage(this.language);
usedCallback(e);
});
} else {
usedCallback(null);
}
}
reloadResources(lngs, ns, callback) {
const deferred = defer();
if (!lngs)
lngs = this.languages;
if (!ns)
ns = this.options.ns;
if (!callback)
callback = noop;
this.services.backendConnector.reload(lngs, ns, (err) => {
deferred.resolve();
callback(err);
});
return deferred;
}
use(module2) {
if (!module2)
throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
if (!module2.type)
throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
if (module2.type === "backend") {
this.modules.backend = module2;
}
if (module2.type === "logger" || module2.log && module2.warn && module2.error) {
this.modules.logger = module2;
}
if (module2.type === "languageDetector") {
this.modules.languageDetector = module2;
}
if (module2.type === "i18nFormat") {
this.modules.i18nFormat = module2;
}
if (module2.type === "postProcessor") {
postProcessor.addPostProcessor(module2);
}
if (module2.type === "formatter") {
this.modules.formatter = module2;
}
if (module2.type === "3rdParty") {
this.modules.external.push(module2);
}
return this;
}
setResolvedLanguage(l) {
if (!l || !this.languages)
return;
if (["cimode", "dev"].indexOf(l) > -1)
return;
for (let li = 0; li < this.languages.length; li++) {
const lngInLngs = this.languages[li];
if (["cimode", "dev"].indexOf(lngInLngs) > -1)
continue;
if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
this.resolvedLanguage = lngInLngs;
break;
}
}
}
changeLanguage(lng, callback) {
var _this2 = this;
this.isLanguageChangingTo = lng;
const deferred = defer();
this.emit("languageChanging", lng);
const setLngProps = (l) => {
this.language = l;
this.languages = this.services.languageUtils.toResolveHierarchy(l);
this.resolvedLanguage = void 0;
this.setResolvedLanguage(l);
};
const done = (err, l) => {
if (l) {
setLngProps(l);
this.translator.changeLanguage(l);
this.isLanguageChangingTo = void 0;
this.emit("languageChanged", l);
this.logger.log("languageChanged", l);
} else {
this.isLanguageChangingTo = void 0;
}
deferred.resolve(function() {
return _this2.t(...arguments);
});
if (callback)
callback(err, function() {
return _this2.t(...arguments);
});
};
const setLng = (lngs) => {
if (!lng && !lngs && this.services.languageDetector)
lngs = [];
const l = typeof lngs === "string" ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
if (l) {
if (!this.language) {
setLngProps(l);
}
if (!this.translator.language)
this.translator.changeLanguage(l);
if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage)
this.services.languageDetector.cacheUserLanguage(l);
}
this.loadResources(l, (err) => {
done(err, l);
});
};
if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
setLng(this.services.languageDetector.detect());
} else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
if (this.services.languageDetector.detect.length === 0) {
this.services.languageDetector.detect().then(setLng);
} else {
this.services.languageDetector.detect(setLng);
}
} else {
setLng(lng);
}
return deferred;
}
getFixedT(lng, ns, keyPrefix) {
var _this3 = this;
const fixedT = function(key, opts) {
let options;
if (typeof opts !== "object") {
for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
rest[_key3 - 2] = arguments[_key3];
}
options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
} else {
options = {
...opts
};
}
options.lng = options.lng || fixedT.lng;
options.lngs = options.lngs || fixedT.lngs;
options.ns = options.ns || fixedT.ns;
options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
const keySeparator = _this3.options.keySeparator || ".";
let resultKey;
if (options.keyPrefix && Array.isArray(key)) {
resultKey = key.map((k) => `${options.keyPrefix}${keySeparator}${k}`);
} else {
resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
}
return _this3.t(resultKey, options);
};
if (typeof lng === "string") {
fixedT.lng = lng;
} else {
fixedT.lngs = lng;
}
fixedT.ns = ns;
fixedT.keyPrefix = keyPrefix;
return fixedT;
}
t() {
return this.translator && this.translator.translate(...arguments);
}
exists() {
return this.translator && this.translator.exists(...arguments);
}
setDefaultNamespace(ns) {
this.options.defaultNS = ns;
}
hasLoadedNamespace(ns) {
let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
if (!this.isInitialized) {
this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
return false;
}
if (!this.languages || !this.languages.length) {
this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
return false;
}
const lng = options.lng || this.resolvedLanguage || this.languages[0];
const fallbackLng = this.options ? this.options.fallbackLng : false;
const lastLng = this.languages[this.languages.length - 1];
if (lng.toLowerCase() === "cimode")
return true;
const loadNotPending = (l, n) => {
const loadState = this.services.backendConnector.state[`${l}|${n}`];
return loadState === -1 || loadState === 2;
};
if (options.precheck) {
const preResult = options.precheck(this, loadNotPending);
if (preResult !== void 0)
return preResult;
}
if (this.hasResourceBundle(lng, ns))
return true;
if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages)
return true;
if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
return true;
return false;
}
loadNamespaces(ns, callback) {
const deferred = defer();
if (!this.options.ns) {
if (callback)
callback();
return Promise.resolve();
}
if (typeof ns === "string")
ns = [ns];
ns.forEach((n) => {
if (this.options.ns.indexOf(n) < 0)
this.options.ns.push(n);
});
this.loadResources((err) => {
deferred.resolve();
if (callback)
callback(err);
});
return deferred;
}
loadLanguages(lngs, callback) {
const deferred = defer();
if (typeof lngs === "string")
lngs = [lngs];
const preloaded = this.options.preload || [];
const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0);
if (!newLngs.length) {
if (callback)
callback();
return Promise.resolve();
}
this.options.preload = preloaded.concat(newLngs);
this.loadResources((err) => {
deferred.resolve();
if (callback)
callback(err);
});
return deferred;
}
dir(lng) {
if (!lng)
lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
if (!lng)
return "rtl";
const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get());
return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
}
static createInstance() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
let callback = arguments.length > 1 ? arguments[1] : void 0;
return new _I18n(options, callback);
}
cloneInstance() {
let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop;
const forkResourceStore = options.forkResourceStore;
if (forkResourceStore)
delete options.forkResourceStore;
const mergedOptions = {
...this.options,
...options,
...{
isClone: true
}
};
const clone = new _I18n(mergedOptions);
if (options.debug !== void 0 || options.prefix !== void 0) {
clone.logger = clone.logger.clone(options);
}
const membersToCopy = ["store", "services", "language"];
membersToCopy.forEach((m) => {
clone[m] = this[m];
});
clone.services = {
...this.services
};
clone.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
if (forkResourceStore) {
clone.store = new ResourceStore(this.store.data, mergedOptions);
clone.services.resourceStore = clone.store;
}
clone.translator = new Translator(clone.services, mergedOptions);
clone.translator.on("*", function(event) {
for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
args[_key4 - 1] = arguments[_key4];
}
clone.emit(event, ...args);
});
clone.init(mergedOptions, callback);
clone.translator.options = mergedOptions;
clone.translator.backendConnector.services.utils = {
hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
};
return clone;
}
toJSON() {
return {
options: this.options,
store: this.store,
language: this.language,
languages: this.languages,
resolvedLanguage: this.resolvedLanguage
};
}
};
var instance = I18n.createInstance();
instance.createInstance = I18n.createInstance;
var createInstance = instance.createInstance;
var dir = instance.dir;
var init = instance.init;
var loadResources = instance.loadResources;
var reloadResources = instance.reloadResources;
var use = instance.use;
var changeLanguage = instance.changeLanguage;
var getFixedT = instance.getFixedT;
var t = instance.t;
var exists = instance.exists;
var setDefaultNamespace = instance.setDefaultNamespace;
var hasLoadedNamespace = instance.hasLoadedNamespace;
var loadNamespaces = instance.loadNamespaces;
var loadLanguages = instance.loadLanguages;
// src/i18n/zh/index.ts
var zh = {
validator: "\u9A8C\u8BC1\u65B9\u5F0F",
strategy: "\u7B56\u7565",
cancel: "\u53D6\u6D88",
apply: "\u5E94\u7528",
feature: {
["alias" /* Alias */]: {
name: "\u522B\u540DAlias",
desc: "\u4FEE\u6539\u5143\u6570\u636E\uFF08frontmatter\uFF09\u7F13\u5B58\u4E2D\u7684\u522B\u540D\uFF0C\u4E0D\u5F71\u54CD\u5B9E\u9645\u522B\u540D",
validator: {
auto: {
name: "\u81EA\u52A8Frontmatter",
desc: "\u5982\u679C frontmatter \u4E0D\u5B58\u5728\uFF0C\u5219\u4F1A\u5728\u7F13\u5B58\u4E2D\u521B\u5EFA\u3002\u53EF\u80FD\u4F1A\u53D1\u751F\u526F\u4F5C\u7528\u3002"
},
required: {
name: "\u6709Frontmatter\u624D\u751F\u6548",
desc: "\u53EA\u5904\u7406\u6709 frontmatter \u7684\u6587\u4EF6\u3002"
}
},
strategy: {
ensure: {
name: "\u589E\u5F3A",
desc: "\u4EC5\u5F53\u6807\u9898\u4E0D\u5728\u522B\u540D\u4E2D\u65F6\uFF0C\u624D\u5C06\u6807\u9898\u8BBE\u7F6E\u4E3A\u522B\u540D"
},
adjust: {
name: "\u8C03\u6574",
desc: "\u5C06\u6807\u9898\u6DFB\u52A0\u5230\u522B\u540D\u4E2D\uFF0C\u4F46\u4E0D\u5F71\u54CD\u73B0\u6709\u522B\u540D"
},
replace: {
name: "\u66FF\u6362",
desc: "\u7528\u6807\u9898\u66FF\u6362\u5F53\u524D\u522B\u540D"
}
}
},
["explorer" /* Explorer */]: {
name: "\u6587\u4EF6\u8D44\u6E90\u7BA1\u7406\u5668",
desc: "\u66FF\u6362\u6587\u4EF6\u8D44\u6E90\u7BA1\u7406\u5668\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["explorer:sort" /* ExplorerSort */]: {
name: "\u6807\u9898\u6392\u5E8F",
desc: "\u901A\u8FC7\u8D44\u6E90\u7BA1\u7406\u5668\u529F\u80FD\uFF0C\u6309\u6807\u9898\u5BF9\u8D44\u6E90\u7BA1\u7406\u5668\u4E2D\u7684\u6587\u4EF6\u8FDB\u884C\u6392\u5E8F"
},
["graph" /* Graph */]: {
name: "\u56FE\u8C31",
desc: "\u66FF\u6362\u56FE\u8C31/\u672C\u5730\u56FE\u8C31\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["header" /* Header */]: {
name: "\u9875\u9876\u6807\u9898",
desc: "\u66FF\u6362Tab\u6807\u7B7E\u9875\u9876\u90E8\u7684\u6807\u9898\u5E76\u66F4\u65B0\u5B83\u4EEC"
},
["starred" /* Starred */]: {
name: "\u4E66\u7B7E",
desc: "\u66FF\u6362\u5185\u7F6E\u4E66\u7B7E\u63D2\u4EF6\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["search" /* Search */]: {
name: "\u641C\u7D22",
desc: "\u66FF\u6362\u641C\u7D22\u9875\u9762\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["suggest" /* Suggest */]: {
name: "\u5EFA\u8BAE",
desc: "\u66FF\u6362\u5EFA\u8BAE\u7A97\u53E3\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["tab" /* Tab */]: {
name: "\u6807\u7B7E\u9875",
desc: "\u66FF\u6362Tab\u6807\u7B7E\u9875\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["inlineTitle" /* InlineTitle */]: {
name: "\u9875\u5185\u6807\u9898",
desc: "\u66FF\u6362\u9875\u9762\u5185\u663E\u793A\u7684\u6807\u9898"
},
["canvas" /* Canvas */]: {
name: "\u767D\u677F",
desc: "\u66FF\u6362\u767D\u677F\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["backlink" /* Backlink */]: {
name: "\u53CD\u5411\u94FE\u63A5",
desc: "\u66FF\u6362\u53CD\u5411\u94FE\u63A5(\u94FE\u63A5\u63D0\u53CA)\u4E2D\u663E\u793A\u7684\u6807\u9898"
},
["noteLink" /* NoteLink */]: {
name: "\u7B14\u8BB0\u94FE\u63A5",
desc: "\u66FF\u6362\u7B14\u8BB0\u4E2D\u7684\u5185\u90E8\u94FE\u63A5",
strategy: {
all: "\u66FF\u6362\u5168\u90E8\u94FE\u63A5",
onlyEmpty: "\u53EA\u66FF\u6362\u6CA1\u6709\u522B\u540D\u7684\u94FE\u63A5"
},
approval: {
showModal: "\u663E\u793A\u786E\u8BA4\u7A97\u53E3",
auto: "\u4F7F\u7528\u81EA\u52A8\u786E\u8BA4"
}
}
},
manage: "\u7BA1\u7406",
template: {
features: {
name: "\u7279\u6027\u6A21\u677F",
desc: "\u6839\u636E\u5404\u7279\u6027\u529F\u80FD\u72EC\u7ACB\u7BA1\u7406\u6A21\u677F"
},
main: "\u4E3B\u6A21\u677F",
fallback: "\u5907\u7528",
placeholder: "\u8F93\u5165\u6A21\u677F",
commmon: {
main: {
name: "\u901A\u7528\u4E3B\u6A21\u677F",
desc: `\u8BBE\u7F6E yaml \u8DEF\u5F84\uFF0C\u8BE5\u503C\u5C06\u7528\u4E8E\u6587\u4EF6\u6807\u9898\u3002\u503C\u5FC5\u987B\u662F\u5B57\u7B26\u4E32\u6216\u6570\u503C\u3002\u8FD8\u53EF\u4EE5\u4F7F\u7528\u7C7B\u4F3C\u6A21\u677F\u8DEF\u5F84 "{{ }}"\u3002
\u8FD8\u53EF\u4EE5\u4F7F\u7528 #\u6807\u9898 \u6765\u4F7F\u7528\u4E00\u7EA7\u6807\u9898\uFF0C\u6216 _ basename \u548C\u5176\u4ED6\u4FDD\u7559\u5B57\u3002
\u67E5\u9605 Readme \u4E86\u89E3\u66F4\u591A`
},
fallback: {
name: "\u901A\u7528\u5907\u7528\u6A21\u677F",
desc: "\u4F5C\u4E3A\u5907\u7528\u9009\u9879\u7684\u6A21\u677F\uFF0C\u5F53\u901A\u7528\u4E3B\u6A21\u677F\u65E0\u6CD5\u89E3\u6790\u51FA\u6765\u65F6\u4F7F\u7528"
}
},
used: "\u901A\u7528\u6A21\u677F\u5C06\u4F1A\u4F7F\u7528. \u503C\u4E3A {{value}}",
specific: "\u8FD9\u4E2A\u7279\u6027\u529F\u80FD\u5C06\u4F7F\u7528\u5F53\u524D\u6A21\u677F"
},
settings: "\u63D2\u4EF6\u8BBE\u7F6E",
rule: {
name: "\u89C4\u5219",
path: {
name: "\u6587\u4EF6\u8DEF\u5F84\u89C4\u5219",
black: {
name: "\u9ED1\u540D\u5355\u6A21\u5F0F",
desc: "\u63D2\u4EF6\u5C06\u5FFD\u7565\u8DEF\u5F84\u4E2D\u7684\u6587\u4EF6\uFF0C\u6BCF\u4E2A\u8DEF\u5F84\u5FC5\u987B\u4F7F\u7528\u5728\u65B0\u884C\u4E2D\u5199\u5165."
},
white: {
name: "\u767D\u540D\u5355\u6A21\u5F0F",
desc: "\u63D2\u4EF6\u5C06\u5904\u7406\u8DEF\u5F84\u4E2D\u7684\u6587\u4EF6\uFF0C\u6BCF\u4E2A\u8DEF\u5F84\u5FC5\u987B\u4F7F\u7528\u5728\u65B0\u884C\u4E2D\u5199\u5165."
}
},
delimiter: {
name: "\u5217\u8868\u503C",
desc: "\u8BBE\u7F6E\u5904\u7406\u5217\u8868\u503C\u7684\u89C4\u5219",
first: "\u4F7F\u7528\u7B2C\u4E00\u4E2A\u503C",
join: "\u7528\u5206\u9694\u7B26\u62FC\u63A5\u5168\u90E8",
placeholder: {
first: "\u4F1A\u91C7\u7528\u7B2C\u4E00\u4E2A\u503C",
join: "\u8F93\u5165\u5206\u9694\u7B26"
}
}
},
features: "\u7279\u6027\u529F\u80FD",
util: "\u5DE5\u5177",
coffee: "\u5982\u679C\u60A8\u559C\u6B22\u6B64\u63D2\u4EF6\u5E76\u5E0C\u671B\u5E2E\u52A9/\u652F\u6301\u4F5C\u8005\u6301\u7EED\u5F00\u53D1\uFF0C\u8BF7\u70B9\u51FB\u4EE5\u4E0B\u6309\u94AE:",
debug_info: {
title: "\u8C03\u8BD5\u4FE1\u606F",
desc: "\u5728\u7EC8\u7AEF\u4E2D\u663E\u793A\u8C03\u8BD5\u4FE1\u606F\u548C\u6355\u6349\u5230\u7684\u9519\u8BEF\u4FE1\u606F"
},
boot_delay: {
title: "\u5EF6\u8FDF\u542F\u52A8\u52A0\u8F7D",
desc: "\u63D2\u4EF6\u5C06\u5728\u6307\u5B9A\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09\u540E\u52A0\u8F7D"
},
disabled: "\u7981\u7528",
processor: {
name: "\u5904\u7406\u5668",
desc: "\u4FEE\u6539\u89E3\u6790\u7684\u6807\u9898",
replace: {
name: "\u66FF\u6362",
desc: "\u5C06\u6267\u884C",
pattern: {
name: "\u6B63\u5219Pattern",
desc: "\u5C06\u9996\u5148\u7528\u4F5C RegExp \u7684\u7B2C\u4E00\u4E2A\u53C2\u6570\uFF0C\u7136\u540E\u7528\u4F5C replace()\u7684\u7B2C\u4E00\u4E2A\u53C2\u6570"
},
flags: {
name: "\u4FEE\u9970\u7B26Flags",
desc: "\u5C06\u7528\u4F5C\u65B0RegExp \u7684\u7B2C\u4E8C\u4E2A\u53C2\u6570"
},
replacement: {
name: "\u66FF\u6362\u503CReplacement",
desc: "\u5C06\u7528\u4F5C replace() \u7684\u7B2C\u4E8C\u4E2A\u53C2\u6570"
}
},
function: {
name: "\u51FD\u6570",
desc: "\u5C06\u600E\u6837\u8D77\u4F5C\u7528:",
valueDesc: "\u4F60\u5728\u6587\u672C\u533A\u8F93\u5165\u7684\u503C"
}
},
command: {
features: {
reload: "\u91CD\u65B0\u52A0\u8F7D\u7279\u6027\u529F\u80FD",
disable: "\u7981\u7528\u7279\u6027\u529F\u80FD"
}
}
};
var zh_default = zh;
// src/i18n/zh-tw/index.ts
var zh_tw = {
validator: "\u9A57\u8B49\u65B9\u5F0F",
strategy: "\u7B56\u7565",
cancel: "\u53D6\u6D88",
apply: "\u61C9\u7528",
feature: {
["alias" /* Alias */]: {
name: "\u5225\u540DAlias",
desc: "\u4FEE\u6539\u5143\u6578\u64DA\uFF08frontmatter\uFF09\u7DE9\u5B58\u4E2D\u7684\u5225\u540D\uFF0C\u4E0D\u5F71\u97FF\u5BE6\u969B\u5225\u540D",
validator: {
auto: {
name: "\u81EA\u52D5Frontmatter",
desc: "\u5982\u679C frontmatter \u4E0D\u5B58\u5728\uFF0C\u5247\u6703\u5728\u7DE9\u5B58\u4E2D\u5275\u5EFA\u3002\u53EF\u80FD\u6703\u767C\u751F\u526F\u4F5C\u7528\u3002"
},
required: {
name: "\u6709Frontmatter\u624D\u751F\u6548",
desc: "\u53EA\u8655\u7406\u6709 frontmatter \u7684\u6A94\u3002"
}
},
strategy: {
ensure: {
name: "\u589E\u5F37",
desc: "\u50C5\u7576\u6A19\u984C\u4E0D\u5728\u5225\u540D\u4E2D\u6642\uFF0C\u624D\u5C07\u6A19\u984C\u8A2D\u7F6E\u70BA\u5225\u540D"
},
adjust: {
name: "\u8ABF\u6574",
desc: "\u5C07\u6A19\u984C\u6DFB\u52A0\u5230\u5225\u540D\u4E2D\uFF0C\u4F46\u4E0D\u5F71\u97FF\u73FE\u6709\u5225\u540D"
},
replace: {
name: "\u66FF\u63DB",
desc: "\u7528\u6A19\u984C\u66FF\u63DB\u7576\u524D\u5225\u540D"
}
}
},
["explorer" /* Explorer */]: {
name: "\u6A94\u8CC7\u6E90\u7BA1\u7406\u5668",
desc: "\u66FF\u63DB\u6A94\u8CC7\u6E90\u7BA1\u7406\u5668\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["explorer:sort" /* ExplorerSort */]: {
name: "\u6A19\u984C\u6392\u5E8F",
desc: "\u901A\u904E\u8CC7\u6E90\u7BA1\u7406\u5668\u529F\u80FD\uFF0C\u6309\u6A19\u984C\u5C0D\u8CC7\u6E90\u7BA1\u7406\u5668\u4E2D\u7684\u6A94\u9032\u884C\u6392\u5E8F"
},
["graph" /* Graph */]: {
name: "\u5716\u8B5C",
desc: "\u66FF\u63DB\u5716\u8B5C/\u672C\u5730\u5716\u8B5C\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["header" /* Header */]: {
name: "\u9801\u9802\u6A19\u984C",
desc: "\u66FF\u63DBTab\u6A19\u7C64\u9801\u9802\u90E8\u7684\u6A19\u984C\u4E26\u66F4\u65B0\u5B83\u5011"
},
["starred" /* Starred */]: {
name: "\u66F8\u7C3D",
desc: "\u66FF\u63DB\u5167\u7F6E\u66F8\u7C3D\u63D2\u4EF6\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["search" /* Search */]: {
name: "\u641C\u7D22",
desc: "\u66FF\u63DB\u641C\u7D22\u9801\u9762\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["suggest" /* Suggest */]: {
name: "\u5EFA\u8B70",
desc: "\u66FF\u63DB\u5EFA\u8B70\u7A97\u53E3\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["tab" /* Tab */]: {
name: "\u6A19\u7C64\u9801",
desc: "\u66FF\u63DBTab\u6A19\u7C64\u9801\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["inlineTitle" /* InlineTitle */]: {
name: "\u9801\u5167\u6A19\u984C",
desc: "\u66FF\u63DB\u9801\u9762\u5167\u986F\u793A\u7684\u6A19\u984C"
},
["canvas" /* Canvas */]: {
name: "\u767D\u677F",
desc: "\u66FF\u63DB\u767D\u677F\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["backlink" /* Backlink */]: {
name: "\u53CD\u5411\u93C8\u63A5",
desc: "\u66FF\u63DB\u53CD\u5411\u93C8\u63A5(\u93C8\u63A5\u63D0\u53CA)\u4E2D\u986F\u793A\u7684\u6A19\u984C"
},
["noteLink" /* NoteLink */]: {
name: "\u7B46\u8A18\u93C8\u63A5",
desc: "\u66FF\u63DB\u7B46\u8A18\u4E2D\u7684\u5167\u90E8\u93C8\u63A5",
strategy: {
all: "\u66FF\u63DB\u5168\u90E8\u93C8\u63A5",
onlyEmpty: "\u53EA\u66FF\u63DB\u6C92\u6709\u5225\u540D\u7684\u93C8\u63A5"
},
approval: {
showModal: "\u986F\u793A\u78BA\u8A8D\u7A97\u53E3",
auto: "\u4F7F\u7528\u81EA\u52D5\u78BA\u8A8D"
}
}
},
manage: "\u7BA1\u7406",
template: {
features: {
name: "\u7279\u6027\u7BC4\u672C",
desc: "\u6839\u64DA\u5404\u7279\u6027\u529F\u80FD\u7368\u7ACB\u7BA1\u7406\u7BC4\u672C"
},
main: "\u4E3B\u7BC4\u672C",
fallback: "\u5099\u7528",
placeholder: "\u8F38\u5165\u7BC4\u672C",
commmon: {
main: {
name: "\u901A\u7528\u4E3B\u7BC4\u672C",
desc: `\u8A2D\u7F6E yaml \u8DEF\u5F91\uFF0C\u8A72\u503C\u5C07\u7528\u65BC\u6A94\u6A19\u984C\u3002\u503C\u5FC5\u9808\u662F\u5B57\u4E32\u6216\u6578\u503C\u3002\u9084\u53EF\u4EE5\u4F7F\u7528\u985E\u4F3C\u7BC4\u672C\u8DEF\u5F91 "{{ }}"\u3002
\u9084\u53EF\u4EE5\u4F7F\u7528 #\u6A19\u984C \u4F86\u4F7F\u7528\u4E00\u7D1A\u6A19\u984C\uFF0C\u6216 _ basename \u548C\u5176\u4ED6\u4FDD\u7559\u5B57\u3002
\u67E5\u95B1 Readme \u77AD\u89E3\u66F4\u591A`
},
fallback: {
name: "\u901A\u7528\u5099\u7528\u7BC4\u672C",
desc: "\u4F5C\u70BA\u5099\u7528\u9078\u9805\u7684\u7BC4\u672C\uFF0C\u7576\u901A\u7528\u4E3B\u7BC4\u672C\u7121\u6CD5\u89E3\u6790\u51FA\u4F86\u6642\u4F7F\u7528"
}
},
used: "\u901A\u7528\u7BC4\u672C\u5C07\u6703\u4F7F\u7528. \u503C\u70BA {{value}}",
specific: "\u9019\u500B\u7279\u6027\u529F\u80FD\u5C07\u4F7F\u7528\u7576\u524D\u7BC4\u672C"
},
settings: "\u63D2\u4EF6\u8A2D\u7F6E",
rule: {
name: "\u898F\u5247",
path: {
name: "\u6A94\u8DEF\u5F91\u898F\u5247",
black: {
name: "\u9ED1\u540D\u55AE\u6A21\u5F0F",
desc: "\u63D2\u4EF6\u5C07\u5FFD\u7565\u8DEF\u5F91\u4E2D\u7684\u6A94\uFF0C\u6BCF\u500B\u8DEF\u5F91\u5FC5\u9808\u4F7F\u7528\u5728\u65B0\u884C\u4E2D\u5BEB\u5165."
},
white: {
name: "\u767D\u540D\u55AE\u6A21\u5F0F",
desc: "\u63D2\u4EF6\u5C07\u8655\u7406\u8DEF\u5F91\u4E2D\u7684\u6A94\uFF0C\u6BCF\u500B\u8DEF\u5F91\u5FC5\u9808\u4F7F\u7528\u5728\u65B0\u884C\u4E2D\u5BEB\u5165."
}
},
delimiter: {
name: "\u5217\u8868\u503C",
desc: "\u8A2D\u7F6E\u8655\u7406\u5217\u8868\u503C\u7684\u898F\u5247",
first: "\u4F7F\u7528\u7B2C\u4E00\u500B\u503C",
join: "\u7528\u5206\u9694\u7B26\u865F\u62FC\u63A5\u5168\u90E8",
placeholder: {
first: "\u6703\u63A1\u7528\u7B2C\u4E00\u500B\u503C",
join: "\u8F38\u5165\u5206\u9694\u7B26\u865F"
}
}
},
features: "\u7279\u6027\u529F\u80FD",
util: "\u5DE5\u5177",
coffee: "\u5982\u679C\u60A8\u559C\u6B61\u6B64\u63D2\u4EF6\u4E26\u5E0C\u671B\u5E6B\u52A9/\u652F\u6301\u4F5C\u8005\u6301\u7E8C\u958B\u767C\uFF0C\u8ACB\u9EDE\u64CA\u4EE5\u4E0B\u6309\u9215:",
debug_info: {
title: "\u8ABF\u8A66\u8CC7\u8A0A",
desc: "\u5728\u7D42\u7AEF\u4E2D\u986F\u793A\u8ABF\u8A66\u8CC7\u8A0A\u548C\u6355\u6349\u5230\u7684\u932F\u8AA4\u8CC7\u8A0A"
},
boot_delay: {
title: "\u5EF6\u9072\u555F\u52D5\u52A0\u8F09",
desc: "\u63D2\u4EF6\u5C07\u5728\u6307\u5B9A\u6642\u9593\uFF08\u6BEB\u79D2\uFF09\u5F8C\u52A0\u8F09"
},
disabled: "\u7981\u7528",
processor: {
name: "\u8655\u7406\u5668",
desc: "\u4FEE\u6539\u89E3\u6790\u7684\u6A19\u984C",
replace: {
name: "\u66FF\u63DB",
desc: "\u5C07\u57F7\u884C",
pattern: {
name: "\u6B63\u5247Pattern",
desc: "\u5C07\u9996\u5148\u7528\u4F5C RegExp \u7684\u7B2C\u4E00\u500B\u53C3\u6578\uFF0C\u7136\u5F8C\u7528\u4F5C replace()\u7684\u7B2C\u4E00\u500B\u53C3\u6578"
},
flags: {
name: "\u4FEE\u98FE\u7B26Flags",
desc: "\u5C07\u7528\u4F5C\u65B0RegExp \u7684\u7B2C\u4E8C\u500B\u53C3\u6578"
},
replacement: {
name: "\u66FF\u63DB\u503CReplacement",
desc: "\u5C07\u7528\u4F5C replace() \u7684\u7B2C\u4E8C\u500B\u53C3\u6578"
}
},
function: {
name: "\u51FD\u6578",
desc: "\u5C07\u600E\u6A23\u8D77\u4F5C\u7528:",
valueDesc: "\u4F60\u5728\u6587\u672C\u5340\u8F38\u5165\u7684\u503C"
}
},
command: {
features: {
reload: "\u91CD\u65B0\u52A0\u8F09\u7279\u6027\u529F\u80FD",
disable: "\u7981\u7528\u7279\u6027\u529F\u80FD"
}
}
};
var zh_tw_default = zh_tw;
// src/i18n/ko/index.ts
var ko = {};
var ko_default = ko;
// src/i18n/it/index.ts
var it = {};
var it_default = it;
// src/i18n/id/index.ts
var id2 = {};
var id_default = id2;
// src/i18n/ro/index.ts
var ro = {};
var ro_default = ro;
// src/i18n/pl/index.ts
var pl = {};
var pl_default = pl;
// src/i18n/cs/index.ts
var cs = {};
var cs_default = cs;
// src/i18n/de/index.ts
var de = {};
var de_default = de;
// src/i18n/es/index.ts
var es = {};
var es_default = es;
// src/i18n/fr/index.ts
var fr = {};
var fr_default = fr;
// src/i18n/no/index.ts
var no = {};
var no_default = no;
// src/i18n/pr-br/index.ts
var pr_br = {};
var pr_br_default = pr_br;
// src/i18n/pt/index.ts
var pt = {};
var pt_default = pt;
// src/i18n/ja/index.ts
var ja = {};
var ja_default = ja;
// src/i18n/da/index.ts
var da = {};
var da_default = da;
// src/i18n/uk/index.ts
var uk = {};
var uk_default = uk;
// src/i18n/sq/index.ts
var sq = {};
var sq_default = sq;
// src/i18n/th/index.ts
var th = {};
var th_default = th;
// src/i18n/fa/index.ts
var fa = {};
var fa_default = fa;
// src/i18n/tr/index.ts
var tr = {};
var tr_default = tr;
// src/i18n/nl/index.ts
var nl = {};
var nl_default = nl;
// src/i18n/am/index.ts
var am = {};
var am_default = am;
// src/i18n/ms/index.ts
var ms = {};
var ms_default = ms;
// src/i18n/Locale.ts
var defaultLocale = "en";
var locale = import_obsidian.moment.locale();
instance.init({
lng: locale,
fallbackLng: defaultLocale,
resources: {
en: { translation: en_default },
ru: { translation: ru_default },
zh: { translation: zh_default },
"zh-TW": { translation: zh_tw_default },
ko: { translation: ko_default },
it: { translation: it_default },
id: { translation: id_default },
ro: { translation: ro_default },
"pt-BR": { translation: pr_br_default },
cs: { translation: cs_default },
de: { translation: de_default },
es: { translation: es_default },
fr: { translation: fr_default },
no: { translation: no_default },
pl: { translation: pl_default },
pt: { translation: pt_default },
ja: { translation: ja_default },
da: { translation: da_default },
uk: { translation: uk_default },
sq: { translation: sq_default },
th: { translation: th_default },
fa: { translation: fa_default },
tr: { translation: tr_default },
nl: { translation: nl_default },
am: { translation: am_default },
ms: { translation: ms_default }
},
nsSeparator: "|"
});
var resolved = instance.resolvedLanguage;
if (resolved !== locale) {
if (instance.languages.includes(locale)) {
console.warn(`Locale ${locale} empty. Resolved ${resolved}`);
} else {
console.warn(`Locale ${locale} does not exist. Resolved ${resolved}`);
}
}
var t2 = (path, params) => {
return instance.t(path, params);
};
// src/Settings/SettingsTab.ts
var SettingsTab = class {
constructor(app, plugin, storage, dispatcher, factory) {
this.storage = storage;
this.dispatcher = dispatcher;
this.factory = factory;
const self2 = this;
this.tab = new class extends import_obsidian2.PluginSettingTab {
constructor() {
super(...arguments);
this.display = () => self2.display();
this.hide = () => self2.hide();
}
}(app, plugin);
this.updatePrevious();
dispatcher.dispatch("settings.loaded", new Event({ settings: this.storage.collect() }));
}
get containerEl() {
return this.getTab().containerEl;
}
getTab() {
return this.tab;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: t2("settings") });
const builders = this.factory("main");
for (const k of this.orderedKeys) {
for (const builder of builders) {
if (builder.support(k)) {
builder.build({
name: k,
item: this.storage.get(k),
container: this.containerEl
});
}
}
}
this.buildDonation();
}
get orderedKeys() {
return ["templates", "processor", "rules", "features", "debug", "boot"];
}
buildDonation() {
const div = this.containerEl.createEl("div");
div.style.width = "75%";
div.style.textAlign = "center";
div.style.margin = "0 auto";
const text = document.createElement("p");
text.textContent = t2("coffee");
div.appendChild(text);
const anchor = document.createElement("a");
anchor.setAttribute("href", "https://www.buymeacoffee.com/snezhig");
anchor.appendChild(new DOMParser().parseFromString(coffee, "text/xml").documentElement);
div.appendChild(anchor);
}
updatePrevious() {
this.previous = JSON.parse(JSON.stringify(this.storage.collect()));
}
hide() {
this.dispatch();
}
dispatch() {
this.dispatcher.dispatch("settings:tab:close", null);
const changed = ObjectHelper.compare(this.previous, this.storage.collect());
if (Object.keys(changed).length === 0) {
return;
}
this.dispatcher.dispatch(
"settings:changed",
new Event({
old: this.previous,
actual: this.storage.collect(),
changed: ObjectHelper.compare(this.previous, this.storage.collect())
})
);
this.updatePrevious();
}
};
SettingsTab = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["obsidian:app"])),
__decorateParam(1, inject(inversify_types_default["obsidian:plugin"])),
__decorateParam(2, inject(inversify_types_default["settings:storage"])),
__decorateParam(3, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(4, inject(inversify_types_default["factory:settings:builder"]))
], SettingsTab);
var coffee = '';
// src/Storage/Storage.ts
var Storage = class {
constructor(data) {
this.set(data);
}
get(k) {
return this.item.get(k);
}
set(value) {
this.item = new StorageObjectItem(value);
}
collect() {
return this.item.value();
}
};
var create = (value) => {
if (typeof value === "object" && !Array.isArray(value) && value !== null) {
return new StorageObjectItem(value);
} else {
return new StoragePrimitiveItem(value);
}
};
var StorageObjectItem = class {
constructor(data) {
this.items = null;
this.set(data);
}
add(key, value) {
this.items[key] = create(value);
return this.get(key);
}
get(key) {
return this.items[key];
}
set(value) {
this.items = {};
for (const [key, v] of ObjectHelper.entries(value)) {
this.items[key] = create(v);
}
}
value() {
const data = {};
for (const [k, v] of ObjectHelper.entries(this.items)) {
data[k] = v.value();
}
return data;
}
};
var StoragePrimitiveItem = class {
constructor(data) {
this.data = data;
}
value() {
return this.data;
}
set(value) {
this.data = value;
}
};
// src/Creator/Template/Factory.ts
var Factory = class {
constructor(pattern, factory) {
this.pattern = pattern;
this.factory = factory;
}
create(template) {
const type = new RegExp(this.pattern).test(template) ? "composite" : "simple";
const obj = this.factory(type);
obj.setTemplate(template);
return obj;
}
};
Factory = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["template:pattern"])),
__decorateParam(1, inject(inversify_types_default["factory:template:resolver"]))
], Factory);
// src/Creator/Template/Simple.ts
var Simple = class {
constructor(factory) {
this.factory = factory;
this.placeholder = null;
}
getPlaceholders() {
if (this.placeholder === null) {
this.placeholder = this.factory.create(this.template);
}
return [this.placeholder];
}
getTemplate() {
return this.template;
}
setTemplate(template) {
this.template = template;
}
};
Simple = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:placeholder"]))
], Simple);
// src/Creator/Template/Placeholders/AbstractPlaceholder.ts
var AbstractPlaceholder = class {
getPlaceholder() {
return this.placeholder;
}
};
AbstractPlaceholder = __decorateClass([
injectable()
], AbstractPlaceholder);
// src/Creator/Template/Placeholders/MetaPlaceholder.ts
var MetaPlaceholder = class extends AbstractPlaceholder {
constructor(extractor, factory) {
super();
this.extractor = extractor;
this.factory = factory;
}
makeValue(path) {
return this.extractor.extract(this.placeholder, this.factory(path, "frontmatter"));
}
setPlaceholder(placeholder) {
this.placeholder = placeholder;
}
};
MetaPlaceholder = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["component:extractor"])),
__decorateParam(1, inject(inversify_types_default["factory:obsidian:meta"]))
], MetaPlaceholder);
// src/Components/Extractor/Exceptions/PathNotFoundException.ts
var PathNotFoundException = class extends Error {
};
// src/Components/Extractor/Exceptions/TypeNotSupportedException.ts
var TypeNotSupportedException = class extends Error {
};
// src/Creator/Creator.ts
var Creator = class {
constructor(factory, logger) {
this.factory = factory;
this.logger = logger;
this.cache = /* @__PURE__ */ new Map();
}
pull(template) {
const key = `template:${template}`;
if (this.cache.has(key) === false) {
this.logger.log(`Create template fo ${template}`);
this.cache.set(key, this.factory.create(template));
}
return this.cache.get(key);
}
create(path, template) {
var _a, _b;
for (const placeholder of this.pull(template).getPlaceholders()) {
let value = "";
try {
value = (_a = placeholder.makeValue(path)) != null ? _a : "";
} catch (e) {
if (e instanceof PathNotFoundException || e instanceof TypeNotSupportedException) {
this.logger.log(`Error by path: ${path}. ${e.message}`);
} else {
throw e;
}
}
template = template.replace(placeholder.getPlaceholder(), value);
}
if ((_b = template == null ? void 0 : template.trim()) == null ? void 0 : _b.length) {
return template.trim();
}
return null;
}
};
Creator = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:creator:template"])),
__decorateParam(1, inject(inversify_types_default.logger)),
__decorateParam(1, named("creator"))
], Creator);
// src/Creator/Template/Placeholders/Factory.ts
var Factory2 = class {
constructor(factory) {
this.factory = factory;
}
create(placeholder) {
let type = "meta";
if (placeholder.startsWith("{{") && placeholder.endsWith("}}")) {
type = "brackets";
} else if (placeholder.startsWith("_")) {
type = "file";
} else if (placeholder === "#heading") {
type = "heading";
}
return this.factory(type, placeholder);
}
};
Factory2 = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:placeholder:resolver"]))
], Factory2);
// src/Creator/Template/Composite.ts
var Composite = class {
constructor(pattern, factory) {
this.pattern = pattern;
this.factory = factory;
this.placeholders = [];
}
getPlaceholders() {
if (this.placeholders.length === 0) {
const parts = this.template.match(new RegExp(this.pattern, "g"));
for (const part of parts) {
const {
groups: { placeholder }
} = part.match(this.pattern);
this.placeholders.push(this.factory.create(placeholder));
}
}
return this.placeholders;
}
getTemplate() {
return this.template;
}
setTemplate(template) {
this.template = template;
}
};
Composite = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["template:pattern"])),
__decorateParam(1, inject(inversify_types_default["factory:placeholder"]))
], Composite);
// src/Creator/Template/Placeholders/BracketsPlaceholder.ts
var BracketsPlaceholder = class {
constructor(factory) {
this.factory = factory;
}
getPlaceholder() {
return this.placeholder;
}
makeValue(path) {
return this.child.makeValue(path);
}
setPlaceholder(placeholder) {
this.placeholder = placeholder;
const {
groups: { inside }
} = this.placeholder.match(new RegExp(`^{{(?.*?)}}`));
this.child = this.factory.create(inside);
}
};
BracketsPlaceholder = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:placeholder"]))
], BracketsPlaceholder);
// src/Creator/Template/Placeholders/FilePlaceholder.ts
var FilePlaceholder = class extends AbstractPlaceholder {
constructor(extractor, factory) {
super();
this.extractor = extractor;
this.factory = factory;
}
makeValue(path) {
return this.extractor.extract(this.path, this.factory(path));
}
setPlaceholder(placeholder) {
this.placeholder = placeholder;
this.path = placeholder.substring(1);
}
};
FilePlaceholder = __decorateClass([
__decorateParam(0, inject(inversify_types_default["component:extractor"])),
__decorateParam(1, inject(inversify_types_default["factory:obsidian:file"]))
], FilePlaceholder);
// src/Creator/Template/Placeholders/HeadingPlaceholder.ts
var HeadingPlaceholder = class {
constructor(factory) {
this.factory = factory;
}
getPlaceholder() {
return this.placeholder;
}
makeValue(path) {
var _a, _b, _c;
return (_c = (_b = (_a = this.factory(path, "headings")) == null ? void 0 : _a[0]) == null ? void 0 : _b.heading) != null ? _c : "";
}
setPlaceholder(placeholder) {
this.placeholder = placeholder;
}
};
HeadingPlaceholder = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:obsidian:meta"]))
], HeadingPlaceholder);
// config/services/creator.config.ts
var creator_config_default = new ContainerModule((bind) => {
bind(inversify_types_default["factory:creator:template"]).to(Factory);
bind(inversify_types_default["factory:template:resolver"]).toAutoNamedFactory(
inversify_types_default["creator:template"]
);
bind(inversify_types_default["creator:template"]).to(Simple).whenTargetNamed("simple");
bind(inversify_types_default["creator:template"]).to(Composite).whenTargetNamed("composite");
bind(inversify_types_default.placeholder).to(MetaPlaceholder).whenTargetNamed("meta");
bind(inversify_types_default.placeholder).to(FilePlaceholder).whenTargetNamed("file");
bind(inversify_types_default.placeholder).to(BracketsPlaceholder).whenTargetNamed("brackets");
bind(inversify_types_default.placeholder).to(HeadingPlaceholder).whenTargetNamed("heading");
bind(inversify_types_default["creator:creator"]).to(Creator);
bind(inversify_types_default["factory:placeholder:resolver"]).toFactory((context) => (type, placeholder) => {
const item = context.container.getNamed(inversify_types_default.placeholder, type);
item.setPlaceholder(placeholder);
return item;
});
bind(inversify_types_default["getter:delimiter"]).toDynamicValue((c) => () => c.container.get(inversify_types_default.delimiter));
bind(inversify_types_default["factory:placeholder"]).to(Factory2).inSingletonScope();
});
// src/Feature/AbstractFeature.ts
var AbstractFeature = class {
static getId() {
throw new Error("Static function 'getId()' is not implemented");
}
};
AbstractFeature = __decorateClass([
injectable()
], AbstractFeature);
// src/Feature/AbstractManager.ts
var AbstractManager = class extends AbstractFeature {
disable() {
this.isEnabled() && this.doDisable();
}
enable() {
!this.isEnabled() && this.doEnable();
}
async update(path) {
if (!this.isEnabled()) {
return false;
}
return this.doUpdate(path);
}
async refresh() {
if (this.isEnabled()) {
return this.doRefresh();
}
}
setResolver(resolver) {
this.resolver = resolver;
}
};
AbstractManager = __decorateClass([
injectable()
], AbstractManager);
// src/Feature/Explorer/ExplorerViewUndefined.ts
var ExplorerViewUndefined = class extends Error {
};
// src/Feature/Explorer/ExplorerManager.ts
var ExplorerManager = class extends AbstractManager {
constructor(facade) {
super();
this.facade = facade;
this.explorerView = null;
this.originTitles = /* @__PURE__ */ new Map();
this.enabled = false;
this.isTitleEmpty = (title) => title === null || title === "" || title === void 0;
}
getId() {
return "explorer" /* Explorer */;
}
isEnabled() {
return this.enabled;
}
doDisable() {
if (this.explorerView) {
this.restoreTitles();
this.explorerView = null;
}
this.enabled = false;
}
doEnable() {
this.explorerView = this.getExplorerView();
this.enabled = true;
}
getFileItemInnerTitleEl(fileItem) {
var _a;
return (_a = fileItem.titleInnerEl) != null ? _a : fileItem.innerEl;
}
getExplorerView() {
var _a;
const leaves = this.facade.getLeavesOfType("file-explorer" /* FE */);
if (leaves.length > 1) {
throw new Error("There are some explorers' leaves");
}
const view = (_a = leaves == null ? void 0 : leaves[0]) == null ? void 0 : _a.view;
if (view === void 0) {
throw new ExplorerViewUndefined("Explorer view is undefined");
}
return view;
}
async updateInternal(items) {
if (!items.filter((e) => e).length) {
return {};
}
const result = {};
const promises = items.map((e) => this.setTitle(e).then((r) => result[e.file.path] = r));
await Promise.all(promises);
return result;
}
async setTitle(item) {
const title = await (async () => this.resolver.resolve(item.file.path))().catch(() => null);
if (this.isTitleEmpty(title)) {
return this.restore(item);
} else if (this.getFileItemInnerTitleEl(item).innerText !== title) {
this.keepOrigin(item);
this.getFileItemInnerTitleEl(item).innerText = title;
return true;
}
return false;
}
keepOrigin(item) {
if (!this.originTitles.has(item.file.path)) {
this.originTitles.set(item.file.path, this.getFileItemInnerTitleEl(item).innerText);
}
}
restoreTitles() {
Object.values(this.explorerView.fileItems).map(this.restore.bind(this));
}
restore(item) {
if (this.originTitles.has(item.file.path)) {
this.getFileItemInnerTitleEl(item).innerText = this.originTitles.get(item.file.path);
this.originTitles.delete(item.file.path);
return true;
}
return false;
}
doRefresh() {
return this.updateInternal(Object.values(this.explorerView.fileItems));
}
async doUpdate(path) {
const item = this.explorerView.fileItems[path];
const result = await this.updateInternal(item ? [item] : []);
return result[path] === true;
}
static getId() {
return "explorer" /* Explorer */;
}
};
ExplorerManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["facade:obsidian"]))
], ExplorerManager);
// src/Feature/FeatureComposer.ts
var FeatureComposer = class {
constructor(factory, dispatcher, logger) {
this.factory = factory;
this.dispatcher = dispatcher;
this.logger = logger;
this.features = {};
}
get(id3) {
var _a;
return (_a = this.features[id3]) != null ? _a : null;
}
getIds() {
return Object.keys(this.features);
}
toggle(id3, state) {
const feature = this.features[id3];
if (!state && !feature || state && (feature == null ? void 0 : feature.isEnabled())) {
return;
}
if (!feature) {
this.features[id3] = this.factory(id3);
return this.toggle(id3, state);
}
feature[state ? "enable" : "disable"]();
this.logger.log(`Feature - ${feature.getId()}. State: ${state}`);
if (!state) {
delete this.features[id3];
} else {
this.dispatcher.dispatch("feature:enable", new Event({ feature }));
}
}
disableAll() {
for (const feature of Object.values(this.features)) {
this.logger.log(`Disable feature ${feature.getId()}`);
feature.disable();
}
this.features = {};
}
};
FeatureComposer = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:feature"])),
__decorateParam(1, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named("composer:feature"))
], FeatureComposer);
// src/Utils/FunctionReplacer.ts
var FunctionReplacer = class _FunctionReplacer {
constructor(target, method, args, implementation) {
this.target = target;
this.method = method;
this.args = args;
this.implementation = implementation;
this.vanilla = null;
this.valid();
}
getTarget() {
return this.target;
}
valid() {
if (typeof this.target[this.method] !== "function") {
throw new Error(`Method ${this.method} is not a function`);
}
}
enable() {
if (this.vanilla !== null) {
return false;
}
const self2 = this;
this.vanilla = this.target[this.method];
this.target[this.method] = function(...args) {
return self2.implementation.call(this, self2.args, args, self2.vanilla);
};
return true;
}
disable() {
if (this.vanilla !== null) {
this.target[this.method] = this.vanilla;
this.vanilla = null;
}
}
isEnabled() {
return this.vanilla !== null;
}
static create(target, method, args, implementation) {
return new _FunctionReplacer(target, method, args, implementation);
}
};
// src/Feature/Explorer/ExplorerSort.ts
var import_obsidian3 = require("obsidian");
var ExplorerSort = class extends AbstractFeature {
constructor(logger, facade, dispatcher, service) {
super();
this.logger = logger;
this.facade = facade;
this.dispatcher = dispatcher;
this.enabled = false;
this.refs = [];
this.resolver = service.createResolver("explorer" /* Explorer */);
const trigger = (0, import_obsidian3.debounce)(this.onManagerUpdate.bind(this), 1e3);
this.cb = (e) => {
if (e.id === "explorer" /* Explorer */ && (e.result === true || e.result === void 0)) {
trigger();
}
};
}
onManagerUpdate() {
this.logger.log("Try to request sort by event");
if (!this.isEnabled()) {
this.logger.log("Skipped because feature is not enabled");
return;
}
this.view.requestSort();
}
static getId() {
return "explorer:sort" /* ExplorerSort */;
}
initView() {
var _a, _b, _c;
this.view = (_c = (_b = (_a = this.facade.getLeavesOfType("file-explorer" /* FE */)) == null ? void 0 : _a[0]) == null ? void 0 : _b.view) != null ? _c : null;
}
tryToReplaceOriginalSort() {
if (!this.isEnabled()) {
return;
}
if (this.replacer) {
this.logger.log(`Replacer is exist already. State is ${this.replacer.isEnabled()}`);
if (!this.replacer.isEnabled()) {
this.logger.log("Enable replacer");
this.replacer.enable();
}
return;
}
const item = this.getFolderItem();
if (!item) {
this.logger.log("Folder item not found. Try again in 1000 ms");
setTimeout(() => this.tryToReplaceOriginalSort(), 1e3);
return;
}
this.logger.log("Init replacer");
this.replacer = new FunctionReplacer(
//@ts-ignore
item.__proto__,
"sort",
this,
function(args, defaultArgs, vanilla) {
args.sort(this, vanilla);
}
);
this.replacer.enable();
}
isSortSupported(sort) {
return ["alphabeticalReverse", "alphabetical"].includes(sort);
}
isAsc(order) {
return order === "alphabetical";
}
sort(item, vanilla) {
const sortOrder = this.view.sortOrder;
if (!this.isSortSupported(sortOrder)) {
this.logger.log(`Sort is ${sortOrder}. Skipped.`);
vanilla.call(item);
return;
}
if (!(item.file instanceof import_obsidian3.TFolder)) {
this.logger.log("File is not TFolder. Why? Skipped.");
vanilla.call(item);
return;
}
this.logger.log("Sort by feature");
const children = item.file.children.slice();
const result = [];
children.sort((a, b) => {
var _a, _b;
const i = a instanceof import_obsidian3.TFolder;
const r = b instanceof import_obsidian3.TFolder;
let k;
if (i && !r) {
k = -1;
} else if (!i && r) {
k = 1;
} else {
const at = i ? a.name : (_a = this.resolver.resolve(a.path)) != null ? _a : a.name;
const bt = r ? b.name : (_b = this.resolver.resolve(b.path)) != null ? _b : b.name;
k = at.localeCompare(bt);
k = this.isAsc(sortOrder) ? k : -k;
}
return k;
});
for (const child of children) {
const f = this.view.fileItems[child.path];
f && result.push(f);
}
item.vChildren.setChildren(result);
}
getFolderItem() {
for (const item of Object.values(this.view.fileItems)) {
if (item.file instanceof import_obsidian3.TFolder) {
return item;
}
}
}
async enable() {
if (this.isEnabled()) {
return;
}
if (!this.view && (this.initView(), !this.view)) {
throw new ExplorerViewUndefined();
}
this.refs.push(this.dispatcher.addListener({ name: "manager:refresh", cb: (e) => this.cb({ id: e.get().id }) }));
this.refs.push(
this.dispatcher.addListener({
name: "manager:update",
cb: (e) => this.cb(e.get())
})
);
this.enabled = true;
this.tryToReplaceOriginalSort();
this.logger.log("enabled");
}
async disable() {
var _a, _b;
this.enabled = false;
this.refs.forEach((e) => this.dispatcher.removeListener(e));
this.refs = [];
(_a = this.replacer) == null ? void 0 : _a.disable();
(_b = this.view) == null ? void 0 : _b.requestSort();
this.logger.log("disabled");
}
isEnabled() {
return this.enabled;
}
getId() {
return "explorer:sort" /* ExplorerSort */;
}
};
ExplorerSort = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default.logger)),
__decorateParam(0, named("explorer:feature:sort")),
__decorateParam(1, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(3, inject(inversify_types_default["feature:service"]))
], ExplorerSort);
// src/Feature/ManagerComposer.ts
var ManagerComposer = class {
constructor(features, logger, dispatcher) {
this.features = features;
this.logger = logger;
this.dispatcher = dispatcher;
this.ids = Managers;
}
async update(path, id3 = null) {
const ids = id3 ? [id3] : this.ids;
const result = {};
const promises = [];
for (const i of ids) {
const manager = this.features.get(i);
if (manager) {
this.logger.log(`Run update for [${path}] on [${manager.getId()}]`);
promises.push(
manager.update(path).then((r) => {
result[i] = r;
this.dispatcher.dispatch("manager:update", new Event({ id: i, result: r, path }));
})
);
}
}
await Promise.all(promises);
return result;
}
async refresh(id3 = null) {
this.logger.log("refresh");
const ids = id3 ? [id3] : this.ids;
const promises = [];
for (const i of ids) {
const manager = this.features.get(i);
if (manager) {
promises.push(
manager.refresh().then(() => this.dispatcher.dispatch("manager:refresh", new Event({ id: i })))
);
}
}
await Promise.all(promises);
}
};
ManagerComposer = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["feature:composer"])),
__decorateParam(1, inject(inversify_types_default.logger)),
__decorateParam(1, named("composer:manager")),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"]))
], ManagerComposer);
// src/Feature/Search/SearchFeature.ts
var SearchManager = class extends AbstractFeature {
constructor(facade, logger, service, featureService) {
super();
this.facade = facade;
this.logger = logger;
this.service = service;
this.enabled = false;
this.dom = null;
this.resolver = featureService.createResolver(this.getId());
}
getView() {
var _a, _b;
return (_b = (_a = this.facade.getViewsOfType("search" /* S */)) == null ? void 0 : _a[0]) != null ? _b : null;
}
getSearchDom() {
var _a, _b;
if (!this.dom) {
this.dom = (_b = (_a = this.getView()) == null ? void 0 : _a.dom) != null ? _b : null;
}
return this.dom;
}
disable() {
this.dom = null;
this.service.destroyByTag(this.getId());
this.enabled = false;
}
enable() {
const dom = this.getSearchDom();
if (!dom) {
throw new Error(`View of ${"search" /* S */} not found`);
}
this.service.wrapDom(dom, this.resolver, this.getId());
this.enabled = true;
}
static getId() {
return "search" /* Search */;
}
getId() {
return SearchManager.getId();
}
isEnabled() {
return this.enabled;
}
};
SearchManager = __decorateClass([
__decorateParam(0, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(1, inject(inversify_types_default.logger)),
__decorateParam(1, named("manager:starred")),
__decorateParam(2, inject(inversify_types_default["service:search:dom:wrapper"])),
__decorateParam(3, inject(inversify_types_default["feature:service"]))
], SearchManager);
// src/Feature/Tab/TabManager.ts
var TabManager = class extends AbstractManager {
constructor(facade, dispatcher, factory) {
super();
this.facade = facade;
this.dispatcher = dispatcher;
this.enabled = false;
this.callback = null;
this.replacer = null;
this.callback = () => {
const file = factory();
file && this.update(file.path);
};
}
async doDisable() {
var _a;
this.dispatcher.removeListener(this.ref);
(_a = this.replacer) == null ? void 0 : _a.disable();
this.ref = null;
this.reset();
this.enabled = false;
}
async doEnable() {
this.enabled = true;
this.initReplacer();
this.ref = this.dispatcher.addListener({ name: "layout:change", cb: this.callback });
return;
}
initReplacer() {
const leaf = this.facade.getActiveLeaf();
this.replacer = FunctionReplacer.create(
Object.getPrototypeOf(leaf),
"setPinned",
this,
function(self2, [pinned], vanilla) {
var _a;
const result = vanilla.call(this, pinned);
if (((_a = this == null ? void 0 : this.view) == null ? void 0 : _a.getViewType()) === "markdown" /* MD */) {
self2.innerUpdate(this.view.file.path);
}
return result;
}
);
this.replacer.enable();
}
reset() {
var _a;
const leaves = this.facade.getLeavesOfType("markdown");
for (const leaf of leaves) {
const file = (_a = leaf.view) == null ? void 0 : _a.file;
if (file) {
leaf.tabHeaderInnerTitleEl.setText(file.basename);
}
}
}
async innerUpdate(path = null) {
var _a;
const leaves = this.facade.getLeavesOfType("markdown");
const result = {};
for (const leaf of leaves) {
const file = (_a = leaf.view) == null ? void 0 : _a.file;
if (path && path !== file.path) {
continue;
}
result[file.path] = false;
const title = file ? this.resolver.resolve(file.path) : null;
if (title && title !== leaf.tabHeaderInnerTitleEl.getText()) {
leaf.tabHeaderInnerTitleEl.setText(title);
result[file.path] = true;
}
}
return result;
}
async doRefresh() {
return this.innerUpdate();
}
async doUpdate(path) {
const result = await this.innerUpdate(path);
return result[path] === true;
}
static getId() {
return "tab" /* Tab */;
}
getId() {
return TabManager.getId();
}
isEnabled() {
return this.enabled;
}
};
TabManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(1, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(2, inject(inversify_types_default["factory:obsidian:active:file"]))
], TabManager);
// src/Feature/Alias/Alias.ts
var Alias = class {
constructor(cache) {
this.cache = cache;
this.changed = false;
this.original = void 0;
}
getPossibleKeys() {
return ["alias", "aliases"];
}
getKey() {
for (const key of Object.keys(this.cache)) {
if (this.getPossibleKeys().includes(key)) {
return key;
}
}
return null;
}
getValue() {
var _a;
return (_a = this.cache[this.getKey()]) != null ? _a : null;
}
setValue(alias) {
if (this.original === void 0) {
const value = this.getValue();
this.original = {
value: Array.isArray(value) ? [...value] : value,
key: this.getKey()
};
}
this.modify(alias);
this.changed = true;
}
isChanged() {
return this.changed;
}
restore() {
const key = this.getKey();
if (this.original.key === null && key) {
delete this.cache[key];
} else if (this.original.key) {
this.modify(this.original.value);
}
this.changed = false;
}
modify(alias) {
var _a;
const key = (_a = this.getKey()) != null ? _a : this.getPossibleKeys()[0];
this.cache[key] = alias;
}
};
// src/Feature/Alias/AliasFeature.ts
var AliasFeature = class extends AbstractFeature {
constructor(strategyFactory, validatorFactory, logger, factory, dispatcher, config) {
super();
this.strategyFactory = strategyFactory;
this.validatorFactory = validatorFactory;
this.logger = logger;
this.factory = factory;
this.dispatcher = dispatcher;
this.config = config;
this.enabled = false;
this.strategy = null;
this.validator = null;
this.items = {};
this.ref = null;
}
setValidator(type) {
this.validator = this.validatorFactory(type);
this.logger.log(`Set validator [${type}]. Status: ${this.validator !== null}`);
}
setStrategy(type) {
this.strategy = this.strategyFactory(type);
this.logger.log(`Set strategy [${type}]. Status: ${this.strategy !== null}`);
}
disable() {
this.reset();
this.dispatcher.removeListener(this.ref);
this.ref = null;
this.enabled = false;
}
enable() {
this.ref = this.dispatcher.addListener({
name: "metadata:cache:changed",
cb: (e) => this.update(e.get().path, e.get().cache)
});
this.setValidator(this.config.getValidator());
this.setStrategy(this.config.getStrategy());
this.enabled = true;
this.refresh().catch(console.error);
}
process(frontmatter, path) {
const alias = new Alias(frontmatter);
this.strategy.process(alias, path);
const result = alias.isChanged();
if (result) {
this.items[path] = alias;
}
return result;
}
reset() {
for (const alias of Object.values(this.items)) {
alias.restore();
}
this.items = {};
}
async update(path, metadata = null) {
if (this.validator.validate(metadata)) {
this.process(metadata.frontmatter, path);
}
}
async refresh() {
const cache = this.factory();
const promises = [];
for (const path of cache.getCachedFiles()) {
promises.push(this.update(path, cache.getCache(path)));
}
await Promise.all(promises);
}
static getId() {
return "alias" /* Alias */;
}
getId() {
return AliasFeature.getId();
}
isEnabled() {
return this.enabled;
}
};
AliasFeature = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:alias:modifier:strategy"])),
__decorateParam(1, inject(inversify_types_default["factory:alias:modifier:validator"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named("alias:modifier")),
__decorateParam(3, inject(inversify_types_default["factory:metadata:cache"])),
__decorateParam(4, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(5, inject(inversify_types_default["feature:alias:config"]))
], AliasFeature);
// src/Feature/Alias/Strategy/AbstractStrategy.ts
var AbstractStrategy = class {
constructor(service) {
this.service = service;
this.resolver = service.createResolver("alias" /* Alias */);
}
process(alias, path) {
const title = this.resolver.resolve(path);
if (title) {
this.modify(alias, title);
}
}
};
AbstractStrategy = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["feature:service"]))
], AbstractStrategy);
// src/Feature/Alias/Strategy/ReplaceStrategy.ts
var ReplaceStrategy = class extends AbstractStrategy {
modify(alias, title) {
alias.setValue(title);
}
};
// src/Feature/Alias/Strategy/EnsureStrategy.ts
var EnsureStrategy = class extends ReplaceStrategy {
process(alias, path) {
if (alias.getValue() === null) {
super.process(alias, path);
}
}
};
// src/Feature/Alias/Strategy/AdjustStrategy.ts
var AdjustStrategy = class extends AbstractStrategy {
modify(alias, title) {
var _a;
let value = (_a = alias.getValue()) != null ? _a : [];
if (!Array.isArray(value)) {
value = [value];
}
value.push(title);
alias.setValue(value);
}
};
// src/Feature/Suggest/SuggestFeature.ts
var SuggestFeature = class extends AbstractFeature {
constructor(chooser, service) {
super();
this.replacer = null;
this.resolver = service.createResolver(this.getId());
this.createChooserReplacer(chooser);
}
isEnabled() {
return this.state;
}
enable() {
if (this.isEnabled()) {
return;
}
this.replacer.enable();
this.state = true;
}
disable() {
this.replacer.disable();
this.state = false;
}
getId() {
return SuggestFeature.getId();
}
static getId() {
return "suggest" /* Suggest */;
}
createChooserReplacer(chooser) {
if (typeof chooser.prototype.setSuggestions !== "function") {
return;
}
this.replacer = new FunctionReplacer(chooser.prototype, "setSuggestions", this, function(self2, args, vanilla) {
if (Array.isArray(args == null ? void 0 : args[0])) {
args[0] = self2.modifySuggestions(args[0]);
}
return vanilla.call(this, ...args);
});
this.replacer.enable();
}
modifySuggestions(items) {
const aliases = /* @__PURE__ */ new Set();
for (const item of items) {
if (!(item == null ? void 0 : item.file)) {
continue;
}
aliases.add(item.alias + item.file.path);
if (!item || !item.type || item.type !== "file") {
continue;
}
const alias = this.resolver.resolve(item.file.path);
const value = alias + item.file.path;
if (alias && !aliases.has(value)) {
item.alias = alias;
item.type = "alias";
aliases.add(value);
}
}
return items;
}
};
SuggestFeature = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["newable:obsidian:chooser"])),
__decorateParam(1, inject(inversify_types_default["feature:service"]))
], SuggestFeature);
// src/Feature/Starred/StarredManager.ts
var StarredManager = class extends AbstractManager {
constructor(facade, logger) {
super();
this.facade = facade;
this.logger = logger;
this.enabled = false;
this.view = null;
this.ref = null;
}
async doUpdate(path) {
return this.onChanged(path)[path] === true;
}
async doRefresh() {
return this.onChanged();
}
initView() {
var _a, _b;
const view = (_b = (_a = this.facade.getViewsOfType("starred" /* ST */)) == null ? void 0 : _a[0]) != null ? _b : null;
if (view === null) {
this.logger.log("Could not find a view of starred type");
return false;
}
this.view = view;
return true;
}
subscribe() {
var _a;
const plugin = (_a = this.view.plugin) != null ? _a : null;
if (plugin === null) {
this.logger.log("Leaf does not have a plugin");
return false;
}
this.ref = plugin.on("changed", () => {
this.logger.log("Triggered by event");
this.onChanged();
});
return true;
}
unsubscribe() {
this.view.plugin.offref(this.ref);
this.view.plugin.trigger("changed");
}
onChanged(path = null) {
const listEl = this.view.listEl.findAll(".nav-file");
const items = this.view.itemLookup;
const result = {};
for (const div of Array.from(listEl)) {
const item = items.get(div);
const content = div.find(".nav-file-title-content");
result[item.path] = false;
if (content && item.type === "file" && (!path || item.path === path)) {
this.process(content, item.path, item.title).catch(console.error);
result[item.path] = true;
}
}
return result;
}
async process(div, path, original) {
var _a;
const title = (_a = this.resolver.resolve(path)) != null ? _a : original;
if (div.getText() !== title) {
div.setText(title);
}
}
doEnable() {
if (!this.isEnabled() && this.initView() && this.subscribe()) {
this.enabled = true;
}
}
doDisable() {
if (this.isEnabled()) {
this.unsubscribe();
this.view = null;
this.enabled = false;
}
}
static getId() {
return "starred" /* Starred */;
}
getId() {
return StarredManager.getId();
}
isEnabled() {
return this.enabled;
}
};
StarredManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(1, inject(inversify_types_default.logger)),
__decorateParam(1, named("manager:starred"))
], StarredManager);
// src/Feature/Graph/GraphManager.ts
var GraphManager = class extends AbstractManager {
constructor(dispatcher, facade, factory, logger) {
super();
this.dispatcher = dispatcher;
this.facade = facade;
this.factory = factory;
this.logger = logger;
this.enabled = false;
this.ref = null;
this.replacement = null;
}
static getId() {
return "graph" /* Graph */;
}
unbind() {
if (this.ref) {
this.logger.log("unbind");
this.dispatcher.removeListener(this.ref);
this.ref = null;
}
}
bind() {
this.logger.log("bind");
this.ref = this.dispatcher.addListener({
name: "layout:change",
cb: () => {
this.initReplacement() && this.unbind();
}
});
}
initReplacement() {
const node = this.getFirstNode();
if (node) {
this.replacement = this.factory(
Object.getPrototypeOf(node),
"getDisplayText",
this,
function(self2, defaultArgs, vanilla) {
const text = self2.resolver.resolve(this.id);
return text != null ? text : vanilla.call(this, ...defaultArgs);
}
);
this.replacement.enable();
this.refresh().catch(console.error);
return true;
} else if (this.getViews().length) {
this.runBackgroundInit();
return true;
}
return false;
}
runBackgroundInit() {
setTimeout(async () => {
this.logger.log("init by backgroundInit");
this.initReplacement();
}, 200);
}
getFirstNode() {
var _a, _b, _c;
for (const view of this.getViews()) {
const node = (_c = ((_b = (_a = view.renderer) == null ? void 0 : _a.nodes) != null ? _b : []).first()) != null ? _c : null;
if (node) {
return node;
}
}
return null;
}
getViews() {
return [...this.facade.getViewsOfType("graph" /* G */), ...this.facade.getViewsOfType("localgraph" /* LG */)];
}
doDisable() {
var _a;
this.unbind();
(_a = this.replacement) == null ? void 0 : _a.disable();
this.enabled = false;
}
doEnable() {
if (!this.initReplacement()) {
this.bind();
}
this.enabled = true;
}
doRefresh() {
var _a;
for (const view of this.getViews()) {
(_a = view.renderer) == null ? void 0 : _a.onIframeLoad();
}
return Promise.resolve();
}
async doUpdate(path) {
var _a, _b;
let result = false;
for (const view of this.getViews()) {
for (const node of (_b = (_a = view.renderer) == null ? void 0 : _a.nodes) != null ? _b : []) {
if (node.id === path) {
result = true;
view.renderer.onIframeLoad();
break;
}
}
}
return result;
}
getId() {
return GraphManager.getId();
}
isEnabled() {
return this.enabled;
}
};
GraphManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(1, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(2, inject(inversify_types_default["factory:replacer"])),
__decorateParam(3, inject(inversify_types_default.logger)),
__decorateParam(3, named("manager:graph"))
], GraphManager);
// src/Feature/MarkdownHeader/MarkdownHeaderManager.ts
var MarkdownHeaderManager = class extends AbstractManager {
constructor(dispatcher, facade, logger) {
super();
this.dispatcher = dispatcher;
this.facade = facade;
this.logger = logger;
this.ref = null;
this.enabled = false;
}
static getId() {
return "header" /* Header */;
}
doDisable() {
this.dispatcher.removeListener(this.ref);
this.facade.getViewsOfType("markdown" /* MD */).forEach(this.revert.bind(this));
this.enabled = false;
}
doEnable() {
this.ref = this.dispatcher.addListener({
name: "layout:change",
cb: () => this.refresh().catch(console.error)
});
this.enabled = true;
}
async doRefresh() {
await this.innerUpdate();
return Promise.resolve({});
}
async doUpdate(path) {
return this.innerUpdate(path);
}
async innerUpdate(path = null) {
const views = this.facade.getViewsOfType("markdown" /* MD */);
let updated = false;
for (const view of views) {
if (!path || view.file.path === path) {
const title = this.resolver.resolve(view.file.path);
this.setTitle(view, title);
updated = true;
}
}
return updated;
}
setTitle(view, title) {
this.logger.log(`Set title "${title != null ? title : " "}" for ${view.file.path}`);
const container = view.titleContainerEl;
if (!title) {
return this.revert(view);
}
let el = this.findExistingFakeEl(container);
if (title && el && el.innerText === title && !el.hidden) {
return this.logger.log(`Set title "${title}" for ${view.file.path} is skipped`);
}
el = el != null ? el : this.createFakeEl(title, view);
el.innerText = title;
el.hidden = false;
view.titleEl.hidden = true;
}
revert(view) {
const container = view.titleContainerEl;
const el = this.findExistingFakeEl(container);
if (el) {
container.removeChild(el);
}
view.titleEl.hidden = false;
return;
}
findExistingFakeEl(container) {
for (const i of Array.from(container.children)) {
if (i.hasAttribute("data-ofmt") && i instanceof HTMLDivElement) {
return i;
}
}
return null;
}
createFakeEl(title, view) {
const el = document.createElement("div");
el.className = "view-header-title";
el.dataset["ofmt"] = "true";
el.innerText = title;
el.hidden = true;
el.onclick = () => {
el.hidden = true;
view.titleEl.hidden = false;
view.titleEl.focus();
view.titleEl.onblur = () => {
view.titleEl.hidden = true;
el.hidden = false;
};
};
view.titleContainerEl.appendChild(el);
return el;
}
getId() {
return MarkdownHeaderManager.getId();
}
isEnabled() {
return this.enabled;
}
};
MarkdownHeaderManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(1, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named(`manager:${MarkdownHeaderManager.getId()}`))
], MarkdownHeaderManager);
// src/Feature/Alias/Validator.ts
var ValidatorRequired = class {
validate(metadata) {
return metadata.frontmatter ? true : false;
}
};
ValidatorRequired = __decorateClass([
injectable()
], ValidatorRequired);
var ValidatorAuto = class {
validate(metadata) {
if (!metadata.frontmatter) {
metadata.frontmatter = {
position: {
end: {
col: 0,
line: 0,
offset: 0
},
start: {
col: 0,
line: 0,
offset: 0
}
}
};
}
return true;
}
};
ValidatorAuto = __decorateClass([
injectable()
], ValidatorAuto);
// src/Feature/InlineTitle/InlineTitleManager.ts
var InlineTitleManager = class extends AbstractManager {
constructor(dispatcher, facade, logger, fakeTitleElementService) {
super();
this.dispatcher = dispatcher;
this.facade = facade;
this.logger = logger;
this.fakeTitleElementService = fakeTitleElementService;
this.ref = null;
this.enabled = false;
}
static getId() {
return "inlineTitle" /* InlineTitle */;
}
doDisable() {
this.dispatcher.removeListener(this.ref);
this.fakeTitleElementService.removeAll();
this.enabled = false;
}
doEnable() {
this.ref = this.dispatcher.addListener({
name: "layout:change",
cb: () => this.refresh().catch(console.error)
});
this.enabled = true;
}
async doRefresh() {
await this.innerUpdate();
return Promise.resolve({});
}
async doUpdate(path) {
return this.innerUpdate(path);
}
async resolve(path) {
return this.resolver.resolve(path);
}
async innerUpdate(path = null) {
const views = this.facade.getViewsOfType("markdown" /* MD */);
const promises = [];
const ids = [];
for (const view of views) {
if (!path || view.file.path === path) {
promises.push(
this.resolve(view.file.path).then(
(title) => title ? ids.push(this.setTitle(view, title)) : this.resetTitle(this.getTitleElId(view))
).catch(console.error)
);
}
}
await Promise.all(promises);
this.fakeTitleElementService.removeExcept(ids);
return promises.length > 0;
}
resetTitle(id3) {
this.fakeTitleElementService.remove(id3);
}
setTitle(view, title) {
this.logger.log(`Set inline title "${title != null ? title : " "}" for ${view.file.path}`);
const id3 = this.getTitleElId(view);
const original = view.inlineTitleEl;
const { created } = this.fakeTitleElementService.getOrCreate({ original, title, id: id3, events: ["click"] });
if (created) {
this.fakeTitleElementService.setVisible(id3, true);
}
return id3;
}
getTitleElId(view) {
return `${view.getState().mode}-${this.getId()}-${view.leaf.id}`;
}
getId() {
return InlineTitleManager.getId();
}
isEnabled() {
return this.enabled;
}
};
InlineTitleManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(1, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named(`manager:${InlineTitleManager.getId()}`)),
__decorateParam(3, inject(inversify_types_default["service:fake_title_element"]))
], InlineTitleManager);
// src/Feature/Canvas/CanvasManager.ts
var import_obsidian4 = require("obsidian");
var CanvasManager = class extends AbstractManager {
constructor(dispatcher, facade, logger, fakeTitleElementService) {
super();
this.dispatcher = dispatcher;
this.facade = facade;
this.logger = logger;
this.fakeTitleElementService = fakeTitleElementService;
this.ref = null;
this.enabled = false;
this.queue = /* @__PURE__ */ new Set();
this.updateByRequestFrame = (0, import_obsidian4.debounce)(
() => {
this.logger.log(`updateByRequestFrame`, this.queue);
Array.from(this.queue.values()).forEach((e) => this.innerUpdate(e) && this.queue.delete(e));
},
1e3,
true
);
}
static getId() {
return "canvas" /* Canvas */;
}
doDisable() {
this.dispatcher.removeListener(this.ref);
this.fakeTitleElementService.removeAll();
this.enabled = false;
}
doEnable() {
this.ref = this.dispatcher.addListener({
name: "layout:change",
cb: () => this.refresh().catch(console.error)
});
this.enabled = true;
}
async doRefresh() {
await this.innerUpdate();
return Promise.resolve({});
}
async doUpdate(path) {
return this.innerUpdate(path);
}
async resolve(path) {
return this.resolver.resolve(path);
}
async innerUpdate(path = null) {
const promises = [];
this.logger.log(`inner update "${path}"`);
const canvasViews = this.facade.getViewsOfType("canvas" /* CV */);
for (const view of canvasViews) {
if (!view.file) {
continue;
}
const currentPath = view.file.path;
const canvas = view.canvas;
for (const node of canvas.nodes.values()) {
if (!node.filePath || path && path !== node.filePath && path !== currentPath) {
continue;
}
promises.push(
this.resolve(node.filePath).then((title) => {
if (title) {
this.setNodeTitle(node, title);
} else {
this.restoreNodeTitle(node);
}
})
);
}
if (!canvas.requestFrame._originalFunc) {
const originalFunc = canvas.requestFrame;
const manager = this;
canvas.requestFrame = function(...args) {
canvas.requestFrame._originalFunc.apply(this, args);
if (manager.enabled) {
manager.queue.add(currentPath);
manager.updateByRequestFrame();
} else {
canvas.requestFrame = canvas.requestFrame._originalFunc;
}
};
canvas.requestFrame._originalFunc = originalFunc;
}
}
await Promise.all(promises);
return promises.length > 0;
}
restoreNodeTitle(node) {
const ids = this.makeFakeElementIds(node.canvas.view.file.path, node.filePath);
this.fakeTitleElementService.remove(ids.label);
this.fakeTitleElementService.remove(ids.inline);
}
async setNodeTitle(node, title) {
var _a;
do {
await new Promise((resolve2) => setTimeout(resolve2, 200));
} while (!node.initialized);
const view = node.canvas.view;
this.logger.log(`Set canvas title "${title}" for canvas "${view.file.path}" and node "${node.filePath}"`);
const ids = this.makeFakeElementIds(view.file.path, node.filePath);
const label = this.fakeTitleElementService.getOrCreate({
original: node.labelEl,
title,
id: ids.label,
events: ["hover"]
});
if (label == null ? void 0 : label.created) {
this.fakeTitleElementService.setVisible(ids.label, true);
}
const inlineTitleEl = (_a = node.contentEl) == null ? void 0 : _a.querySelector(".inline-title");
const inline = this.fakeTitleElementService.getOrCreate({
original: inlineTitleEl,
title,
id: ids.inline,
events: ["click"]
});
if (inline == null ? void 0 : inline.created) {
this.fakeTitleElementService.setVisible(ids.inline, true);
}
if (node.placeholderEl.getText() !== title) {
node.placeholderEl.setText(title);
}
}
makeFakeElementIds(canvasPath, nodePath) {
const prefix = `${canvasPath}-${nodePath}`;
return {
label: `${prefix}-label`,
inline: `${prefix}-inline`
};
}
getId() {
return CanvasManager.getId();
}
isEnabled() {
return this.enabled;
}
};
CanvasManager = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(1, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named(`manager:${CanvasManager.getId()}`)),
__decorateParam(3, inject(inversify_types_default["service:fake_title_element"]))
], CanvasManager);
// src/Utils/FeatureHelper.ts
var FeatureHelper = class {
getOrderedFeatures() {
return [
"alias" /* Alias */,
"explorer" /* Explorer */,
"explorer:sort" /* ExplorerSort */,
"graph" /* Graph */,
"header" /* Header */,
"starred" /* Starred */,
"search" /* Search */,
"suggest" /* Suggest */,
"tab" /* Tab */,
"inlineTitle" /* InlineTitle */,
"canvas" /* Canvas */,
"backlink" /* Backlink */,
"noteLink" /* NoteLink */
];
}
getName(feature) {
switch (feature) {
case "alias" /* Alias */:
return t2("feature.alias.name");
case "explorer" /* Explorer */:
return t2("feature.explorer.name");
case "explorer:sort" /* ExplorerSort */:
return t2("feature.explorer:sort.name");
case "graph" /* Graph */:
return t2("feature.graph.name");
case "header" /* Header */:
return t2("feature.header.name");
case "starred" /* Starred */:
return t2("feature.starred.name");
case "search" /* Search */:
return t2("feature.search.name");
case "suggest" /* Suggest */:
return t2("feature.suggest.name");
case "tab" /* Tab */:
return t2("feature.tab.name");
case "inlineTitle" /* InlineTitle */:
return t2("feature.inlineTitle.name");
case "canvas" /* Canvas */:
return t2("feature.canvas.name");
case "backlink" /* Backlink */:
return t2("feature.backlink.name");
case "noteLink" /* NoteLink */:
return t2("feature.noteLink.name");
}
}
getDescription(feature) {
switch (feature) {
case "alias" /* Alias */:
return t2("feature.alias.desc");
case "explorer" /* Explorer */:
return t2("feature.explorer.desc");
case "explorer:sort" /* ExplorerSort */:
return t2("feature.explorer:sort.desc");
case "graph" /* Graph */:
return t2("feature.graph.desc");
case "header" /* Header */:
return t2("feature.header.desc");
case "starred" /* Starred */:
return t2("feature.starred.desc");
case "search" /* Search */:
return t2("feature.search.desc");
case "suggest" /* Suggest */:
return t2("feature.suggest.desc");
case "tab" /* Tab */:
return t2("feature.tab.desc");
case "inlineTitle" /* InlineTitle */:
return t2("feature.inlineTitle.desc");
case "canvas" /* Canvas */:
return t2("feature.canvas.desc");
case "backlink" /* Backlink */:
return t2("feature.backlink.desc");
case "noteLink" /* NoteLink */:
return t2("feature.noteLink.desc");
}
}
getDocSection(feature) {
switch (feature) {
case "noteLink" /* NoteLink */:
return "Features/NoteLink.md";
default:
return feature;
}
}
};
FeatureHelper = __decorateClass([
injectable()
], FeatureHelper);
// src/Feature/FeatureService.ts
var FeatureService = class {
constructor(service) {
this.service = service;
}
createResolver(name) {
const main = this.service.createNamed(`${name}:main`);
const fallback = this.service.createNamed(`${name}:fallback`);
return {
resolve(path) {
var _a;
return (_a = main.resolve(path)) != null ? _a : fallback.resolve(path);
}
};
}
};
FeatureService = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["resolver:service"]))
], FeatureService);
// src/Feature/Backlink/BacklinkFeature.ts
var BacklinkFeature = class extends AbstractFeature {
constructor(facade, logger, dispatcher, service, mutateService) {
super();
this.facade = facade;
this.logger = logger;
this.dispatcher = dispatcher;
this.mutateService = mutateService;
this.enabled = false;
this.refs = [];
this.dProcess = null;
this.timer = null;
this.isBacklinkWrapped = false;
this.resolver = service.createResolver(this.getId());
this.dProcess = () => {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(this.process.bind(this), 50);
};
}
isEnabled() {
return this.enabled;
}
enable() {
this.enabled = this.facade.isInternalPluginEnabled(this.getId());
this.logger.log(`Manager state is ${this.enabled}`);
if (!this.enabled) {
return;
}
this.refs = [
this.dispatcher.addListener({
name: "metadata:cache:changed",
cb: this.dProcess.bind(this)
}),
this.dispatcher.addListener({
name: "layout:change",
cb: this.dProcess.bind(this)
})
];
this.process();
}
disable() {
this.enabled = false;
if (this.refs.length) {
this.refs.forEach((e) => this.dispatcher.removeListener(e));
this.refs = [];
this.mutateService.destroyByTag(this.getId());
}
}
process() {
var _a;
this.logger.log("process");
this.processBacklinkLayout();
for (const view of this.facade.getViewsOfType("markdown" /* MD */)) {
const dom = (_a = view == null ? void 0 : view.backlinks) == null ? void 0 : _a.backlinkDom;
if (dom) {
this.mutateService.wrapDom(dom, this.resolver, this.getId());
}
}
}
processBacklinkLayout() {
var _a, _b;
if (this.isBacklinkWrapped) {
return;
}
const view = (_a = this.facade.getViewsOfType("backlink" /* BL */)[0]) != null ? _a : null;
if ((_b = view == null ? void 0 : view.backlink) == null ? void 0 : _b.backlinkDom) {
this.mutateService.wrapDom(view.backlink.backlinkDom, this.resolver, this.getId());
}
this.isBacklinkWrapped = true;
}
getId() {
return BacklinkFeature.getId();
}
static getId() {
return "backlink" /* Backlink */;
}
};
BacklinkFeature = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(1, inject(inversify_types_default.logger)),
__decorateParam(1, named("backlink")),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(3, inject(inversify_types_default["feature:service"])),
__decorateParam(4, inject(inversify_types_default["service:search:dom:wrapper"]))
], BacklinkFeature);
// src/Feature/NoteLink/NoteLinkFeature.ts
var import_obsidian5 = require("obsidian");
var NoteLinkFeature = class extends AbstractFeature {
constructor(featureService, service, dispatcher, approve, facade, config) {
super();
this.service = service;
this.dispatcher = dispatcher;
this.approve = approve;
this.facade = facade;
this.config = config;
this.enabled = false;
this.refs = [];
this.resolver = featureService.createResolver(this.getId());
}
disable() {
this.refs.forEach((e) => this.dispatcher.removeListener(e));
this.refs = [];
this.enabled = false;
}
enable() {
this.refs.push(
this.dispatcher.addListener({
name: "metadata:cache:changed",
cb: (e) => this.requestApprove(e.get().path)
})
);
this.enabled = true;
}
shouldChangeLink(link, destTitle) {
if (!destTitle || destTitle === link.alias) {
return false;
}
const hasAlias = /.+\|.+/.test(link.original);
return this.config.strategy === "all" /* All */ || !hasAlias;
}
async requestApprove(path) {
const links = this.service.getNoteLinks(path);
const changes = [];
for (const link of links) {
const title = this.resolver.resolve(link.dest);
if (this.shouldChangeLink(link, title)) {
changes.push({
original: link.original,
replace: `[[${link.link}|${title}]]`
});
}
}
if (changes.length === 0) {
return;
}
const exec = this.config.approval ? await this.approve.request(path, changes) : true;
if (exec) {
await this.executeChanges(path, changes);
}
}
async executeChanges(path, changes) {
const file = this.facade.getTFile(path);
let content = file instanceof import_obsidian5.TFile ? await this.facade.getFileContent(file) : null;
if (!content) {
return;
}
for (const { original, replace } of changes) {
content = content.replace(original, replace);
}
await this.facade.modifyFile(file, content).catch(console.error);
}
getId() {
return NoteLinkFeature.getId();
}
isEnabled() {
return this.enabled;
}
static getId() {
return "noteLink" /* NoteLink */;
}
};
NoteLinkFeature = __decorateClass([
__decorateParam(0, inject(inversify_types_default["feature:service"])),
__decorateParam(1, inject(inversify_types_default["service:note:link"])),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(3, inject(inversify_types_default["feature:notelink:approve"])),
__decorateParam(4, inject(inversify_types_default["facade:obsidian"])),
__decorateParam(5, inject(inversify_types_default["feature:config"])),
__decorateParam(5, named("noteLink" /* NoteLink */))
], NoteLinkFeature);
// src/Feature/NoteLink/NoteLinkApprove.ts
var NoteLinkApprove = class {
constructor(factory) {
this.factory = factory;
}
async request(path, changes) {
return new Promise((r) => {
const modal = this.factory();
let approved = false;
modal.onClose = () => r(approved);
const { contentEl } = modal;
contentEl.setText(`Approve changes for ${path}`);
contentEl.createEl(
"ul",
null,
(ul) => changes.forEach((e) => ul.createEl("li", { text: `${e.original} => ${e.replace}` }))
);
const btnContainer = contentEl.createDiv("modal-button-container");
btnContainer.createEl("button", { cls: "mod-cta", text: t2("apply") }).addEventListener("click", () => {
approved = true;
modal.close();
});
btnContainer.createEl("button", { text: t2("cancel") }).addEventListener("click", () => modal.close());
modal.open();
});
}
};
NoteLinkApprove = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:obsidian:modal"]))
], NoteLinkApprove);
// src/Feature/Alias/AliasConfig.ts
var AliasConfig = class {
constructor(storage) {
this.storage = storage;
}
get config() {
return this.storage.get("features").get("alias" /* Alias */);
}
getStrategy() {
return this.config.get("strategy").value();
}
getValidator() {
return this.config.get("validator").value();
}
};
AliasConfig = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["settings:storage"]))
], AliasConfig);
// config/services/feature.config.ts
var feature_config_default = (container) => {
container.bind(inversify_types_default["feature:service"]).to(FeatureService).inSingletonScope();
container.bind(inversify_types_default["feature:composer"]).to(FeatureComposer).inSingletonScope();
container.bind(inversify_types_default["manager:composer"]).to(ManagerComposer).inSingletonScope();
container.bind(inversify_types_default["feature:helper"]).to(FeatureHelper).inSingletonScope();
container.bind(inversify_types_default["factory:feature"]).toAutoNamedFactory(inversify_types_default.feature).onActivation((c, i) => (name) => {
const feature = i(name);
if (feature instanceof AbstractManager) {
const service = c.container.get(inversify_types_default["feature:service"]);
feature.setResolver(service.createResolver(feature.getId()));
}
return feature;
});
container.bind(inversify_types_default.feature).to(AliasFeature).whenTargetNamed(AliasFeature.getId());
container.bind(inversify_types_default.feature).to(ExplorerManager).whenTargetNamed(ExplorerManager.getId());
container.bind(inversify_types_default.feature).to(ExplorerSort).whenTargetNamed(ExplorerSort.getId());
container.bind(inversify_types_default.feature).to(SearchManager).whenTargetNamed(SearchManager.getId());
container.bind(inversify_types_default.feature).to(StarredManager).whenTargetNamed(StarredManager.getId());
container.bind(inversify_types_default.feature).to(TabManager).whenTargetNamed(TabManager.getId());
container.bind(inversify_types_default.feature).to(SuggestFeature).whenTargetNamed(SuggestFeature.getId());
container.bind(inversify_types_default.feature).to(GraphManager).whenTargetNamed(GraphManager.getId());
container.bind(inversify_types_default.feature).to(MarkdownHeaderManager).whenTargetNamed(MarkdownHeaderManager.getId());
container.bind(inversify_types_default.feature).to(BacklinkFeature).whenTargetNamed(BacklinkFeature.getId());
container.bind(inversify_types_default.feature).to(NoteLinkFeature).whenTargetNamed(NoteLinkFeature.getId());
container.bind(inversify_types_default.feature).to(InlineTitleManager).whenTargetNamed(InlineTitleManager.getId());
container.bind(inversify_types_default.feature).to(CanvasManager).whenTargetNamed(CanvasManager.getId());
container.bind(inversify_types_default["factory:alias:modifier:strategy"]).toAutoNamedFactory(inversify_types_default["alias:modifier:strategy"]);
container.bind(inversify_types_default["alias:modifier:strategy"]).to(EnsureStrategy).whenTargetNamed("ensure" /* Ensure */);
container.bind(inversify_types_default["alias:modifier:strategy"]).to(AdjustStrategy).whenTargetNamed("adjust" /* Adjust */);
container.bind(inversify_types_default["alias:modifier:strategy"]).to(ReplaceStrategy).whenTargetNamed("replace" /* Replace */);
container.bind(inversify_types_default["feature:alias:config"]).to(AliasConfig);
container.bind(inversify_types_default["factory:alias:modifier:validator"]).toAutoNamedFactory(inversify_types_default["alias:modifier:validator"]);
container.bind(inversify_types_default["alias:modifier:validator"]).to(ValidatorAuto).whenTargetNamed("fa" /* FrontmatterAuto */);
container.bind(inversify_types_default["alias:modifier:validator"]).to(ValidatorRequired).whenTargetNamed("fr" /* FrontmatterRequired */);
container.bind(inversify_types_default["feature:notelink:approve"]).to(NoteLinkApprove);
container.bind(inversify_types_default["feature:config"]).toDynamicValue((c) => {
const feature = c.currentRequest.target.getNamedTag().value;
return c.container.get(inversify_types_default["settings:storage"]).get("features").get(feature).value();
}).when(() => true);
};
// src/Settings/FeatureBuilder/DefaultBuilder.ts
var import_obsidian6 = require("obsidian");
// src/Settings/FeatureBuilder/AbstractBuilder.ts
var AbstractBuilder = class {
setContext(context) {
this.context = context;
}
};
// src/Settings/FeatureBuilder/DefaultBuilder.ts
var DefaultBuilder = class extends AbstractBuilder {
build({ id: id3, name, desc, settings }) {
new import_obsidian6.Setting(this.context.getContainer()).setName(name).setDesc(desc).addToggle(
(e) => e.setValue(settings.enabled).onChange((v) => {
this.context.getDispatcher().dispatch("settings:tab:feature:changed", new Event({ id: id3, value: { enabled: v } }));
})
);
}
};
// src/Settings/FeatureBuilder/AliasBuilder.ts
var import_obsidian7 = require("obsidian");
var AliasBuilder = class extends AbstractBuilder {
build({ id: id3, name, desc, settings }) {
this.id = id3;
this.desc = desc;
this.setting = new import_obsidian7.Setting(this.context.getContainer()).setName(name).setDesc(desc);
this.buildValidatorDropdown(settings.validator);
this.buildStrategyDropdown(settings.strategy);
this.buildToggle(settings.enabled);
this.actualizeDesc();
}
buildValidatorDropdown(value) {
this.validatorDropdown = new import_obsidian7.DropdownComponent(this.setting.controlEl).addOptions({
["fa" /* FrontmatterAuto */]: t2("feature.alias.validator.auto.name"),
["fr" /* FrontmatterRequired */]: t2("feature.alias.validator.required.name")
}).setValue(value ? value : "fr" /* FrontmatterRequired */).onChange(this.onChange.bind(this));
}
buildStrategyDropdown(value) {
this.strategyDropdown = new import_obsidian7.DropdownComponent(this.setting.controlEl).addOptions({
["ensure" /* Ensure */]: t2("feature.alias.strategy.ensure.name"),
["adjust" /* Adjust */]: t2("feature.alias.strategy.adjust.name"),
["replace" /* Replace */]: t2("feature.alias.strategy.replace.name")
}).setValue(value ? value : "ensure" /* Ensure */).onChange(this.onChange.bind(this));
}
buildToggle(value) {
this.setting.addToggle((e) => this.toggle = e.setValue(value).onChange(this.onChange.bind(this)));
}
onChange() {
this.context.getDispatcher().dispatch(
"settings:tab:feature:changed",
new Event({
id: this.id,
value: {
enabled: this.toggle.getValue(),
strategy: this.strategyDropdown.getValue(),
validator: this.validatorDropdown.getValue()
}
})
);
this.actualizeDesc();
}
getStrategyFragment() {
let text = "";
switch (this.strategyDropdown.getValue()) {
case "ensure" /* Ensure */:
text = t2("feature.alias.strategy.ensure.desc");
break;
case "replace" /* Replace */:
text = t2("feature.alias.strategy.replace.desc");
break;
case "adjust" /* Adjust */:
text = t2("feature.alias.strategy.adjust.desc");
break;
}
const fragment = createFragment();
fragment.createEl("b", "", (e) => e.setText(`${t2("strategy")}: `));
fragment.appendText(text);
return fragment;
}
getValidatorFragment() {
let text = "";
switch (this.validatorDropdown.getValue()) {
case "fa" /* FrontmatterAuto */: {
text = t2("feature.alias.validator.auto.desc");
break;
}
case "fr" /* FrontmatterRequired */: {
text = t2("feature.alias.validator.required.desc");
break;
}
}
const fragment = createFragment();
fragment.createEl("b", "", (e) => e.setText(`${t2("validator")}: `));
fragment.appendText(text);
return fragment;
}
actualizeDesc() {
const fragment = createFragment();
fragment.appendText(this.desc);
fragment.createEl("br");
fragment.append(this.getValidatorFragment());
fragment.createEl("br");
fragment.append(this.getStrategyFragment());
this.setting.setDesc(fragment);
}
};
// src/Settings/FeatureBuilder/ExplorerSortBuilder.ts
var import_obsidian8 = require("obsidian");
var ExplorerSortBuilder = class extends AbstractBuilder {
constructor() {
super();
this.toggle = null;
this.setting = null;
this.ref = null;
}
build(options) {
this.bind();
this.setting = new import_obsidian8.Setting(this.context.getContainer()).setName(options.name).setDesc(options.desc);
this.setting.addToggle((c) => this.toggle = c);
this.toggle.setValue(options.settings.enabled).onChange(
(v) => this.context.getDispatcher().dispatch(
"settings:tab:feature:changed",
new Event({
id: options.id,
value: { enabled: v }
})
)
);
if (!this.context.getSettings().explorer.enabled) {
this.setting.settingEl.hide();
}
}
bind() {
this.ref = this.context.getDispatcher().addListener({
name: "settings:tab:feature:changed",
cb: (e) => {
if (e.get().id === "explorer" /* Explorer */) {
this.toggle.setValue(false);
if (e.get().value.enabled) {
this.setting.settingEl.show();
} else {
this.setting.settingEl.hide();
}
}
}
});
this.context.getDispatcher().addListener({
name: "settings:tab:close",
once: true,
cb: () => {
this.context.getDispatcher().removeListener(this.ref);
this.ref = null;
}
});
}
};
// src/Settings/SettingBuilders/AbstractBuilder.ts
var AbstractBuilder2 = class {
constructor() {
this.item = null;
this.container = null;
this.name = null;
}
build({ name, container, item }) {
this.name = name;
this.item = item;
this.container = container;
this.doBuild();
}
};
AbstractBuilder2 = __decorateClass([
injectable()
], AbstractBuilder2);
// src/Settings/SettingBuilders/Templates/TemplatesBuilder.ts
var import_obsidian9 = require("obsidian");
var TemplatesBuilder = class extends AbstractBuilder2 {
constructor(factory, helper) {
super();
this.factory = factory;
this.helper = helper;
}
support(k) {
return k === "templates";
}
doBuild() {
this.buildTemplate();
this.buildFallbackTemplate();
this.buildConfigButton();
}
createDocFragment(text, section = null) {
return createFragment(
(e) => e.createEl("a", {
href: GITHUB_DOCS + "Templates.md" + (section ? `#${section}` : ""),
text
})
);
}
buildTemplate() {
new import_obsidian9.Setting(this.container).setName(this.createDocFragment(t2("template.commmon.main.name"))).setDesc(t2("template.commmon.main.desc")).addText(
(text) => {
var _a;
return text.setPlaceholder(t2("template.placeholder")).setValue((_a = this.item.get("common").get("main").value()) != null ? _a : "").onChange(async (value) => this.item.get("common").get("main").set(value));
}
);
}
buildFallbackTemplate() {
new import_obsidian9.Setting(this.container).setName(this.createDocFragment(t2("template.commmon.fallback.name"))).setDesc(t2("template.commmon.fallback.desc")).addText(
(text) => {
var _a;
return text.setPlaceholder(t2("template.placeholder")).setValue((_a = this.item.get("common").get("fallback").value()) != null ? _a : "").onChange(async (value) => this.item.get("common").get("fallback").set(value));
}
);
}
buildConfigButton() {
const getDesc = (type, value) => value ? t2("template.specific") : t2("template.used", { value: this.item.get("common").get(type).value() });
new import_obsidian9.Setting(this.container).setName(this.createDocFragment(t2("template.features.name"), "features-templates")).setDesc(t2("template.features.desc")).addButton(
(cb) => cb.setButtonText(t2("manage")).onClick(() => {
const modal = this.factory();
const { contentEl } = modal;
contentEl.setText(t2("template.features.name"));
for (const feature of Object.values(Feature)) {
if (feature === "explorer:sort" /* ExplorerSort */) {
continue;
}
if (!this.item.get(feature)) {
this.item.add(feature, { main: null, fallback: null });
}
const templates = this.item.get(feature);
contentEl.createEl("h4", null, (e) => e.setText(this.helper.getName(feature)));
for (const type of Object.keys(templates.value())) {
const s = new import_obsidian9.Setting(contentEl).setName(t2(`template.${type}`)).setDesc(getDesc(type, templates.get(type).value())).addText(
(text) => text.setPlaceholder(this.item.get("common").get(type).value()).setValue(templates.get(type).value()).onChange((value) => {
templates.get(type).set(value ? value : null);
s.setDesc(getDesc(type, value));
})
);
}
}
modal.open();
})
);
}
};
TemplatesBuilder = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:obsidian:modal"])),
__decorateParam(1, inject(inversify_types_default["feature:helper"]))
], TemplatesBuilder);
// src/Settings/SettingBuilders/Rules/RulesBuilder.ts
var RulesBuiler = class extends AbstractBuilder2 {
constructor(factory) {
super();
this.factory = factory;
}
doBuild() {
this.container.createEl("h4", { text: t2("rule.name") });
const builders = this.factory("rules");
for (const key of this.orderedKeys) {
for (const builder of builders) {
builder.support(key) && builder.build({
name: key,
container: this.container,
item: this.item.get(key)
});
}
}
}
get orderedKeys() {
return ["paths", "delimiter"];
}
support(k) {
return k === "rules";
}
};
RulesBuiler = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:settings:builder"]))
], RulesBuiler);
// src/Settings/SettingBuilders/Features/FeaturesBuilder.ts
var FeaturesBuilder = class extends AbstractBuilder2 {
constructor(builderFactory, dispatcher, helper) {
super();
this.builderFactory = builderFactory;
this.dispatcher = dispatcher;
this.helper = helper;
this.ref = null;
}
support(k) {
return k === "features";
}
bind() {
this.ref = this.dispatcher.addListener({
name: "settings:tab:feature:changed",
cb: (e) => this.item.get(e.get().id).set(e.get().value)
});
this.dispatcher.addListener({
name: "settings:tab:close",
cb: () => this.dispatcher.removeListener(this.ref),
once: true
});
}
doBuild() {
var _a;
this.bind();
this.container.createEl("h4", { text: t2("features") });
const data = this.helper.getOrderedFeatures().map((feature) => ({
desc: this.helper.getDescription(feature),
feature,
name: this.helper.getName(feature),
doc: {
link: `${GITHUB_DOCS}/${this.helper.getDocSection(feature)}`
}
}));
for (const item of data) {
const builder = (_a = this.builderFactory(item.feature)) != null ? _a : this.builderFactory("default");
const settings = this.item.get(item.feature).value();
builder.setContext({
getContainer: () => this.container,
getSettings: () => this.item.value(),
getDispatcher: () => this.dispatcher
});
builder.build({ id: item.feature, desc: item.desc, name: item.name, settings, doc: item.doc });
}
}
};
FeaturesBuilder = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:settings:feature:builder"])),
__decorateParam(1, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(2, inject(inversify_types_default["feature:helper"]))
], FeaturesBuilder);
// src/Settings/SettingBuilders/Util/UtilBuilder.ts
var import_obsidian10 = require("obsidian");
var UtilBuilder = class {
constructor() {
this.isTitleBuild = false;
}
build({ name, item, container }) {
this.buildTitle(container);
switch (name) {
case "boot": {
this.buildBoot(item, container);
break;
}
case "debug": {
this.buildDebug(item, container);
break;
}
}
}
buildTitle(container) {
if (!this.isTitleBuild) {
container.createEl("h4", { text: t2("util") });
this.isTitleBuild = true;
}
}
buildDebug(item, container) {
new import_obsidian10.Setting(container).setName(t2("debug_info.title")).setDesc(t2("debug_info.desc")).addToggle((e) => e.setValue(item.value()).onChange((e2) => item.set(e2)));
}
buildBoot(item, container) {
new import_obsidian10.Setting(container).setName(t2("boot_delay.title")).setDesc(t2("boot_delay.desc")).addText(
(e) => e.setValue(item.get("delay").value().toString()).onChange((s) => {
const v = !isNaN(parseInt(s)) ? parseInt(s) : 0;
e.setValue(v.toString());
item.get("delay").set(v);
})
);
}
support(k) {
return ["boot", "debug"].includes(k);
}
};
UtilBuilder = __decorateClass([
injectable()
], UtilBuilder);
// src/Settings/SettingBuilders/Rules/RulesDelimiterBuilder.ts
var import_obsidian11 = require("obsidian");
var RulesDelimiterBuilder = class extends AbstractBuilder2 {
constructor() {
super(...arguments);
this.setting = null;
this.text = null;
}
support(k) {
return k === "delimiter";
}
doBuild() {
this.setting = new import_obsidian11.Setting(this.container).setName(t2("rule.delimiter.name")).setDesc(t2("rule.delimiter.desc"));
this.buildDropdown();
this.buildText();
}
buildDropdown() {
const enabled = this.item.get("enabled");
new import_obsidian11.DropdownComponent(this.setting.controlEl).addOptions({ N: t2("rule.delimiter.first"), Y: t2("rule.delimiter.join") }).setValue(enabled.value() ? "Y" : "N").onChange((e) => {
enabled.set(e === "Y");
this.text.setValue("").setPlaceholder(this.getPlaceholder()).setDisabled(e === "N").onChanged();
});
}
buildText() {
const v = this.item.get("value");
this.text = new import_obsidian11.TextComponent(this.setting.controlEl).setValue(v.value()).setDisabled(!this.isEnabled()).setPlaceholder(this.getPlaceholder()).onChange((e) => v.set(e));
}
getPlaceholder() {
return this.isEnabled() ? t2("rule.delimiter.placeholder.join") : t2("rule.delimiter.placeholder.first");
}
isEnabled() {
return this.item.get("enabled").value();
}
};
RulesDelimiterBuilder = __decorateClass([
injectable()
], RulesDelimiterBuilder);
// src/Settings/SettingBuilders/Rules/RulesPathsBuilder.ts
var import_obsidian12 = require("obsidian");
var RulesPathsBuilder = class extends AbstractBuilder2 {
constructor() {
super(...arguments);
this.settings = null;
}
doBuild() {
this.settings = new import_obsidian12.Setting(this.container).setName(t2("rule.path.name")).addDropdown(
(e) => e.addOptions({ white: t2("rule.path.white.name"), black: t2("rule.path.black.name") }).setValue(this.item.get("mode").value()).onChange((e2) => {
this.item.get("mode").set(e2);
this.updateDesc();
})
).addTextArea(
(e) => e.setValue(this.item.get("values").value().join("\n")).onChange((e2) => this.item.get("values").set(e2.split("\n").filter((e3) => e3)))
);
this.updateDesc();
}
support(k) {
return k === "paths";
}
updateDesc() {
const descriptions = {
white: t2("rule.path.white.desc"),
black: t2("rule.path.black.desc")
};
this.settings.setDesc(descriptions[this.item.get("mode").value()]);
}
};
RulesPathsBuilder = __decorateClass([
injectable()
], RulesPathsBuilder);
// src/Settings/SettingBuilders/Processor/ProcessorBuilder.ts
var import_obsidian13 = require("obsidian");
// src/Components/Processor/ProcessorUtils.ts
var ProcessorTypes = /* @__PURE__ */ ((ProcessorTypes2) => {
ProcessorTypes2["Function"] = "function";
ProcessorTypes2["Replace"] = "replace";
return ProcessorTypes2;
})(ProcessorTypes || {});
// src/Settings/SettingBuilders/Processor/ProcessorBuilder.ts
var ProcessorBuilder = class extends AbstractBuilder2 {
constructor() {
super(...arguments);
this.lastArgs = {};
}
support(k) {
return k === "processor";
}
doBuild() {
const fragment = createFragment(
(e) => e.createEl("a", {
text: t2("processor.name"),
href: GITHUB_DOCS + "Processor.md"
})
);
this.setting = new import_obsidian13.Setting(this.container).setName(fragment);
this.buildDynamic();
}
updateDesc() {
const fragment = createFragment();
fragment.appendText(t2("processor.desc"));
let additional = [];
switch (this.item.get("type").value()) {
case "replace" /* Replace */:
additional = [
"",
t2("processor.replace.desc"),
"title.replace(",
createSpan(
"",
(e) => e.innerHTML = " new RegExp(
#pattern#,
#flags#
),"
),
createSpan("", (e) => e.innerHTML = " #replacement#"),
")"
];
break;
case "function" /* Function */:
additional = [
"",
t2("processor.function.desc"),
`const value = new Function('title', #${t2("processor.function.valueDesc")}#)`
];
break;
}
additional.forEach((e) => {
fragment.appendChild(createEl("br"));
typeof e === "string" ? fragment.appendText(e) : fragment.appendChild(e);
});
this.setting.setDesc(fragment);
}
buildDynamic() {
this.updateDesc();
this.setting.addDropdown(
(c) => {
var _a;
return c.addOptions({
"": t2("disabled"),
["replace" /* Replace */]: t2("processor.replace.name"),
["function" /* Function */]: t2("processor.function.name")
}).setValue((_a = this.item.get("type").value()) != null ? _a : "").onChange((v) => {
var _a2, _b;
const value = v === "" ? null : v;
const type = this.item.get("type").value();
this.lastArgs[type] = [...this.item.get("args").value()];
this.item.get("type").set(value);
this.item.get("args").set([...(_b = (_a2 = this.lastArgs) == null ? void 0 : _a2[value]) != null ? _b : []]);
this.setting.controlEl.innerHTML = "";
this.buildDynamic();
});
}
);
this.setAlignItemsMode("center");
switch (this.item.get("type").value()) {
case "function" /* Function */:
this.setAlignItemsMode("start");
return this.buildFunction();
case "replace" /* Replace */:
this.setAlignItemsMode("start");
return this.buildReplace();
}
}
setAlignItemsMode(mode) {
this.setting.settingEl.style.alignItems = mode;
this.setting.controlEl.style.alignItems = mode;
}
buildReplace() {
const items = [
{
name: t2("processor.replace.pattern.name"),
desc: t2("processor.replace.pattern.desc")
},
{ name: t2("processor.replace.flags.name"), desc: t2("processor.replace.flags.desc") },
{ name: t2("processor.replace.replacement.name"), desc: t2("processor.replace.replacement.desc") }
];
const container = createDiv({ attr: { style: "margin-left: 20px" } });
let margin = "10px";
const value = this.item.get("args").value();
for (const [i, item] of items.entries()) {
const c = createDiv({
attr: { style: `margin-bottom: ${margin}` }
});
margin = "0px";
c.appendChild(
createDiv(
{
attr: { style: "display: flex; align-items: center; justify-content: space-between;" }
},
(e) => {
var _a;
e.appendChild(
createDiv({ attr: { style: "margin-right: 10px" } }, (e2) => e2.appendText(`${item.name}:`))
);
new import_obsidian13.TextComponent(e).setValue((_a = value == null ? void 0 : value[i]) != null ? _a : "").onChange((e2) => value.splice(i, 1, e2)).onChanged();
}
)
);
c.appendChild(
createDiv(
{ cls: "setting-item-description", attr: { style: "text-align: left" } },
(e) => e.appendText(item.desc)
)
);
container.appendChild(c);
}
this.setting.controlEl.prepend(container);
}
buildFunction() {
this.setting.addTextArea(
(e) => e.setValue(this.item.get("args").value().join()).onChange((e2) => this.item.get("args").set([e2]))
);
}
};
// src/Settings/FeatureBuilder/NoteLinkBuilder.ts
var import_obsidian14 = require("obsidian");
var NoteLinkBuilder = class extends AbstractBuilder {
build({ id: id3, name, desc, settings, doc }) {
var _a;
this.id = id3;
const fragment = createFragment((e) => e.createEl("a", { text: name, href: doc.link }));
this.setting = new import_obsidian14.Setting(this.context.getContainer()).setName(fragment).setDesc(desc);
this.setting.addDropdown((e) => this.strategy = e);
this.strategy.addOptions({
["all" /* All */]: t2("feature.noteLink.strategy.all"),
["onlyEmpty" /* OnlyEmpty */]: t2("feature.noteLink.strategy.onlyEmpty")
}).setValue((_a = settings.strategy) != null ? _a : "onlyEmpty" /* OnlyEmpty */).onChange(this.onChange.bind(this));
this.setting.addDropdown((e) => this.approval = e);
this.approval.addOptions({ Y: t2("feature.noteLink.approval.showModal"), N: t2("feature.noteLink.approval.auto") }).setValue(settings.approval ? "Y" : "N").onChange(this.onChange.bind(this));
this.setting.addToggle((e) => this.toggle = e);
this.toggle.setValue(settings.enabled).onChange(this.onChange.bind(this));
}
onChange() {
this.context.getDispatcher().dispatch(
"settings:tab:feature:changed",
new Event({
id: this.id,
value: {
enabled: this.toggle.getValue(),
approval: this.approval.getValue() === "Y",
strategy: this.strategy.getValue()
}
})
);
}
};
// config/services/settings.config.ts
var settings_config_default = (c) => {
c.bind(inversify_types_default["settings:feature:builder"]).toDynamicValue(() => new DefaultBuilder()).whenTargetNamed("default");
c.bind(inversify_types_default["settings:feature:builder"]).toDynamicValue(() => new AliasBuilder()).whenTargetNamed("alias" /* Alias */);
c.bind(inversify_types_default["settings:feature:builder"]).toDynamicValue(() => new ExplorerSortBuilder()).whenTargetNamed("explorer:sort" /* ExplorerSort */);
c.bind(inversify_types_default["settings:feature:builder"]).toDynamicValue(() => new NoteLinkBuilder()).whenTargetNamed("noteLink" /* NoteLink */);
c.bind(inversify_types_default["factory:settings:feature:builder"]).toFunction(
(name) => c.isBoundNamed(inversify_types_default["settings:feature:builder"], name) ? c.getNamed(inversify_types_default["settings:feature:builder"], name) : null
);
c.bind(inversify_types_default["settings:builder"]).to(TemplatesBuilder).whenTargetNamed("main");
c.bind(inversify_types_default["settings:builder"]).to(FeaturesBuilder).whenTargetNamed("main");
c.bind(inversify_types_default["settings:builder"]).to(UtilBuilder).whenTargetNamed("main");
c.bind(inversify_types_default["settings:builder"]).to(RulesBuiler).whenTargetNamed("main");
c.bind(inversify_types_default["settings:builder"]).to(ProcessorBuilder).whenTargetNamed("main");
c.bind(inversify_types_default["settings:builder"]).to(RulesDelimiterBuilder).whenTargetNamed("rules");
c.bind(inversify_types_default["settings:builder"]).to(RulesPathsBuilder).whenTargetNamed("rules");
c.bind(inversify_types_default["factory:settings:builder"]).toFunction(
(name) => c.getAllNamed(inversify_types_default["settings:builder"], name)
);
};
// src/Components/Processor/ReplaceProcessor.ts
var ReplaceProcessor = class {
constructor(args) {
var _a, _b;
try {
this.pattern = new RegExp((_a = args == null ? void 0 : args[0]) != null ? _a : null, args == null ? void 0 : args[1]);
this.replacement = (_b = args == null ? void 0 : args[2]) != null ? _b : null;
} catch (e) {
console.error(e);
}
}
process(value) {
return value.replace(this.pattern, this.replacement);
}
};
ReplaceProcessor = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["processor:args"]))
], ReplaceProcessor);
// src/Components/Processor/FunctionProcessor.ts
var FunctionProcessor = class {
constructor(args) {
this.func = (args == null ? void 0 : args[0]) ? new Function("title", args[0]) : null;
}
process(value) {
var _a, _b;
return (_b = (_a = this.func) == null ? void 0 : _a.call(this, value)) != null ? _b : value;
}
};
FunctionProcessor = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["processor:args"]))
], FunctionProcessor);
// config/services/processors.config.ts
var processors_config_default = new ContainerModule((bind) => {
bind(inversify_types_default.processor).to(ReplaceProcessor).whenTargetNamed("replace" /* Replace */);
bind(inversify_types_default.processor).to(FunctionProcessor).whenTargetNamed("function" /* Function */);
bind(inversify_types_default["processor:args"]).toDynamicValue((c) => c.container.get(inversify_types_default["settings:storage"]).get("processor").get("args").value());
bind(inversify_types_default["factory:processor"]).toAutoNamedFactory(inversify_types_default.processor);
});
// src/Resolver/ResolverService.ts
var ResolverService = class {
constructor(factory, templateFactory, logger) {
this.factory = factory;
this.templateFactory = templateFactory;
this.logger = logger;
this.resolvers = /* @__PURE__ */ new Map();
}
create(template) {
this.logger.log(`Create "${template}" template`);
return this.getOrCreate(template);
}
createNamed(name) {
this.logger.log(`Create named "${name}" template`);
return this.create(this.templateFactory(name));
}
getOrCreate(template) {
if (!this.resolvers.has(template)) {
this.logger.log(`Create resolver for "${template}" template`);
const resolver = this.factory();
resolver.setTemplate(template);
this.resolvers.set(template, resolver);
}
return this.resolvers.get(template);
}
};
ResolverService = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:resolver:resolver"])),
__decorateParam(1, inject(inversify_types_default["factory:resolver:template"])),
__decorateParam(2, inject(inversify_types_default.logger)),
__decorateParam(2, named("resolver:service"))
], ResolverService);
// src/Resolver/ResolverCachedProxy.ts
var ResolverCachedProxy = class {
constructor(resolver, cache, dispatcher) {
this.resolver = resolver;
this.cache = cache;
this.dispatcher = dispatcher;
dispatcher.addListener({ name: "resolver:clear", cb: () => this.cache.clear(), sort: 0 });
dispatcher.addListener({ name: "metadata:cache:changed", cb: (e) => this.handleDelete(e.get().path), sort: 0 });
dispatcher.addListener({
name: "file:rename",
cb: (e) => {
this.cache.delete(e.get().old);
this.cache.save(this.cache.getItem(e.get().actual).set(null));
this.handleDelete(e.get().actual);
}
});
}
handleDelete(path) {
const item = this.cache.getItem(path);
if (!item.isHit()) {
return;
}
const old = item.get();
this.actualize(item);
if (old !== item.get()) {
this.dispatcher.dispatch("resolver:unresolved", new Event({ path }));
}
}
resolve(path) {
return this.get(path);
}
actualize(item) {
const title = this.resolver.resolve(item.getKey());
this.cache.save(item.set(title));
}
get(path) {
var _a;
const item = this.cache.getItem(path);
if (item.isHit() === false) {
this.actualize(item);
}
return (_a = item.get()) != null ? _a : null;
}
setTemplate(template) {
this.resolver.setTemplate(template);
}
};
ResolverCachedProxy = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default.resolver)),
__decorateParam(0, named("original")),
__decorateParam(1, inject(inversify_types_default.cache)),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"]))
], ResolverCachedProxy);
// src/Resolver/Resolver.ts
var Resolver = class {
constructor(filters, creator, dispatcher) {
this.filters = filters;
this.creator = creator;
this.dispatcher = dispatcher;
this.template = "";
}
setTemplate(template) {
this.template = template;
}
resolve(path) {
return this.valid(path) ? this.get(path) : null;
}
get(path) {
var _a;
try {
return (_a = this.dispatch(this.creator.create(path, this.template))) != null ? _a : null;
} catch (e) {
console.error(`Error by path ${path}`, e);
}
return null;
}
dispatch(title) {
var _a;
const event = new Event({
value: title,
modify(v) {
this.value = v;
}
});
this.dispatcher.dispatch("resolver:resolved", event);
return (_a = event.get().value) != null ? _a : null;
}
valid(path) {
for (const filter of this.filters) {
if (filter.check(path) === false) {
return false;
}
}
return true;
}
};
Resolver = __decorateClass([
injectable(),
__decorateParam(0, multiInject(inversify_types_default.filter)),
__decorateParam(1, inject(inversify_types_default["creator:creator"])),
__decorateParam(2, inject(inversify_types_default["event:dispatcher"]))
], Resolver);
// config/services/resolver.config.ts
var resolver_config_default = new ContainerModule((bind) => {
bind(inversify_types_default["factory:resolver:template"]).toFactory((c) => (value) => {
var _a, _b;
const storage = c.container.get(inversify_types_default["settings:storage"]);
const [name, type] = value.split(":");
const targetTemplates = storage.get("templates").get(name);
return (_b = (_a = targetTemplates == null ? void 0 : targetTemplates.get(type)) == null ? void 0 : _a.value()) != null ? _b : storage.get("templates").get("common").get(type).value();
});
bind(inversify_types_default.resolver).to(ResolverCachedProxy).whenTargetIsDefault();
bind(inversify_types_default.resolver).to(Resolver).whenTargetNamed("original");
bind(inversify_types_default["resolver:service"]).to(ResolverService).inSingletonScope();
bind(
inversify_types_default["factory:resolver:resolver"]
).toFactory((c) => () => c.container.get(inversify_types_default.resolver));
});
// src/Components/ApiAdapter/Api.ts
var Api = class {
constructor(factory, dispatcher, composer) {
this.factory = factory;
this.dispatcher = dispatcher;
this.composer = composer;
}
getResolverFactory() {
return this.factory;
}
getEventDispatcher() {
return this.dispatcher;
}
getEnabledFeatures() {
return this.composer.getIds();
}
};
Api = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["feature:service"])),
__decorateParam(1, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(2, inject(inversify_types_default["feature:composer"]))
], Api);
// src/Components/ApiAdapter/Defer.ts
var DeferPluginReady = 2;
var DeferFeaturesReady = 4;
var Defer = class {
constructor(factory) {
this.factory = factory;
this.state = 0;
this.promises = {
plugin: null,
managers: null
};
this.resolves = {
plugin: null,
managers: null
};
this.promises.plugin = new Promise((r) => this.resolves.plugin = r);
this.promises.managers = new Promise((r) => this.resolves.managers = r);
}
setFlag(flag) {
if (!(this.state & flag)) {
this.state = this.state | flag;
this.processState();
}
}
processState() {
if (this.isPluginReady()) {
this.resolves.plugin();
if (this.isFeaturesReady()) {
this.resolves.managers();
}
}
}
async awaitPlugin() {
return await this.promises.plugin;
}
async awaitFeatures() {
return this.promises.managers;
}
isPluginReady() {
return (this.state & DeferPluginReady) !== 0;
}
isFeaturesReady() {
return (this.state & DeferFeaturesReady) !== 0;
}
getApi() {
return this.isPluginReady() ? this.factory() : null;
}
};
Defer = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["factory:api"]))
], Defer);
// config/services/api.adapter.config.ts
var api_adapter_config_default = new ContainerModule((bind) => {
bind(inversify_types_default.api).to(Api).inSingletonScope();
bind(inversify_types_default["factory:api"]).toFactory((c) => () => c.container.get(inversify_types_default.api));
bind(inversify_types_default.defer).to(Defer).inSingletonScope();
});
// src/Filters/ExtensionFilter.ts
var ExtensionFilter = class {
check(path) {
return /.*\.md$/.test(path);
}
};
ExtensionFilter = __decorateClass([
injectable()
], ExtensionFilter);
// src/Filters/PathListFilter.ts
var PathListFilter = class {
constructor(list) {
this.list = list;
}
check(path) {
return this.list.isFileAllowed(path);
}
};
PathListFilter = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["component:black_white_list"]))
], PathListFilter);
// src/Components/BlackWhiteList/BlackWhiteList.ts
var BlackWhiteList = class {
constructor() {
this.mode = "black";
this.list = [];
}
get default() {
return this.mode === "black";
}
isFileAllowed(path) {
if (this.list.length === 0) {
return true;
}
for (const item of this.list) {
if (path.startsWith(item)) {
return this.mode === "white";
}
}
return this.default;
}
setMode(mode) {
this.mode = mode;
}
setList(list) {
this.list = [...list];
}
};
BlackWhiteList = __decorateClass([
injectable()
], BlackWhiteList);
// src/Components/Cache/CacheItem.ts
var CacheItem = class {
constructor(_isHit, value, key) {
this._isHit = _isHit;
this.value = value;
this.key = key;
}
get() {
return this.value;
}
isHit() {
return this._isHit;
}
set(value) {
this.value = value;
return this;
}
getKey() {
return this.key;
}
};
// src/Components/Cache/Cache.ts
var Cache = class {
constructor() {
this.pool = /* @__PURE__ */ new Map();
this.serialized = /* @__PURE__ */ new Map();
}
clear() {
this.pool.clear();
this.serialized.clear();
}
delete(key) {
this.pool.delete(key);
this.serialized.delete(key);
}
getItem(key) {
const isHit = this.pool.has(key) || this.serialized.has(key);
const value = isHit ? this.resolve(key) : null;
return new CacheItem(isHit, value, key);
}
resolve(key) {
if (this.pool.has(key)) {
return this.pool.get(key);
}
return JSON.parse(this.serialized.get(key));
}
save(item) {
const key = item.getKey();
const value = item.get();
this.pool.delete(key);
this.serialized.delete(key);
if (this.isObject(value)) {
if (!this.canBeSerialized(value)) {
throw new Error("Object with functions can not be serialized");
}
this.serialized.set(key, JSON.stringify(value));
} else {
this.pool.set(key, value);
}
}
isObject(value) {
return typeof value === "object" && ![null, void 0].includes(value);
}
canBeSerialized(object) {
return !ObjectHelper.values(object).some(
(e) => this.isObject(e) ? !this.canBeSerialized(e) : typeof e === "function"
);
}
};
Cache = __decorateClass([
injectable()
], Cache);
// src/Components/Extractor/Extractor.ts
var Extractor = class {
constructor(strategies) {
this.strategies = strategies;
}
/**
* @throws {PathNotFoundException}
* @throws {TypeNotSupportedException}
* @param path
* @param obj
*/
extract(path, obj) {
const parts = path.split(".");
let part;
let extracted = obj;
while (part = parts.shift()) {
extracted = this.extractInternal(part, extracted);
}
let strategy = null;
let type = extracted === null ? "null" : typeof extracted;
type = type === "object" && Array.isArray(extracted) ? "array" : type;
for (const item of this.strategies) {
if (item.support(type)) {
strategy = item;
break;
}
}
if (strategy === null) {
throw new TypeNotSupportedException(`Type ${type} is not supported`);
}
return strategy.process(extracted);
}
/**
* @throws {PathNotFoundException}
* @param key
* @param obj
* @private
*/
extractInternal(key, obj) {
if (obj === void 0 || (obj == null ? void 0 : obj[key]) === void 0) {
throw new PathNotFoundException(`Key ${key} not found`);
}
return obj[key];
}
};
Extractor = __decorateClass([
injectable(),
__decorateParam(0, multiInject(inversify_types_default["component:extractor:strategy"]))
], Extractor);
// src/Components/Extractor/LiteralStrategy.ts
var LiteralStrategy = class {
support(type) {
return ["number", "string"].includes(type);
}
process(v) {
return v.toString();
}
};
LiteralStrategy = __decorateClass([
injectable()
], LiteralStrategy);
// src/Components/Extractor/ArrayStrategy.ts
var ArrayStrategy = class {
constructor(delimiterGetter) {
this.delimiterGetter = delimiterGetter;
}
process(v) {
if (v.length === 0) {
return null;
}
const delimiter = this.delimiterGetter();
return !delimiter.enabled ? v[0] : v.join(delimiter.value);
}
support(type) {
return type === "array";
}
};
ArrayStrategy = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["getter:delimiter"]))
], ArrayStrategy);
// src/Components/Extractor/NullStrategy.ts
var NullStrategy = class {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
process(v) {
return null;
}
support(type) {
return type === "null";
}
};
NullStrategy = __decorateClass([
injectable()
], NullStrategy);
// src/Components/Debug/Debugger.ts
var Debugger = class {
constructor(name, enabled) {
this.name = name;
this.enabled = enabled;
}
log(...value) {
if (this.enabled()) {
console.debug(`[${this.name}]`, ...value);
}
}
};
Debugger = __decorateClass([
injectable()
], Debugger);
// src/Components/Debug/LoggerComposer.ts
var LoggerComposer = class {
constructor() {
this.loggers = /* @__PURE__ */ new Map();
this.enabled = false;
}
create(name) {
if (!this.loggers.has(name)) {
this.loggers.set(name, new Debugger(name, this.isEnabled.bind(this)));
}
return this.loggers.get(name);
}
isEnabled() {
return this.enabled;
}
enable() {
this.enabled = true;
}
disable() {
this.enabled = false;
}
};
LoggerComposer = __decorateClass([
injectable()
], LoggerComposer);
// src/Utils/FileNoteLinkService.ts
var import_obsidian15 = require("obsidian");
var FileNoteLinkService = class {
constructor(facade) {
this.facade = facade;
this.REGEXP = /^\[\[.+\]\]$/;
}
getNoteLinks(path) {
var _a;
const links = this.facade.getFileLinksCache(path);
const result = [];
for (const link of links) {
if (!this.REGEXP.test(link.original)) {
continue;
}
const file = this.facade.getFirstLinkpathDest(link.link, path);
if (file instanceof import_obsidian15.TFile === false) {
continue;
}
result.push({
dest: file.path,
link: link.link,
original: link.original,
alias: (_a = link == null ? void 0 : link.displayText) != null ? _a : null
});
}
return result;
}
};
FileNoteLinkService = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["facade:obsidian"]))
], FileNoteLinkService);
// src/Components/EventDispatcher/EventDispatcher.ts
var EventDispatcher = class {
constructor(logger) {
this.logger = logger;
this.events = /* @__PURE__ */ new Map();
}
addListener({ name, cb, sort = null, once = false }) {
var _a, _b, _c;
const ref = { getName: () => name };
const events = (_a = this.events.get(name)) != null ? _a : [];
sort = sort != null ? sort : ((_c = (_b = events[0]) == null ? void 0 : _b.sort) != null ? _c : 0) + 1;
const event = { cb, sort, ref, once };
events.push(event);
events.sort((a, b) => a.sort - b.sort);
this.logger.log(`Added listener: ${name.toString()}`, event);
this.events.set(name, events);
return ref;
}
dispatch(name, e) {
var _a, _b;
this.logger.log(name);
let shift = 0;
for (const [i, item] of [...(_b = (_a = this.events.get(name)) == null ? void 0 : _a.entries()) != null ? _b : []]) {
item.cb(e);
if (item.once) {
this.events.get(name).splice(i - shift++, 1);
}
}
}
removeListener(ref) {
for (const [i, item] of this.events.get(ref.getName()).entries()) {
if (item.ref === ref) {
this.events.get(ref.getName()).splice(i, 1);
this.logger.log(`Removed listener: ${ref.getName().toString()}`);
return;
}
}
}
};
EventDispatcher = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default.logger)),
__decorateParam(0, named("event:dispatcher"))
], EventDispatcher);
// src/Components/BlackWhiteList/BlackWhiteListListener.ts
var BlackWhiteListListener = class {
constructor(component, dispatcher) {
this.component = component;
this.dispatcher = dispatcher;
this.ref = null;
}
bind() {
this.ref = this.dispatcher.addListener({ name: "settings:changed", cb: (e) => this.handle(e.get()) });
this.dispatcher.addListener({
name: "settings.loaded",
once: true,
cb: (e) => {
this.component.setMode(e.get().settings.rules.paths.mode);
this.component.setList(e.get().settings.rules.paths.values);
}
});
}
handle({ changed, actual }) {
var _a, _b, _c, _d;
if ((_b = (_a = changed == null ? void 0 : changed.rules) == null ? void 0 : _a.paths) == null ? void 0 : _b.values) {
this.component.setList(actual.rules.paths.values);
}
if ((_d = (_c = changed == null ? void 0 : changed.rules) == null ? void 0 : _c.paths) == null ? void 0 : _d.mode) {
this.component.setMode(actual.rules.paths.mode);
}
}
unbind() {
this.dispatcher.removeListener(this.ref);
this.ref = null;
}
};
BlackWhiteListListener = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["component:black_white_list"])),
__decorateParam(1, inject(inversify_types_default["event:dispatcher"]))
], BlackWhiteListListener);
// src/Components/Processor/ProccessorListener.ts
var ProcessorListener = class {
constructor(dispatcher, factory) {
this.dispatcher = dispatcher;
this.factory = factory;
this.changedRef = null;
this.resolvedRef = null;
this.processor = null;
}
bind() {
this.changedRef = this.dispatcher.addListener({ name: "settings:changed", cb: (e) => this.make(e.get().actual) });
this.dispatcher.addListener({ name: "settings.loaded", cb: (e) => this.make(e.get().settings), once: true });
}
unbind() {
this.dispatcher.removeListener(this.changedRef);
this.changedRef = null;
this.disable();
}
make(actual) {
const { type, args } = actual.processor;
if (Object.values(ProcessorTypes).includes(type)) {
this.enable(type, args);
} else {
this.disable();
}
}
disable() {
if (this.resolvedRef) {
this.dispatcher.removeListener(this.resolvedRef);
this.resolvedRef = null;
}
this.processor = null;
}
enable(type, args) {
this.processor = this.factory(type, args);
if (this.resolvedRef === null) {
this.resolvedRef = this.dispatcher.addListener({
name: "resolver:resolved",
cb: this.handleResolved.bind(this)
});
}
}
handleResolved(event) {
var _a, _b;
const obj = event.get();
if (typeof obj.value !== "string") {
return;
}
const value = (_b = (_a = this.processor) == null ? void 0 : _a.process(obj.value)) != null ? _b : null;
if (value) {
obj.modify(value);
}
}
};
ProcessorListener = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default["event:dispatcher"])),
__decorateParam(1, inject(inversify_types_default["factory:processor"]))
], ProcessorListener);
// src/Utils/FakeTitleElementService.ts
var FakeTitleElementService = class {
constructor() {
this.attr = {
fake: "ofmt-fake-id",
original: "ofmt-original-id"
};
this.elements = /* @__PURE__ */ new Map();
//TODO: add logs for events
this.events = {
click: (e) => {
const id3 = this.extractId(e.target);
this.setVisible(id3, false).getOriginal(id3).focus();
},
blur: (e) => this.setVisible(this.extractId(e.target), true),
hover: (e) => this.setVisible(this.extractId(e.target), false),
out: (e) => this.setVisible(this.extractId(e.target), true)
};
}
extractId(e) {
var _a;
if (e instanceof HTMLElement) {
return (_a = e.getAttribute(this.attr.fake)) != null ? _a : e.getAttribute(this.attr.original);
}
return null;
}
getOriginal(id3) {
var _a, _b;
return (_b = (_a = this.elements.get(id3)) == null ? void 0 : _a.original) != null ? _b : null;
}
has(id3) {
return this.elements.has(id3);
}
removeExcept(id3) {
const ids = Array.isArray(id3) ? id3 : [id3];
for (const [key, { fake }] of this.elements.entries()) {
if (!ids.includes(key)) {
fake.remove();
this.elements.delete(key);
}
}
}
remove(id3) {
if (!this.has(id3)) {
return;
}
this.setVisible(id3, false);
const { fake, events = [], original } = this.elements.get(id3);
events.forEach((e) => {
if (e === "click") {
original.removeEventListener("click", this.events.blur);
}
if (e === "hover") {
original.removeEventListener("mouseout", this.events.out);
}
});
original.removeAttribute(this.attr.original);
fake.remove();
this.elements.delete(id3);
}
removeAll() {
Array.from(this.elements.keys()).forEach((e) => this.remove(e));
}
getOrCreate({
original,
title,
id: id3,
events = []
}) {
const container = original == null ? void 0 : original.parentElement;
if (!container) {
return;
}
let element = this.find(container, id3);
if (element) {
element.setText(title);
return { created: false, element };
}
element = document.createElement(original.tagName);
element.className = original.className;
element.setText(title);
element.setAttribute(this.attr.fake, id3);
original.setAttribute(this.attr.original, id3);
this.elements.set(id3, { original, fake: element, events: [...events] });
if (events.contains("click")) {
this.bindClick(id3);
}
if (events.contains("hover")) {
this.bindHover(id3);
}
container.insertBefore(element, original);
return { created: true, element };
}
setVisible(id3, visible) {
if (this.elements.has(id3)) {
const { fake, original } = this.elements.get(id3);
original.hidden = visible;
fake.hidden = !visible;
}
return this;
}
bindClick(id3) {
if (this.has(id3)) {
const { fake, original } = this.elements.get(id3);
fake.addEventListener("click", this.events.click);
original.addEventListener("blur", this.events.blur);
}
}
bindHover(id3) {
if (this.has(id3)) {
const { fake, original } = this.elements.get(id3);
fake.addEventListener("mouseover", this.events.hover);
original.addEventListener("mouseout", this.events.out);
}
}
find(container, id3) {
for (const node of Array.from(container.children)) {
const cId = node.getAttribute(this.attr.fake);
if (id3 === cId && node instanceof HTMLElement) {
return node;
}
}
return null;
}
};
FakeTitleElementService = __decorateClass([
injectable()
], FakeTitleElementService);
// src/Components/Extractor/BooleanStrategy.ts
var BooleanStrategy = class {
process(v) {
return v ? "true" : "false";
}
support(type) {
return "boolean" === type;
}
};
BooleanStrategy = __decorateClass([
injectable()
], BooleanStrategy);
// src/Utils/ResultDomWrapper.ts
var ResultDomWrapper = class {
constructor(resolver = null, dom) {
this.resolver = resolver;
this.replacer = null;
this.replacer = FunctionReplacer.create(dom, "addResult", this, (self2, defaultArgs, vanilla) => {
const c = vanilla.call(dom, ...defaultArgs);
const file = defaultArgs[0];
self2.processLookupItem(file, c);
return c;
});
this.replacer.enable();
this.process();
}
disable() {
this.replacer.disable();
this.replacer = null;
}
process() {
var _a, _b, _c;
const lookup = (_c = (_b = (_a = this.replacer) == null ? void 0 : _a.getTarget()) == null ? void 0 : _b.resultDomLookup) != null ? _c : /* @__PURE__ */ new Map();
for (const [file, item] of lookup) {
this.processLookupItem(file, item);
}
}
processLookupItem(file, item) {
var _a, _b;
const restore = !((_a = this == null ? void 0 : this.replacer) == null ? void 0 : _a.isEnabled());
if (file.extension !== "md") {
return;
}
const node = item.containerEl.firstElementChild.find(".tree-item-inner");
const text = (_b = restore ? null : this.resolver.resolve(file.path)) != null ? _b : file.basename;
if (node.getText() !== text) {
node.setText(text);
}
}
};
// src/Utils/SearchDomWrapperService.ts
var SearchDomWrapperService = class {
constructor(logger) {
this.logger = logger;
this.entities = /* @__PURE__ */ new Map();
this.timer = null;
}
wrapDom(dom, resolver, tag) {
if (!this.entities.has(tag)) {
this.entities.set(tag, /* @__PURE__ */ new Map());
}
const tagged = this.entities.get(tag);
if (!tagged.has(dom)) {
const wrapper = new ResultDomWrapper(resolver, dom);
tagged.set(dom, wrapper);
this.logger.log(`Entity created`);
this.runTimer();
}
}
destroyByTag(tag) {
if (!this.entities.has(tag)) {
return;
}
for (const [dom, wrapper] of this.entities.get(tag)) {
wrapper.disable();
this.entities.get(tag).delete(dom);
}
}
runTimer() {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(this.selfClean.bind(this), 1e4);
}
selfClean() {
this.timer = null;
for (const [tag, entities] of this.entities) {
this.logger.log(`Tag ${tag} has ${entities.size} entities before self-clean`);
for (const [dom, wrapper] of entities) {
if (!document.body.contains(dom.el)) {
wrapper.disable();
this.logger.log(`Dom from ${tag} tag has been removed`);
this.entities.get(tag).delete(dom);
}
}
this.logger.log(`Tag ${tag} has ${entities.size} entities after self-clean`);
}
}
};
SearchDomWrapperService = __decorateClass([
injectable(),
__decorateParam(0, inject(inversify_types_default.logger)),
__decorateParam(0, named(SearchDomWrapperService.name))
], SearchDomWrapperService);
// config/inversify.config.ts
var Container2 = new Container();
Container2.bind(inversify_types_default["event:dispatcher"]).to(EventDispatcher).inSingletonScope();
Container2.bind(inversify_types_default["template:pattern"]).toConstantValue("(?{{[^{}]+?}})");
Container2.bind(inversify_types_default.filter).to(ExtensionFilter);
Container2.bind(inversify_types_default.filter).to(PathListFilter);
Container2.bind(inversify_types_default["component:black_white_list"]).to(BlackWhiteList).inSingletonScope();
Container2.bind(inversify_types_default.cache).to(Cache);
Container2.bind(inversify_types_default["component:extractor"]).to(Extractor);
Container2.bind(inversify_types_default["component:extractor:strategy"]).to(LiteralStrategy);
Container2.bind(inversify_types_default["component:extractor:strategy"]).to(ArrayStrategy);
Container2.bind(inversify_types_default["component:extractor:strategy"]).to(NullStrategy);
Container2.bind(inversify_types_default["component:extractor:strategy"]).to(BooleanStrategy);
Container2.bind(inversify_types_default["logger:composer"]).to(LoggerComposer).inSingletonScope();
Container2.bind(inversify_types_default.logger).toDynamicValue((context) => {
return context.container.get(inversify_types_default["logger:composer"]).create(context.currentRequest.target.getNamedTag().value);
}).when(() => true);
Container2.bind(inversify_types_default["service:note:link"]).to(FileNoteLinkService).inSingletonScope();
Container2.bind(inversify_types_default["service:fake_title_element"]).to(FakeTitleElementService);
Container2.bind(inversify_types_default.listener).to(BlackWhiteListListener).whenTargetNamed("unnamed");
Container2.bind(inversify_types_default.listener).to(ProcessorListener).whenTargetNamed("unnamed");
Container2.load(creator_config_default);
feature_config_default(Container2);
settings_config_default(Container2);
Container2.load(processors_config_default);
Container2.load(resolver_config_default);
Container2.load(api_adapter_config_default);
Container2.bind(inversify_types_default["factory:replacer"]).toFunction(
(t3, m, a, i) => FunctionReplacer.create(t3, m, a, i)
);
Container2.bind(inversify_types_default["service:search:dom:wrapper"]).to(SearchDomWrapperService).inSingletonScope();
var inversify_config_default = Container2;
// src/App.ts
var App2 = class {
constructor() {
this.container = inversify_config_default;
this.bind();
}
bind() {
const dispatcher = this.container.get(inversify_types_default["event:dispatcher"]);
dispatcher.addListener({
name: "settings:changed",
cb: (e) => this.onSettingsChanged(e.get())
});
dispatcher.addListener({
name: "settings.loaded",
once: true,
cb: (e) => this.init(e.get().settings)
});
}
init(settings) {
this.container.bind(inversify_types_default.delimiter).toConstantValue(settings.rules.delimiter);
this.container.get(inversify_types_default["logger:composer"])[settings.debug ? "enable" : "disable"]();
}
onSettingsChanged({ actual, changed }) {
var _a;
if ((_a = changed == null ? void 0 : changed.rules) == null ? void 0 : _a.delimiter) {
this.container.rebind(inversify_types_default.delimiter).toConstantValue(actual.rules.delimiter);
}
if (changed.debug) {
this.container.get(inversify_types_default["logger:composer"])[actual.debug ? "enable" : "disable"]();
}
const dispatcher = this.container.get(inversify_types_default["event:dispatcher"]);
dispatcher.dispatch("resolver:clear", null);
}
};
App2 = __decorateClass([
injectable()
], App2);
// src/Utils/PluginHelper.ts
var PluginHelper = class {
static createDefaultSettings() {
return {
templates: {
common: { main: "title", fallback: "fallback_title" },
...Object.fromEntries(Object.values(Feature).map((e) => [e, { main: null, fallback: null }]))
},
rules: {
paths: {
mode: "black",
values: []
},
delimiter: {
enabled: false,
value: ""
}
},
debug: false,
boot: {
delay: 1e3
},
features: {
["alias" /* Alias */]: {
enabled: false,
strategy: "ensure" /* Ensure */,
validator: "fr" /* FrontmatterRequired */
},
["explorer" /* Explorer */]: { enabled: false },
["explorer:sort" /* ExplorerSort */]: { enabled: false },
["tab" /* Tab */]: { enabled: false },
["header" /* Header */]: { enabled: false },
["graph" /* Graph */]: { enabled: false },
["starred" /* Starred */]: { enabled: false },
["search" /* Search */]: { enabled: false },
["suggest" /* Suggest */]: { enabled: false },
["inlineTitle" /* InlineTitle */]: { enabled: false },
["canvas" /* Canvas */]: { enabled: false },
["backlink" /* Backlink */]: { enabled: false },
["noteLink" /* NoteLink */]: { enabled: false, strategy: "onlyEmpty" /* OnlyEmpty */, approval: true }
},
processor: {
args: [],
type: null
}
};
}
};
// src/Obsidian/ObsidianFacade.ts
var import_obsidian16 = require("obsidian");
var ObsidianFacade = class {
constructor(app) {
this.app = app;
}
isInternalPluginEnabled(id3) {
return this.app.internalPlugins.getEnabledPluginById(id3) !== null;
}
getTFile(path) {
const file = this.app.vault.getAbstractFileByPath(path);
return file instanceof import_obsidian16.TFile ? file : null;
}
getFileContent(file) {
return this.app.vault.cachedRead(file);
}
modifyFile(file, c) {
return this.app.vault.modify(file, c);
}
getFileCache(path) {
return this.app.metadataCache.getCache(path);
}
getFileLinksCache(path) {
var _a, _b;
return (_b = (_a = this.getFileCache(path)) == null ? void 0 : _a.links) != null ? _b : [];
}
getLeavesOfType(type) {
return this.app.workspace.getLeavesOfType(type);
}
getViewsOfType(type) {
return this.getLeavesOfType(type).map((e) => e.view);
}
getFirstLinkpathDest(linkpath, from) {
return this.app.metadataCache.getFirstLinkpathDest(linkpath, from);
}
getActiveLeaf() {
var _a, _b;
return (_b = (_a = this.app.workspace) == null ? void 0 : _a.activeLeaf) != null ? _b : null;
}
};
// main.ts
var MetaTitlePlugin = class extends import_obsidian17.Plugin {
constructor() {
super(...arguments);
this.container = inversify_config_default;
}
getDefer() {
return this.container.get(inversify_types_default.defer);
}
async loadSettings() {
var _a, _b, _c, _d;
const loaded = await this.loadData();
if (Array.isArray(loaded == null ? void 0 : loaded.templates)) {
loaded.templates = {
...PluginHelper.createDefaultSettings().templates,
common: { main: (_b = (_a = loaded.templates) == null ? void 0 : _a[0]) != null ? _b : "title", fallback: (_d = (_c = loaded.templates) == null ? void 0 : _c[1]) != null ? _d : "" }
};
}
const data = ObjectHelper.fillFrom(PluginHelper.createDefaultSettings(), loaded != null ? loaded : {});
this.storage = new Storage(data);
this.container.bind(inversify_types_default["settings:storage"]).toConstantValue(this.storage);
this.addSettingTab(this.container.resolve(SettingsTab).getTab());
}
async onSettingsChange(settings) {
await this.saveData(settings);
this.reloadFeatures();
await this.mc.refresh();
}
async delay() {
const delay = this.storage.get("boot").get("delay").value();
this.logger.log(`Plugin manual delay ${delay}`);
await new Promise((r) => setTimeout(r, delay));
}
async onload() {
this.bindServices();
this.dispatcher = this.container.get(inversify_types_default["event:dispatcher"]);
this.logger = this.container.getNamed(inversify_types_default.logger, "main");
this.app.workspace.on("layout-change", () => this.dispatcher.dispatch("layout:change", null));
this.app.workspace.on("active-leaf-change", () => this.dispatcher.dispatch("active:leaf:change", null));
this.app.workspace.on("file-open", (file) => this.dispatcher.dispatch("file:open", new Event(file)));
new App2();
this.container.getAllNamed(inversify_types_default.listener, "unnamed").map((e) => e.bind());
await this.loadSettings();
this.app.workspace.onLayoutReady(() => this.getDefer().setFlag(DeferPluginReady));
await this.delay();
this.fc = inversify_config_default.get(inversify_types_default["feature:composer"]);
this.mc = inversify_config_default.get(inversify_types_default["manager:composer"]);
this.bind();
this.registerCommands();
}
bindServices() {
inversify_config_default.bind(inversify_types_default["factory:obsidian:file"]).toFactory(
() => (path) => this.app.vault.getAbstractFileByPath(path)
);
inversify_config_default.bind(inversify_types_default["factory:obsidian:meta"]).toFactory(
() => (path, type) => {
var _a;
return (_a = this.app.metadataCache.getCache(path)) == null ? void 0 : _a[type];
}
);
inversify_config_default.bind(inversify_types_default["facade:obsidian"]).toConstantValue(new ObsidianFacade(this.app));
inversify_config_default.bind(inversify_types_default["factory:metadata:cache"]).toFunction(() => this.app.metadataCache);
inversify_config_default.bind(inversify_types_default["obsidian:app"]).toConstantValue(this.app);
inversify_config_default.bind(inversify_types_default["obsidian:plugin"]).toConstantValue(this);
inversify_config_default.bind(inversify_types_default["newable:obsidian:chooser"]).toConstructor(
//@ts-ignore
Object.getPrototypeOf(this.app.workspace.editorSuggest.suggests[0].suggestions).constructor
);
inversify_config_default.bind(inversify_types_default["factory:obsidian:active:file"]).toFunction(() => this.app.workspace.getActiveFile());
inversify_config_default.bind(inversify_types_default["factory:obsidian:modal"]).toFunction(() => new import_obsidian17.Modal(this.app));
}
onunload() {
this.fc.disableAll();
}
bind() {
this.registerEvent(
this.app.metadataCache.on(
"changed",
(file, _, cache) => this.dispatcher.dispatch("metadata:cache:changed", new Event({ path: file.path, cache }))
)
);
this.app.workspace.onLayoutReady(async () => {
this.registerEvent(
this.app.vault.on(
"rename",
({ path: actual }, old) => this.dispatcher.dispatch("file:rename", new Event({ old, actual }))
)
);
this.reloadFeatures();
await this.mc.refresh();
this.getDefer().setFlag(DeferFeaturesReady);
});
this.dispatcher.addListener({
name: "resolver:unresolved",
cb: (e) => this.mc.update(e.get().path).catch(console.error)
});
this.dispatcher.addListener({ name: "settings:changed", cb: (e) => this.onSettingsChange(e.get().actual) });
}
reloadFeatures() {
this.fc.disableAll();
const f = this.storage.get("features");
const states = [];
for (const feature of Object.values(Feature)) {
states.push([feature, f.get(feature).get("enabled").value()]);
}
for (const [id3, state] of states) {
this.fc.toggle(id3, state);
}
}
registerCommands() {
this.addCommand({
id: "ofmt-features-disable",
name: t2("command.features.disable"),
callback: () => this.fc.disableAll()
});
this.addCommand({
id: "ofmt-features-reload",
name: t2("command.features.reload"),
callback: () => {
this.reloadFeatures();
this.mc.refresh().catch(console.error);
}
});
}
};
/*! Bundled license information:
reflect-metadata/Reflect.js:
(*! *****************************************************************************
Copyright (C) Microsoft. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** *)
*/