mirror of
https://github.com/CorentinTh/it-tools.git
synced 2026-10-21 21:31:21 +00:00
feat(new tool): snowflake id decoder
This commit is contained in:
parent
9a1d8b10c3
commit
026383ffba
5 changed files with 211 additions and 1 deletions
|
|
@ -45,6 +45,7 @@ import { tool as htmlWysiwygEditor } from './html-wysiwyg-editor';
|
|||
import { tool as rsaKeyPairGenerator } from './rsa-key-pair-generator';
|
||||
import { tool as textToNatoAlphabet } from './text-to-nato-alphabet';
|
||||
import { tool as slugifyString } from './slugify-string';
|
||||
import { tool as snowflakeIdDecoder } from './snowflake-id-decoder';
|
||||
import { tool as keycodeInfo } from './keycode-info';
|
||||
import { tool as jsonMinify } from './json-minify';
|
||||
import { tool as bcrypt } from './bcrypt';
|
||||
|
|
@ -91,7 +92,7 @@ import { tool as yamlViewer } from './yaml-viewer';
|
|||
export const toolsByCategory: ToolCategory[] = [
|
||||
{
|
||||
name: 'Crypto',
|
||||
components: [tokenGenerator, hashText, bcrypt, uuidGenerator, ulidGenerator, cypher, bip39, hmacGenerator, rsaKeyPairGenerator, passwordStrengthAnalyser, pdfSignatureChecker],
|
||||
components: [snowflakeIdDecoder, tokenGenerator, hashText, bcrypt, uuidGenerator, ulidGenerator, cypher, bip39, hmacGenerator, rsaKeyPairGenerator, passwordStrengthAnalyser, pdfSignatureChecker],
|
||||
},
|
||||
{
|
||||
name: 'Converter',
|
||||
|
|
|
|||
12
src/tools/snowflake-id-decoder/index.ts
Normal file
12
src/tools/snowflake-id-decoder/index.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { Snowflake } from '@vicons/tabler';
|
||||
import { defineTool } from '../tool';
|
||||
|
||||
export const tool = defineTool({
|
||||
name: 'Snowflake id decoder',
|
||||
path: '/snowflake-id-decoder',
|
||||
description: 'Decode Twitter, Discord, Instagram or Mastodon snowflake ids into timestamps, worker ids and sequences',
|
||||
keywords: ['snowflake', 'twitter', 'discord', 'instagram', 'mastodon', 'id', 'timestamp', 'decoder'],
|
||||
component: () => import('./snowflake-id-decoder.vue'),
|
||||
icon: Snowflake,
|
||||
createdAt: new Date('2026-10-01'),
|
||||
});
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeSnowflake } from './snowflake-id-decoder.models';
|
||||
|
||||
describe('snowflake-id-decoder', () => {
|
||||
it('decodes a Twitter snowflake against the Twitter epoch', () => {
|
||||
// 565419792856637440 was posted on 2015-02-09
|
||||
const decoded = decodeSnowflake('565419792856637440', 1288834974657);
|
||||
expect(decoded.timestamp).toBe(1423641558265);
|
||||
expect(decoded.isoDate).toContain('2015-02-11');
|
||||
});
|
||||
|
||||
it('decodes a Discord id against the Discord epoch', () => {
|
||||
// Discord docs example: id 175928847299117063 -> 2016-04-30T11:18:25.796Z
|
||||
const decoded = decodeSnowflake('175928847299117063', 1420070400000);
|
||||
expect(decoded.timestamp).toBe(1462015105796);
|
||||
expect(decoded.isoDate).toBe('2016-04-30 11:18:25 UTC');
|
||||
expect(decoded.datacenterId).toBe(1);
|
||||
expect(decoded.workerId).toBe(0);
|
||||
expect(decoded.sequence).toBe(7);
|
||||
});
|
||||
|
||||
it('rejects non-numeric input', () => {
|
||||
expect(() => decodeSnowflake('abc', 0)).toThrow('positive integer');
|
||||
expect(() => decodeSnowflake('12 34', 0)).toThrow('positive integer');
|
||||
expect(() => decodeSnowflake('-5', 0)).toThrow('positive integer');
|
||||
});
|
||||
|
||||
it('handles very large ids beyond Number safe range', () => {
|
||||
// 2^63-1 must not lose precision
|
||||
const decoded = decodeSnowflake('9223372036854775807', 0);
|
||||
expect(decoded.timestamp).toBe(Number(9223372036854775807n >> 22n));
|
||||
});
|
||||
|
||||
it('extracts sequence bits', () => {
|
||||
// 0b1 << 22 | sequence 0b101010101010
|
||||
const id = ((1n << 22n) | 0b101010101010n).toString();
|
||||
const decoded = decodeSnowflake(id, 0);
|
||||
expect(decoded.sequence).toBe(0b101010101010);
|
||||
});
|
||||
});
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
export interface SnowflakePlatform {
|
||||
key: string
|
||||
label: string
|
||||
epoch: number
|
||||
}
|
||||
|
||||
/** Well-known Snowflake epochs. Twitter uses a custom 41-bit timestamp; the
|
||||
* others use the standard 64-bit layout with a platform-specific epoch. */
|
||||
export const SNOWFLAKE_PLATFORMS: SnowflakePlatform[] = [
|
||||
{ key: 'twitter', label: 'Twitter / X', epoch: 1288834974657 },
|
||||
{ key: 'discord', label: 'Discord', epoch: 1420070400000 },
|
||||
{ key: 'instagram', label: 'Instagram', epoch: 1314220021721 },
|
||||
{ key: 'mastodon', label: 'Mastodon', epoch: 0 },
|
||||
{ key: 'custom', label: 'Custom epoch', epoch: 0 },
|
||||
];
|
||||
|
||||
export interface SnowflakeDecoded {
|
||||
/** Millisecond Unix timestamp encoded in the id. */
|
||||
timestamp: number
|
||||
isoDate: string
|
||||
/** Datacenter / worker / sequence when the platform uses the standard layout. */
|
||||
workerId: number
|
||||
datacenterId: number
|
||||
sequence: number
|
||||
}
|
||||
|
||||
function parseSnowflakeId(id: string): bigint {
|
||||
const trimmed = id.trim();
|
||||
if (!/^\d{1,20}$/.test(trimmed)) {
|
||||
throw new Error('A snowflake id is a positive integer');
|
||||
}
|
||||
return BigInt(trimmed);
|
||||
}
|
||||
|
||||
/** Standard 64-bit Snowflake: 1 unused sign bit, 41-bit ms timestamp,
|
||||
* 5-bit datacenter, 5-bit worker, 12-bit sequence. */
|
||||
export function decodeSnowflake(id: string, epoch: number): SnowflakeDecoded {
|
||||
const value = parseSnowflakeId(id);
|
||||
const timestamp = Number((value >> 22n) & 0x1FFFFFFFFFFFFn) + epoch;
|
||||
const datacenterId = Number((value >> 17n) & 0x1Fn);
|
||||
const workerId = Number((value >> 12n) & 0x1Fn);
|
||||
const sequence = Number(value & 0xFFFn);
|
||||
|
||||
const date = new Date(timestamp);
|
||||
return {
|
||||
timestamp,
|
||||
isoDate: `${date.toISOString().replace('T', ' ').replace(/\..+/, '')} UTC`,
|
||||
workerId,
|
||||
datacenterId,
|
||||
sequence,
|
||||
};
|
||||
}
|
||||
105
src/tools/snowflake-id-decoder/snowflake-id-decoder.vue
Normal file
105
src/tools/snowflake-id-decoder/snowflake-id-decoder.vue
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
<script setup lang="ts">
|
||||
import { SNOWFLAKE_PLATFORMS, type SnowflakePlatform, decodeSnowflake } from './snowflake-id-decoder.models';
|
||||
import { withDefaultOnError } from '@/utils/defaults';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
|
||||
const id = ref('175928847299117063');
|
||||
const platformKey = useStorage('snowflake:platform', 'discord');
|
||||
const customEpoch = ref<number | null>(null);
|
||||
|
||||
const platform = computed<SnowflakePlatform>(() =>
|
||||
SNOWFLAKE_PLATFORMS.find(p => p.key === platformKey.value) ?? SNOWFLAKE_PLATFORMS[1]!,
|
||||
);
|
||||
const effectiveEpoch = computed(() => (platformKey.value === 'custom' ? Number(customEpoch.value ?? 0) : platform.value.epoch));
|
||||
|
||||
const validation = useValidation({
|
||||
source: id,
|
||||
rules: [
|
||||
{
|
||||
validator: value => !value || /^\d{1,20}$/.test(value.trim()),
|
||||
message: 'A snowflake id is a positive integer (up to 20 digits)',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const decoded = computed(() =>
|
||||
withDefaultOnError(() => (id.value.trim() && validation.isValid ? decodeSnowflake(id.value, effectiveEpoch.value) : undefined), undefined),
|
||||
);
|
||||
|
||||
const epochOptions = SNOWFLAKE_PLATFORMS.map(p => ({ label: p.label, value: p.key }));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div style="max-width: 640px; margin: 0 auto;">
|
||||
<c-card mb-3>
|
||||
<c-input-text
|
||||
v-model:value="id"
|
||||
label="Snowflake id"
|
||||
placeholder="e.g. 175928847299117063"
|
||||
:validation="id ? validation : undefined"
|
||||
mb-3
|
||||
/>
|
||||
|
||||
<n-grid cols="2" x-gap="12">
|
||||
<n-gi>
|
||||
<c-select v-model:value="platformKey" label="Platform" label-position="top" :options="epochOptions" />
|
||||
</n-gi>
|
||||
<n-gi>
|
||||
<c-input-text
|
||||
v-if="platformKey === 'custom'"
|
||||
v-model:value="customEpoch"
|
||||
label="Custom epoch (ms)"
|
||||
placeholder="e.g. 0"
|
||||
/>
|
||||
</n-gi>
|
||||
</n-grid>
|
||||
</c-card>
|
||||
|
||||
<c-card v-if="decoded">
|
||||
<n-table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td class="labels">
|
||||
Timestamp (ms):
|
||||
</td>
|
||||
<td>{{ decoded.timestamp }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="labels">
|
||||
Date:
|
||||
</td>
|
||||
<td>{{ decoded.isoDate }}</td>
|
||||
</tr>
|
||||
<tr v-if="platformKey !== 'twitter'">
|
||||
<td class="labels">
|
||||
Datacenter id:
|
||||
</td>
|
||||
<td>{{ decoded.datacenterId }}</td>
|
||||
</tr>
|
||||
<tr v-if="platformKey !== 'twitter'">
|
||||
<td class="labels">
|
||||
Worker id:
|
||||
</td>
|
||||
<td>{{ decoded.workerId }}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="labels">
|
||||
Sequence:
|
||||
</td>
|
||||
<td>{{ decoded.sequence }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</n-table>
|
||||
<div mt-2 text-xs op-60>
|
||||
Epoch: {{ effectiveEpoch }} ms · layout: 41-bit timestamp / 5-bit datacenter / 5-bit worker / 12-bit sequence
|
||||
</div>
|
||||
</c-card>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="less">
|
||||
.labels {
|
||||
width: 180px;
|
||||
font-weight: bold;
|
||||
}
|
||||
</style>
|
||||
Loading…
Add table
Add a link
Reference in a new issue