darkcord
Version:
A NodeJS Package to interact with Discord API
115 lines (114 loc) • 3.35 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Base = exports.Snowflake = void 0;
const Cache_1 = require("../cache/Cache");
const index_1 = require("../utils/index");
var Snowflake;
(function (Snowflake) {
Snowflake.InvalidSnowflakeError = (id) => (0, index_1.MakeError)({
name: "InvalidSnowflake",
message: `${id} is not a snowflake`,
});
function valid(id) {
return Number.isInteger(Number(id));
}
Snowflake.valid = valid;
function getEpoch(id) {
verify(id);
return Math.floor(Number(id) / 4194304);
}
Snowflake.getEpoch = getEpoch;
function getCreatedAt(id) {
verify(id);
return getEpoch(id) + Snowflake.Epoch;
}
Snowflake.getCreatedAt = getCreatedAt;
function getCreatedTimestamp(id) {
verify(id);
return (Number(id) >> 22) + Snowflake.Epoch;
}
Snowflake.getCreatedTimestamp = getCreatedTimestamp;
function getWorkerId(id) {
verify(id);
return (Number(id) & 0x3e0000) >> 17;
}
Snowflake.getWorkerId = getWorkerId;
function getProcessId(id) {
verify(id);
return (Number(id) & 0x1f000) >> 12;
}
Snowflake.getProcessId = getProcessId;
function getIncrement(id) {
verify(id);
return Number(id) & 0xfff;
}
Snowflake.getIncrement = getIncrement;
/**
* Checks if the snowflake is valid and if not, it throw's an error
*/
function verify(id) {
if (!valid(id))
throw Snowflake.InvalidSnowflakeError(id);
return true;
}
Snowflake.verify = verify;
function deconstruct(id) {
return {
timestamp: getCreatedTimestamp(id),
createdAt: getCreatedAt(id),
workerId: getWorkerId(id),
processId: getProcessId(id),
increment: getIncrement(id),
};
}
Snowflake.deconstruct = deconstruct;
Snowflake.Epoch = 1420070400000;
})(Snowflake = exports.Snowflake || (exports.Snowflake = {}));
class Base {
_client;
/**
* Object id
*/
id;
rawData;
constructor(data, client, id) {
/**
* Using this way we hide the client structure in the logs
*/
Object.defineProperty(this, "_client", {
value: client,
});
this.rawData = data;
this.id = data.id ?? id;
}
get createdAt() {
return Snowflake.getCreatedAt(this.id);
}
toJSON() {
Base.toJSON(this, ["createdAt", "id", "rawData"]);
}
static toJSON(source, props) {
const json = {};
for (const prop of props) {
if (prop.startsWith("_")) {
continue;
}
let value = source[prop];
if (typeof value === "object" && value?.toJSON) {
value = value.toJSON();
}
else if (typeof value === "bigint") {
value = value.toString();
}
else if (value instanceof Map || value instanceof Cache_1.Cache) {
value = [...value.values()];
}
else if (typeof value === "function" || !value) {
continue;
}
json[prop] = value;
}
return json;
}
}
exports.Base = Base;