chore: global code formatting

This commit is contained in:
ShareVB committed 2026-09-06 09:02:45 +02:00
1 parent 5bf94bc567
commit bc44870665
830 files changed
+21075 -13592

No files matched your search

+1 -4
View File
@@ -43,10 +43,7 @@ watchEffect(() => {
locale.value = get(getITToolsSetting('default_locale', locale.value));
syncRef(
locale,
useStorage('locale', locale),
);
syncRef(locale, useStorage('locale', locale));
</script>
<template>
+46 -25
View File
@@ -21,8 +21,8 @@ const collapsedCategories = useStorage<Record<string, boolean>>(
{
deep: true,
serializer: {
read: v => (v ? JSON.parse(v) : null),
write: v => JSON.stringify(v),
read: (v) => (v ? JSON.parse(v) : null),
write: (v) => JSON.stringify(v),
},
},
);
@@ -52,9 +52,7 @@ function toggleCategoryCollapse({ name }: { name: string }) {
}
const areAllCollapsed = computed(() => {
return toolsByCategory.value.every(({ name }) =>
collapsedCategories.value[name] !== false,
);
return toolsByCategory.value.every(({ name }) => collapsedCategories.value[name] !== false);
});
async function toggleAllCategories() {
@@ -82,12 +80,12 @@ function getAnimationDuration(itemCount: number): number {
const baseDuration = 250;
const durationIncrement = 5;
return baseDuration + (Math.min(itemCount, 30) * durationIncrement);
return baseDuration + Math.min(itemCount, 30) * durationIncrement;
}
// Function to check if any tool in the category is active
function isCategoryActive(components: Tool[]): boolean {
return components.some(tool => tool.path === route.path);
return components.some((tool) => tool.path === route.path);
}
const menuOptions = computed(() =>
@@ -96,7 +94,7 @@ const menuOptions = computed(() =>
isCollapsed: collapsedCategories.value[name],
isActive: isCategoryActive(components),
animationDuration: getAnimationDuration(components.length),
tools: components.map(tool => ({
tools: components.map((tool) => ({
label: makeLabel(tool),
icon: makeIcon(tool),
key: tool.path,
@@ -105,16 +103,14 @@ const menuOptions = computed(() =>
);
async function scrollToActiveItem() {
const activeCategory = toolsByCategory.value.find(({ components }) =>
isCategoryActive(components),
);
const activeCategory = toolsByCategory.value.find(({ components }) => isCategoryActive(components));
if (activeCategory) {
// Expand the active category
collapsedCategories.value[activeCategory.name] = false;
// Wait for the entire animation to complete
await new Promise(resolve => setTimeout(resolve, getAnimationDuration(activeCategory.components.length) + 50));
await new Promise((resolve) => setTimeout(resolve, getAnimationDuration(activeCategory.components.length) + 50));
// Scroll to the active menu item
const menuContainer = menuContainerRefs.value[activeCategory.name];
@@ -131,9 +127,12 @@ onMounted(() => {
scrollToActiveItem();
});
watch(() => route.path, () => {
scrollToActiveItem();
});
watch(
() => route.path,
() => {
scrollToActiveItem();
},
);
const themeVars = useThemeVars();
</script>
@@ -147,19 +146,37 @@ const themeVars = useThemeVars();
{{ areAllCollapsed ? $t('collapsibleToolMenu.text.expanding') : $t('collapsibleToolMenu.text.collapsing') }}
</span>
<span v-else>
{{ areAllCollapsed ? $t('collapsibleToolMenu.text.expand-all-tools') : $t('collapsibleToolMenu.text.collapse-all-tools') }}
{{
areAllCollapsed
? $t('collapsibleToolMenu.text.expand-all-tools')
: $t('collapsibleToolMenu.text.collapse-all-tools')
}}
</span>
</c-button>
</div>
<div v-for="{ name, tools, isCollapsed, isActive, animationDuration } of menuOptions" :key="name" class="category-container">
<div
v-for="{ name, tools, isCollapsed, isActive, animationDuration } of menuOptions"
:key="name"
class="category-container"
>
<button
class="category-button"
:class="{ 'category-active': isActive }"
flex cursor-pointer items-center op-60
flex
cursor-pointer
items-center
op-60
@click="toggleCategoryCollapse({ name })"
>
<span :class="{ 'rotate-0': isCollapsed, 'rotate-90': !isCollapsed }" text-16px lh-1 op-50 transition-transform duration-200>
<span
:class="{ 'rotate-0': isCollapsed, 'rotate-90': !isCollapsed }"
text-16px
lh-1
op-50
transition-transform
duration-200
>
<icon-mdi-chevron-right />
</span>
@@ -169,7 +186,11 @@ const themeVars = useThemeVars();
</button>
<div
:ref="el => { if (el) menuContainerRefs[name] = el as HTMLElement }"
:ref="
(el) => {
if (el) menuContainerRefs[name] = el as HTMLElement;
}
"
class="menu-container"
:class="{ collapsed: isCollapsed }"
:style="{ '--animation-duration': `${animationDuration}ms` }"
@@ -227,11 +248,11 @@ const themeVars = useThemeVars();
content-visibility: auto;
contain-intrinsic-size: auto 36px;
.menu-container {
display: grid;
grid-template-rows: 1fr;
transition: grid-template-rows var(--animation-duration, 250ms) ease-out;
will-change: grid-template-rows;
.menu-container {
display: grid;
grid-template-rows: 1fr;
transition: grid-template-rows var(--animation-duration, 250ms) ease-out;
will-change: grid-template-rows;
&.collapsed {
grid-template-rows: 0fr;
+1 -1
View File
@@ -24,7 +24,7 @@ function toggleFavorite(event: MouseEvent) {
</script>
<template>
<c-tooltip :tooltip="isFavorite ? $t('favoriteButton.remove') : $t('favoriteButton.add') ">
<c-tooltip :tooltip="isFavorite ? $t('favoriteButton.remove') : $t('favoriteButton.add')">
<c-button
variant="text"
circle
+45 -28
View File
@@ -9,19 +9,19 @@ import { useAppTheme } from '@/ui/theme/themes';
const props = withDefaults(
defineProps<{
transformer?: (v: string) => string
inputValidationRules?: UseValidationRule<string>[]
inputLabel?: string
inputPlaceholder?: string
inputDefault?: string
outputLabel?: string
outputLanguage?: string
downloadFileName?: string
downloadButtonText?: string
rows?: number
inputLineNumbers?: boolean
inputMaxRows?: number
inputAutosize?: boolean
transformer?: (v: string) => string;
inputValidationRules?: UseValidationRule<string>[];
inputLabel?: string;
inputPlaceholder?: string;
inputDefault?: string;
outputLabel?: string;
outputLanguage?: string;
downloadFileName?: string;
downloadButtonText?: string;
rows?: number;
inputLineNumbers?: boolean;
inputMaxRows?: number;
inputAutosize?: boolean;
}>(),
{
transformer: _.identity,
@@ -41,8 +41,19 @@ const props = withDefaults(
);
const {
transformer, inputValidationRules, inputLabel, outputLabel, outputLanguage,
inputPlaceholder, inputDefault, downloadFileName, downloadButtonText, rows, inputLineNumbers, inputMaxRows, inputAutosize,
transformer,
inputValidationRules,
inputLabel,
outputLabel,
outputLanguage,
inputPlaceholder,
inputDefault,
downloadFileName,
downloadButtonText,
rows,
inputLineNumbers,
inputMaxRows,
inputAutosize,
} = toRefs(props);
const appTheme = useAppTheme();
@@ -140,12 +151,13 @@ watch(
watch(
input,
() => nextTick(() => {
const textarea = textareaElement.value;
if (textarea) {
lineNumbersOffset.value = textarea.scrollTop;
}
}),
() =>
nextTick(() => {
const textarea = textareaElement.value;
if (textarea) {
lineNumbersOffset.value = textarea.scrollTop;
}
}),
{ flush: 'post' },
);
@@ -154,11 +166,10 @@ function focusInput() {
}
const outputBase64 = computed(() => Base64.encode(output.value));
const { download } = useDownloadFileFromBase64(
{
source: outputBase64,
filename: downloadFileName,
});
const { download } = useDownloadFileFromBase64({
source: outputBase64,
filename: downloadFileName,
});
</script>
<template>
@@ -191,7 +202,9 @@ const { download } = useDownloadFileFromBase64(
aria-hidden="true"
@click="focusInput"
>
<pre class="line-numbers__content" :style="{ transform: `translateY(-${lineNumbersOffset}px)` }">{{ lineNumbersText }}</pre>
<pre class="line-numbers__content" :style="{ transform: `translateY(-${lineNumbersOffset}px)` }">{{
lineNumbersText
}}</pre>
</div>
</template>
</CInputText>
@@ -199,7 +212,11 @@ const { download } = useDownloadFileFromBase64(
<div overflow-auto>
<n-tabs type="line">
<n-tab-pane name="output" :tab="outputLabel">
<textarea-copyable :value="output" :language="outputLanguage" :follow-height-of="inputElement?.inputWrapperRef" />
<textarea-copyable
:value="output"
:language="outputLanguage"
:follow-height-of="inputElement?.inputWrapperRef"
/>
</n-tab-pane>
<n-tab-pane name="editable" :tab="t('formatTransformer.viewer')">
<CodeBlockCopyable :value="output" :language="outputLanguage" />
+7 -15
View File
@@ -4,7 +4,7 @@ import { nextTick, onMounted, onUnmounted, ref } from 'vue';
import type { Tool } from '@/tools/tools.types';
defineProps<{
tool: Tool
tool: Tool;
}>();
const textRef = ref<HTMLElement>();
@@ -25,9 +25,10 @@ async function checkTruncation() {
const textWidth = context.measureText(text).width;
// Calculate precise container width by accounting for padding
const containerWidth = textRef.value.clientWidth
- Number.parseFloat(computedStyle.paddingLeft)
- Number.parseFloat(computedStyle.paddingRight);
const containerWidth =
textRef.value.clientWidth -
Number.parseFloat(computedStyle.paddingLeft) -
Number.parseFloat(computedStyle.paddingRight);
showTooltip.value = textWidth > containerWidth;
}
@@ -55,19 +56,10 @@ onUnmounted(() => {
</script>
<template>
<n-tooltip
placement="right"
:delay="500"
:show-arrow="true"
:disabled="!showTooltip"
>
<n-tooltip placement="right" :delay="500" :show-arrow="true" :disabled="!showTooltip">
<template #trigger>
<RouterLink :to="tool.path" class="menu-link">
<span
ref="textRef"
class="menu-text"
@mouseenter="checkTruncation"
>
<span ref="textRef" class="menu-text" @mouseenter="checkTruncation">
{{ tool.name }}
</span>
</RouterLink>
+8 -5
View File
@@ -48,11 +48,14 @@ watchEffect(() => {
// Close the menu when navigating (tool links, the about button, ...) so the
// destination page is visible.
const route = useRoute();
watch(() => route.path, () => {
if (isSmallScreen.value) {
isMenuCollapsed.value = true;
}
});
watch(
() => route.path,
() => {
if (isSmallScreen.value) {
isMenuCollapsed.value = true;
}
},
);
onUnmounted(() => {
document.body.style.overflow = '';
});
+1 -1
View File
@@ -8,7 +8,7 @@ const { value } = toRefs(props);
const initialText = t('spanCopyable.copy');
const { copy, isJustCopied } = useCopy({ source: value, createToast: false });
const tooltipText = computed(() => isJustCopied.value ? t('spanCopyable.copied') : initialText);
const tooltipText = computed(() => (isJustCopied.value ? t('spanCopyable.copied') : initialText));
</script>
<template>
+38 -27
View File
@@ -24,16 +24,16 @@ import { translate as t } from '@/plugins/i18n.plugin';
const props = withDefaults(
defineProps<{
value: string
followHeightOf?: HTMLElement | null
language?: string
copyPlacement?: 'top-right' | 'bottom-right' | 'outside' | 'none'
copyMessage?: string
wordWrap?: boolean
downloadFileName?: string
downloadButtonText?: string
scrollable?: boolean
maxHeight?: string
value: string;
followHeightOf?: HTMLElement | null;
language?: string;
copyPlacement?: 'top-right' | 'bottom-right' | 'outside' | 'none';
copyMessage?: string;
wordWrap?: boolean;
downloadFileName?: string;
downloadButtonText?: string;
scrollable?: boolean;
maxHeight?: string;
}>(),
{
followHeightOf: null,
@@ -65,36 +65,46 @@ hljs.registerLanguage('python', pythonHljs);
hljs.registerLanguage('php', phpHljs);
hljs.registerLanguage('protobuf', protobufHljs);
const { value, language, followHeightOf, copyPlacement, copyMessage, downloadFileName, downloadButtonText } = toRefs(props);
const { value, language, followHeightOf, copyPlacement, copyMessage, downloadFileName, downloadButtonText } =
toRefs(props);
const { height } = followHeightOf.value ? useElementSize(followHeightOf) : { height: ref(null) };
const scrollbarRef = ref();
// Watch for content changes and scroll to bottom
watch(value, () => {
nextTick(() => {
if (scrollbarRef.value) {
scrollbarRef.value.scrollTo({ top: scrollbarRef.value.scrollbarInstRef.containerRef.scrollHeight });
}
});
}, { flush: 'post' });
watch(
value,
() => {
nextTick(() => {
if (scrollbarRef.value) {
scrollbarRef.value.scrollTo({ top: scrollbarRef.value.scrollbarInstRef.containerRef.scrollHeight });
}
});
},
{ flush: 'post' },
);
const { copy, isJustCopied } = useCopy({ source: value, createToast: false });
const tooltipText = computed(() => isJustCopied.value ? t('textareaCopyable.copied') : copyMessage.value);
const tooltipText = computed(() => (isJustCopied.value ? t('textareaCopyable.copied') : copyMessage.value));
const valueBase64 = computed(() => Base64.encode(value.value));
const { download } = useDownloadFileFromBase64(
{
source: valueBase64,
filename: downloadFileName,
});
const { download } = useDownloadFileFromBase64({
source: valueBase64,
filename: downloadFileName,
});
</script>
<template>
<div style="overflow-x: hidden; width: 100%">
<c-card
relative
:style="copyPlacement === 'top-right' ? 'padding-top: 50px' : (copyPlacement === 'bottom-right' ? 'padding-bottom: 50px' : '')"
:style="
copyPlacement === 'top-right'
? 'padding-top: 50px'
: copyPlacement === 'bottom-right'
? 'padding-bottom: 50px'
: ''
"
>
<n-scrollbar
ref="scrollbarRef"
@@ -112,8 +122,9 @@ const { download } = useDownloadFileFromBase64(
</n-scrollbar>
<div
v-if="value && copyPlacement !== 'none'"
absolute right-10px
:class="copyPlacement === 'top-right' ? 'top-10px' : (copyPlacement === 'bottom-right' ? 'bottom-10px' : '')"
absolute
right-10px
:class="copyPlacement === 'top-right' ? 'top-10px' : copyPlacement === 'bottom-right' ? 'bottom-10px' : ''"
:style="scrollable ? 'z-index: 10; background: var(--bg-color); border-radius: 50%; padding: 2px;' : ''"
>
<c-tooltip v-if="value && copyPlacement !== 'outside'" :tooltip="tooltipText" position="left">
+2 -5
View File
@@ -32,10 +32,7 @@ const theme = useThemeVars();
<div class="truncat my-5px text-lg text-black dark:text-white">
{{ tool.name }}
<World
v-if="tool.externAccessDescription"
class="tool-privacy-icon"
/>
<World v-if="tool.externAccessDescription" class="tool-privacy-icon" />
</div>
<div class="line-clamp-2 text-neutral-500 dark:text-neutral-400">
@@ -48,6 +45,6 @@ const theme = useThemeVars();
<style lang="css" scoped>
.tool-privacy-icon {
display: inline-block;
height: .9em;
height: 0.9em;
}
</style>
+20 -10
View File
@@ -2,8 +2,14 @@ import { type Ref, ref, watchEffect } from 'vue';
export { computedCatch, computedCatchAsync };
function computedCatch<T, D>(getter: () => T, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>];
function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) {
function computedCatch<T, D>(
getter: () => T,
{ defaultValue }: { defaultValue: D; defaultErrorMessage?: string },
): [Ref<T | D>, Ref<string | undefined>];
function computedCatch<T, D>(
getter: () => T,
{ defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {},
) {
const error = ref<string | undefined>();
const value = ref<T | D | undefined>();
@@ -11,9 +17,8 @@ function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessag
try {
error.value = undefined;
value.value = getter();
}
catch (err) {
error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage;
} catch (err) {
error.value = err instanceof Error ? err.message : (err?.toString() ?? defaultErrorMessage);
value.value = defaultValue;
}
});
@@ -21,8 +26,14 @@ function computedCatch<T, D>(getter: () => T, { defaultValue, defaultErrorMessag
return [value, error] as const;
}
function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue }: { defaultValue: D; defaultErrorMessage?: string }): [Ref<T | D>, Ref<string | undefined>];
function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {}) {
function computedCatchAsync<T, D>(
getterAsync: () => Promise<T>,
{ defaultValue }: { defaultValue: D; defaultErrorMessage?: string },
): [Ref<T | D>, Ref<string | undefined>];
function computedCatchAsync<T, D>(
getterAsync: () => Promise<T>,
{ defaultValue, defaultErrorMessage = 'Unknown error' }: { defaultValue?: D; defaultErrorMessage?: string } = {},
) {
const error = ref<string | undefined>();
const value = ref<T | D | undefined>();
@@ -30,9 +41,8 @@ function computedCatchAsync<T, D>(getterAsync: () => Promise<T>, { defaultValue,
try {
error.value = undefined;
value.value = await getterAsync();
}
catch (err) {
error.value = err instanceof Error ? err.message : err?.toString() ?? defaultErrorMessage;
} catch (err) {
error.value = err instanceof Error ? err.message : (err?.toString() ?? defaultErrorMessage);
value.value = defaultValue;
}
});
+1 -2
View File
@@ -11,8 +11,7 @@ function computedRefreshable<T>(getter: () => T, { throttle }: { throttle?: numb
if (throttle) {
watchThrottled(getter, update, { throttle });
}
else {
} else {
watch(getter, update);
}
+33 -20
View File
@@ -4,7 +4,11 @@ import { useMessage } from 'naive-ui';
import type { MaybeRefOrGetter } from 'vue';
import { translate as t } from '@/plugins/i18n.plugin';
export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { source?: MaybeRefOrGetter<string>; text?: string; createToast?: boolean } = {}) {
export function useCopy({
source,
text = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: { source?: MaybeRefOrGetter<string>; text?: string; createToast?: boolean } = {}) {
const { copy, copied, ...rest } = useClipboard({
source,
legacy: true,
@@ -18,8 +22,7 @@ export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipbo
async copy(content?: string, { notificationMessage }: { notificationMessage?: string } = {}) {
if (source) {
await copy();
}
else {
} else {
await copy(content);
}
@@ -30,7 +33,11 @@ export function useCopy({ source, text = t('tools.copy.text.copied-to-the-clipbo
};
}
export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) {
export function useCopyClipboardItems({
source,
text = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: { source?: MaybeRefOrGetter<Array<{ mime: string; content: string }>>; text?: string; createToast?: boolean } = {}) {
function toClipboardItem(item: { mime: string; content: string }) {
return new ClipboardItem({
[item.mime]: new Blob([item.content], { type: item.mime }),
@@ -46,11 +53,13 @@ export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied
return {
...rest,
isJustCopied: copied,
async copy(content?: { mime: string; content: string }[], { notificationMessage }: { notificationMessage?: string } = {}) {
async copy(
content?: { mime: string; content: string }[],
{ notificationMessage }: { notificationMessage?: string } = {},
) {
if (source) {
await copy();
}
else {
} else {
await copy((content || []).map(toClipboardItem));
}
@@ -61,7 +70,17 @@ export function useCopyClipboardItems({ source, text = t('tools.copy.text.copied
};
}
export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.copy.text.copied-to-the-clipboard'), createToast = true }: { sourceHtml?: MaybeRefOrGetter<string>; fallbackText?: MaybeRefOrGetter<string>; toastText?: string; createToast?: boolean } = {}) {
export function useCopyHtml({
sourceHtml,
fallbackText,
toastText = t('tools.copy.text.copied-to-the-clipboard'),
createToast = true,
}: {
sourceHtml?: MaybeRefOrGetter<string>;
fallbackText?: MaybeRefOrGetter<string>;
toastText?: string;
createToast?: boolean;
} = {}) {
const message = useMessage();
const copied = ref(false);
@@ -81,8 +100,7 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
try {
document.execCommand('copy');
}
finally {
} finally {
document.body.removeChild(textarea);
}
}
@@ -100,19 +118,16 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
const blobText = new Blob([fallbackText || html], { type: 'text/plain' });
const item = new ClipboardItemCtor({ 'text/plain': blobText, 'text/html': blobHtml });
await navigator.clipboard.write([item]);
}
else if (navigator.clipboard?.writeText) {
} else if (navigator.clipboard?.writeText) {
// Async text fallback
await navigator.clipboard.writeText(fallbackText || html);
}
else {
} else {
// Legacy execCommand fallback
legacyCopy(fallbackText || html);
}
copied.value = true;
}
catch (e: any) {
} catch (e: any) {
error.value = e.toString();
}
}
@@ -122,16 +137,14 @@ export function useCopyHtml({ sourceHtml, fallbackText, toastText = t('tools.cop
async copy(html?: string, text?: string, { notificationMessage }: { notificationMessage?: string } = {}) {
if (sourceHtml) {
await copyHtml(toValue(sourceHtml), toValue(fallbackText));
}
else if (html) {
} else if (html) {
await copyHtml(html, text);
}
if (createToast) {
if (error.value) {
message.error(error.value);
}
else {
} else {
message.success(notificationMessage ?? toastText);
}
}
+9 -3
View File
@@ -4,15 +4,21 @@ import { getMimeTypeFromBase64 } from './downloadBase64';
describe('downloadBase64', () => {
describe('getMimeTypeFromBase64', () => {
it('when the base64 string has a data URI, it returns the mime type', () => {
expect(getMimeTypeFromBase64({ base64String: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/png' });
expect(getMimeTypeFromBase64({ base64String: 'data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/jpg' });
expect(
getMimeTypeFromBase64({ base64String: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' }),
).to.deep.equal({ mimeType: 'image/png' });
expect(
getMimeTypeFromBase64({ base64String: 'data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' }),
).to.deep.equal({ mimeType: 'image/jpg' });
});
it('when the base64 string has no data URI, it try to infer the mime type from the signature', () => {
// https://en.wikipedia.org/wiki/List_of_file_signatures
// PNG
expect(getMimeTypeFromBase64({ base64String: 'iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({ mimeType: 'image/png' });
expect(getMimeTypeFromBase64({ base64String: 'iVBORw0KGgoAAAANSUhEUgAAAAUA' })).to.deep.equal({
mimeType: 'image/png',
});
// GIF
expect(getMimeTypeFromBase64({ base64String: 'R0lGODdh' })).to.deep.equal({ mimeType: 'image/gif' });
+45 -22
View File
@@ -5,27 +5,31 @@ import { get } from '@vueuse/core';
export {
getMimeTypeFromBase64,
getMimeTypeFromExtension, getExtensionFromMimeType,
useDownloadFileFromBase64, useDownloadFileFromBase64Refs,
getMimeTypeFromExtension,
getExtensionFromMimeType,
useDownloadFileFromBase64,
useDownloadFileFromBase64Refs,
previewImageFromBase64,
};
const commonMimeTypesSignatures = {
'JVBERi0': 'application/pdf',
'R0lGODdh': 'image/gif',
'R0lGODlh': 'image/gif',
'iVBORw0KGgo': 'image/png',
JVBERi0: 'application/pdf',
R0lGODdh: 'image/gif',
R0lGODlh: 'image/gif',
iVBORw0KGgo: 'image/png',
'/9j/': 'image/jpg',
};
function getMimeTypeFromBase64({ base64String }: { base64String: string }) {
const [,mimeTypeFromBase64] = base64String.match(/data:(.*?);base64/i) ?? [];
const [, mimeTypeFromBase64] = base64String.match(/data:(.*?);base64/i) ?? [];
if (mimeTypeFromBase64) {
return { mimeType: mimeTypeFromBase64 };
}
const inferredMimeType = _.find(commonMimeTypesSignatures, (_mimeType, signature) => base64String.startsWith(signature));
const inferredMimeType = _.find(commonMimeTypesSignatures, (_mimeType, signature) =>
base64String.startsWith(signature),
);
if (inferredMimeType) {
return { mimeType: inferredMimeType };
@@ -38,8 +42,8 @@ function getFileExtensionFromMimeType({
mimeType,
defaultExtension = 'txt',
}: {
mimeType: string | undefined
defaultExtension?: string
mimeType: string | undefined;
defaultExtension?: string;
}) {
if (mimeType) {
return getExtensionFromMimeType(mimeType) ?? defaultExtension;
@@ -48,8 +52,17 @@ function getFileExtensionFromMimeType({
return defaultExtension;
}
function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
{ sourceValue: string; filename?: string; extension?: string; fileMimeType?: string }) {
function downloadFromBase64({
sourceValue,
filename,
extension,
fileMimeType,
}: {
sourceValue: string;
filename?: string;
extension?: string;
fileMimeType?: string;
}) {
if (sourceValue === '') {
throw new Error('Base64 string is empty');
}
@@ -62,8 +75,7 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
base64String = `data:${targetMimeType};base64,${sourceValue}`;
}
const cleanExtension = extension ?? getFileExtensionFromMimeType(
{ mimeType, defaultExtension });
const cleanExtension = extension ?? getFileExtensionFromMimeType({ mimeType, defaultExtension });
let cleanFileName = filename ?? `file.${cleanExtension}`;
if (extension && !cleanFileName.endsWith(`.${extension}`)) {
cleanFileName = `${cleanFileName}.${cleanExtension}`;
@@ -75,9 +87,15 @@ function downloadFromBase64({ sourceValue, filename, extension, fileMimeType }:
a.click();
}
function useDownloadFileFromBase64(
{ source, filename, extension }:
{ source: MaybeRef<string>; filename?: MaybeRef<string>; extension?: MaybeRef<string> }) {
function useDownloadFileFromBase64({
source,
filename,
extension,
}: {
source: MaybeRef<string>;
filename?: MaybeRef<string>;
extension?: MaybeRef<string>;
}) {
return {
download() {
downloadFromBase64({ sourceValue: get(source), filename: get(filename), extension: get(extension) });
@@ -105,17 +123,22 @@ function previewImageFromBase64(base64String: string): HTMLImageElement {
if (previewContainer) {
previewContainer.innerHTML = '';
previewContainer.appendChild(container);
}
else {
} else {
throw new Error('Preview container element not found');
}
return img;
}
function useDownloadFileFromBase64Refs(
{ source, filename, extension }:
{ source: Ref<string>; filename?: Ref<string>; extension?: Ref<string> }) {
function useDownloadFileFromBase64Refs({
source,
filename,
extension,
}: {
source: Ref<string>;
filename?: Ref<string>;
extension?: Ref<string>;
}) {
return {
download() {
downloadFromBase64({ sourceValue: source.value, filename: filename?.value, extension: extension?.value });
+4 -4
View File
@@ -14,10 +14,10 @@ function useFuzzySearch<Data>({
options = {},
limit = -1,
}: {
search: MaybeRef<string>
data: Data[]
options?: IFuseOptions<Data> & { filterEmpty?: boolean }
limit?: number
search: MaybeRef<string>;
data: Data[];
options?: IFuseOptions<Data> & { filterEmpty?: boolean };
limit?: number;
}) {
const fuse = new Fuse(data, options);
const filterEmpty = options.filterEmpty ?? true;
+37 -13
View File
@@ -26,7 +26,15 @@ const transformers = {
},
};
function useQueryParam<T>({ tool, name, defaultValue }: { tool: string; name: string; defaultValue: T }): RemovableRef<T> {
function useQueryParam<T>({
tool,
name,
defaultValue,
}: {
tool: string;
name: string;
defaultValue: T;
}): RemovableRef<T> {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
const defaultValueOrSetting = getITToolsSetting(`${tool}:${name}`, defaultValue);
@@ -43,7 +51,15 @@ function useQueryParam<T>({ tool, name, defaultValue }: { tool: string; name: st
});
}
function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name: string; storageName: string; defaultValue: T }) {
function useQueryParamOrStorage<T>({
name,
storageName,
defaultValue,
}: {
name: string;
storageName: string;
defaultValue: T;
}) {
const type = typeof defaultValue;
const transformer = transformers[type as keyof typeof transformers] ?? transformers.string;
@@ -53,23 +69,32 @@ function useQueryParamOrStorage<T>({ name, storageName, defaultValue }: { name:
const proxyDefaultValue = transformer.toQuery(defaultValueOrSetting as never);
const proxy = useRouteQuery(name, proxyDefaultValue);
const r = isRef(defaultValueOrSetting) ? defaultValueOrSetting as Ref<T> : ref(get(defaultValueOrSetting));
const r = isRef(defaultValueOrSetting) ? (defaultValueOrSetting as Ref<T>) : ref(get(defaultValueOrSetting));
watch(r,
watch(
r,
(value) => {
proxy.value = transformer.toQuery(value as never);
storageRef.value = value as never;
},
{ deep: true });
{ deep: true },
);
r.value = (proxy.value && proxy.value !== proxyDefaultValue
? transformer.fromQuery(proxy.value) as unknown as T
: storageRef.value as T) as never;
r.value = (
proxy.value && proxy.value !== proxyDefaultValue
? (transformer.fromQuery(proxy.value) as unknown as T)
: (storageRef.value as T)
) as never;
return r;
}
function useITStorage<T>(key: string, defaults: MaybeRef<T>, storage?: StorageLike, options?: UseStorageOptions<T>): RemovableRef<T> {
function useITStorage<T>(
key: string,
defaults: MaybeRef<T>,
storage?: StorageLike,
options?: UseStorageOptions<T>,
): RemovableRef<T> {
const defaultValueOrSetting = getITToolsSetting(key, defaults);
return useStorage<T>(key, defaultValueOrSetting, storage, options);
}
@@ -81,10 +106,9 @@ function getITToolsSetting<T>(key: string, defaultValue: MaybeRef<T>) {
}
if (key.includes(':')) {
const [tool, subkey] = key.split(':');
return (itToolsSettings[tool] || {})[subkey] as T ?? defaultValue;
}
else {
return (itToolsSettings)[key] as T ?? defaultValue;
return ((itToolsSettings[tool] || {})[subkey] as T) ?? defaultValue;
} else {
return (itToolsSettings[key] as T) ?? defaultValue;
}
}
+19 -19
View File
@@ -6,9 +6,9 @@ type ValidatorReturnType = unknown;
type GetErrorMessageReturnType = string;
export interface UseValidationRule<T> {
validator: (value: T) => ValidatorReturnType
getErrorMessage?: (value: T) => GetErrorMessageReturnType
message: string
validator: (value: T) => ValidatorReturnType;
getErrorMessage?: (value: T) => GetErrorMessageReturnType;
message: string;
}
export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
@@ -20,8 +20,7 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
}
return returnValue === false;
}
catch (_) {
} catch (_) {
return true;
}
}
@@ -29,15 +28,14 @@ export function isFalsyOrHasThrown(cb: () => ValidatorReturnType): boolean {
export function getErrorMessageOrThrown(cb: () => GetErrorMessageReturnType): string {
try {
return cb() || '';
}
catch (e: any) {
} catch (e: any) {
return e.toString();
}
}
export interface ValidationAttrs {
feedback: string
validationStatus: string | undefined
feedback: string;
validationStatus: string | undefined;
}
export function useValidation<T>({
@@ -45,15 +43,15 @@ export function useValidation<T>({
rules,
watch: watchRefs = [],
}: {
source: Ref<T>
rules: MaybeRef<UseValidationRule<T>[]>
watch?: Ref<unknown>[]
source: Ref<T>;
rules: MaybeRef<UseValidationRule<T>[]>;
watch?: Ref<unknown>[];
}) {
const state = reactive<{
message: string
status: undefined | 'error'
isValid: boolean
attrs: ValidationAttrs
message: string;
status: undefined | 'error';
isValid: boolean;
attrs: ValidationAttrs;
}>({
message: '',
status: undefined,
@@ -74,9 +72,11 @@ export function useValidation<T>({
if (isFalsyOrHasThrown(() => rule.validator(source.value))) {
if (rule.getErrorMessage) {
const getErrorMessage = rule.getErrorMessage;
state.message = rule.message.replace('{0}', getErrorMessageOrThrown(() => getErrorMessage(source.value)));
}
else {
state.message = rule.message.replace(
'{0}',
getErrorMessageOrThrown(() => getErrorMessage(source.value)),
);
} else {
state.message = rule.message;
}
state.status = 'error';
@@ -2,14 +2,14 @@ import type { Component } from 'vue';
import type { RouteLocationRaw } from 'vue-router';
export interface PaletteOption {
name: string
description?: string
icon?: Component
action?: () => void
to?: RouteLocationRaw
category: string
keywords?: string[]
href?: string
closeOnSelect?: boolean
externAccessDescription?: string
name: string;
description?: string;
icon?: Component;
action?: () => void;
to?: RouteLocationRaw;
category: string;
keywords?: string[];
href?: string;
closeOnSelect?: boolean;
externAccessDescription?: string;
}
@@ -20,7 +20,16 @@ const { selected } = toRefs(props);
'text-white': selected,
'bg-primary': selected,
}"
w-full flex cursor-pointer items-center overflow-hidden rounded pa-3 transition hover:bg-primary hover:text-white
w-full
flex
cursor-pointer
items-center
overflow-hidden
rounded
pa-3
transition
hover:bg-primary
hover:text-white
@click="() => emit('activated', option)"
>
<component :is="option.icon" v-if="option.icon" mr-3 h-30px w-30px shrink-0 op-50 />
@@ -28,14 +37,8 @@ const { selected } = toRefs(props);
<div flex-1 overflow-hidden>
<div truncate font-bold lh-tight op-90>
{{ option.name }}
<World
v-if="option.externAccessDescription"
class="tool-privacy-icon"
/>
<DeviceDesktop
v-else
class="tool-privacy-icon"
/>
<World v-if="option.externAccessDescription" class="tool-privacy-icon" />
<DeviceDesktop v-else class="tool-privacy-icon" />
</div>
<div v-if="option.description" truncate lh-tight op-60>
@@ -48,6 +51,6 @@ const { selected } = toRefs(props);
<style lang="css" scoped>
.tool-privacy-icon {
display: inline-block;
height: .9em;
height: 0.9em;
}
</style>
+2 -2
View File
@@ -7,6 +7,6 @@ export type TrackerService = ReturnType<typeof createTrackerService>;
* and the tracker service are not tied to the tracking library currently in use.
*/
export interface PlausibleInstance {
trackEvent: (eventName: string) => void
enableAutoPageviews: () => void
trackEvent: (eventName: string) => void;
enableAutoPageviews: () => void;
}
+11 -5
View File
@@ -13,7 +13,9 @@ const FALLBACK_LOCALE = 'en';
// only fetched the first time it becomes the active locale.
const eagerToolMessages = import.meta.glob('../tools/*/locales/en.yml', { eager: true, import: 'default' });
const lazyBaseMessages = import.meta.glob(['../../locales/*.yml', '!../../locales/en.yml'], { import: 'default' });
const lazyToolMessages = import.meta.glob(['../tools/*/locales/*.yml', '!../tools/*/locales/en.yml'], { import: 'default' });
const lazyToolMessages = import.meta.glob(['../tools/*/locales/*.yml', '!../tools/*/locales/en.yml'], {
import: 'default',
});
function localeOfPath(path: string): string {
return path.replace(/^.*\/([^/]+)\.yml$/, '$1');
@@ -31,8 +33,8 @@ export const appLocales = (() => {
if (available === '*' || available === 'all') {
return allLocales;
}
const wantedLocales = available.split(',').map(locale => locale.trim());
return allLocales.filter(locale => wantedLocales.includes(locale) || locale === FALLBACK_LOCALE);
const wantedLocales = available.split(',').map((locale) => locale.trim());
return allLocales.filter((locale) => wantedLocales.includes(locale) || locale === FALLBACK_LOCALE);
})();
const i18n = createI18n({
@@ -64,7 +66,7 @@ export async function loadLocaleMessages(locale: string) {
return;
}
const messageParts = await Promise.all(loaders.map(loader => loader()));
const messageParts = await Promise.all(loaders.map((loader) => loader()));
i18n.global.setLocaleMessage(locale, merge({}, ...messageParts));
loadedLocales.add(locale);
}
@@ -75,7 +77,11 @@ export const i18nPlugin: Plugin = {
// Messages arrive after the switch; vue-i18n falls back to English until
// setLocaleMessage triggers a reactive re-render. Watching through the getter
// avoids depending on vue-i18n's locale ref generics.
watch(() => getCurrentLocale(), locale => loadLocaleMessages(locale), { immediate: true });
watch(
() => getCurrentLocale(),
(locale) => loadLocaleMessages(locale),
{ immediate: true },
);
},
};
+6 -6
View File
@@ -18,11 +18,11 @@ export function createPlausibleInstance({
config,
}: {
config: {
isTrackerEnabled: boolean
domain: string
apiHost: string
trackLocalhost: boolean
}
isTrackerEnabled: boolean;
domain: string;
apiHost: string;
trackLocalhost: boolean;
};
}): PlausibleInstance {
// `init` throws when no domain is configured. Without a domain the events would be attributed to
// nothing anyway, so stay with the no-op instance instead.
@@ -46,7 +46,7 @@ export function createPlausibleInstance({
}
return {
trackEvent: eventName => track(eventName, {}),
trackEvent: (eventName) => track(eventName, {}),
// `init` already captures pageviews, `autoCapturePageviews` being enabled by default
enableAutoPageviews: noop,
};
+3 -4
View File
@@ -10,9 +10,8 @@ import { useAppTheme } from './ui/theme/themes';
// Conditional dynamic import: import.meta.env.DEV is statically false in production
// builds, so the demo gallery (and everything it imports: c-markdown, markdown-it, …)
// is dead-code-eliminated from the bundle instead of shipping in the entry graph.
const demoRoutes = import.meta.env.DEV && config.app.env === 'development'
? (await import('./ui/demo/demo.routes')).routes
: [];
const demoRoutes =
import.meta.env.DEV && config.app.env === 'development' ? (await import('./ui/demo/demo.routes')).routes : [];
const $loading = useLoading();
const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
@@ -24,7 +23,7 @@ const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({
const toolsRedirectRoutes = tools
.filter(({ redirectFrom }) => redirectFrom && redirectFrom.length > 0)
.flatMap(
({ path, redirectFrom }) => redirectFrom?.map(redirectSource => ({ path: redirectSource, redirect: path })) ?? [],
({ path, redirectFrom }) => redirectFrom?.map((redirectSource) => ({ path: redirectSource, redirect: path })) ?? [],
);
const router = createRouter({
+15 -7
View File
@@ -17,15 +17,23 @@ export const useStyleStore = defineStore('style', {
const isSmallScreen = useMediaQuery('(max-width: 700px)');
const isMenuCollapsed = useITStorage('isMenuCollapsed', isSmallScreen.value) as Ref<boolean>;
watch(isSmallScreen, v => (isMenuCollapsed.value = v));
watch(isSmallScreen, (v) => (isMenuCollapsed.value = v));
// Keep browser UI (iOS Safari chrome, PWA title bar) matching the app background
watch(isDarkTheme, (isDark) => {
// Cast: naive-ui's Layout override type resolves to '{}' under
// tsconfig.vitest.json, even though the value is a plain color string
const themeColor = (isDark ? darkThemeOverrides.Layout?.color : lightThemeOverrides.Layout?.color) as string | undefined;
document.querySelector('meta[name="theme-color"]')?.setAttribute('content', themeColor ?? (isDark ? '#1c1c1c' : '#f1f5f9'));
}, { immediate: true });
watch(
isDarkTheme,
(isDark) => {
// Cast: naive-ui's Layout override type resolves to '{}' under
// tsconfig.vitest.json, even though the value is a plain color string
const themeColor = (isDark ? darkThemeOverrides.Layout?.color : lightThemeOverrides.Layout?.color) as
| string
| undefined;
document
.querySelector('meta[name="theme-color"]')
?.setAttribute('content', themeColor ?? (isDark ? '#1c1c1c' : '#f1f5f9'));
},
{ immediate: true },
);
return {
themeMode,
+1 -1
View File
@@ -4,5 +4,5 @@ import { appBaseUrl as base } from '@/utils/base-url';
// fetch runs concurrently with the config fetches in src/tools/index.ts (sibling async
// module subgraphs evaluate in parallel) instead of serially after them.
export const toolsSettings: Record<string, Record<string, any> | any> = await fetch(`${base}tools-settings.json`)
.then(response => (response.ok ? response.json() as Promise<Record<string, Record<string, any> | any>> : {}))
.then((response) => (response.ok ? (response.json() as Promise<Record<string, Record<string, any> | any>>) : {}))
.catch(() => ({}));
@@ -5,7 +5,10 @@ import UnitsConverter from '@/components/UnitsConverter.vue';
const supportedUnits = {
'g-force': { value: 'g-force', label: t('tools.acceleration-converter.texts.label-g-force') },
'm/s2': { value: 'meter per second squared', label: t('tools.acceleration-converter.texts.label-meter-per-second-squared') },
'm/s2': {
value: 'meter per second squared',
label: t('tools.acceleration-converter.texts.label-meter-per-second-squared'),
},
};
</script>
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.acceleration-converter.title'),
path: '/acceleration-converter',
description: t('tools.acceleration-converter.description'),
keywords: ['acceleration', 'converter',
'units', 'g (g-force)', 'm/s2',
],
keywords: ['acceleration', 'converter', 'units', 'g (g-force)', 'm/s2'],
component: () => import('./acceleration-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Run')),
createdAt: new Date('2026-01-30'),
@@ -24,7 +24,8 @@ const { searchResult } = useFlexSearch({
<c-input-text
v-model:value="search"
:placeholder="t('tools.ad-ldap-searcher.texts.placeholder-search-active-directory-ldap-mapping')"
mx-auto max-w-600px
mx-auto
max-w-600px
>
<template #prefix>
<icon-mdi-search mr-6px color-black op-70 dark:color-white />
@@ -33,11 +34,7 @@ const { searchResult } = useFlexSearch({
</div>
<div>
<div
v-if="searchResult.length === 0"
mt-4 text-center text-20px font-bold
>
<div v-if="searchResult.length === 0" mt-4 text-center text-20px font-bold>
{{ t('tools.ad-ldap-searcher.texts.tag-no-results') }}
</div>
@@ -16,8 +16,7 @@ const splittedPrompts = computed(() => {
splitLength: splitLength.value,
newLine: true,
});
}
catch (e: any) {
} catch (e: any) {
return [e.toString()];
}
});
@@ -26,7 +25,7 @@ const promptValidation = useValidation({
source: prompt,
rules: [
{
validator: v => v !== '',
validator: (v) => v !== '',
message: t('tools.ai-prompt-splitter.texts.message-prompt-must-not-be-empty'),
},
],
+7 -7
View File
@@ -1,7 +1,7 @@
declare module "chatgpt-prompt-splitter" {
export default function promptSplitter(options: {
prompt: string
splitLength: number
newLine: boolean
}): Array<string>;
}
declare module 'chatgpt-prompt-splitter' {
export default function promptSplitter(options: {
prompt: string;
splitLength: number;
newLine: boolean;
}): Array<string>;
}
@@ -301,8 +301,8 @@ describe('StandardAmortizationCalculator', () => {
// 60 months + 5 year summary rows = 65 total
expect(schedule).toHaveLength(65);
const monthRows = schedule.filter(row => row.type === 'month');
const yearRows = schedule.filter(row => row.type === 'year');
const monthRows = schedule.filter((row) => row.type === 'month');
const yearRows = schedule.filter((row) => row.type === 'year');
expect(monthRows).toHaveLength(60);
expect(yearRows).toHaveLength(5);
@@ -331,7 +331,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params));
// Filter to only month rows for balance comparison
const monthRows = schedule.filter(row => row.type === 'month');
const monthRows = schedule.filter((row) => row.type === 'month');
for (let i = 1; i < monthRows.length; i++) {
expect(monthRows[i].remainingBalance).toBeLessThan(monthRows[i - 1].remainingBalance);
@@ -346,7 +346,7 @@ describe('StandardAmortizationCalculator', () => {
};
const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month');
const monthRows = schedule.filter((row) => row.type === 'month');
const lastMonthPayment = monthRows[monthRows.length - 1];
expect(lastMonthPayment.remainingBalance).toBeCloseTo(0, 0);
@@ -376,7 +376,7 @@ describe('StandardAmortizationCalculator', () => {
};
const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month');
const monthRows = schedule.filter((row) => row.type === 'month');
const firstPayment = monthRows[0].payment;
monthRows.forEach((payment) => {
@@ -392,7 +392,7 @@ describe('StandardAmortizationCalculator', () => {
};
const schedule = Array.from(calculator.getAmortizationSchedule(params));
const yearRows = schedule.filter(row => row.type === 'year');
const yearRows = schedule.filter((row) => row.type === 'year');
expect(yearRows).toHaveLength(2); // 2 years
expect(yearRows[0].paymentIndex).toBe(1); // Year 1
@@ -407,8 +407,8 @@ describe('StandardAmortizationCalculator', () => {
};
const schedule = Array.from(calculator.getAmortizationSchedule(params));
const monthRows = schedule.filter(row => row.type === 'month');
const yearRows = schedule.filter(row => row.type === 'year');
const monthRows = schedule.filter((row) => row.type === 'month');
const yearRows = schedule.filter((row) => row.type === 'year');
// Calculate cumulative totals for the year
const totalPrincipal = monthRows.reduce((sum, row) => sum + row.principalPayment, 0);
@@ -465,7 +465,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params));
// 3 months, no year summary (< 12 months)
expect(schedule).toHaveLength(3);
const monthRows = schedule.filter(row => row.type === 'month');
const monthRows = schedule.filter((row) => row.type === 'month');
expect(monthRows[2].remainingBalance).toBeCloseTo(0, 0);
});
@@ -479,7 +479,7 @@ describe('StandardAmortizationCalculator', () => {
const schedule = Array.from(calculator.getAmortizationSchedule(params));
// 480 months + 40 year summary rows = 520 total
expect(schedule).toHaveLength(520);
const monthRows = schedule.filter(row => row.type === 'month');
const monthRows = schedule.filter((row) => row.type === 'month');
expect(monthRows).toHaveLength(480);
expect(monthRows[479].remainingBalance).toBeCloseTo(0, 0);
});
@@ -1,23 +1,23 @@
export interface AmortizationParams {
readonly principal: number
readonly periodInterestRate: number
readonly numberOfPayments: number
readonly principal: number;
readonly periodInterestRate: number;
readonly numberOfPayments: number;
}
export interface CachedPaymentResults {
readonly payment: number
readonly totalPayments: number
readonly payment: number;
readonly totalPayments: number;
}
export interface GetNthResult extends CachedPaymentResults {
readonly paymentIndex: number
readonly principalPayment: number
readonly interestPayment: number
readonly remainingBalance: number
readonly paymentIndex: number;
readonly principalPayment: number;
readonly interestPayment: number;
readonly remainingBalance: number;
}
export interface AmortizationScheduleItem extends GetNthResult {
readonly type: 'month' | 'year'
readonly type: 'month' | 'year';
}
type AmortizationPaymentCacheKey = `principal:${number};interest-rate:${number};number-of-payments:${number}`;
@@ -162,8 +162,8 @@ export class StandardAmortizationCalculator extends AmortizationCalculator {
const r = 1 + periodInterestRate;
const balanceBeforePayment
= principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
const balanceBeforePayment =
principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
const interestPayment = balanceBeforePayment * periodInterestRate;
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.angle-converter.title'),
path: '/angle-converter',
description: t('tools.angle-converter.description'),
keywords: ['angle', 'converter',
'units', 'degree', 'radian', 'turn', 'grad',
],
keywords: ['angle', 'converter', 'units', 'degree', 'radian', 'turn', 'grad'],
component: () => import('./angle-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Angle')),
createdAt: new Date('2024-08-15'),
@@ -1,9 +1,7 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { onMounted, ref } from 'vue';
import {
NButton, NCheckbox, NCheckboxGroup, NInput,
} from 'naive-ui';
import { NButton, NCheckbox, NCheckboxGroup, NInput } from 'naive-ui';
import { Terminal } from '@xterm/xterm';
import '@xterm/xterm/css/xterm.css';
import styles from 'ansi-styles';
@@ -27,11 +25,9 @@ const outputEscapeSequence = computed(() => {
if (foregroundColor.value) {
if (colorMode.value === 'basic') {
openSeq += styles.color.ansi(styles.hexToAnsi(foregroundColor.value));
}
else if (colorMode.value === '256') {
} else if (colorMode.value === '256') {
openSeq += styles.color.ansi256(styles.hexToAnsi256(foregroundColor.value));
}
else {
} else {
openSeq += styles.color.ansi16m(...styles.hexToRgb(foregroundColor.value));
}
closeSeq = styles.color.close + closeSeq;
@@ -39,11 +35,9 @@ const outputEscapeSequence = computed(() => {
if (backgroundColor.value) {
if (colorMode.value === 'basic') {
openSeq += styles.bgColor.ansi(styles.hexToAnsi(backgroundColor.value));
}
else if (colorMode.value === '256') {
} else if (colorMode.value === '256') {
openSeq += styles.bgColor.ansi256(styles.hexToAnsi256(backgroundColor.value));
}
else {
} else {
openSeq += styles.bgColor.ansi16m(...styles.hexToRgb(backgroundColor.value));
}
closeSeq = styles.bgColor.close + closeSeq;
@@ -75,7 +69,7 @@ onMounted(() => {
writeTermAndScrollBottom(outputEscapeSequence.value);
});
watch(outputEscapeSequence, seq => writeTermAndScrollBottom(seq), { immediate: true });
watch(outputEscapeSequence, (seq) => writeTermAndScrollBottom(seq), { immediate: true });
const escapeSequenceToTest = useQueryParam({ tool: 'ansi', name: 'seq', defaultValue: '' });
</script>
@@ -142,7 +136,10 @@ const escapeSequenceToTest = useQueryParam({ tool: 'ansi', name: 'seq', defaultV
</c-card>
<c-card :title="t('tools.ansi-escape-tester.texts.title-terminal-preview')">
<n-form-item label-placement="left" :label="t('tools.ansi-escape-tester.texts.label-custom-ansi-sequence')">
<NInput v-model:value="escapeSequenceToTest" :placeholder="t('tools.ansi-escape-tester.texts.placeholder-enter-ansi-escape-sequence')" />
<NInput
v-model:value="escapeSequenceToTest"
:placeholder="t('tools.ansi-escape-tester.texts.placeholder-enter-ansi-escape-sequence')"
/>
<NButton type="primary" ml-1 @click="term?.writeln(escapeSequenceToTest)">
{{ t('tools.ansi-escape-tester.texts.tag-test') }}
</NButton>
@@ -8,32 +8,26 @@ const { t } = useI18n();
const decryptedInput = ref('');
const encryptPassword = ref('');
const encryptId = ref('');
const cryptedOutput = computedAsync(
async () => {
try {
const v = new Vault({ password: encryptPassword.value });
return await v.encrypt(decryptedInput.value, encryptId.value);
}
catch (e: any) {
return e.toString();
}
},
);
const cryptedOutput = computedAsync(async () => {
try {
const v = new Vault({ password: encryptPassword.value });
return await v.encrypt(decryptedInput.value, encryptId.value);
} catch (e: any) {
return e.toString();
}
});
const cryptedInput = ref('');
const decryptPassword = ref('');
const decryptedOutput = computedAsync(
async () => {
try {
const v = new Vault({ password: decryptPassword.value });
// handle mac \r
return (await v.decrypt(cryptedInput.value?.replace(/\r(?!\n)/, '\n'), undefined)) ?? '';
}
catch (e: any) {
return e.toString();
}
},
);
const decryptedOutput = computedAsync(async () => {
try {
const v = new Vault({ password: decryptPassword.value });
// handle mac \r
return (await v.decrypt(cryptedInput.value?.replace(/\r(?!\n)/, '\n'), undefined)) ?? '';
} catch (e: any) {
return e.toString();
}
});
</script>
<template>
@@ -80,7 +74,9 @@ const decryptedOutput = computedAsync(
v-model:value="cryptedInput"
:placeholder="t('tools.ansible-vault-crypt-decrypt.texts.placeholder-put-your-encrypted-string-here')"
:label="t('tools.ansible-vault-crypt-decrypt.texts.label-string-to-decrypt')"
raw-text multiline mb-5
raw-text
multiline
mb-5
rows="5"
/>
+55 -22
View File
@@ -6,14 +6,26 @@ import TextareaCopyable from '@/components/TextareaCopyable.vue';
const { t } = useI18n();
interface KeyValuePair {
key: string
value?: string
key: string;
value?: string;
}
const baseUrl = useQueryParamOrStorage({ name: 'url', storageName: 'api-tester:url', defaultValue: '' });
const method = useQueryParamOrStorage({ name: 'method', storageName: 'api-tester:m', defaultValue: 'POST' });
const queryParams = useQueryParamOrStorage<KeyValuePair[]>({ name: 'params', storageName: 'api-tester:params', defaultValue: [] });
const headers = useQueryParamOrStorage<KeyValuePair[]>({ name: 'headers', storageName: 'api-tester:headers', defaultValue: [] });
const contentType = useQueryParamOrStorage({ name: 'ct', storageName: 'api-tester:ct', defaultValue: 'application/json' });
const queryParams = useQueryParamOrStorage<KeyValuePair[]>({
name: 'params',
storageName: 'api-tester:params',
defaultValue: [],
});
const headers = useQueryParamOrStorage<KeyValuePair[]>({
name: 'headers',
storageName: 'api-tester:headers',
defaultValue: [],
});
const contentType = useQueryParamOrStorage({
name: 'ct',
storageName: 'api-tester:ct',
defaultValue: 'application/json',
});
const body = useQueryParamOrStorage({ name: 'body', storageName: 'api-tester:body', defaultValue: '' });
const noCORS = ref(false);
const apiCallResult = ref();
@@ -40,23 +52,20 @@ async function callAPI() {
const response = await fetch(url, {
method: method.value,
headers: queryHeaders,
body: (method.value === 'GET' || method.value === 'HEAD') ? null : body.value,
body: method.value === 'GET' || method.value === 'HEAD' ? null : body.value,
mode: noCORS.value ? 'no-cors' : 'cors',
});
let responseText = await response.text();
try {
responseText = JSON.stringify(JSON.parse(responseText), null, 2);
}
catch (_) {
}
} catch (_) {}
apiCallResult.value = {
code: response.status,
error: '',
result: responseText,
};
}
catch (err: any) {
} catch (err: any) {
apiCallResult.value = {
code: -1,
error: err.toString(),
@@ -97,8 +106,16 @@ function emptyKeyPair() {
</template>
<template #default="{ value }">
<div v-if="value" w-100 flex justify-center gap-2>
<c-input-text v-model:value="value.key" :placeholder="t('tools.api-tester.texts.placeholder-header-name')" type="text" />
<c-input-text v-model:value="value.value" :placeholder="t('tools.api-tester.texts.placeholder-value')" type="text" />
<c-input-text
v-model:value="value.key"
:placeholder="t('tools.api-tester.texts.placeholder-header-name')"
type="text"
/>
<c-input-text
v-model:value="value.value"
:placeholder="t('tools.api-tester.texts.placeholder-value')"
type="text"
/>
</div>
</template>
</n-dynamic-input>
@@ -117,8 +134,16 @@ function emptyKeyPair() {
</template>
<template #default="{ value }">
<div v-if="value" w-100 flex justify-center gap-2>
<c-input-text v-model:value="value.key" :placeholder="t('tools.api-tester.texts.placeholder-param-name')" type="text" />
<c-input-text v-model:value="value.value" :placeholder="t('tools.api-tester.texts.placeholder-value')" type="text" />
<c-input-text
v-model:value="value.key"
:placeholder="t('tools.api-tester.texts.placeholder-param-name')"
type="text"
/>
<c-input-text
v-model:value="value.value"
:placeholder="t('tools.api-tester.texts.placeholder-value')"
type="text"
/>
</div>
</template>
</n-dynamic-input>
@@ -143,15 +168,23 @@ function emptyKeyPair() {
</c-button>
</div>
</c-card>
<n-spin
v-if="inprogress"
size="small"
/>
<c-alert v-if="!inprogress && apiCallResult && apiCallResult.code !== 200" type="error" mt-12 :title="t('tools.api-tester.texts.title-error-while-calling-api')">
<p><strong>Status code = {{ apiCallResult.code }}</strong></p>
<n-spin v-if="inprogress" size="small" />
<c-alert
v-if="!inprogress && apiCallResult && apiCallResult.code !== 200"
type="error"
mt-12
:title="t('tools.api-tester.texts.title-error-while-calling-api')"
>
<p>
<strong>Status code = {{ apiCallResult.code }}</strong>
</p>
<TextareaCopyable :value="apiCallResult.error" copy-placement="none" />
</c-alert>
<c-card v-if="!inprogress && apiCallResult && apiCallResult.code === 200" mt-12 :title="t('tools.api-tester.texts.title-api-call-result')">
<c-card
v-if="!inprogress && apiCallResult && apiCallResult.code === 200"
mt-12
:title="t('tools.api-tester.texts.title-api-call-result')"
>
<TextareaCopyable :value="apiCallResult.result" word-wrap />
</c-card>
</div>
+1 -3
View File
@@ -5,9 +5,7 @@ export const tool = defineTool({
name: t('tools.area-converter.title'),
path: '/area-converter',
description: t('tools.area-converter.description'),
keywords: ['area', 'converter',
'units', 'square meter', 'are', 'square',
],
keywords: ['area', 'converter', 'units', 'square meter', 'are', 'square'],
component: () => import('./area-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/SquaresDiagonal')),
createdAt: new Date('2024-08-15'),
+16 -12
View File
@@ -7,7 +7,11 @@ const { t } = useI18n();
// Inputs
const password = ref('');
const algorithm = useQueryParamOrStorage<'argon2id' | 'argon2i' | 'argon2d'>({ name: 'algo', storageName: 'argon2:a', defaultValue: 'argon2id' });
const algorithm = useQueryParamOrStorage<'argon2id' | 'argon2i' | 'argon2d'>({
name: 'algo',
storageName: 'argon2:a',
defaultValue: 'argon2id',
});
// Parameters
const salt = useQueryParamOrStorage({ name: 'salt', storageName: 'argon2:s', defaultValue: '' });
@@ -15,7 +19,11 @@ const iterations = useQueryParamOrStorage({ name: 'iter', storageName: 'argon2:i
const memorySizeKB = useQueryParamOrStorage({ name: 'memory', storageName: 'argon2:m', defaultValue: 512 });
const parallelism = useQueryParamOrStorage({ name: 'paral', storageName: 'argon2:p', defaultValue: 1 });
const hashLength = useQueryParamOrStorage({ name: 'len', storageName: 'argon2:l', defaultValue: 32 });
const outputType = useQueryParamOrStorage<'hex' | 'encoded' | 'binary'>({ name: 'output', storageName: 'argon2:o', defaultValue: 'encoded' });
const outputType = useQueryParamOrStorage<'hex' | 'encoded' | 'binary'>({
name: 'output',
storageName: 'argon2:o',
defaultValue: 'encoded',
});
// Result
const result = ref('');
@@ -45,16 +53,10 @@ async function generateHash() {
outputType: outputType.value,
} as const;
const fn
= algorithm.value === 'argon2id'
? argon2id
: algorithm.value === 'argon2i'
? argon2i
: argon2d;
const fn = algorithm.value === 'argon2id' ? argon2id : algorithm.value === 'argon2i' ? argon2i : argon2d;
result.value = await fn(options);
}
catch (err: any) {
} catch (err: any) {
error.value = err.toString();
}
}
@@ -65,7 +67,8 @@ async function generateHash() {
<NForm label-width="120" label-placement="left">
<NFormItem :label="t('tools.argon2-hash.texts.label-algorithm')">
<NSelect
v-model:value="algorithm" :options="[
v-model:value="algorithm"
:options="[
{ label: t('tools.argon2-hash.texts.label-argon2id'), value: 'argon2id' },
{ label: t('tools.argon2-hash.texts.label-argon2i'), value: 'argon2i' },
{ label: t('tools.argon2-hash.texts.label-argon2d'), value: 'argon2d' },
@@ -101,7 +104,8 @@ async function generateHash() {
<NFormItem :label="t('tools.argon2-hash.texts.label-output-type')">
<NSelect
v-model:value="outputType" :options="[
v-model:value="outputType"
:options="[
{ label: t('tools.argon2-hash.texts.label-hex'), value: 'hex' },
{ label: t('tools.argon2-hash.texts.label-encoded'), value: 'encoded' },
{ label: t('tools.argon2-hash.texts.label-binary'), value: 'binary' },
+5 -3
View File
@@ -9,8 +9,7 @@ const arpaInput = ref('');
const decodedIP = computed(() => {
try {
return fromARPA(arpaInput.value.trim());
}
catch (e: any) {
} catch (e: any) {
return `# ${e.toString()}`;
}
});
@@ -19,7 +18,10 @@ const decodedIP = computed(() => {
<template>
<div>
<NFormItem :label="t('tools.arpa-decoder.texts.label-arpa-address')" label-placement="left" mb-2>
<NInput v-model:value="arpaInput" :placeholder="t('tools.arpa-decoder.texts.placeholder-e-g-10-1-168-192-in-addr-arpa-or-xxxx-ip6-arpa')" />
<NInput
v-model:value="arpaInput"
:placeholder="t('tools.arpa-decoder.texts.placeholder-e-g-10-1-168-192-in-addr-arpa-or-xxxx-ip6-arpa')"
/>
</NFormItem>
<c-card v-if="decodedIP">
@@ -1,13 +1,13 @@
// aspect-ratio-calculator.service.ts
export interface AspectRatio {
r1: number
r2: number
r1: number;
r2: number;
}
export interface Dimensions {
width: number
height: number
width: number;
height: number;
}
export function calculateAspectRatio(width: number, height: number): AspectRatio {
@@ -19,16 +19,11 @@ export function calculateAspectRatio(width: number, height: number): AspectRatio
};
}
export function calculateDimensions(
knownDimension: number,
ratio: AspectRatio,
isWidth: boolean,
): Dimensions {
export function calculateDimensions(knownDimension: number, ratio: AspectRatio, isWidth: boolean): Dimensions {
if (isWidth) {
const height = Math.round((knownDimension * ratio.r2) / ratio.r1);
return { width: knownDimension, height };
}
else {
} else {
const width = Math.round((knownDimension * ratio.r1) / ratio.r2);
return { width, height: knownDimension };
}
@@ -3,10 +3,7 @@
import { useI18n } from 'vue-i18n';
import { ref } from 'vue';
import { NButton, NRadio, NRadioGroup, NSpace } from 'naive-ui';
import {
calculateAspectRatio,
calculateDimensions,
} from './aspect-ratio-calculator.service';
import { calculateAspectRatio, calculateDimensions } from './aspect-ratio-calculator.service';
const { t } = useI18n();
@@ -22,37 +19,30 @@ function calculateResult() {
const ratio = calculateAspectRatio(width.value, height.value);
if (r2.value) {
r1.value = ratio.r1 / ratio.r2;
}
else if (r1.value) {
} else if (r1.value) {
r2.value = ratio.r2 / ratio.r1;
}
else {
} else {
r1.value = ratio.r1;
r2.value = ratio.r2;
}
if (ratio.r1 !== r1.value) {
result.value = `Aspect Ratio: ${r1.value}:${r2.value} or ${ratio.r1}:${ratio.r2}`;
}
else {
} else {
result.value = `Aspect Ratio: ${ratio.r1}:${ratio.r2}`;
}
}
else if (mode.value === 'dimensions' && r1.value && r2.value) {
} else if (mode.value === 'dimensions' && r1.value && r2.value) {
if (width.value) {
const dimensions = calculateDimensions(width.value, { r1: r1.value, r2: r2.value }, true);
height.value = dimensions.height;
result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`;
}
else if (height.value) {
} else if (height.value) {
const dimensions = calculateDimensions(height.value, { r1: r1.value, r2: r2.value }, false);
width.value = dimensions.width;
result.value = `Dimensions: ${dimensions.width}x${dimensions.height}`;
}
else {
} else {
result.value = 'Please enter either width or height to calculate dimensions';
}
}
else {
} else {
result.value = 'Please fill in the required fields';
}
}
@@ -85,25 +75,41 @@ function clearRatio() {
<div class="input-group">
<div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-width') }}</label>
<n-input-number-i18n v-model:value="width" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-width')" :min="1" />
<n-input-number-i18n
v-model:value="width"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-width')"
:min="1"
/>
</div>
<div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-pixels-height') }}</label>
<n-input-number-i18n v-model:value="height" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-height')" :min="1" />
<n-input-number-i18n
v-model:value="height"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-pixels-height')"
:min="1"
/>
</div>
</div>
<div class="input-group">
<div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-width') }}</label>
<n-input-number-i18n v-model:value="r1" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-width')" :min="1" />
<n-input-number-i18n
v-model:value="r1"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-width')"
:min="1"
/>
</div>
<div class="separator">
{{ t('tools.aspect-ratio-calculator.texts.tag-') }}
</div>
<div class="input-pair">
<label>{{ t('tools.aspect-ratio-calculator.texts.tag-ratio-height') }}</label>
<n-input-number-i18n v-model:value="r2" :placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-height')" :min="1" />
<n-input-number-i18n
v-model:value="r2"
:placeholder="t('tools.aspect-ratio-calculator.texts.placeholder-ratio-height')"
:min="1"
/>
</div>
</div>
@@ -14,7 +14,11 @@ const scale = useQueryParamOrStorage({ name: 'scale', storageName: 'barcode-gen:
const height = useQueryParamOrStorage({ name: 'height', storageName: 'barcode-gen:height', defaultValue: 25 });
const margin = useQueryParamOrStorage({ name: 'margin', storageName: 'barcode-gen:margin', defaultValue: 10 });
const format = useQueryParamOrStorage({ name: 'format', storageName: 'barcode-gen:format', defaultValue: 'code128' });
const displayValue = useQueryParamOrStorage({ name: 'display', storageName: 'barcode-gen:display', defaultValue: true });
const displayValue = useQueryParamOrStorage({
name: 'display',
storageName: 'barcode-gen:display',
defaultValue: true,
});
const value = useQueryParam({ tool: 'barcode-gen', name: 'text', defaultValue: '123456789' });
const barcodeCanvas = ref<HTMLCanvasElement>();
@@ -39,8 +43,7 @@ watchEffect(() => {
try {
bwipjs.toCanvas(barcodeCanvas.value, options.value);
}
catch (e: any) {
} catch (e: any) {
error.value = e.toString();
}
});
@@ -51,8 +54,7 @@ const barcodePNG = computed(() => {
const barcodeSVG = computed(() => {
try {
return Base64.encode(bwipjs.toSVG(options.value));
}
catch (e: any) {
} catch (e: any) {
return '';
}
});
+64 -64
View File
@@ -1,82 +1,82 @@
declare module 'bwip-js/browser' {
export interface BwippOptions {
includecheck?: boolean | undefined;
includecheckintext?: boolean | undefined;
export interface BwippOptions {
includecheck?: boolean | undefined;
includecheckintext?: boolean | undefined;
parse?: boolean | undefined;
parsefnc?: boolean | undefined;
parse?: boolean | undefined;
parsefnc?: boolean | undefined;
height?: number | undefined;
width?: number | undefined;
height?: number | undefined;
width?: number | undefined;
inkspread?: number | undefined;
inkspreadh?: number | undefined;
inkspreadv?: number | undefined;
dotty?: boolean | undefined;
inkspread?: number | undefined;
inkspreadh?: number | undefined;
inkspreadv?: number | undefined;
dotty?: boolean | undefined;
binarytext?: boolean | undefined; // really a bwip-js option but better positioned here
includetext?: boolean | undefined;
textfont?: string | undefined;
textsize?: number | undefined;
textgaps?: number | undefined;
alttext?: string | undefined;
binarytext?: boolean | undefined; // really a bwip-js option but better positioned here
includetext?: boolean | undefined;
textfont?: string | undefined;
textsize?: number | undefined;
textgaps?: number | undefined;
alttext?: string | undefined;
textxalign?: 'offleft' | 'left' | 'center' | 'right' | 'offright' | 'justify' | undefined;
textyalign?: 'below' | 'center' | 'above' | undefined;
textxoffset?: number | undefined;
textyoffset?: number | undefined;
textxalign?: 'offleft' | 'left' | 'center' | 'right' | 'offright' | 'justify' | undefined;
textyalign?: 'below' | 'center' | 'above' | undefined;
textxoffset?: number | undefined;
textyoffset?: number | undefined;
showborder?: boolean | undefined;
borderwidth?: number | undefined;
borderleft?: number | undefined;
borderright?: number | undefined;
bordertop?: number | undefined;
boraderbottom?: number | undefined;
showborder?: boolean | undefined;
borderwidth?: number | undefined;
borderleft?: number | undefined;
borderright?: number | undefined;
bordertop?: number | undefined;
boraderbottom?: number | undefined;
barcolor?: string | undefined;
backgroundcolor?: string | undefined;
bordercolor?: string | undefined;
textcolor?: string | undefined;
barcolor?: string | undefined;
backgroundcolor?: string | undefined;
bordercolor?: string | undefined;
textcolor?: string | undefined;
addontextxoffset?: number | undefined;
addontextyoffset?: number | undefined;
addontextfont?: string | undefined;
addontextsize?: number | undefined;
addontextxoffset?: number | undefined;
addontextyoffset?: number | undefined;
addontextfont?: string | undefined;
addontextsize?: number | undefined;
guardwhitespace?: boolean | undefined;
guardwidth?: number | undefined;
guardheight?: number | undefined;
guardleftpos?: number | undefined;
guardrightpos?: number | undefined;
guardleftypos?: number | undefined;
guardrightypos?: number | undefined;
}
export interface RenderOptions extends BwippOptions {
bcid: string;
text: string;
guardwhitespace?: boolean | undefined;
guardwidth?: number | undefined;
guardheight?: number | undefined;
guardleftpos?: number | undefined;
guardrightpos?: number | undefined;
guardleftypos?: number | undefined;
guardrightypos?: number | undefined;
}
export interface RenderOptions extends BwippOptions {
bcid: string;
text: string;
scaleX?: number | undefined;
scaleY?: number | undefined;
scale?: number | undefined;
scaleX?: number | undefined;
scaleY?: number | undefined;
scale?: number | undefined;
rotate?: 'N' | 'R' | 'L' | 'I' | undefined;
rotate?: 'N' | 'R' | 'L' | 'I' | undefined;
paddingwidth?: number | undefined;
paddingheight?: number | undefined;
paddingwidth?: number | undefined;
paddingheight?: number | undefined;
paddingleft?: number | undefined;
paddingright?: number | undefined;
paddingtop?: number | undefined;
paddingbottom?: number | undefined;
paddingleft?: number | undefined;
paddingright?: number | undefined;
paddingtop?: number | undefined;
paddingbottom?: number | undefined;
monochrome?: boolean | undefined;
sizelimit?: number | undefined;
}
monochrome?: boolean | undefined;
sizelimit?: number | undefined;
}
export const BWIPP_VERSION: string;
export const BWIPJS_VERSION: string;
export const BWIPP_VERSION: string;
export const BWIPJS_VERSION: string;
export function toSVG(opts: RenderOptions): string;
export function toSVG(opts: RenderOptions): string;
export function toCanvas(canvas: string | HTMLCanvasElement, opts: RenderOptions): HTMLCanvasElement;
}
export function toCanvas(canvas: string | HTMLCanvasElement, opts: RenderOptions): HTMLCanvasElement;
}
+6 -8
View File
@@ -12,10 +12,9 @@ const barCode = computedAsync(async () => {
}
try {
const barcodeReader = new BrowserMultiFormatReader();
const result = (await barcodeReader.decodeFromImageUrl(imageBase64.value));
const result = await barcodeReader.decodeFromImageUrl(imageBase64.value);
return { text: result.getText(), format: BarcodeFormat[result.getBarcodeFormat()], error: '' };
}
catch (e: any) {
} catch (e: any) {
return { error: e.toString(), text: '', format: '' };
}
});
@@ -50,11 +49,10 @@ async function onUpload(file: File) {
<div v-if="barCode?.text">
<n-divider />
<h3>{{ t('tools.barcode-reader.texts.tag-decoded') }}<span v-if="barCode?.format">({{ barCode?.format }})</span></h3>
<TextareaCopyable
:value="barCode?.text"
:word-wrap="true"
/>
<h3>
{{ t('tools.barcode-reader.texts.tag-decoded') }}<span v-if="barCode?.format">({{ barCode?.format }})</span>
</h3>
<TextareaCopyable :value="barCode?.text" :word-wrap="true" />
</div>
<c-alert v-if="barCode?.error">
{{ barCode?.error }}
@@ -3,7 +3,12 @@ import { useI18n } from 'vue-i18n';
import { useBase64 } from '@vueuse/core';
import type { Ref } from 'vue';
import { useCopy } from '@/composable/copy';
import { getExtensionFromMimeType, getMimeTypeFromBase64, previewImageFromBase64, useDownloadFileFromBase64Refs } from '@/composable/downloadBase64';
import {
getExtensionFromMimeType,
getMimeTypeFromBase64,
previewImageFromBase64,
useDownloadFileFromBase64Refs,
} from '@/composable/downloadBase64';
import { useValidation } from '@/composable/validation';
import { isValidBase64 } from '@/utils/base64';
@@ -12,31 +17,27 @@ const { t } = useI18n();
const fileName = ref('file');
const fileExtension = ref('');
const base64Input = ref('');
const { download } = useDownloadFileFromBase64Refs(
{
source: base64Input,
filename: fileName,
extension: fileExtension,
});
const { download } = useDownloadFileFromBase64Refs({
source: base64Input,
filename: fileName,
extension: fileExtension,
});
const base64InputValidation = useValidation({
source: base64Input,
rules: [
{
message: t('tools.base64-file-converter.texts.message-invalid-base-64-string'),
validator: value => isValidBase64(value.trim()),
validator: (value) => isValidBase64(value.trim()),
},
],
});
watch(
base64Input,
(newValue, _) => {
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
if (mimeType) {
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
}
},
);
watch(base64Input, (newValue, _) => {
const { mimeType } = getMimeTypeFromBase64({ base64String: newValue });
if (mimeType) {
fileExtension.value = getExtensionFromMimeType(mimeType) || fileExtension.value;
}
});
function previewImage() {
if (!base64InputValidation.isValid) {
@@ -51,8 +52,7 @@ function previewImage() {
previewContainer.innerHTML = '';
previewContainer.appendChild(image);
}
}
catch (_) {
} catch (_) {
//
}
}
@@ -64,8 +64,7 @@ function downloadFile() {
try {
download();
}
catch (_) {
} catch (_) {
//
}
}
@@ -79,7 +78,10 @@ const cleanedFileBase64 = computed(() => {
}
return fileBase64.value.replace(/^data:[^;]*;base64,/, '');
});
const { copy: copyFileBase64 } = useCopy({ source: cleanedFileBase64, text: t('tools.base64-file-converter.texts.text-base64-string-copied-to-the-clipboard') });
const { copy: copyFileBase64 } = useCopy({
source: cleanedFileBase64,
text: t('tools.base64-file-converter.texts.text-base64-string-copied-to-the-clipboard'),
});
async function onUpload(file: File) {
if (file) {
@@ -145,7 +147,14 @@ async function onUpload(file: File) {
</n-checkbox>
</n-space>
<c-input-text :value="cleanedFileBase64" multiline readonly :placeholder="t('tools.base64-file-converter.texts.placeholder-file-in-base64-will-be-here')" rows="5" my-2 />
<c-input-text
:value="cleanedFileBase64"
multiline
readonly
:placeholder="t('tools.base64-file-converter.texts.placeholder-file-in-base64-will-be-here')"
rows="5"
my-2
/>
<div flex justify-center>
<c-button @click="copyFileBase64()">
@@ -11,12 +11,14 @@ const textInput = ref('');
const base64Output = computed(() => {
try {
return Base64.fromUint8Array(hexArray.fromString(textInput.value));
}
catch (e: any) {
} catch (e: any) {
return e.toString();
}
});
const { copy: copyTextBase64 } = useCopy({ source: base64Output, text: t('tools.base64-hex-converter.texts.text-base64-hex-array-copied-to-the-clipboard') });
const { copy: copyTextBase64 } = useCopy({
source: base64Output,
text: t('tools.base64-hex-converter.texts.text-base64-hex-array-copied-to-the-clipboard'),
});
const uppercase = ref(false);
const grouping = ref(0);
@@ -30,13 +32,14 @@ const textOutput = computed(() => {
grouping: grouping.value,
rowlength: rowlength.value,
});
}
catch (e: any) {
} catch (e: any) {
return e.toString();
}
},
);
const { copy: copyText } = useCopy({ source: textOutput, text: t('tools.base64-hex-converter.texts.text-hex-array-copied-to-the-clipboard') });
});
const { copy: copyText } = useCopy({
source: textOutput,
text: t('tools.base64-hex-converter.texts.text-hex-array-copied-to-the-clipboard'),
});
const b64ValidationRules = [
{
message: t('tools.base64-hex-converter.texts.message-invalid-base64-string'),
@@ -62,7 +65,9 @@ const b64ValidationRules = [
:value="base64Output"
multiline
readonly
:placeholder="t('tools.base64-hex-converter.texts.placeholder-the-base64-encoding-of-your-hex-array-will-be-here')"
:placeholder="
t('tools.base64-hex-converter.texts.placeholder-the-base64-encoding-of-your-hex-array-will-be-here')
"
rows="5"
mb-5
/>
@@ -80,10 +85,14 @@ const b64ValidationRules = [
<n-switch v-model:value="uppercase" />
</n-form-item>
<n-form-item :label="t('tools.base64-hex-converter.texts.label-group-by')" label-placement="left">
<n-input-number-i18n v-model:value="grouping" :min="0" style="width: 6em" mr-1 />{{ t('tools.base64-hex-converter.texts.tag-digits-0-no-grouping') }}
<n-input-number-i18n v-model:value="grouping" :min="0" style="width: 6em" mr-1 />{{
t('tools.base64-hex-converter.texts.tag-digits-0-no-grouping')
}}
</n-form-item>
<n-form-item :label="t('tools.base64-hex-converter.texts.label-split-as-rows-by')" label-placement="left">
<n-input-number-i18n v-model:value="rowlength" :min="0" style="width: 6em" mr-1 />{{ t('tools.base64-hex-converter.texts.tag-group-of-digits-0-no-rows') }}
<n-input-number-i18n v-model:value="rowlength" :min="0" style="width: 6em" mr-1 />{{
t('tools.base64-hex-converter.texts.tag-group-of-digits-0-no-rows')
}}
</n-form-item>
</n-space>
<c-input-text
+9 -9
View File
@@ -8,7 +8,7 @@ set -euo pipefail
## ⌨️ Keyboard Shortcuts
| Keys | Does |
|---------------------|--------------------------------------------------|
| ------------------- | ------------------------------------------------ |
| `Ctrl+A` / `Ctrl+E` | Jump to the start / end of the line |
| `Ctrl+B` / `Ctrl+F` | Back / forward one character |
| `Alt+B` / `Alt+F` | Back / forward one word |
@@ -213,7 +213,7 @@ declare -i counter=0
```
| Variable | Holds |
|----------------------------------|-------------------------------------------|
| -------------------------------- | ----------------------------------------- |
| `$0` | The name of the script |
| `$1` … `$9` | Positional arguments |
| `$#` | How many arguments were passed |
@@ -230,7 +230,7 @@ declare -i counter=0
## 🔤 Parameter Expansion
| Expansion | Result |
|-------------------------|----------------------------------------------------------------------------|
| ----------------------- | -------------------------------------------------------------------------- |
| `${var:-default}` | `default` when `var` is unset or empty |
| `${var:=default}` | The same, and assigns it |
| `${var:?message}` | Abort with `message` when unset — great for required arguments |
@@ -285,7 +285,7 @@ done
Use `[[ ... ]]` in bash — it handles empty variables and patterns far better than the old `[ ... ]`.
| Files | True when |
|----------------|-------------------------------------------|
| -------------- | ----------------------------------------- |
| `-e file` | It exists |
| `-f file` | It exists and is a regular file |
| `-d file` | It exists and is a directory |
@@ -296,7 +296,7 @@ Use `[[ ... ]]` in bash — it handles empty variables and patterns far better t
| `f1 -nt f2` | `f1` is newer than `f2` (`-ot` for older) |
| Strings | True when |
|----------------|-----------------------------------------------|
| -------------- | --------------------------------------------- |
| `-z "$s"` | The string is empty |
| `-n "$s"` | The string is not empty |
| `"$a" == "$b"` | They are equal (`=` also works) |
@@ -306,7 +306,7 @@ Use `[[ ... ]]` in bash — it handles empty variables and patterns far better t
| `"$s" =~ ^re$` | Regex match, captures land in `$BASH_REMATCH` |
| Numbers | Meaning |
|---------|-----------------------|
| ------- | --------------------- |
| `-eq` | Equal |
| `-ne` | Not equal |
| `-lt` | Less than |
@@ -383,7 +383,7 @@ export -f greet
## ➡️ Redirection
| Syntax | Does |
|--------------------|--------------------------------------------|
| ------------------ | ------------------------------------------ |
| `> file` | Send stdout to a file, replacing it |
| `>> file` | Append stdout to a file |
| `2> file` | Send stderr to a file |
@@ -490,7 +490,7 @@ shellcheck script.sh
Escape sequences take the form `\033[<style>;<colour>m`, and `\033[0m` resets. `\e` and `\x1B` are the same character as `\033`.
| Colour | Foreground | Bright | Background |
|---------|------------|--------|------------|
| ------- | ---------- | ------ | ---------- |
| Black | `30` | `90` | `40` |
| Red | `31` | `91` | `41` |
| Green | `32` | `92` | `42` |
@@ -501,7 +501,7 @@ Escape sequences take the form `\033[<style>;<colour>m`, and `\033[0m` resets. `
| White | `37` | `97` | `47` |
| Style | Code | Style | Code |
|-------|------|-----------|------|
| ----- | ---- | --------- | ---- |
| Reset | `0` | Underline | `4` |
| Bold | `1` | Blink | `5` |
| Dim | `2` | Reverse | `7` |
+1 -1
View File
@@ -570,4 +570,4 @@ echo -e "${Green}这是绿色文本${Color_Off} 和正常文本"
echo -e "${Red}${On_White}这是白色背景上的红色测试${Color_Off}"
# 选项 -e 是必需的,它启用反斜杠转义解释
printf "${Red} 这是红色的 \n"
```
```
+21 -24
View File
@@ -2,26 +2,24 @@ import { getCurrentLocale, translate as t } from '@/plugins/i18n.plugin';
Intl.DurationFormat ??= class DurationFormat {
format(duration: { seconds?: number; milliseconds?: number }): string {
return 'seconds' in duration
? `${duration.seconds} seconds`
: `${duration.milliseconds} milliseconds`;
return 'seconds' in duration ? `${duration.seconds} seconds` : `${duration.milliseconds} milliseconds`;
}
};
export type Update<Result> =
| {
kind: 'progress'
progress: number
}
kind: 'progress';
progress: number;
}
| {
kind: 'success'
value: Result
timeTakenMs: number
}
kind: 'success';
value: Result;
timeTakenMs: number;
}
| {
kind: 'error'
message: string
};
kind: 'error';
message: string;
};
// generic type for the callback versions of bcryptjs's `hash` and `compare`
export type BcryptFn<Param, Result> = (
@@ -32,8 +30,8 @@ export type BcryptFn<Param, Result> = (
) => void;
interface BcryptWithProgressOptions {
signal: AbortSignal
timeoutMs: number
signal: AbortSignal;
timeoutMs: number;
}
export async function* bcryptWithProgressUpdates<Param, Result>(
@@ -44,13 +42,12 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
const { timeoutMs = 10_000 } = options ?? {};
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore: AbortSignal.any breaks typecheck
const signal: AbortSignal = AbortSignal.any([
AbortSignal.timeout(timeoutMs),
options?.signal,
].filter(x => x != null));
const signal: AbortSignal = AbortSignal.any(
[AbortSignal.timeout(timeoutMs), options?.signal].filter((x) => x != null),
);
let res = (_: Update<Result>) => {};
const nextPromise = () => new Promise<Update<Result>>(resolve => res = resolve);
const nextPromise = () => new Promise<Update<Result>>((resolve) => (res = resolve));
const promises = [nextPromise()];
const nextValue = (value: Update<Result>) => {
res(value);
@@ -74,8 +71,9 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
nextValue({ kind: 'progress', progress: 0 });
if (signal.reason instanceof DOMException && signal.reason.name === 'TimeoutError') {
const message = t('tools.bcrypt.texts.timed-out-after-timeout-period', {
timeoutPeriod: new Intl.DurationFormat(getCurrentLocale(), { style: 'long' })
.format({ seconds: Math.round(timeoutMs / 1000) }),
timeoutPeriod: new Intl.DurationFormat(getCurrentLocale(), { style: 'long' }).format({
seconds: Math.round(timeoutMs / 1000),
}),
});
nextValue({ kind: 'error', message });
@@ -83,8 +81,7 @@ export async function* bcryptWithProgressUpdates<Param, Result>(
// throw inside callback to cancel execution of hashing/comparing
throw signal.reason;
}
else {
} else {
nextValue({ kind: 'progress', progress });
}
},
+46 -14
View File
@@ -10,10 +10,10 @@ const { t, locale } = useI18n();
const themeVars = useThemeVars();
interface ExecutionState<T> {
result: T | null
percentage: number
error: string | null
timeTakenMs: number | null
result: T | null;
percentage: number;
error: string | null;
timeTakenMs: number | null;
}
const blankState = () => ({ result: null, percentage: 0, error: null, timeTakenMs: null });
@@ -89,7 +89,13 @@ initWatcher(compare, [compareString, compareHash], compareState);
mb-2
/>
<n-form-item :label="t('tools.bcrypt.texts.label-salt-count')" label-placement="left" label-width="120">
<n-input-number v-model:value="saltCount" :placeholder="t('tools.bcrypt.texts.placeholder-salt-rounds')" :max="20" :min="4" w-full />
<n-input-number
v-model:value="saltCount"
:placeholder="t('tools.bcrypt.texts.placeholder-salt-rounds')"
:max="20"
:min="4"
w-full
/>
</n-form-item>
<n-progress :percentage="hashState.percentage" :show-indicator="false" />
@@ -100,9 +106,15 @@ initWatcher(compare, [compareString, compareHash], compareState);
text-center
/>
<div mt-1 h-3 op-60>
{{ hashState.timeTakenMs == null ? '' : t('tools.bcrypt.texts.hashed-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: "long" }).format({ milliseconds: hashState.timeTakenMs }),
}) }}
{{
hashState.timeTakenMs == null
? ''
: t('tools.bcrypt.texts.hashed-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({
milliseconds: hashState.timeTakenMs,
}),
})
}}
</div>
<div mt-5 flex justify-center>
@@ -115,17 +127,31 @@ initWatcher(compare, [compareString, compareHash], compareState);
<c-card :title="t('tools.bcrypt.texts.title-compare-string-with-hash')">
<n-form label-width="120">
<n-form-item :label="t('tools.bcrypt.texts.label-your-string')" label-placement="left">
<c-input-text v-model:value="compareString" :placeholder="t('tools.bcrypt.texts.placeholder-your-string-to-compare')" raw-text />
<c-input-text
v-model:value="compareString"
:placeholder="t('tools.bcrypt.texts.placeholder-your-string-to-compare')"
raw-text
/>
</n-form-item>
<n-form-item :label="t('tools.bcrypt.texts.label-your-hash')" label-placement="left">
<c-input-text v-model:value="compareHash" :placeholder="t('tools.bcrypt.texts.placeholder-your-hash-to-compare')" raw-text />
<c-input-text
v-model:value="compareHash"
:placeholder="t('tools.bcrypt.texts.placeholder-your-hash-to-compare')"
raw-text
/>
</n-form-item>
<n-progress :percentage="compareState.percentage" :show-indicator="false" />
<div>
<c-input-text
id="bcrypt-compare-result"
:value="compareState.result == null ? undefined : compareState.result ? t('tools.bcrypt.texts.matched') : t('tools.bcrypt.texts.no-match')"
:value="
compareState.result == null
? undefined
: compareState.result
? t('tools.bcrypt.texts.matched')
: t('tools.bcrypt.texts.no-match')
"
:placeholder="compareState.error ?? t('tools.bcrypt.texts.comparison-result')"
readonly
text-center
@@ -134,9 +160,15 @@ initWatcher(compare, [compareString, compareHash], compareState);
/>
</div>
<div mb-1 mt-1 h-3 op-60>
{{ compareState.timeTakenMs == null ? '' : t('tools.bcrypt.texts.compared-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({ milliseconds: compareState.timeTakenMs }),
}) }}
{{
compareState.timeTakenMs == null
? ''
: t('tools.bcrypt.texts.compared-in-elapsed-period', {
elapsedPeriod: new Intl.DurationFormat(locale, { style: 'long' }).format({
milliseconds: compareState.timeTakenMs,
}),
})
}}
</div>
</n-form>
</c-card>
@@ -13,22 +13,28 @@ function computeAverage({ data }: { data: number[] }) {
function computeVariance({ data }: { data: number[] }) {
const mean = computeAverage({ data });
const squaredDiffs = data.map(value => (value - mean) ** 2);
const squaredDiffs = data.map((value) => (value - mean) ** 2);
return computeAverage({ data: squaredDiffs });
}
function arrayToMarkdownTable({ data, headerMap = {} }: { data: Record<string, unknown>[]; headerMap?: Record<string, string> }) {
function arrayToMarkdownTable({
data,
headerMap = {},
}: {
data: Record<string, unknown>[];
headerMap?: Record<string, string>;
}) {
if (!Array.isArray(data) || data.length === 0) {
return '';
}
const headers = Object.keys(data[0]);
const rows = data.map(obj => Object.values(obj));
const rows = data.map((obj) => Object.values(obj));
const headerRow = `| ${headers.map(header => headerMap[header] ?? header).join(' | ')} |`;
const headerRow = `| ${headers.map((header) => headerMap[header] ?? header).join(' | ')} |`;
const separatorRow = `| ${headers.map(() => '---').join(' | ')} |`;
const dataRows = rows.map(row => `| ${row.join(' | ')} |`).join('\n');
const dataRows = rows.map((row) => `| ${row.join(' | ')} |`).join('\n');
return `${headerRow}\n${separatorRow}\n${dataRows}`;
}
@@ -38,8 +38,8 @@ const results = computed(() => {
const deltaWithBestMean = mean - bestMean;
const ratioWithBestMean = bestMean === 0 ? '∞' : round(mean / bestMean);
const comparisonValues: string
= (index !== 0 && bestMean !== mean) ? ` (+${round(deltaWithBestMean)}${cleanUnit} ; x${ratioWithBestMean})` : '';
const comparisonValues: string =
index !== 0 && bestMean !== mean ? ` (+${round(deltaWithBestMean)}${cleanUnit} ; x${ratioWithBestMean})` : '';
return {
position: index + 1,
@@ -102,7 +102,9 @@ function copyAsBulletList() {
<div flex justify-center>
<c-button v-if="suites.length > 1" variant="text" @click="suites.splice(index, 1)">
<n-icon :component="Trash" depth="3" mr-2 size="18" />{{ t('tools.benchmark-builder.texts.tag-delete-suite') }}
<n-icon :component="Trash" depth="3" mr-2 size="18" />{{
t('tools.benchmark-builder.texts.tag-delete-suite')
}}
</c-button>
<c-button
variant="text"
@@ -118,7 +120,13 @@ function copyAsBulletList() {
<div style="flex: 0 0 100%">
<div style="max-width: 600px; margin: 0 auto">
<div mx-auto max-w-sm flex justify-center gap-3>
<c-input-text v-model:value="unit" :placeholder="t('tools.benchmark-builder.texts.placeholder-unit-eg-ms')" :label="t('tools.benchmark-builder.texts.label-unit')" label-position="left" mb-4 />
<c-input-text
v-model:value="unit"
:placeholder="t('tools.benchmark-builder.texts.placeholder-unit-eg-ms')"
:label="t('tools.benchmark-builder.texts.label-unit')"
label-position="left"
mb-4
/>
<c-button
@click="
@@ -32,13 +32,22 @@ const bimiRecord = computed(() => {
<NCard :title="t('tools.bimi-dns-generator.texts.title-bimi-dns-record-generator')">
<NForm :model="bimiData" label-placement="left" label-width="150px">
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-domain')">
<NInput v-model:value="bimiData.domain" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-example-com')" />
<NInput
v-model:value="bimiData.domain"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-example-com')"
/>
</NFormItem>
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-logo-url')">
<NInput v-model:value="bimiData.logoUrl" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-logo-svg')" />
<NInput
v-model:value="bimiData.logoUrl"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-logo-svg')"
/>
</NFormItem>
<NFormItem :label="t('tools.bimi-dns-generator.texts.label-vmc-certificate-url')">
<NInput v-model:value="bimiData.vmcUrl" :placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-vmc-pem')" />
<NInput
v-model:value="bimiData.vmcUrl"
:placeholder="t('tools.bimi-dns-generator.texts.placeholder-https-example-com-vmc-pem')"
/>
</NFormItem>
</NForm>
@@ -7,8 +7,16 @@ const { t } = useI18n();
type NumberFormat = 'dec' | 'hex' | 'oct' | 'bin';
const inputFormatA = useQueryParamOrStorage<NumberFormat>({ name: 'text', storageName: 'bin-calc:fa', defaultValue: 'dec' });
const inputFormatB = useQueryParamOrStorage<NumberFormat>({ name: 'text', storageName: 'bin-calc:fb', defaultValue: 'dec' });
const inputFormatA = useQueryParamOrStorage<NumberFormat>({
name: 'text',
storageName: 'bin-calc:fa',
defaultValue: 'dec',
});
const inputFormatB = useQueryParamOrStorage<NumberFormat>({
name: 'text',
storageName: 'bin-calc:fb',
defaultValue: 'dec',
});
const operation = useQueryParamOrStorage({ name: 'op', storageName: 'bin-calc:o', defaultValue: 'AND' });
const inputA = ref('');
const inputB = ref('');
@@ -34,7 +42,7 @@ const inputAValidation = useValidation({
watch: [inputFormatA],
rules: [
{
validator: v => parseInputA(v) !== null,
validator: (v) => parseInputA(v) !== null,
message: t('tools.binary-calculator.texts.message-number-is-invalid'),
},
],
@@ -44,7 +52,7 @@ const inputBValidation = useValidation({
watch: [inputFormatB],
rules: [
{
validator: v => parseInputB(v) !== null,
validator: (v) => parseInputB(v) !== null,
message: t('tools.binary-calculator.texts.message-number-is-invalid'),
},
],
@@ -77,8 +85,7 @@ function parseInput(value: string, format: NumberFormat): number | null {
return null;
}
return num;
}
catch {
} catch {
return null;
}
}
@@ -115,22 +122,35 @@ const result = computed(() => {
}
});
const signedResult = computed(() => result.value !== null ? (result.value | 0).toString() : '');
const unsignedResult = computed(() => result.value !== null ? (result.value >>> 0).toString() : '');
const signedResult = computed(() => (result.value !== null ? (result.value | 0).toString() : ''));
const unsignedResult = computed(() => (result.value !== null ? (result.value >>> 0).toString() : ''));
const bitmask = computed(() =>
result.value !== null
? (result.value >>> 0).toString(2).padStart(32, '0').split('')
: [],
result.value !== null ? (result.value >>> 0).toString(2).padStart(32, '0').split('') : [],
);
</script>
<template>
<div style="min-height: 50vh; max-width: 800px;">
<div style="min-height: 50vh; max-width: 800px">
<n-space justify="space-evenly" mb-2>
<NSelect v-model:value="inputFormatA" :options="formatOptions" style="width: 130px" />
<c-input-text v-model:value="inputA" style="width: 150px" :validation="inputAValidation" label-position="left" :label="t('tools.binary-calculator.texts.label-a')" :placeholder="t('tools.binary-calculator.texts.placeholder-enter-a')" />
<c-input-text
v-model:value="inputA"
style="width: 150px"
:validation="inputAValidation"
label-position="left"
:label="t('tools.binary-calculator.texts.label-a')"
:placeholder="t('tools.binary-calculator.texts.placeholder-enter-a')"
/>
<NSelect v-model:value="inputFormatB" :options="formatOptions" style="width: 130px" />
<c-input-text v-model:value="inputB" style="width: 150px" :validation="inputBValidation" label-position="left" :label="t('tools.binary-calculator.texts.label-b')" :placeholder="t('tools.binary-calculator.texts.placeholder-enter-b')" :disabled="isUnary" />
<c-input-text
v-model:value="inputB"
style="width: 150px"
:validation="inputBValidation"
label-position="left"
:label="t('tools.binary-calculator.texts.label-b')"
:placeholder="t('tools.binary-calculator.texts.placeholder-enter-b')"
:disabled="isUnary"
/>
</n-space>
<c-select
@@ -143,21 +163,46 @@ const bitmask = computed(() =>
/>
<c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-result')" mb-1>
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-decimal-signed')" label-position="left" :value="signedResult" />
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-decimal-unigned')" label-position="left" :value="unsignedResult" />
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-binary')" label-position="left" :value="`0b${result.toString(2).padStart(32, '0')}`" />
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-hexadecimal')" label-position="left" :value="`0x${result.toString(16).toUpperCase()}`" />
<input-copyable label-width="130px" mb-1 :label="t('tools.binary-calculator.texts.label-octal')" label-position="left" :value="`0o${result.toString(8)}`" />
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-decimal-signed')"
label-position="left"
:value="signedResult"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-decimal-unigned')"
label-position="left"
:value="unsignedResult"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-binary')"
label-position="left"
:value="`0b${result.toString(2).padStart(32, '0')}`"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-hexadecimal')"
label-position="left"
:value="`0x${result.toString(16).toUpperCase()}`"
/>
<input-copyable
label-width="130px"
mb-1
:label="t('tools.binary-calculator.texts.label-octal')"
label-position="left"
:value="`0o${result.toString(8)}`"
/>
</c-card>
<c-card v-if="result !== null" :title="t('tools.binary-calculator.texts.title-bitmask')">
<NSpace justify="center" wrap>
<NTag
v-for="(bit, index) in bitmask"
:key="index"
:type="bit === '1' ? 'success' : 'default'"
size="small"
>
<NTag v-for="(bit, index) in bitmask" :key="index" :type="bit === '1' ? 'success' : 'default'" size="small">
{{ bit }}
</NTag>
</NSpace>
+33 -16
View File
@@ -26,22 +26,26 @@ import { useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n();
const languages = {
'English': englishWordList,
English: englishWordList,
'Chinese simplified': chineseSimplifiedWordList,
'Chinese traditional': chineseTraditionalWordList,
'Czech': czechWordList,
'French': frenchWordList,
'Italian': italianWordList,
'Japanese': japaneseWordList,
'Korean': koreanWordList,
'Portuguese': portugueseWordList,
'Spanish': spanishWordList,
Czech: czechWordList,
French: frenchWordList,
Italian: italianWordList,
Japanese: japaneseWordList,
Korean: koreanWordList,
Portuguese: portugueseWordList,
Spanish: spanishWordList,
};
const entropy = ref(generateEntropy());
const passphraseInput = ref('');
const language = useQueryParamOrStorage<keyof typeof languages>({ name: 'lang', storageName: 'bip39-gen:l', defaultValue: 'English' });
const language = useQueryParamOrStorage<keyof typeof languages>({
name: 'lang',
storageName: 'bip39-gen:l',
defaultValue: 'English',
});
const passphrase = computed({
get() {
@@ -57,11 +61,11 @@ const entropyValidation = useValidation({
source: entropy,
rules: [
{
validator: value => value === '' || (value.length <= 32 && value.length >= 16 && value.length % 4 === 0),
validator: (value) => value === '' || (value.length <= 32 && value.length >= 16 && value.length % 4 === 0),
message: t('tools.bip39-generator.texts.message-entropy-length-should-be-16-32-and-be-a-multiple-of-4'),
},
{
validator: value => /^[a-fA-F0-9]*$/.test(value),
validator: (value) => /^[a-fA-F0-9]*$/.test(value),
message: t('tools.bip39-generator.texts.message-entropy-should-be-an-hexadecimal-string'),
},
],
@@ -71,7 +75,7 @@ const mnemonicValidation = useValidation({
source: passphrase,
rules: [
{
validator: value => isNotThrowing(() => mnemonicToEntropy(value, languages[language.value])),
validator: (value) => isNotThrowing(() => mnemonicToEntropy(value, languages[language.value])),
message: t('tools.bip39-generator.texts.message-invalid-mnemonic'),
},
],
@@ -81,8 +85,14 @@ function refreshEntropy() {
entropy.value = generateEntropy();
}
const { copy: copyEntropy } = useCopy({ source: entropy, text: t('tools.bip39-generator.texts.text-entropy-copied-to-the-clipboard') });
const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bip39-generator.texts.text-passphrase-copied-to-the-clipboard') });
const { copy: copyEntropy } = useCopy({
source: entropy,
text: t('tools.bip39-generator.texts.text-entropy-copied-to-the-clipboard'),
});
const { copy: copyPassphrase } = useCopy({
source: passphrase,
text: t('tools.bip39-generator.texts.text-passphrase-copied-to-the-clipboard'),
});
</script>
<template>
@@ -103,7 +113,10 @@ const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bi
:validation-status="entropyValidation.status"
>
<n-input-group>
<c-input-text v-model:value="entropy" :placeholder="t('tools.bip39-generator.texts.placeholder-your-string')" />
<c-input-text
v-model:value="entropy"
:placeholder="t('tools.bip39-generator.texts.placeholder-your-string')"
/>
<c-button @click="refreshEntropy()">
<n-icon size="22">
@@ -125,7 +138,11 @@ const { copy: copyPassphrase } = useCopy({ source: passphrase, text: t('tools.bi
:validation-status="mnemonicValidation.status"
>
<n-input-group>
<c-input-text v-model:value="passphrase" :placeholder="t('tools.bip39-generator.texts.placeholder-your-mnemonic')" raw-text />
<c-input-text
v-model:value="passphrase"
:placeholder="t('tools.bip39-generator.texts.placeholder-your-mnemonic')"
raw-text
/>
<c-button @click="copyPassphrase()">
<n-icon size="22" :component="Copy" />
+30 -7
View File
@@ -52,18 +52,41 @@ const bmiCategory = computed(() => {
<template>
<c-card :title="t('tools.bmi-calculator.texts.title-bmi-calculator')" max-w-800px>
<c-select v-model:value="units" :label="t('tools.bmi-calculator.texts.label-select-units')" :options="options" mb-2 label-position="left" />
<c-select
v-model:value="units"
:label="t('tools.bmi-calculator.texts.label-select-units')"
:options="options"
mb-2
label-position="left"
/>
<n-space justify="space-evenly">
<n-form-item :label="`Weight (${(units === 'metric' ? 'kg' : 'lbs')}):`" label-placement="left" mb-2>
<n-input-number-i18n v-model:value="weight" :placeholder="t('tools.bmi-calculator.texts.placeholder-enter-weight')" />
<n-form-item :label="`Weight (${units === 'metric' ? 'kg' : 'lbs'}):`" label-placement="left" mb-2>
<n-input-number-i18n
v-model:value="weight"
:placeholder="t('tools.bmi-calculator.texts.placeholder-enter-weight')"
/>
</n-form-item>
<n-form-item :label="`Height (${(units === 'metric' ? 'm' : 'in')}):`" label-placement="left" mb-2>
<n-input-number-i18n v-model:value="height" :placeholder="t('tools.bmi-calculator.texts.placeholder-enter-height')" />
<n-form-item :label="`Height (${units === 'metric' ? 'm' : 'in'}):`" label-placement="left" mb-2>
<n-input-number-i18n
v-model:value="height"
:placeholder="t('tools.bmi-calculator.texts.placeholder-enter-height')"
/>
</n-form-item>
</n-space>
<c-card v-if="bmi" :title="t('tools.bmi-calculator.texts.title-result')">
<input-copyable :label="t('tools.bmi-calculator.texts.label-bmi')" label-position="left" label-width="100px" :value="bmi" mb-1 />
<input-copyable :label="t('tools.bmi-calculator.texts.label-category')" label-position="left" label-width="100px" :value="bmiCategory" />
<input-copyable
:label="t('tools.bmi-calculator.texts.label-bmi')"
label-position="left"
label-width="100px"
:value="bmi"
mb-1
/>
<input-copyable
:label="t('tools.bmi-calculator.texts.label-category')"
label-position="left"
label-width="100px"
:value="bmiCategory"
/>
</c-card>
</c-card>
</template>
+72 -16
View File
@@ -9,8 +9,7 @@ const emailContent = ref('');
const parsedBounce = computed(() => {
try {
return { email: new EmailBounceParse().read(emailContent.value) };
}
catch (e: any) {
} catch (e: any) {
return { parsingError: e.toString() };
}
});
@@ -39,23 +38,80 @@ const parsedBounce = computed(() => {
<c-alert v-if="parsedBounce.parsingError" mb-2>
{{ parsedBounce.parsingError }}
</c-alert>
<input-copyable v-if="parsedBounce.email?.data?.recipient" :label="t('tools.bounce-parser.texts.label-recipient')" :value="parsedBounce.email?.data?.recipient" mb-2 />
<input-copyable
v-if="parsedBounce.email?.data?.recipient"
:label="t('tools.bounce-parser.texts.label-recipient')"
:value="parsedBounce.email?.data?.recipient"
mb-2
/>
<div v-if="parsedBounce.email?.email?.error">
<c-card :title="t('tools.bounce-parser.texts.title-error')" mb-2>
<input-copyable v-if="parsedBounce.email?.data?.command" :label="t('tools.bounce-parser.texts.label-command')" :value="parsedBounce.email?.data?.command" />
<input-copyable v-if="parsedBounce.email?.data?.error?.code?.basic || parsedBounce.email?.data?.error?.code?.enhanced" :label="t('tools.bounce-parser.texts.label-code')" :value="`${parsedBounce.email?.data?.error?.code?.basic}/${parsedBounce.email?.data?.error?.code?.enhanced}`" />
<input-copyable v-if="parsedBounce.email?.data?.error?.label" :label="t('tools.bounce-parser.texts.label-label')" :value="parsedBounce.email?.data?.error?.label" />
<input-copyable v-if="parsedBounce.email?.data?.error?.type" :label="t('tools.bounce-parser.texts.label-type')" :value="parsedBounce.email?.data?.error?.type" />
<input-copyable v-if="parsedBounce.email?.data?.error?.temporary" :label="t('tools.bounce-parser.texts.label-temporary')" :value="parsedBounce.email?.data?.error?.temporary" />
<input-copyable v-if="parsedBounce.email?.data?.error?.permanent" :label="t('tools.bounce-parser.texts.label-permanent')" :value="parsedBounce.email?.data?.error?.permanent" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.type" :label="t('tools.bounce-parser.texts.label-subtype')" :value="parsedBounce.email?.data?.error?.data?.type" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.blocked" :label="t('tools.bounce-parser.texts.label-blocked')" :value="parsedBounce.email?.data?.error?.data?.blocked" />
<input-copyable v-if="parsedBounce.email?.data?.error?.data?.spam" :label="t('tools.bounce-parser.texts.label-spam')" :value="parsedBounce.email?.data?.error?.data?.spam" />
<input-copyable
v-if="parsedBounce.email?.data?.command"
:label="t('tools.bounce-parser.texts.label-command')"
:value="parsedBounce.email?.data?.command"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.code?.basic || parsedBounce.email?.data?.error?.code?.enhanced"
:label="t('tools.bounce-parser.texts.label-code')"
:value="`${parsedBounce.email?.data?.error?.code?.basic}/${parsedBounce.email?.data?.error?.code?.enhanced}`"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.label"
:label="t('tools.bounce-parser.texts.label-label')"
:value="parsedBounce.email?.data?.error?.label"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.type"
:label="t('tools.bounce-parser.texts.label-type')"
:value="parsedBounce.email?.data?.error?.type"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.temporary"
:label="t('tools.bounce-parser.texts.label-temporary')"
:value="parsedBounce.email?.data?.error?.temporary"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.permanent"
:label="t('tools.bounce-parser.texts.label-permanent')"
:value="parsedBounce.email?.data?.error?.permanent"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.type"
:label="t('tools.bounce-parser.texts.label-subtype')"
:value="parsedBounce.email?.data?.error?.data?.type"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.blocked"
:label="t('tools.bounce-parser.texts.label-blocked')"
:value="parsedBounce.email?.data?.error?.data?.blocked"
/>
<input-copyable
v-if="parsedBounce.email?.data?.error?.data?.spam"
:label="t('tools.bounce-parser.texts.label-spam')"
:value="parsedBounce.email?.data?.error?.data?.spam"
/>
</c-card>
<c-card v-if="parsedBounce.email?.data?.server?.hostname || parsedBounce.email?.data?.server?.ip" :title="t('tools.bounce-parser.texts.title-server')" mb-2>
<input-copyable v-if="parsedBounce.email?.data?.server?.hostname" :label="t('tools.bounce-parser.texts.label-host')" :value="parsedBounce.email?.data?.server?.hostname" />
<input-copyable v-if="parsedBounce.email?.data?.server?.ip" :label="t('tools.bounce-parser.texts.label-ip')" :value="parsedBounce.email?.data?.server?.ip" />
<input-copyable v-if="parsedBounce.email?.data?.server?.port" :label="t('tools.bounce-parser.texts.label-port')" :value="parsedBounce.email?.data?.server?.port" />
<c-card
v-if="parsedBounce.email?.data?.server?.hostname || parsedBounce.email?.data?.server?.ip"
:title="t('tools.bounce-parser.texts.title-server')"
mb-2
>
<input-copyable
v-if="parsedBounce.email?.data?.server?.hostname"
:label="t('tools.bounce-parser.texts.label-host')"
:value="parsedBounce.email?.data?.server?.hostname"
/>
<input-copyable
v-if="parsedBounce.email?.data?.server?.ip"
:label="t('tools.bounce-parser.texts.label-ip')"
:value="parsedBounce.email?.data?.server?.ip"
/>
<input-copyable
v-if="parsedBounce.email?.data?.server?.port"
:label="t('tools.bounce-parser.texts.label-port')"
:value="parsedBounce.email?.data?.server?.port"
/>
</c-card>
<c-card :title="t('tools.bounce-parser.texts.title-details')" mb-2>
<textarea-copyable :value="JSON.stringify(parsedBounce.email?.data, null, 2)" />
+36 -36
View File
@@ -1,36 +1,36 @@
declare module "email-bounce-parser-browser" {
export default class EmailBounceParse {
read(emailContent: string): {
bounce: boolean
email?: {
body?: string
intro?: string
error?: string
}
data?: {
error?: {
code?: {
basic?: string
enhanced?:string
}
label?: string
type?: string
temporary?: boolean
permanent?: boolean
data?: {
type?: string
blocked?: boolean
spam?: boolean
}
}
recipient?:string
server?: {
hostname?: string
ip?: string
port?: string
}
command?: string
}
}
}
}
declare module 'email-bounce-parser-browser' {
export default class EmailBounceParse {
read(emailContent: string): {
bounce: boolean;
email?: {
body?: string;
intro?: string;
error?: string;
};
data?: {
error?: {
code?: {
basic?: string;
enhanced?: string;
};
label?: string;
type?: string;
temporary?: boolean;
permanent?: boolean;
data?: {
type?: string;
blocked?: boolean;
spam?: boolean;
};
};
recipient?: string;
server?: {
hostname?: string;
ip?: string;
port?: string;
};
command?: string;
};
};
}
}
File diff suppressed because it is too large. Load diff
@@ -7,12 +7,18 @@ const { t } = useI18n();
const converter = ref(new CalendarConverter());
const monthOptions = [
{ label: t('tools.calendar-converter.texts.label-january'), value: 1 }, { label: t('tools.calendar-converter.texts.label-february'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-march'), value: 3 }, { label: t('tools.calendar-converter.texts.label-april'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-may'), value: 5 }, { label: t('tools.calendar-converter.texts.label-june'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-july'), value: 7 }, { label: t('tools.calendar-converter.texts.label-august'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-september'), value: 9 }, { label: t('tools.calendar-converter.texts.label-october'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-november'), value: 11 }, { label: t('tools.calendar-converter.texts.label-december'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-january'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-february'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-march'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-april'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-may'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-june'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-july'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-august'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-september'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-october'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-november'), value: 11 },
{ label: t('tools.calendar-converter.texts.label-december'), value: 12 },
];
const hebrewMonths = [
@@ -77,12 +83,18 @@ const indianMonths = [
];
const frenchMonths = [
{ label: t('tools.calendar-converter.texts.label-vendémiaire'), value: 1 }, { label: t('tools.calendar-converter.texts.label-brumaire'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-frimaire'), value: 3 }, { label: t('tools.calendar-converter.texts.label-nivôse'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-pluviôse'), value: 5 }, { label: t('tools.calendar-converter.texts.label-ventôse'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-germinal'), value: 7 }, { label: t('tools.calendar-converter.texts.label-floréal'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-prairial'), value: 9 }, { label: t('tools.calendar-converter.texts.label-messidor'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-thermidor'), value: 11 }, { label: t('tools.calendar-converter.texts.label-fructidor'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-vendémiaire'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-brumaire'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-frimaire'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-nivôse'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-pluviôse'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-ventôse'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-germinal'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-floréal'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-prairial'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-messidor'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-thermidor'), value: 11 },
{ label: t('tools.calendar-converter.texts.label-fructidor'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-sans-culottides'), value: 13 },
];
@@ -93,23 +105,32 @@ const frenchDecades = [
];
const frenchDays = [
{ label: t('tools.calendar-converter.texts.label-primidi-1'), value: 1 }, { label: t('tools.calendar-converter.texts.label-duodi-2'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-tridi-3'), value: 3 }, { label: t('tools.calendar-converter.texts.label-quartidi-4'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-quintidi-5'), value: 5 }, { label: t('tools.calendar-converter.texts.label-sextidi-6'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-septidi-7'), value: 7 }, { label: t('tools.calendar-converter.texts.label-octidi-8'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-nonidi-9'), value: 9 }, { label: t('tools.calendar-converter.texts.label-décadi-10'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-vertu-1'), value: 12 }, { label: t('tools.calendar-converter.texts.label-génie-2'), value: 13 },
{ label: t('tools.calendar-converter.texts.label-travail-3'), value: 14 }, { label: t('tools.calendar-converter.texts.label-opinion-4'), value: 15 },
{ label: t('tools.calendar-converter.texts.label-récompenses-5'), value: 16 }, { label: t('tools.calendar-converter.texts.label-révolution-6'), value: 17 },
{ label: t('tools.calendar-converter.texts.label-primidi-1'), value: 1 },
{ label: t('tools.calendar-converter.texts.label-duodi-2'), value: 2 },
{ label: t('tools.calendar-converter.texts.label-tridi-3'), value: 3 },
{ label: t('tools.calendar-converter.texts.label-quartidi-4'), value: 4 },
{ label: t('tools.calendar-converter.texts.label-quintidi-5'), value: 5 },
{ label: t('tools.calendar-converter.texts.label-sextidi-6'), value: 6 },
{ label: t('tools.calendar-converter.texts.label-septidi-7'), value: 7 },
{ label: t('tools.calendar-converter.texts.label-octidi-8'), value: 8 },
{ label: t('tools.calendar-converter.texts.label-nonidi-9'), value: 9 },
{ label: t('tools.calendar-converter.texts.label-décadi-10'), value: 10 },
{ label: t('tools.calendar-converter.texts.label-vertu-1'), value: 12 },
{ label: t('tools.calendar-converter.texts.label-génie-2'), value: 13 },
{ label: t('tools.calendar-converter.texts.label-travail-3'), value: 14 },
{ label: t('tools.calendar-converter.texts.label-opinion-4'), value: 15 },
{ label: t('tools.calendar-converter.texts.label-récompenses-5'), value: 16 },
{ label: t('tools.calendar-converter.texts.label-révolution-6'), value: 17 },
];
</script>
<template>
<div>
<n-p>
{{ t('tools.calendar-converter.texts.tag-this-is-a-port-of-wonderful') }}<c-link target="_blank" href="https://www.fourmilab.ch/documents/calendar">
{{ t('tools.calendar-converter.texts.tag-fourmilab-ch-calendar-converter') }}
</c-link>{{ t('tools.calendar-converter.texts.tag-by-john-walker') }}
{{ t('tools.calendar-converter.texts.tag-this-is-a-port-of-wonderful')
}}<c-link target="_blank" href="https://www.fourmilab.ch/documents/calendar">
{{ t('tools.calendar-converter.texts.tag-fourmilab-ch-calendar-converter') }} </c-link
>{{ t('tools.calendar-converter.texts.tag-by-john-walker') }}
</n-p>
<n-tabs type="line" animated>
<!-- Gregorian -->
@@ -117,7 +138,12 @@ const frenchDays = [
<n-form :model="converter.document.gregorian" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.gregorian.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.gregorian.month" :options="monthOptions" style="width: 160px; " mr-1 />
<n-select
v-model:value="converter.document.gregorian.month"
:options="monthOptions"
style="width: 160px"
mr-1
/>
<n-input-number v-model:value="converter.document.gregorian.year" style="width: 100px" />
</n-form-item>
@@ -141,7 +167,14 @@ const frenchDays = [
<n-button type="primary" mr-1 @click="() => converter.calcGregorian()">
{{ t('tools.calendar-converter.texts.tag-update-other-calendars') }}
</n-button>
<n-button @click="() => { converter.setDateToToday(); converter.updateFromGregorian(); }">
<n-button
@click="
() => {
converter.setDateToToday();
converter.updateFromGregorian();
}
"
>
{{ t('tools.calendar-converter.texts.tag-today') }}
</n-button>
</n-space>
@@ -181,7 +214,12 @@ const frenchDays = [
<n-form :model="converter.document.juliancalendar" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.juliancalendar.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.juliancalendar.month" :options="monthOptions" style="width: 160px; " mr-1 />
<n-select
v-model:value="converter.document.juliancalendar.month"
:options="monthOptions"
style="width: 160px"
mr-1
/>
<n-input-number v-model:value="converter.document.juliancalendar.year" style="width: 100px" />
</n-form-item>
<n-form-item :label="t('tools.calendar-converter.texts.label-leap')">
@@ -218,7 +256,12 @@ const frenchDays = [
<n-form :model="converter.document.hebrew" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.hebrew.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.hebrew.month" :options="hebrewMonths" style="width: 220px; " mr-1 />
<n-select
v-model:value="converter.document.hebrew.month"
:options="hebrewMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.hebrew.year" style="width: 100px" />
</n-form-item>
@@ -239,7 +282,12 @@ const frenchDays = [
<n-form :model="converter.document.islamic" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.islamic.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.islamic.month" :options="islamicMonths" style="width: 250px; " mr-1 />
<n-select
v-model:value="converter.document.islamic.month"
:options="islamicMonths"
style="width: 250px"
mr-1
/>
<n-input-number v-model:value="converter.document.islamic.year" style="width: 100px" />
</n-form-item>
@@ -264,7 +312,12 @@ const frenchDays = [
<n-form :model="converter.document.persian" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.persian.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.persian.month" :options="persianMonths" style="width: 220px; " mr-1 />
<n-select
v-model:value="converter.document.persian.month"
:options="persianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.persian.year" style="width: 100px" />
</n-form-item>
@@ -289,7 +342,12 @@ const frenchDays = [
<n-form :model="converter.document.persiana" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.persiana.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.persiana.month" :options="persianMonths" style="width: 220px; " mr-1 />
<n-select
v-model:value="converter.document.persiana.month"
:options="persianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.persiana.year" style="width: 100px" />
</n-form-item>
@@ -344,7 +402,12 @@ const frenchDays = [
<n-form :model="converter.document.indiancivilcalendar" label-placement="left">
<n-form-item :label="t('tools.calendar-converter.texts.label-date')">
<n-input-number v-model:value="converter.document.indiancivilcalendar.day" style="width: 90px" mr-1 />
<n-select v-model:value="converter.document.indiancivilcalendar.month" :options="indianMonths" style="width: 220px;" mr-1 />
<n-select
v-model:value="converter.document.indiancivilcalendar.month"
:options="indianMonths"
style="width: 220px"
mr-1
/>
<n-input-number v-model:value="converter.document.indiancivilcalendar.year" style="width: 100px" />
</n-form-item>
<n-form-item :label="t('tools.calendar-converter.texts.label-leap')">
+16 -1
View File
@@ -5,7 +5,22 @@ export const tool = defineTool({
name: t('tools.calendar-converter.title'),
path: '/calendar-converter',
description: t('tools.calendar-converter.description'),
keywords: ['calendar', 'gregorian', 'julian', 'hebrew', 'islamic', 'persian', 'mayan', 'indian', 'french', 'republican', 'iso-8601', 'unix', 'excel', 'converter'],
keywords: [
'calendar',
'gregorian',
'julian',
'hebrew',
'islamic',
'persian',
'mayan',
'indian',
'french',
'republican',
'iso-8601',
'unix',
'excel',
'converter',
],
component: () => import('./calendar-converter.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/Calendar')),
createdAt: new Date('2026-02-21'),
+11 -7
View File
@@ -6,7 +6,11 @@ import { useMediaRecorder } from './useMediaRecorder';
const { t } = useI18n();
interface Media { type: 'image' | 'video'; value: string; createdAt: Date }
interface Media {
type: 'image' | 'video';
value: string;
createdAt: Date;
}
const {
videoInputs: cameras,
@@ -58,11 +62,11 @@ onRecordAvailable((value) => {
});
function refreshCurrentDevices() {
if (_.isNil(currentCamera) || !cameras.value.find(i => i.deviceId === currentCamera.value)) {
if (_.isNil(currentCamera) || !cameras.value.find((i) => i.deviceId === currentCamera.value)) {
currentCamera.value = cameras.value[0]?.deviceId;
}
if (_.isNil(microphones) || !microphones.value.find(i => i.deviceId === currentMicrophone.value)) {
if (_.isNil(microphones) || !microphones.value.find((i) => i.deviceId === currentMicrophone.value)) {
currentMicrophone.value = microphones.value[0]?.deviceId;
}
}
@@ -92,8 +96,7 @@ onBeforeUnmount(() => stop());
async function requestPermissions() {
try {
await ensurePermissions();
}
catch (e) {
} catch (e) {
permissionCannotBePrompted.value = true;
}
}
@@ -113,7 +116,8 @@ function downloadMedia({ type, value, createdAt }: Media) {
</c-card>
<c-card v-else-if="!permissionGranted" text-center>
{{ t('tools.camera-recorder.texts.tag-you-need-to-grant-permission-to-use-your-camera-and-microphone') }}<c-alert v-if="permissionCannotBePrompted" mt-4 text-left>
{{ t('tools.camera-recorder.texts.tag-you-need-to-grant-permission-to-use-your-camera-and-microphone')
}}<c-alert v-if="permissionCannotBePrompted" mt-4 text-left>
Your browser has blocked permission request or does not support it. You need to grant permission manually in
your browser settings (usually the lock icon in the address bar).
</c-alert>
@@ -188,7 +192,7 @@ function downloadMedia({ type, value, createdAt }: Media) {
<div grid grid-cols-2 mt-5 gap-2>
<c-card v-for="({ type, value, createdAt }, index) in medias" :key="index">
<img v-if="type === 'image'" :src="value" max-h-full w-full alt="screenshot">
<img v-if="type === 'image'" :src="value" max-h-full w-full alt="screenshot" />
<video v-else :src="value" controls max-h-full w-full />
@@ -3,13 +3,13 @@ import { type Ref, computed, ref } from 'vue';
export { useMediaRecorder };
function useMediaRecorder({ stream }: { stream: Ref<MediaStream | undefined> }): {
isRecordingSupported: Ref<boolean>
recordingState: Ref<'stopped' | 'recording' | 'paused'>
startRecording: () => void
stopRecording: () => void
pauseRecording: () => void
resumeRecording: () => void
onRecordAvailable: (cb: (url: string) => void) => void
isRecordingSupported: Ref<boolean>;
recordingState: Ref<'stopped' | 'recording' | 'paused'>;
startRecording: () => void;
stopRecording: () => void;
pauseRecording: () => void;
resumeRecording: () => void;
onRecordAvailable: (cb: (url: string) => void) => void;
} {
const isRecordingSupported = computed(() => MediaRecorder.isTypeSupported('video/webm'));
const mediaRecorder = ref<MediaRecorder | null>(null);
+23 -5
View File
@@ -8,7 +8,7 @@ import { useQueryParamOrStorage } from '@/composable/queryParams';
const { t } = useI18n();
const cardKeys = [...Object.keys(cards).filter(k => k !== 'joker'), 'joker', 'joker'];
const cardKeys = [...Object.keys(cards).filter((k) => k !== 'joker'), 'joker', 'joker'];
type CardNames = keyof typeof cards;
const numberOfCards = useQueryParamOrStorage({ name: 'cards', storageName: 'card-picker:n', defaultValue: 5 });
@@ -47,23 +47,41 @@ function translateName(cardId: string) {
const cardPickedString = computed(() => cardPicked.value.map(translateName).join(', '));
const { copy } = useCopy({ source: cardPickedString, text: t('tools.card-picker.texts.text-cards-picked-copied-to-the-clipboard') });
const { copy } = useCopy({
source: cardPickedString,
text: t('tools.card-picker.texts.text-cards-picked-copied-to-the-clipboard'),
});
</script>
<template>
<c-card>
<n-space justify="space-around" mb-1>
<img v-for="(card, index) in cardPicked" :key="index" style="width:90px" mr-1 :src="`data:image/svg+xml;base64,${cards[card as CardNames]}`">
<img
v-for="(card, index) in cardPicked"
:key="index"
style="width: 90px"
mr-1
:src="`data:image/svg+xml;base64,${cards[card as CardNames]}`"
/>
</n-space>
<div mb-2>
<textarea-copyable :value="cardPickedString" readonly mb-1 />
</div>
<div flex justify-center gap-3>
<n-form-item :label="t('tools.card-picker.texts.label-number-of-cards')" label-placement="left">
<n-input-number-i18n v-model:value="numberOfCards" min="1" :max="maxCards" :placeholder="t('tools.card-picker.texts.placeholder-number-of-cards-to-pick')" />
<n-input-number-i18n
v-model:value="numberOfCards"
min="1"
:max="maxCards"
:placeholder="t('tools.card-picker.texts.placeholder-number-of-cards-to-pick')"
/>
</n-form-item>
<n-form-item :label="t('tools.card-picker.texts.label-number-of-packs')" label-placement="left">
<n-input-number-i18n v-model:value="numberOfPacks" min="1" :placeholder="t('tools.card-picker.texts.placeholder-number-of-card-packs-to-pick-in')" />
<n-input-number-i18n
v-model:value="numberOfPacks"
min="1"
:placeholder="t('tools.card-picker.texts.placeholder-number-of-card-packs-to-pick-in')"
/>
</n-form-item>
</div>
<div mb-4 flex justify-center>
@@ -194,7 +194,7 @@ describe('certificate-key-parser', async () => {
const { input, pass, type, title } = format;
it(`Parse '${title ?? type}' format with right type (${type})`, async () => {
const { values } = await getKeyOrCertificateInfosAsync(input, pass);
const result_type = values.find(v => v.label === 'Type:')?.value;
const result_type = values.find((v) => v.label === 'Type:')?.value;
expect(result_type).toBe(type);
});
@@ -1,39 +1,51 @@
import type { Buffer } from 'node:buffer';
import {
parseCertificate, parseFingerprint,
parseKey,
parsePrivateKey,
parseSignature,
} from 'sshpk';
import { parseCertificate, parseFingerprint, parseKey, parsePrivateKey, parseSignature } from 'sshpk';
import type {
AlgorithmType,
Certificate,
CertificateFormat,
Fingerprint,
Key,
PrivateKey, Signature, SignatureFormatType,
PrivateKey,
Signature,
SignatureFormatType,
} from 'sshpk';
import { Base64 } from 'js-base64';
import * as openpgp from 'openpgp';
import * as forge from 'node-forge';
import { type LabelValue, getCSRLabelValues, getCertificateLabelValues, getFingerprintLabelValues, getPGPPrivateKeyLabelValuesAsync, getPGPPublicKeyLabelValuesAsync, getPrivateKeyLabelValues, getPublicKeyLabelValues, getSignatureLabelValues } from './certificate-key-parser.infos';
import {
type LabelValue,
getCSRLabelValues,
getCertificateLabelValues,
getFingerprintLabelValues,
getPGPPrivateKeyLabelValuesAsync,
getPGPPublicKeyLabelValuesAsync,
getPrivateKeyLabelValues,
getPublicKeyLabelValues,
getSignatureLabelValues,
} from './certificate-key-parser.infos';
import { translate as t } from '@/plugins/i18n.plugin';
export async function getKeysOrCertificatesInfosAsync(
keyOrCertificateValue: string | Buffer,
passphrase: string,
add_missing_type: string | null = null) {
add_missing_type: string | null = null,
) {
if (add_missing_type && !keyOrCertificateValue.toString().trim().startsWith('-----BEGIN')) {
keyOrCertificateValue = `-----BEGIN ${add_missing_type}-----\n${keyOrCertificateValue.toString().trim()}\n-----END ${add_missing_type}-----`;
}
const parts = keyOrCertificateValue.toString().trim().split(/(-----BEGIN [^-]+-----\n)/).filter(s => s !== '');
const parts = keyOrCertificateValue
.toString()
.trim()
.split(/(-----BEGIN [^-]+-----\n)/)
.filter((s) => s !== '');
if (!parts.length) {
return [await getKeyOrCertificateInfosAsync(keyOrCertificateValue, passphrase)];
}
const parsedPEMs: Array<{
values: LabelValue[]
certificateX509DER?: undefined | string
values: LabelValue[];
certificateX509DER?: undefined | string;
}> = [];
for (let i = 0; i < parts.length; i += 2) {
const pemPart = parts[i] + parts[i + 1];
@@ -47,24 +59,24 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
const canParse = (value: string | Buffer, parseFunction: (value: string | Buffer) => any) => {
try {
return parseFunction(value);
}
catch {
} catch {
return null;
}
};
const canParseAsync = async (value: string | Buffer, parseFunction: (value: string | Buffer) => Promise<any>) => {
try {
return await parseFunction(value);
}
catch {
} catch {
return null;
}
};
const inputKeyOrCertificateValue = (typeof keyOrCertificateValue === 'string' ? keyOrCertificateValue?.trim() : keyOrCertificateValue);
const inputKeyOrCertificateValue =
typeof keyOrCertificateValue === 'string' ? keyOrCertificateValue?.trim() : keyOrCertificateValue;
const privateKey = canParse(inputKeyOrCertificateValue,
value => parsePrivateKey(value, 'auto', { passphrase })) as PrivateKey;
const privateKey = canParse(inputKeyOrCertificateValue, (value) =>
parsePrivateKey(value, 'auto', { passphrase }),
) as PrivateKey;
if (privateKey) {
return {
values: getPrivateKeyLabelValues(privateKey),
@@ -76,12 +88,16 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
return { values: getPublicKeyLabelValues(publicKey) };
}
const pgpPrivateKey = await canParseAsync(inputKeyOrCertificateValue, value => openpgp.readPrivateKey({ armoredKey: value.toString() })) as openpgp.Key;
const pgpPrivateKey = (await canParseAsync(inputKeyOrCertificateValue, (value) =>
openpgp.readPrivateKey({ armoredKey: value.toString() }),
)) as openpgp.Key;
if (pgpPrivateKey) {
return { values: await getPGPPrivateKeyLabelValuesAsync(pgpPrivateKey) };
}
const pgpPublicKey = await canParseAsync(inputKeyOrCertificateValue, value => openpgp.readKey({ armoredKey: value.toString() })) as openpgp.Key;
const pgpPublicKey = (await canParseAsync(inputKeyOrCertificateValue, (value) =>
openpgp.readKey({ armoredKey: value.toString() }),
)) as openpgp.Key;
if (pgpPublicKey) {
return { values: await getPGPPublicKeyLabelValuesAsync(pgpPublicKey) };
}
@@ -90,8 +106,7 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
for (const format of ['openssh', 'pem', 'x509']) {
try {
return parseCertificate(value, format as CertificateFormat);
}
catch {}
} catch {}
}
return null;
}) as Certificate;
@@ -99,18 +114,15 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
let certificateX509DER = '';
try {
certificateX509DER = Base64.fromUint8Array(cert.toBuffer('x509'));
}
catch {}
} catch {}
let forgeCertificate: forge.pki.Certificate | null = null;
try {
forgeCertificate = forge.pki.certificateFromPem(inputKeyOrCertificateValue?.toString(), false, false);
}
catch {}
} catch {}
if (!forgeCertificate) {
try {
forgeCertificate = forge.pki.certificateFromAsn1(inputKeyOrCertificateValue as never, false);
}
catch {}
} catch {}
}
return { values: getCertificateLabelValues(cert, forgeCertificate), certificateX509DER };
@@ -123,7 +135,9 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
return { values: getCSRLabelValues(csr) };
}
const fingerprint = canParse(inputKeyOrCertificateValue, value => parseFingerprint(value.toString())) as Fingerprint;
const fingerprint = canParse(inputKeyOrCertificateValue, (value) =>
parseFingerprint(value.toString()),
) as Fingerprint;
if (fingerprint) {
return { values: getFingerprintLabelValues(fingerprint) };
}
@@ -134,8 +148,7 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
for (const format of ['asn1', 'ssh', 'raw']) {
try {
return parseSignature(value, algo as AlgorithmType, format as SignatureFormatType);
}
catch {}
} catch {}
}
}
return null;
@@ -149,16 +162,17 @@ export async function getKeyOrCertificateInfosAsync(keyOrCertificateValue: strin
{
label: t('tools.certificate-key-parser.service.text.type'),
value: t('tools.certificate-key-parser.service.text.unknown-format-or-invalid-passphrase'),
}],
},
],
};
}
catch (e: any) {
} catch (e: any) {
return {
values: [
{
label: t('tools.certificate-key-parser.service.text.error'),
value: e.toString(),
}] as LabelValue[],
},
] as LabelValue[],
};
}
}
@@ -28,11 +28,10 @@ async function onUpload(file: File) {
}
const certificateX509DER = ref('');
const { download: downloadX509DER } = useDownloadFileFromBase64(
{
source: certificateX509DER,
extension: 'der',
});
const { download: downloadX509DER } = useDownloadFileFromBase64({
source: certificateX509DER,
extension: 'der',
});
function downloadX509DERFile() {
if (certificateX509DER.value === '') {
@@ -41,8 +40,7 @@ function downloadX509DERFile() {
try {
downloadX509DER();
}
catch (_) {
} catch (_) {
//
}
}
@@ -53,8 +51,7 @@ const parsedSections = computedAsync<LabelValue[][]>(async () => {
let inputKeyOrCertificateValue: string | Buffer = '';
if (inputType.value === 'file' && file) {
inputKeyOrCertificateValue = file;
}
else if (inputType.value === 'content' && inputContent) {
} else if (inputType.value === 'content' && inputContent) {
inputKeyOrCertificateValue = inputContent;
}
try {
@@ -63,15 +60,11 @@ const parsedSections = computedAsync<LabelValue[][]>(async () => {
const { values, certificateX509DER: certPEM } = parsed[0];
certificateX509DER.value = certPEM || '';
return [values];
} else {
return parsed.map((p) => p.values);
}
else {
return parsed.map(p => p.values);
}
}
catch (e: any) {
return [
[{ label: t('tools.certificate-key-parser.texts.label-parsing-error'), value: e.toString() }],
];
} catch (e: any) {
return [[{ label: t('tools.certificate-key-parser.texts.label-parsing-error'), value: e.toString() }]];
}
});
@@ -83,7 +76,10 @@ const pemHeaders = [
{ label: t('tools.certificate-key-parser.texts.private-key-pkcs-8'), value: 'PRIVATE KEY' },
{ label: t('tools.certificate-key-parser.texts.public-key-pkcs-8'), value: 'PUBLIC KEY' },
{ label: t('tools.certificate-key-parser.texts.encrypted-private-key-pkcs-8-encrypted'), value: 'ENCRYPTED PRIVATE KEY' },
{
label: t('tools.certificate-key-parser.texts.encrypted-private-key-pkcs-8-encrypted'),
value: 'ENCRYPTED PRIVATE KEY',
},
{ label: t('tools.certificate-key-parser.texts.rsa-private-key-pkcs-1'), value: 'RSA PRIVATE KEY' },
{ label: t('tools.certificate-key-parser.texts.rsa-public-key-pkcs-1'), value: 'RSA PUBLIC KEY' },
@@ -107,28 +103,34 @@ const pemHeaders = [
<c-card>
<n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="file"
:label="t('tools.certificate-key-parser.texts.label-file')"
/>
<n-radio
value="content"
:label="t('tools.certificate-key-parser.texts.label-content')"
/>
<n-radio value="file" :label="t('tools.certificate-key-parser.texts.label-file')" />
<n-radio value="content" :label="t('tools.certificate-key-parser.texts.label-content')" />
</n-space>
</n-radio-group>
<c-file-upload
v-if="inputType === 'file'"
:title="t('tools.certificate-key-parser.texts.title-drag-and-drop-a-certificate-file-here-or-click-to-select-a-certificate-file')"
:title="
t(
'tools.certificate-key-parser.texts.title-drag-and-drop-a-certificate-file-here-or-click-to-select-a-certificate-file',
)
"
@file-upload="onUpload"
/>
<c-input-text
v-if="inputType === 'content'"
v-model:value="inputKeyOrCertificate"
:label="t('tools.certificate-key-parser.texts.label-paste-your-public-key-private-key-signature-fingerprint-certificate')"
:placeholder="t('tools.certificate-key-parser.texts.placeholder-your-public-key-private-key-signature-fingerprint-certificate')"
:label="
t(
'tools.certificate-key-parser.texts.label-paste-your-public-key-private-key-signature-fingerprint-certificate',
)
"
:placeholder="
t(
'tools.certificate-key-parser.texts.placeholder-your-public-key-private-key-signature-fingerprint-certificate',
)
"
multiline
rows="8"
data-test-id="input"
@@ -155,11 +157,7 @@ const pemHeaders = [
<n-divider />
<c-card
v-for="(part, partIndex) of parsedSections"
:key="partIndex"
mb-2
>
<c-card v-for="(part, partIndex) of parsedSections" :key="partIndex" mb-2>
<input-copyable
v-for="{ label, value, multiline } of part"
:key="label"
@@ -168,8 +166,8 @@ const pemHeaders = [
label-position="left"
label-width="100px"
label-align="right"
autosize mb-2
autosize
mb-2
:multiline="multiline"
:value="value"
:placeholder="t('tools.certificate-key-parser.texts.placeholder-not-set')"
File diff suppressed because it is too large. Load diff
@@ -17,15 +17,13 @@ async function getUInt8ArrayFromInputs() {
const file = fileInput.value;
if (inputType.value === 'file' && file) {
return new Uint8Array(await file.arrayBuffer());
}
else if (inputType.value === 'content' && fileContentValue) {
} else if (inputType.value === 'content' && fileContentValue) {
const uint8Array = new Uint8Array(fileContentValue.length);
for (let i = 0; i < fileContentValue.length; i++) {
uint8Array[i] = fileContentValue.charCodeAt(i);
}
return uint8Array;
}
else {
} else {
return null;
}
}
@@ -38,8 +36,7 @@ const encodings = computedAsync(async () => {
return null;
}
return chardet.analyse(buffer);
}
catch (e: any) {
} catch (e: any) {
error.value = e.toString();
return null;
}
@@ -54,8 +51,7 @@ async function generateEncodedOutput(encoding: string) {
return;
}
contentDecoded.value = iconv.decode(Buffer.from(buffer), encoding);
}
catch (e: any) {
} catch (e: any) {
return e.toString();
}
}
@@ -68,18 +64,12 @@ function onUpload(file: File) {
</script>
<template>
<div style="max-width: 600px;">
<div style="max-width: 600px">
<c-card :title="t('tools.charset-detector.texts.title-input')" mb-2>
<n-radio-group v-model:value="inputType" name="radiogroup" mb-2 flex justify-center>
<n-space>
<n-radio
value="file"
:label="t('tools.charset-detector.texts.label-file')"
/>
<n-radio
value="content"
:label="t('tools.charset-detector.texts.label-content')"
/>
<n-radio value="file" :label="t('tools.charset-detector.texts.label-file')" />
<n-radio value="content" :label="t('tools.charset-detector.texts.label-content')" />
</n-space>
</n-radio-group>
@@ -121,10 +111,7 @@ function onUpload(file: File) {
</tr>
</thead>
<tbody>
<tr
v-for="(enc, index) in encodings || []"
:key="index"
>
<tr v-for="(enc, index) in encodings || []" :key="index">
<td>
{{ enc.confidence }}
</td>
@@ -1,5 +1,11 @@
import { describe, expect, it } from 'vitest';
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation, computeUmaskRepresentation } from './chmod-calculator.service';
import {
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
computeUmaskRepresentation,
} from './chmod-calculator.service';
describe('chmod-calculator', () => {
describe('computeChmodOctalRepresentation', () => {
@@ -248,90 +254,70 @@ describe('chmod-calculator', () => {
});
it('get permissions from octal representation', () => {
expect(
computePermissionsFromChmodOctalRepresentation('777'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('777')).to.eql({
owner: { read: true, write: true, execute: true },
group: { read: true, write: true, execute: true },
public: { read: true, write: true, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('000'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('000')).to.eql({
owner: { read: false, write: false, execute: false },
group: { read: false, write: false, execute: false },
public: { read: false, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('235'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('235')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: true },
public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('421'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('421')).to.eql({
owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('124'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('124')).to.eql({
owner: { read: false, write: false, execute: true },
group: { read: false, write: true, execute: false },
public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('222'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('222')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('7222'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('7222')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: true, stickybit: true },
});
expect(
computePermissionsFromChmodOctalRepresentation('4222'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('4222')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('2222'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('2222')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: true, stickybit: false },
});
expect(
computePermissionsFromChmodOctalRepresentation('1222'),
).to.eql({
expect(computePermissionsFromChmodOctalRepresentation('1222')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
@@ -346,107 +332,83 @@ describe('chmod-calculator', () => {
});
it('get permissions from symbolic representation', () => {
expect(
computePermissionsFromChmodSymbolicRepresentation('dr-xr-xr-x'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('dr-xr-xr-x')).to.eql({
owner: { read: true, write: false, execute: true },
group: { read: true, write: false, execute: true },
public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-rw-r--r--'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-rw-r--r--')).to.eql({
owner: { read: true, write: true, execute: false },
group: { read: true, write: false, execute: false },
public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('rwxrwxrwx'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('rwxrwxrwx')).to.eql({
owner: { read: true, write: true, execute: true },
group: { read: true, write: true, execute: true },
public: { read: true, write: true, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('---------'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('---------')).to.eql({
owner: { read: false, write: false, execute: false },
group: { read: false, write: false, execute: false },
public: { read: false, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('r---wxr-x'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('r---wxr-x')).to.eql({
owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: true },
public: { read: true, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('r---w---x'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('r---w---x')).to.eql({
owner: { read: true, write: false, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: false, execute: true },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('--x-w-r--'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('--x-w-r--')).to.eql({
owner: { read: false, write: false, execute: true },
group: { read: false, write: true, execute: false },
public: { read: true, write: false, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-w--w--w-'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-w--w--w-')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-ws-ws-wt'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-ws-ws-wt')).to.eql({
owner: { read: false, write: true, execute: true },
group: { read: false, write: true, execute: true },
public: { read: false, write: true, execute: true },
flags: { setuid: true, setgid: true, stickybit: true },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-ws-w--w-'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-ws-w--w-')).to.eql({
owner: { read: false, write: true, execute: true },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: false },
flags: { setuid: true, setgid: false, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-w--ws-w-'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-w--ws-w-')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: true },
public: { read: false, write: true, execute: false },
flags: { setuid: false, setgid: true, stickybit: false },
});
expect(
computePermissionsFromChmodSymbolicRepresentation('-w--w--wt'),
).to.eql({
expect(computePermissionsFromChmodSymbolicRepresentation('-w--w--wt')).to.eql({
owner: { read: false, write: true, execute: false },
group: { read: false, write: true, execute: false },
public: { read: false, write: true, execute: true },
@@ -3,7 +3,13 @@ import type { GroupPermissions, Permissions, SpecialPermissions } from './chmod-
import { translate as t } from '@/plugins/i18n.plugin';
export { computeUmaskRepresentation, computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation };
export {
computeUmaskRepresentation,
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
};
function computeChmodOctalRepresentation({ permissions }: { permissions: Permissions }): string {
const permissionValue = { read: 4, write: 2, execute: 1 };
@@ -12,7 +18,11 @@ function computeChmodOctalRepresentation({ permissions }: { permissions: Permiss
const getGroupPermissionValue = (permission: GroupPermissions) =>
_.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, 0) : 0), 0);
const getSpecialPermissionValue = (permission: SpecialPermissions) => {
const octalValue = _.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(specialPermissionValue, key, 0) : 0), 0);
const octalValue = _.reduce(
permission,
(acc, isPermSet, key) => acc + (isPermSet ? _.get(specialPermissionValue, key, 0) : 0),
0,
);
return octalValue > 0 ? octalValue.toString() : '';
};
@@ -29,8 +39,14 @@ function computeChmodSymbolicRepresentation({ permissions }: { permissions: Perm
const specialFlagPermission = 'execute';
const getGroupPermissionValue = (permission: GroupPermissions, specialFlag: null | 's' | 't') =>
_.reduce(permission, (acc, isPermSet, key) => acc + ((key === specialFlagPermission ? specialFlag : undefined)
|| (isPermSet ? _.get(permissionValue, key, '') : '-')), '');
_.reduce(
permission,
(acc, isPermSet, key) =>
acc +
((key === specialFlagPermission ? specialFlag : undefined) ||
(isPermSet ? _.get(permissionValue, key, '') : '-')),
'',
);
return [
getGroupPermissionValue(permissions.owner, permissions.flags?.setuid ? 's' : null),
@@ -44,11 +60,16 @@ function computePermissionsFromChmodOctalRepresentation(octalPermissions: string
const specialPermissionValue = { setuid: 4, setgid: 2, stickybit: 1 };
if (!octalPermissions || !octalPermissions.match(/^[0-7]{3,4}$/)) {
throw new Error(t('tools.chmod-calculator.service.text.invalid-octal-permissions-must-be-3-or-4-octal-digits-octalpermissions', [octalPermissions]));
throw new Error(
t('tools.chmod-calculator.service.text.invalid-octal-permissions-must-be-3-or-4-octal-digits-octalpermissions', [
octalPermissions,
]),
);
}
const fullOctalPermissions = octalPermissions.length === 3 ? `0${octalPermissions}` : octalPermissions;
const hasSet = (position: number, flagValue: number) => (Number(fullOctalPermissions[position]) & flagValue) === flagValue;
const hasSet = (position: number, flagValue: number) =>
(Number(fullOctalPermissions[position]) & flagValue) === flagValue;
function computePermissionObject<T>(permissionSet: object, position: number): T {
return _.reduce(permissionSet, (acc, flag, key) => ({ ...acc, [key]: hasSet(position, flag) }), {}) as T;
}
@@ -67,51 +88,56 @@ function computePermissionsFromChmodOctalRepresentation(octalPermissions: string
function computePermissionsFromChmodSymbolicRepresentation(symbolicPermissions: string): Permissions {
const formatRegex = /^[-dlbcsp]?([r-])([w-])([xs-])([r-])([w-])([xs-])([r-])([w-])([xt-])$/;
if (!symbolicPermissions || !symbolicPermissions.match(formatRegex)) {
throw new Error(t('tools.chmod-calculator.service.text.invalid-string-permissions-must-be-in-form-rwxrwxrwx-symbolicpermissions', [symbolicPermissions]));
throw new Error(
t(
'tools.chmod-calculator.service.text.invalid-string-permissions-must-be-in-form-rwxrwxrwx-symbolicpermissions',
[symbolicPermissions],
),
);
}
const [_, rOwner, wOwner, xOwner, rGroup, wGroup, xGroup, rAll, wAll, xAll] = formatRegex.exec(symbolicPermissions) || [];
const getOctal = (flag: string, flagLetter: string, flagValue: number) => flag === flagLetter ? flagValue : 0;
const owner = getOctal(rOwner, 'r', 4)
+ getOctal(wOwner, 'w', 2)
+ getOctal(xOwner, 'x', 1) + getOctal(xOwner, 's', 1);
const groups = getOctal(rGroup, 'r', 4)
+ getOctal(wGroup, 'w', 2)
+ getOctal(xGroup, 'x', 1) + getOctal(xGroup, 's', 1);
const all = getOctal(rAll, 'r', 4)
+ getOctal(wAll, 'w', 2)
+ getOctal(xAll, 'x', 1) + getOctal(xAll, 't', 1);
const flags = getOctal(xOwner, 's', 4)
+ getOctal(xGroup, 's', 2)
+ getOctal(xAll, 't', 1);
const octalString = `${(flags > 0 ? flags : '')}${owner}${groups}${all}`;
const [_, rOwner, wOwner, xOwner, rGroup, wGroup, xGroup, rAll, wAll, xAll] =
formatRegex.exec(symbolicPermissions) || [];
const getOctal = (flag: string, flagLetter: string, flagValue: number) => (flag === flagLetter ? flagValue : 0);
const owner =
getOctal(rOwner, 'r', 4) + getOctal(wOwner, 'w', 2) + getOctal(xOwner, 'x', 1) + getOctal(xOwner, 's', 1);
const groups =
getOctal(rGroup, 'r', 4) + getOctal(wGroup, 'w', 2) + getOctal(xGroup, 'x', 1) + getOctal(xGroup, 's', 1);
const all = getOctal(rAll, 'r', 4) + getOctal(wAll, 'w', 2) + getOctal(xAll, 'x', 1) + getOctal(xAll, 't', 1);
const flags = getOctal(xOwner, 's', 4) + getOctal(xGroup, 's', 2) + getOctal(xAll, 't', 1);
const octalString = `${flags > 0 ? flags : ''}${owner}${groups}${all}`;
return computePermissionsFromChmodOctalRepresentation(octalString);
}
function computeUmaskRepresentation({ permissions }: { permissions: Permissions }): {
octal: string
symbolic: string
octal: string;
symbolic: string;
} {
const permissionValue = { read: 'r', write: 'w', execute: 'x' };
const getGroupPermissionValue = (permission: GroupPermissions) =>
_.reduce(permission, (acc, isPermSet, key) => acc + ((isPermSet ? _.get(permissionValue, key, '') : '')), '');
_.reduce(permission, (acc, isPermSet, key) => acc + (isPermSet ? _.get(permissionValue, key, '') : ''), '');
const symbolic = `umask u=${getGroupPermissionValue(permissions.owner)},g=${getGroupPermissionValue(permissions.group)},o=${getGroupPermissionValue(permissions.public)}`;
const octal = (0o777 - Number.parseInt(
computeChmodOctalRepresentation({
permissions:
{
owner: permissions.owner,
group: permissions.group,
public: permissions.public,
flags: { setuid: false, setgid: false, stickybit: false },
},
}), 8))
const octal = (
0o777 -
Number.parseInt(
computeChmodOctalRepresentation({
permissions: {
owner: permissions.owner,
group: permissions.group,
public: permissions.public,
flags: { setuid: false, setgid: false, stickybit: false },
},
}),
8,
)
)
.toString(8)
.padStart(3, '0');
return {
symbolic, octal,
symbolic,
octal,
};
}
@@ -13,5 +13,5 @@ export type SpecialPermissions = {
export type Permissions = {
[k in Group]: GroupPermissions;
} & {
flags: SpecialPermissions
flags: SpecialPermissions;
};
+36 -28
View File
@@ -3,7 +3,13 @@ import { useI18n } from 'vue-i18n';
import { useThemeVars } from 'naive-ui';
import InputCopyable from '../../components/InputCopyable.vue';
import { computeChmodOctalRepresentation, computeChmodSymbolicRepresentation, computePermissionsFromChmodOctalRepresentation, computePermissionsFromChmodSymbolicRepresentation, computeUmaskRepresentation } from './chmod-calculator.service';
import {
computeChmodOctalRepresentation,
computeChmodSymbolicRepresentation,
computePermissionsFromChmodOctalRepresentation,
computePermissionsFromChmodSymbolicRepresentation,
computeUmaskRepresentation,
} from './chmod-calculator.service';
import type { Group, Scope } from './chmod-calculator.types';
import { useValidation } from '@/composable/validation';
@@ -36,23 +42,19 @@ const octalPermissionsInputValidation = useValidation({
try {
computePermissionsFromChmodOctalRepresentation(value.trim());
return true;
}
catch {
} catch {
return false;
}
},
},
],
});
watch(
octalPermissionsInput,
(newPermissions) => {
if (!octalPermissionsInputValidation.isValid) {
return;
}
permissions.value = computePermissionsFromChmodOctalRepresentation(newPermissions.trim());
},
);
watch(octalPermissionsInput, (newPermissions) => {
if (!octalPermissionsInputValidation.isValid) {
return;
}
permissions.value = computePermissionsFromChmodOctalRepresentation(newPermissions.trim());
});
const symbolicPermissionsInput = ref('---------');
const symbolicPermissionsInputValidation = useValidation({
@@ -64,23 +66,19 @@ const symbolicPermissionsInputValidation = useValidation({
try {
computePermissionsFromChmodSymbolicRepresentation(value.trim());
return true;
}
catch {
} catch {
return false;
}
},
},
],
});
watch(
symbolicPermissionsInput,
(newPermissions) => {
if (!symbolicPermissionsInputValidation.isValid) {
return;
}
permissions.value = computePermissionsFromChmodSymbolicRepresentation(newPermissions.trim());
},
);
watch(symbolicPermissionsInput, (newPermissions) => {
if (!symbolicPermissionsInputValidation.isValid) {
return;
}
permissions.value = computePermissionsFromChmodSymbolicRepresentation(newPermissions.trim());
});
const octal = computed(() => computeChmodOctalRepresentation({ permissions: permissions.value }));
const symbolic = computed(() => computeChmodSymbolicRepresentation({ permissions: permissions.value }));
@@ -90,9 +88,7 @@ const umask = computed(() => computeUmaskRepresentation({ permissions: permissio
<template>
<div>
<div mb-2 flex justify-center>
<c-link target="_blank" to="/chmod-memo">
See <code>chmod</code> command cheatsheet.
</c-link>
<c-link target="_blank" to="/chmod-memo"> See <code>chmod</code> command cheatsheet. </c-link>
</div>
<n-space justify="center">
@@ -169,8 +165,20 @@ const umask = computed(() => computeUmaskRepresentation({ permissions: permissio
</c-card>
<c-card :title="t('tools.chmod-calculator.texts.title-umask')">
<InputCopyable :label="t('tools.chmod-calculator.texts.label-octal')" label-position="left" label-width="100px" :value="umask.octal" readonly />
<InputCopyable :label="t('tools.chmod-calculator.texts.label-symbolic')" label-position="left" label-width="100px" :value="umask.symbolic" readonly />
<InputCopyable
:label="t('tools.chmod-calculator.texts.label-octal')"
label-position="left"
label-width="100px"
:value="umask.octal"
readonly
/>
<InputCopyable
:label="t('tools.chmod-calculator.texts.label-symbolic')"
label-position="left"
label-width="100px"
:value="umask.symbolic"
readonly
/>
</c-card>
</div>
</template>
+11 -5
View File
@@ -23,14 +23,18 @@ async function loadMemo(currentLocale = locale.value) {
memoComponent.value = module.default ?? module;
}
watch(locale, () => {
loadMemo();
}, { immediate: true });
watch(
locale,
() => {
loadMemo();
},
{ immediate: true },
);
</script>
<template>
<div>
<component :is="memoComponent" style="overflow-x: auto;" />
<component :is="memoComponent" style="overflow-x: auto" />
</div>
</template>
@@ -45,7 +49,9 @@ watch(locale, () => {
::v-deep(table) {
border-collapse: collapse;
}
::v-deep(table), ::v-deep(td), ::v-deep(th) {
::v-deep(table),
::v-deep(td),
::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1');
padding: 5px;
}
+16 -16
View File
@@ -1,4 +1,4 @@
**`chmod`** (*change mode*) sets who may read, write, and execute a file or directory on Unix-like systems. The mode can be written **symbolically** (`u+x`) or **numerically** (`755`) — both reach the same result.
**`chmod`** (_change mode_) sets who may read, write, and execute a file or directory on Unix-like systems. The mode can be written **symbolically** (`u+x`) or **numerically** (`755`) — both reach the same result.
```bash
chmod [options] <mode> <file>...
@@ -17,19 +17,19 @@ chmod [options] <mode> <file>...
└─────────────── type : - file · d directory · l symlink · c/b device
```
## 🧑 User Classes (*who*)
## 🧑 User Classes (_who_)
| Symbol | Class | Applies to |
|--------|--------|-------------------------------------------------|
| ------ | ------ | ----------------------------------------------- |
| `u` | User | The file's owner |
| `g` | Group | Members of the file's group |
| `o` | Others | Everyone else |
| `a` | All | `u`, `g` and `o` at once (implied when omitted) |
## 🔐 Permission Bits (*what*)
## 🔐 Permission Bits (_what_)
| Symbol | Permission | Octal | On a file | On a directory |
|--------|------------|-------|---------------------|-------------------------------------------|
| ------ | ---------- | ----- | ------------------- | ----------------------------------------- |
| `r` | Read | `4` | Read the contents | List entry names (`ls`) |
| `w` | Write | `2` | Modify the contents | Create, rename and delete entries |
| `x` | Execute | `1` | Run as a program | Enter it (`cd`) and reach entries by name |
@@ -38,7 +38,7 @@ chmod [options] <mode> <file>...
## 📝 Symbolic Mode
| Operator | Effect |
|----------|-------------------------------------------------------------------|
| -------- | ----------------------------------------------------------------- |
| `+` | Add the listed permissions, leave the rest untouched |
| `-` | Remove the listed permissions, leave the rest untouched |
| `=` | Set exactly these permissions, clearing the others for that class |
@@ -76,7 +76,7 @@ chmod --reference=<ref> <file>
Each digit is the sum of `r` (4), `w` (2) and `x` (1):
| Octal | Sum | Bits |
|-------|-------|-------|
| ----- | ----- | ----- |
| `7` | 4+2+1 | `rwx` |
| `6` | 4+2 | `rw-` |
| `5` | 4+1 | `r-x` |
@@ -86,12 +86,12 @@ Each digit is the sum of `r` (4), `w` (2) and `x` (1):
| `1` | 1 | `--x` |
| `0` | 0 | `---` |
Three digits map to **user, group, others**. An optional fourth *leading* digit sets the special bits (`chmod 4755`, see below).
Three digits map to **user, group, others**. An optional fourth _leading_ digit sets the special bits (`chmod 4755`, see below).
### Common modes
| Mode | Symbolic | Typical use |
|-------|-------------|-------------------------------------------------------------|
| ----- | ----------- | ----------------------------------------------------------- |
| `777` | `rwxrwxrwx` | Full access for everyone — ⚠️ almost never the right answer |
| `755` | `rwxr-xr-x` | Scripts, binaries and directories |
| `750` | `rwxr-x---` | Executable for the owner and their group only |
@@ -115,7 +115,7 @@ chmod 600 ~/.ssh/id_ed25519
These go beyond read/write/execute and control the execution context and deletion rules.
| Bit | Octal | Symbolic | Applies to | Effect | Shown in `ls -l` as |
|----------|-------|----------|--------------------------|----------------------------------------------------------------------|-------------------------|
| -------- | ----- | -------- | ------------------------ | -------------------------------------------------------------------- | ----------------------- |
| `setuid` | `4` | `u+s` | Executable files | Runs with the **file owner's** privileges | `s` in the user field |
| `setgid` | `2` | `g+s` | Executables, directories | Runs as the file's group / new entries inherit the directory's group | `s` in the group field |
| `sticky` | `1` | `+t` | Directories | Only the entry's owner (or root) may delete or rename it | `t` in the others field |
@@ -140,10 +140,10 @@ chmod u-s,g-s,o-t <file>
## 📂 Directory Access Matrix
`x` on a directory means *traverse*, not *execute* — without it nothing below the directory can be reached, no matter how permissive the files themselves are.
`x` on a directory means _traverse_, not _execute_ — without it nothing below the directory can be reached, no matter how permissive the files themselves are.
| Mode | List names (`ls`) | Details (`ls -l`, `stat`) | Enter (`cd`) | Open a known file | Create / delete entries |
|-------|-------------------|---------------------------|--------------|-------------------|-------------------------|
| ----- | ----------------- | ------------------------- | ------------ | ----------------- | ----------------------- |
| `r--` | ✅ | ❌ | ❌ | ❌ | ❌ |
| `--x` | ❌ | ✅ (by exact name) | ✅ | ✅ | ❌ |
| `r-x` | ✅ | ✅ | ✅ | ✅ | ❌ |
@@ -172,7 +172,7 @@ find <dir> -type f -name '*.sh' -exec chmod +x {} +
## ⚙️ Useful Options
| Option | Description |
|-----------------------------|-----------------------------------------------------------------|
| --------------------------- | --------------------------------------------------------------- |
| `-R`, `--recursive` | Apply to directories and everything inside them |
| `-v`, `--verbose` | Print a line for every file processed |
| `-c`, `--changes` | Print a line only when a mode actually changed |
@@ -197,7 +197,7 @@ umask 027
```
| umask | New files | New directories |
|-------|-----------|-----------------|
| ----- | --------- | --------------- |
| `022` | `644` | `755` |
| `002` | `664` | `775` |
| `027` | `640` | `750` |
@@ -208,7 +208,7 @@ umask 027
## 🚑 Common Recipes
| Goal | Command |
|-------------------------------------|------------------------------------------------------------------------------|
| ----------------------------------- | ---------------------------------------------------------------------------- |
| Make a script runnable | `chmod +x deploy.sh` |
| Lock down an SSH key pair | `chmod 700 ~/.ssh && chmod 600 ~/.ssh/id_* && chmod 644 ~/.ssh/*.pub` |
| Serve web content read-only | `chmod -R u=rwX,go=rX /var/www/site` |
@@ -220,7 +220,7 @@ umask 027
## 🧰 Related Commands
| Command | Purpose |
|-----------------------------------|--------------------------------------------------------------------|
| --------------------------------- | ------------------------------------------------------------------ |
| `chown <user>:<group> <file>` | Change the owner and/or group |
| `chgrp <group> <file>` | Change the group only |
| `ls -l` / `ls -ld <dir>` | Show permissions (`-d` for the directory itself, not its contents) |
+32 -33
View File
@@ -2,20 +2,20 @@
## 🧑 用户类别
| 符号 | 含义 |
|--------|----------------|
| `u` | 用户(所有者) |
| `g` | 组 |
| `o` | 其他 |
| `a` | 所有(u+g+o) |
| 符号 | 含义 |
| ---- | -------------- |
| `u` | 用户(所有者) |
| `g` | 组 |
| `o` | 其他 |
| `a` | 所有(u+g+o) |
## 🔐 权限类型
| 符号 | 含义 | 数字 |
|--------|----------|---------|
| `r` | 读 | 4 |
| `w` | 写 | 2 |
| `x` | 执行 | 1 |
| 符号 | 含义 | 数字 |
| ---- | ---- | ---- |
| `r` | 读 | 4 |
| `w` | 写 | 2 |
| `x` | 执行 | 1 |
## 📝 符号模式
@@ -31,12 +31,11 @@ chmod a=r file # 为所有用户设置为只读
将用户、组和其他用户的权限值组合:
| 模式 | 权限 | 含义 |
|------|-------------|---------------|
| 777 | rwxrwxrwx | 完全访问权限 |
| 755 | rwxr-xr-x | 常用于脚本 |
| 644 | rw-r--r-- | 常用于文本文件 |
| 模式 | 权限 | 含义 |
| ---- | --------- | -------------- |
| 777 | rwxrwxrwx | 完全访问权限 |
| 755 | rwxr-xr-x | 常用于脚本 |
| 644 | rw-r--r-- | 常用于文本文件 |
```bash
chmod 755 script.sh
@@ -92,28 +91,28 @@ chmod 1777 /tmp
## 📂 执行(`x`)标志:文件与目录的区别
| 上下文 | `x` 权限的效果 |
|-------------|----------------------------------------|
| **文件** | 允许作为程序/脚本执行 |
| **目录** | 允许进入目录(`cd`)并通过名称访问其内容 |
| 上下文 | `x` 权限的效果 |
| -------- | ---------------------------------------- |
| **文件** | 允许作为程序/脚本执行 |
| **目录** | 允许进入目录(`cd`)并通过名称访问其内容 |
### 🔍 目录访问矩阵
| 权限 | 可列出(`ls`) | 可进入(`cd`) | 可访问文件 |
|------------|------------------|------------------|------------------|
| `r` | ✅ | ❌ | ✅(已知文件名时) |
| `x` | ❌ | ✅ | ✅(已知文件名时) |
| `r+x` | ✅ | ✅ | ✅ |
| 权限 | 可列出(`ls`) | 可进入(`cd`) | 可访问文件 |
| ----- | -------------- | -------------- | ------------------ |
| `r` | ✅ | ❌ | ✅(已知文件名时) |
| `x` | ❌ | ✅ | ✅(已知文件名时) |
| `r+x` | ✅ | ✅ | ✅ |
> 🧠 没有目录的 `x` 权限,你无法 `cd` 进入该目录——即使你可以列出其内容。
## 🔍 快速参考
| 命令 | 描述 |
|---------------------|--------------------------------------|
| `chmod +x file` | 使文件可执行 |
| `chmod -R 755 dir` | 递归设置权限 |
| `chmod u=rwx file` | 仅将用户权限设置为 rwx |
| `chmod a-x file` | 移除所有用户的执行权限 |
| 命令 | 描述 |
| ------------------ | ---------------------- |
| `chmod +x file` | 使文件可执行 |
| `chmod -R 755 dir` | 递归设置权限 |
| `chmod u=rwx file` | 仅将用户权限设置为 rwx |
| `chmod a-x file` | 移除所有用户的执行权限 |
💡 提示:使用 `ls -l` 查看当前权限。
💡 提示:使用 `ls -l` 查看当前权限。
@@ -13,25 +13,45 @@ describe('cidr-in-cidr', () => {
expect(cidrInCidr({ baseRange: '192.168.20.*', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.*', ipOrRangeToTest: '192.168.0.0/28' }).isIncluded).toBe(true); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.12' }).isIncluded).toBe(true); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.20' }).isIncluded).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.12' }).isIncluded).toBe(
true,
); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.20' }).isIncluded).toBe(
false,
); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.12' }).isIncluded).toBe(true); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.20' }).isIncluded).toBe(false); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.12' })
.isIncluded,
).toBe(true); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.1-192.168.20.15', ipOrRangeToTest: '192.168.20.9-192.168.20.20' })
.isIncluded,
).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.20.0/28' }).isIncluded).toBe(true); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.0-192.168.1.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(true); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.20.0/28' }).isIncluded,
).toBe(true); // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.0-192.168.20.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded,
).toBe(false); // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.0-192.168.1.255', ipOrRangeToTest: '192.168.1.0/28' }).isIncluded).toBe(
true,
); // NOSONAR
});
it('should return correct subnet', () => {
expect(cidrInCidr({ baseRange: '192.168.0.0/16', ipOrRangeToTest: '192.168.0.1' }).baseSubnets).to.deep.eq([ // NOSONAR
expect(cidrInCidr({ baseRange: '192.168.0.0/16', ipOrRangeToTest: '192.168.0.1' }).baseSubnets).to.deep.eq([
// NOSONAR
{
cidr: '192.168.0.0/16', // NOSONAR
end: '192.168.255.255', // NOSONAR
start: '192.168.0.0', // NOSONAR
},
]);
expect(cidrInCidr({ baseRange: '192.168.20.1-192.168.20.3', ipOrRangeToTest: '192.168.1.0/28' }).baseSubnets).to.deep.eq([ // NOSONAR
expect(
cidrInCidr({ baseRange: '192.168.20.1-192.168.20.3', ipOrRangeToTest: '192.168.1.0/28' }).baseSubnets,
).to.deep.eq([
// NOSONAR
{
cidr: '192.168.20.1/32', // NOSONAR
end: '192.168.20.1', // NOSONAR
+17 -18
View File
@@ -1,28 +1,27 @@
import { getMatch } from 'ip-matching';
export function cidrInCidr(
{ baseRange, ipOrRangeToTest }:
{
baseRange: string
ipOrRangeToTest: string
}) {
export function cidrInCidr({ baseRange, ipOrRangeToTest }: { baseRange: string; ipOrRangeToTest: string }) {
const baseMatchMasks = getMatch(baseRange)?.convertToMasks() || [];
const ipOrRangeToTestMatchMasks = getMatch(ipOrRangeToTest)?.convertToMasks() || [];
const baseSubnets = baseMatchMasks.map((mask) => {
const subnet = mask.convertToSubnet();
if (!subnet) {
return { cidr: '', start: '', end: '' };
}
return {
cidr: subnet.toString(),
start: subnet.getFirst().toString(),
end: subnet.getLast().toString(),
};
}).filter(subnet => subnet.cidr !== '');
const baseSubnets = baseMatchMasks
.map((mask) => {
const subnet = mask.convertToSubnet();
if (!subnet) {
return { cidr: '', start: '', end: '' };
}
return {
cidr: subnet.toString(),
start: subnet.getFirst().toString(),
end: subnet.getLast().toString(),
};
})
.filter((subnet) => subnet.cidr !== '');
return {
baseSubnets,
isIncluded: baseMatchMasks.some(baseMask => ipOrRangeToTestMatchMasks.every(ipOrRangeMask => ipOrRangeMask.isSubsetOf(baseMask))),
isIncluded: baseMatchMasks.some((baseMask) =>
ipOrRangeToTestMatchMasks.every((ipOrRangeMask) => ipOrRangeMask.isSubsetOf(baseMask)),
),
};
}
+3 -3
View File
@@ -1,4 +1,4 @@
declare module 'citation-formatter' {
function APA(citationObject: any): string;
function MLA(citationObject: any): string;
}
function APA(citationObject: any): string;
function MLA(citationObject: any): string;
}
@@ -11,8 +11,9 @@ describe('formatVancouverCitation', () => {
publisher: 'Publisher',
url: 'https://example.com',
};
expect(formatVancouverCitation(entry))
.toBe('Doe J. Sample Title. Publisher; 2021. Available from: https://example.com');
expect(formatVancouverCitation(entry)).toBe(
'Doe J. Sample Title. Publisher; 2021. Available from: https://example.com',
);
});
it('formats multiple authors correctly', () => {
@@ -25,8 +26,7 @@ describe('formatVancouverCitation', () => {
title: 'Multi Author Work',
publisher: 'TechPress',
};
expect(formatVancouverCitation(entry))
.toBe('Doe J, Smith J. Multi Author Work. TechPress; 2020.');
expect(formatVancouverCitation(entry)).toBe('Doe J, Smith J. Multi Author Work. TechPress; 2020.');
});
it('uses et al. when more than 6 authors', () => {
@@ -44,8 +44,9 @@ describe('formatVancouverCitation', () => {
title: 'Big Team Paper',
publisher: 'SciencePub',
};
expect(formatVancouverCitation(entry))
.toBe('One A, Two B, Three C, Four D, Five E, Six F, et al. Big Team Paper. SciencePub; 2019.');
expect(formatVancouverCitation(entry)).toBe(
'One A, Two B, Three C, Four D, Five E, Six F, et al. Big Team Paper. SciencePub; 2019.',
);
});
it('handles multiple initials in first name', () => {
@@ -53,8 +54,7 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'John Michael', last: 'Doe' }],
title: 'Initials Test',
};
expect(formatVancouverCitation(entry))
.toBe('Doe JM. Initials Test.');
expect(formatVancouverCitation(entry)).toBe('Doe JM. Initials Test.');
});
it('falls back to Anonymous if no authors', () => {
@@ -62,8 +62,7 @@ describe('formatVancouverCitation', () => {
title: 'No Author Work',
year: '2022',
};
expect(formatVancouverCitation(entry))
.toBe('Anonymous. No Author Work. 2022.');
expect(formatVancouverCitation(entry)).toBe('Anonymous. No Author Work. 2022.');
});
it('handles missing title gracefully', () => {
@@ -71,8 +70,7 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'Jane', last: 'Smith' }],
year: '2023',
};
expect(formatVancouverCitation(entry))
.toBe('Smith J. [No title]. 2023.');
expect(formatVancouverCitation(entry)).toBe('Smith J. [No title]. 2023.');
});
it('handles missing publisher and year', () => {
@@ -80,7 +78,6 @@ describe('formatVancouverCitation', () => {
authors: [{ first: 'Jane', last: 'Smith' }],
title: 'Untimed Work',
};
expect(formatVancouverCitation(entry))
.toBe('Smith J. Untimed Work.');
expect(formatVancouverCitation(entry)).toBe('Smith J. Untimed Work.');
});
});
@@ -1,10 +1,13 @@
interface Author { first?: string; last?: string }
interface Author {
first?: string;
last?: string;
}
interface CitationInput {
authors?: Author[]
year?: string
title?: string
publisher?: string
url?: string
authors?: Author[];
year?: string;
title?: string;
publisher?: string;
url?: string;
}
export function formatVancouverCitation(entry: CitationInput): string {
@@ -14,7 +17,7 @@ export function formatVancouverCitation(entry: CitationInput): string {
}
const initials = (author.first || '')
.split(/\s+/)
.map(name => name.charAt(0).toUpperCase())
.map((name) => name.charAt(0).toUpperCase())
.join('');
return `${author.last} ${initials}`;
};
@@ -22,9 +25,7 @@ export function formatVancouverCitation(entry: CitationInput): string {
const authors = Array.isArray(entry.authors) ? entry.authors.map(formatAuthor).filter(Boolean) : [];
let authorStr = 'Anonymous';
if (authors.length > 0) {
authorStr = authors.length > 6
? `${authors.slice(0, 6).join(', ')}, et al`
: authors.join(', ');
authorStr = authors.length > 6 ? `${authors.slice(0, 6).join(', ')}, et al` : authors.join(', ');
}
const title = entry.title?.trim() || '[No title]';
@@ -1,68 +1,69 @@
import { describe, expect, it } from 'vitest';
import { buildEditedCommand, buildOptionsObject, extractOptions, isOption, sanitizeOption } from './cli-command-editor.service';
import {
buildEditedCommand,
buildOptionsObject,
extractOptions,
isOption,
sanitizeOption,
} from './cli-command-editor.service';
describe('cli-command-editor', () => {
describe('extractOptions', () => {
it ('extracts all the options from a command', () => {
it('extracts all the options from a command', () => {
expect(extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer')[0]).toContain(
'--load-balancer-name',
);
expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer')[0],
extractOptions(
'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[0],
).toContain('--load-balancer-name');
expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[0],
).toContain('--load-balancer-name');
expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[1],
extractOptions(
'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[1],
).toContain('--debug');
expect(
extractOptions('aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy')[2],
extractOptions(
'aws elb describe-load-balancers --load-balancer-name my-load-balancer --debug --query my-queryyy',
)[2],
).toContain('--query');
});
it('extracts all the option from a command with a mix of hyphen and double hyphens', () => {
expect(
extractOptions('npm i lodash -g --legacy-peer-deps')[0],
).toContain('-g');
expect(extractOptions('npm i lodash -g --legacy-peer-deps')[0]).toContain('-g');
expect(
extractOptions('npm i lodash -g --legacy-peer-deps')[1],
).toContain('--legacy-peer-deps');
expect(extractOptions('npm i lodash -g --legacy-peer-deps')[1]).toContain('--legacy-peer-deps');
});
it('shouldn\'t extract any options from a command without options', () => {
expect(
extractOptions('npm i lodash'),
).toEqual([]);
it("shouldn't extract any options from a command without options", () => {
expect(extractOptions('npm i lodash')).toEqual([]);
});
it('shouldn\'t return any options if command is not passed', () => {
it("shouldn't return any options if command is not passed", () => {
expect(extractOptions()).toEqual([]);
});
});
describe('buildOptionsObject', () => {
it('returns a valid options object with the given options', () => {
expect(
buildOptionsObject(['--debug', '--load-balancer-names']),
).toEqual({
expect(buildOptionsObject(['--debug', '--load-balancer-names'])).toEqual({
'--debug': '',
'--load-balancer-names': '',
});
});
it('returns an empty obnject with blank options array', () => {
expect(
buildOptionsObject([]),
).toEqual({});
expect(buildOptionsObject([])).toEqual({});
});
});
describe('sanitizeOption', () => {
it('returns the sanitized option without `id` suffix', () => {
expect(sanitizeOption('--debug-id-1dfsj'))
.toEqual('--debug');
expect(sanitizeOption('--debug-id-1dfsj')).toEqual('--debug');
});
it('returns the blank string', () => {
@@ -87,54 +88,66 @@ describe('cli-command-editor', () => {
describe('buildEditedCommand', () => {
it('returns the edited command', () => {
expect(
buildEditedCommand({
'--debug-id-1dfsj': 'stdin',
'-p': '',
'-m': 'nahhhh',
}, {
'--debug-id-1dfsj': 'stdin',
'-p': '',
'-m': 'nahhhh',
}, 'aws node --debug stdio -p -m okayyy'),
buildEditedCommand(
{
'--debug-id-1dfsj': 'stdin',
'-p': '',
'-m': 'nahhhh',
},
{
'--debug-id-1dfsj': 'stdin',
'-p': '',
'-m': 'nahhhh',
},
'aws node --debug stdio -p -m okayyy',
),
).toEqual('aws node --debug stdin -p -m nahhhh');
expect(
buildEditedCommand({
'-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444',
}, {
'-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444',
}, 'docker run -d -p 18123:8123 -p 19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server'),
).toEqual('docker run -d -p 4444:3333 -p 3333:4444 --name clickhouse-server --ulimit nofile=3333:4444 clickhouse/clickhouse-server');
buildEditedCommand(
{
'-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444',
},
{
'-d-id-1dfsj': '',
'-p-id-fdsd': '4444:3333',
'-p-id-fddd': '3333:4444',
'--name-id-nnnn': 'clickhouse-server',
'--ulimit-id-uuuu': 'nofile=3333:4444',
},
'docker run -d -p 18123:8123 -p 19000:9000 --name some-clickhouse-server --ulimit nofile=262144:262144 clickhouse/clickhouse-server',
),
).toEqual(
'docker run -d -p 4444:3333 -p 3333:4444 --name clickhouse-server --ulimit nofile=3333:4444 clickhouse/clickhouse-server',
);
});
it('returns the edited command when options object and CLI options order doesn\'t match', () => {
it("returns the edited command when options object and CLI options order doesn't match", () => {
expect(
buildEditedCommand({
'-d-id-t1dd3': 'true',
'--install-id-only123': 'nodemon',
}, {
'--install-id-only123': 'nodem',
'-d-id-t1dd3': 'false',
}, 'npm --install nodem -d false'),
buildEditedCommand(
{
'-d-id-t1dd3': 'true',
'--install-id-only123': 'nodemon',
},
{
'--install-id-only123': 'nodem',
'-d-id-t1dd3': 'false',
},
'npm --install nodem -d false',
),
).toBe('npm --install nodemon -d true');
});
it('returns the original command', () => {
expect(
buildEditedCommand({}, {}, 'npm install nodemon'),
).toBe('npm install nodemon');
expect(buildEditedCommand({}, {}, 'npm install nodemon')).toBe('npm install nodemon');
expect(
buildEditedCommand({}, {}, 'aws load-balancer describe-load-balancers all'),
).toBe('aws load-balancer describe-load-balancers all');
expect(buildEditedCommand({}, {}, 'aws load-balancer describe-load-balancers all')).toBe(
'aws load-balancer describe-load-balancers all',
);
});
});
});
@@ -14,15 +14,17 @@ export function extractOptions(command: string = ''): string[] {
const tokens = command.split(' ');
// map each token of the command to an option
const options = tokens.map((token: string) => {
// every option in a starts with either a hyphen or double hyphens
if (isOption(token)) {
const randomId = generateRandomId();
return `${token}-${randomId}`;
}
const options = tokens
.map((token: string) => {
// every option in a starts with either a hyphen or double hyphens
if (isOption(token)) {
const randomId = generateRandomId();
return `${token}-${randomId}`;
}
return '';
}).filter((option: string): boolean => !!option);
return '';
})
.filter((option: string): boolean => !!option);
return options;
}
@@ -40,7 +42,11 @@ export function sanitizeOption(option: string): string {
return option.split('-id')?.[0];
}
export function buildEditedCommand(options: Record<string, string>, originalOptions: Record<string, string>, command: string): string {
export function buildEditedCommand(
options: Record<string, string>,
originalOptions: Record<string, string>,
command: string,
): string {
if (!Object.keys(options).length) {
return command;
}
@@ -53,12 +59,11 @@ export function buildEditedCommand(options: Record<string, string>, originalOpti
// order as they appear in the original command, this is done
// to handle the interpolation of edited option values into the
// command
originalOptions = Object.entries(options)
.reduce((previousValue: Record<string, string>, currentValue: string[]) => {
previousValue[currentValue[0]] = currentValue[1];
originalOptions = Object.entries(options).reduce((previousValue: Record<string, string>, currentValue: string[]) => {
previousValue[currentValue[0]] = currentValue[1];
return previousValue;
}, originalOptions);
return previousValue;
}, originalOptions);
const defaultValues: Record<string, string> = {};
// replacing the options and their values (if any) with formatter ($i) to
@@ -92,8 +97,7 @@ export function buildEditedCommand(options: Record<string, string>, originalOpti
if (originalOptions[key]) {
editedCommand = editedCommand.replace(`$${i}`, `${keyWithoutIdSuffix} ${originalOptions[key]}`);
}
else {
} else {
const value = defaultValues[`$${i}`];
const replaceValue = value ? `${keyWithoutIdSuffix} ${value}` : keyWithoutIdSuffix;
editedCommand = editedCommand.replace(`$${i}`, replaceValue);
@@ -25,7 +25,11 @@ const command = ref('');
:placeholder="$t('tools.cli-command-editor.placeholder')"
:aria-placeholder="t('tools.cli-command-editor.placeholder')"
raw-text
@update:value="() => { command = inputCommand }"
@update:value="
() => {
command = inputCommand;
}
"
/>
<div v-for="option in options" :key="option" flex justify-center>
<c-input-text
@@ -38,17 +42,15 @@ const command = ref('');
:placeholder="service.sanitizeOption(option)"
:aria-placeholder="service.sanitizeOption(option)"
mt-6
@update:value="() => { command = service.buildEditedCommand(optionsInput, optionsObject, inputCommand) }"
@update:value="
() => {
command = service.buildEditedCommand(optionsInput, optionsObject, inputCommand);
}
"
/>
</div>
<c-text-copyable
v-if="command"
:value="command"
:show-icon="false"
mt-6 font-mono
/>
<c-text-copyable v-if="command" :value="command" :show-icon="false" mt-6 font-mono />
</n-gi>
</n-grid>
</c-card>
+28 -17
View File
@@ -26,15 +26,25 @@ const themes = ref<{ value: string; label: string }[]>(
value: item.id,
label: item.displayName,
};
}));
}),
);
const langs = ref<{ value: string; label: string }[]>(
bundledLanguagesInfo.map(item => ({
bundledLanguagesInfo.map((item) => ({
value: item.id,
label: item.name,
})));
})),
);
const currentTheme = useQueryParamOrStorage({ name: 'theme', storageName: 'code-highlighter:theme', defaultValue: 'dark-plus' });
const currentLang = useQueryParamOrStorage({ name: 'lang', storageName: 'code-highlighter:lang', defaultValue: 'typescript' });
const currentTheme = useQueryParamOrStorage({
name: 'theme',
storageName: 'code-highlighter:theme',
defaultValue: 'dark-plus',
});
const currentLang = useQueryParamOrStorage({
name: 'lang',
storageName: 'code-highlighter:lang',
defaultValue: 'typescript',
});
const showLineNumbers = ref(false);
@@ -46,11 +56,10 @@ const formattedCodeHtml = computedAsync(async () => {
const lineNumberWidth = Math.log10(codeValue.split('\n').length) + 2;
const highlighter = await createHighlighter(
{
langs: [currentLangValue],
themes: [currentThemeValue],
});
const highlighter = await createHighlighter({
langs: [currentLangValue],
themes: [currentThemeValue],
});
return highlighter.codeToHtml(codeValue, {
lang: currentLangValue,
theme: currentThemeValue,
@@ -59,16 +68,17 @@ const formattedCodeHtml = computedAsync(async () => {
postprocess(html: string) {
// when copied to clipboard and pasted to LibreOffice,
// formatting of first line is only kept if there is a line break before...
const ensureFirstLineFormattedWhenCopied
= (html: string) => html.replace('<code>', '<code>\n');
const ensureFirstLineFormattedWhenCopied = (html: string) => html.replace('<code>', '<code>\n');
if (!needLineNumbers) {
return ensureFirstLineFormattedWhenCopied(html);
}
let lineNumber = 1;
return html.replace(/<span class="line/g, (m) => {
const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' ');
return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`;
}).replace('<code>', '<code>\n');
return html
.replace(/<span class="line/g, (m) => {
const lineNumberFormatted = (lineNumber++).toString().padStart(lineNumberWidth, ' ');
return `<span class="line-number" style="white-space-collapse: preserve">${lineNumberFormatted} </span>${m}`;
})
.replace('<code>', '<code>\n');
},
},
],
@@ -120,7 +130,8 @@ const { copy: copyText } = useCopy({ source: code });
</c-button>
</div>
<div v-html="formattedCodeHtml" /><!-- //NOSONAR -->
<div v-html="formattedCodeHtml" />
<!-- //NOSONAR -->
</div>
</template>
@@ -12,18 +12,18 @@ function removeAlphaChannelWhenOpaque(hexColor: string) {
function buildColorFormat({
label,
parse = value => colord(value),
parse = (value) => colord(value),
format,
placeholder,
invalidMessage = t('tools.color-converter.models.text.invalid-label-tolowercase-format', [label.toLowerCase()]),
type = 'text',
}: {
label: string
parse?: (value: string) => Colord
format: (value: Colord) => string
placeholder?: string
invalidMessage?: string
type?: 'text' | 'color-picker'
label: string;
parse?: (value: string) => Colord;
format: (value: Colord) => string;
placeholder?: string;
invalidMessage?: string;
type?: 'text' | 'color-picker';
}) {
const value = ref('');
@@ -39,16 +39,16 @@ function buildColorFormat({
rules: [
{
message: invalidMessage,
validator: v => withDefaultOnError(() => {
if (v === '') {
return true;
}
validator: (v) =>
withDefaultOnError(() => {
if (v === '') {
return true;
}
return parse(v).isValid();
}, false),
return parse(v).isValid();
}, false),
},
],
}),
};
}
+16 -14
View File
@@ -58,25 +58,25 @@ const formats = {
label: t('tools.color-converter.texts.label-lab'),
format: (v: Colord) => colordx(v.toHex()).toLabString(),
placeholder: 'e.g. lab(54.29 80.8 69.89)',
parse: value => colord(colordx(value).toHex()),
parse: (value) => colord(colordx(value).toHex()),
}),
xyz: buildColorFormat({
label: t('tools.color-converter.texts.label-xyz'),
format: (v: Colord) => JSON.stringify(v.toXyz()),
placeholder: 'e.g. { x: 95.047, y: 100, z: 108.883, a: 1 }',
parse: value => colord(JSON.parse(value)),
parse: (value) => colord(JSON.parse(value)),
}),
oklab: buildColorFormat({
label: t('tools.color-converter.texts.label-oklab'),
format: (v: Colord) => colordx(v.toHex()).toOklabString(),
placeholder: 'e.g. oklab(40.1% 0.1143 0.045)',
parse: value => colord(colordx(value).toHex()),
parse: (value) => colord(colordx(value).toHex()),
}),
oklch: buildColorFormat({
label: t('tools.color-converter.texts.label-oklch'),
format: (v: Colord) => colordx(v.toHex()).toOklchString(),
placeholder: 'e.g. oklch(40.1% 0.123 21.57)',
parse: value => colord(colordx(value).toHex()),
parse: (value) => colord(colordx(value).toHex()),
}),
name: buildColorFormat({
label: t('tools.color-converter.texts.label-name'),
@@ -91,9 +91,7 @@ const grayscale = ref(false);
const invert = ref(false);
let lastColor = colord('#1ea54c');
watch([saturation, brightness, grayscale, invert],
() => updateColorValue(lastColor),
);
watch([saturation, brightness, grayscale, invert], () => updateColorValue(lastColor));
updateColorValue(lastColor);
@@ -119,16 +117,14 @@ function updateColorValue(value: Colord | undefined, omitLabel?: string) {
const saturationFloat = saturation.value / 100.0;
if (saturationFloat > 0) {
correctedValue = correctedValue.saturate(saturationFloat);
}
else if (saturationFloat < 0) {
} else if (saturationFloat < 0) {
correctedValue = correctedValue.desaturate(-saturationFloat);
}
const brightnessFloat = brightness.value / 100.0;
if (brightnessFloat > 0) {
correctedValue = correctedValue.lighten(brightnessFloat);
}
else if (brightnessFloat < 0) {
} else if (brightnessFloat < 0) {
correctedValue = correctedValue.darken(-brightnessFloat);
}
@@ -178,14 +174,20 @@ function updateColorValue(value: Colord | undefined, omitLabel?: string) {
raw-text
clearable
mt-2
@update:value="(v:string) => updateColorValue(parse(v), key)"
@update:value="(v: string) => updateColorValue(parse(v), key)"
/>
<n-form-item v-else-if="type === 'color-picker'" :label="`${label}:`" label-width="100" label-placement="left" :show-feedback="false">
<n-form-item
v-else-if="type === 'color-picker'"
:label="`${label}:`"
label-width="100"
label-placement="left"
:show-feedback="false"
>
<n-color-picker
v-model:value="formats[key].value.value"
placement="bottom-end"
@update:value="(v:string) => updateColorValue(parse(v), key)"
@update:value="(v: string) => updateColorValue(parse(v), key)"
/>
</n-form-item>
</template>
+9 -32
View File
@@ -33,11 +33,11 @@ const harmonyTypes: { type: HarmonyType; label: string }[] = [
];
const colorList = computed(() => {
return colors.value.map(item => colord(item.rgb).toHex());
return colors.value.map((item) => colord(item.rgb).toHex());
});
function handleChangeGradient(harmonyColors: Harmony[]) {
const newColors = harmonyColors.map(color => colord(color.rgb).toHex());
const newColors = harmonyColors.map((color) => colord(color.rgb).toHex());
const [base, secondary] = newColors;
@@ -50,27 +50,15 @@ function handleChangeGradient(harmonyColors: Harmony[]) {
return null;
});
const secondaryRgb = colord(secondary).toRgb();
rootEl.style.setProperty(
'--color-interactive',
`${secondaryRgb.r}, ${secondaryRgb.g}, ${secondaryRgb.b}`,
);
rootEl.style.setProperty('--color-interactive', `${secondaryRgb.r}, ${secondaryRgb.g}, ${secondaryRgb.b}`);
if (newColors.length === 3) {
const lightColor = colord(base).saturate(0.25).toRgb();
const darkColor = colord(base).desaturate(0.25).toRgb();
rootEl.style.setProperty(
'--color4',
`${lightColor.r}, ${lightColor.g}, ${lightColor.b}`,
);
rootEl.style.setProperty(
'--color5',
`${darkColor.r}, ${darkColor.g}, ${darkColor.b}`,
);
rootEl.style.setProperty('--color4', `${lightColor.r}, ${lightColor.g}, ${lightColor.b}`);
rootEl.style.setProperty('--color5', `${darkColor.r}, ${darkColor.g}, ${darkColor.b}`);
}
isColorReadable.value = colord(base).isReadable(
isDarkTheme.value ? '#fff' : '#000',
{ level: 'AAA' },
);
isColorReadable.value = colord(base).isReadable(isDarkTheme.value ? '#fff' : '#000', { level: 'AAA' });
}
function handleChangeColors(harmonyColors: Harmony[]) {
@@ -92,20 +80,13 @@ watch(
<div>
<c-card :title="t('tools.color-wheel.texts.title-pick-a-color')" mb-2>
<n-color-picker v-model:value="inputColor" :show-alpha="false" />
<div
:style="{ backgroundColor: inputColor }"
/>
<div :style="{ backgroundColor: inputColor }" />
</c-card>
<c-card :title="t('tools.color-wheel.texts.title-pick-a-palette-type')" mb-2>
<n-radio-group v-model:value="currentType" name="radiogroup">
<n-space>
<n-radio
v-for="v in harmonyTypes"
:key="v.type"
:value="v.type"
:label="v.label"
/>
<n-radio v-for="v in harmonyTypes" :key="v.type" :value="v.type" :label="v.label" />
</n-space>
</n-radio-group>
</c-card>
@@ -122,11 +103,7 @@ watch(
/>
</div>
</c-card>
<div
v-for="(color, i) in colorList"
:key="i"
mt-1 flex items-center justify-center gap-1
>
<div v-for="(color, i) in colorList" :key="i" mt-1 flex items-center justify-center gap-1>
<div
p-1
:style="{
@@ -23,14 +23,18 @@ async function loadMemo(currentLocale = locale.value) {
memoComponent.value = module.default ?? module;
}
watch(locale, () => {
loadMemo();
}, { immediate: true });
watch(
locale,
() => {
loadMemo();
},
{ immediate: true },
);
</script>
<template>
<div>
<component :is="memoComponent" style="overflow-x: auto;" />
<component :is="memoComponent" style="overflow-x: auto" />
</div>
</template>
@@ -45,7 +49,9 @@ watch(locale, () => {
::v-deep(table) {
border-collapse: collapse;
}
::v-deep(table), ::v-deep(td), ::v-deep(th) {
::v-deep(table),
::v-deep(td),
::v-deep(th) {
border: 1px solid v-bind('themeVars.textColor1');
padding: 5px;
}
+2 -2
View File
@@ -1,4 +1,4 @@
Patterns you reach for again and again, written for the **JavaScript/PCRE** flavour. Drop the surrounding anchors (`^`…`$`) when you want to *find* matches inside a longer text instead of validating a whole string.
Patterns you reach for again and again, written for the **JavaScript/PCRE** flavour. Drop the surrounding anchors (`^`…`$`) when you want to _find_ matches inside a longer text instead of validating a whole string.
> ⚠️ Validation by regex is always an approximation. For emails, phone numbers, URLs and credit cards, a regex is a cheap first filter — the real check is a library, or sending the confirmation.
@@ -134,7 +134,7 @@ https?:\/\/[^\s<>"']+
^P(?!$)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$
```
> ℹ️ These check the *shape*, not the calendar — `2026-02-31` passes. Parse the value if the date has to be real.
> ℹ️ These check the _shape_, not the calendar — `2026-02-31` passes. Parse the value if the date has to be real.
## 🔐 Password Rules
+57 -52
View File
@@ -1,47 +1,46 @@
### 常用正则表达式
#### 1\. 数字
* [整数](https://www.regexpal.com/?fam=104020) – `/^\d+$/`
* [小数](https://www.regexpal.com/?fam=104021) – `/^\d*\.\d+$/`
* [整数 + 小数](https://www.regexpal.com/?fam=104022) – `/^\d*(\.\d+)?$/`
* [负数、正数的整数 + 小数](https://www.regexpal.com/?fam=104023) – `/^-?\d*(\.\d+)?$/`
* [整数 + 小数 + 分数](https://www.regexpal.com/94462) – `/[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/`
- [整数](https://www.regexpal.com/?fam=104020) – `/^\d+$/`
- [小数](https://www.regexpal.com/?fam=104021) – `/^\d*\.\d+$/`
- [整数 + 小数](https://www.regexpal.com/?fam=104022) – `/^\d*(\.\d+)?$/`
- [负数、正数的整数 + 小数](https://www.regexpal.com/?fam=104023) – `/^-?\d*(\.\d+)?$/`
- [整数 + 小数 + 分数](https://www.regexpal.com/94462) – `/[-]?[0-9]+[,.]?[0-9]*([\/][0-9]+[,.]?[0-9]*)*/`
#### 2\. 字母数字字符
* [不含空格的字母数字](https://www.regexpal.com/?fam=104024) – `/^[a-zA-Z0-9]*$/`
* [含空格的字母数字](https://www.regexpal.com/?fam=104025) – `/^[a-zA-Z0-9 ]*$/`
- [不含空格的字母数字](https://www.regexpal.com/?fam=104024) – `/^[a-zA-Z0-9]*$/`
- [含空格的字母数字](https://www.regexpal.com/?fam=104025) – `/^[a-zA-Z0-9 ]*$/`
#### 3\. 邮箱
* [常见邮箱地址](https://www.regexpal.com/?fam=104026) – `/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/`
* [不常见邮箱地址](https://www.regexpal.com/?fam=104027) – `/^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/`
- [常见邮箱地址](https://www.regexpal.com/?fam=104026) – `/^([a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6})*$/`
- [不常见邮箱地址](https://www.regexpal.com/?fam=104027) – `/^([a-z0-9_\.\+-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/`
#### 4\. 密码强度
* [复杂](https://www.regexpal.com/?fam=104028):需包含 1 个小写字母、1 个大写字母、1 个数字、1 个特殊字符,且至少 8 个字符长
- [复杂](https://www.regexpal.com/?fam=104028):需包含 1 个小写字母、1 个大写字母、1 个数字、1 个特殊字符,且至少 8 个字符长
/(?=(.\*\[0-9\]))(?=.\*\[\\!@#$%^&\*()\\\\\[\\\]{}\\-\_+=~\`|:;"'<>,./?\])(?=.\*\[a-z\])(?=(.\*\[A-Z\]))(?=(.\*)).{8,}/
/(?=(.\*\[0-9\]))(?=.\*\[\\!@#$%^&\*()\\\\\[\\\]{}\\-\_+=~\`|:;"'<>,./?\])(?=.\*\[a-z\])(?=(.\*\[A-Z\]))(?=(.\*)).{8,}/
* [中等](https://www.regexpal.com/?fam=104029):需包含 1 个小写字母、1 个大写字母、1 个数字,且至少 8 个字符长
- [中等](https://www.regexpal.com/?fam=104029):需包含 1 个小写字母、1 个大写字母、1 个数字,且至少 8 个字符长
/(?=(.\*\[0-9\]))((?=.\*\[A-Za-z0-9\])(?=.\*\[A-Z\])(?=.\*\[a-z\]))^.{8,}$/
/(?=(.\*\[0-9\]))((?=.\*\[A-Za-z0-9\])(?=.\*\[A-Z\])(?=.\*\[a-z\]))^.{8,}$/
#### 5\. 用户名
* [字母数字字符串](https://www.regexpal.com/?fam=104030),可包含 \_ 和 –,长度为 3 到 16 个字符 – `/^[a-z0-9_-]{3,16}$/`
- [字母数字字符串](https://www.regexpal.com/?fam=104030),可包含 \_ 和 –,长度为 3 到 16 个字符 – `/^[a-z0-9_-]{3,16}$/`
#### 6\. URL
* 包含 [http(s) 协议](https://www.regexpal.com/?fam=104034)
- 包含 [http(s) 协议](https://www.regexpal.com/?fam=104034)
```
/https?:\\/\\/(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#()?&//=\]\*)/
```
* [协议可选](https://www.regexpal.com/?fam=104035)
- [协议可选](https://www.regexpal.com/?fam=104035)
```
/(https?:\\/\\/)?(www\\.)?\[-a-zA-Z0-9@:%.\_\\+~#=\]{2,256}\\.\[a-z\]{2,6}\\b(\[-a-zA-Z0-9@:%\_\\+.~#?&//=\]\*)/
@@ -49,71 +48,76 @@
#### 7\. IP 地址
* [IPv4 地址](https://www.regexpal.com/?fam=104036)
- [IPv4 地址](https://www.regexpal.com/?fam=104036)
```
/^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/
```
* [IPv6 地址](https://www.regexpal.com/?fam=104037)
- [IPv6 地址](https://www.regexpal.com/?fam=104037)
```
/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/
```
* 同时匹配 [IPv4、IPv6 地址](https://www.regexpal.com/?fam=104038)
- 同时匹配 [IPv4、IPv6 地址](https://www.regexpal.com/?fam=104038)
```
/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/
```
#### 8\. 日期
* 日期格式 [YYYY-MM-dd](https://www.regexpal.com/?fam=104039),使用分隔符 `-`
`/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/`
* 日期格式 [dd-MM-YYYY](https://regexr.com/?346hf),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
* 日期格式 [dd-mmm-YYYY](https://regexr.com/39tr1),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
- 日期格式 [YYYY-MM-dd](https://www.regexpal.com/?fam=104039),使用分隔符 `-`
`/([12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]))/`
- 日期格式 [dd-MM-YYYY](https://regexr.com/?346hf),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
- 日期格式 [dd-mmm-YYYY](https://regexr.com/39tr1),使用分隔符 `-` 或 `.` 或 `/`
`/^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec)))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)(?:0?2|(?:Feb))\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/`
#### 9\. 时间
* 时间格式 [HH:MM 12 小时制](https://www.regexpal.com/?fam=104040),前导 0 可选
- 时间格式 [HH:MM 12 小时制](https://www.regexpal.com/?fam=104040),前导 0 可选
`/^(0?[1-9]|1[0-2]):[0-5][0-9]$/`
* 时间格式 HH:MM 12 小时制,前导 0 可选,**[带 AM/PM 标识](https://www.regexpal.com/?fam=104041)**
- 时间格式 HH:MM 12 小时制,前导 0 可选,**[带 AM/PM 标识](https://www.regexpal.com/?fam=104041)**
`/((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))/`
* 时间格式 [HH:MM 24 小时制](https://www.regexpal.com/?fam=104042),带前导 0
- 时间格式 [HH:MM 24 小时制](https://www.regexpal.com/?fam=104042),带前导 0
`/^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/`
* 时间格式 [HH:MM 24 小时制,前导 0 可选](https://www.regexpal.com/?fam=104043)
- 时间格式 [HH:MM 24 小时制,前导 0 可选](https://www.regexpal.com/?fam=104043)
`/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/`
* 时间格式 [HH:MM:SS 24 小时制](https://www.regexpal.com/?fam=104044)
- 时间格式 [HH:MM:SS 24 小时制](https://www.regexpal.com/?fam=104044)
`/(?:[01]\d|2[0123]):(?:[012345]\d):(?:[012345]\d)/`
#### 10\. HTML 标签
* [带属性的元素](https://www.regexpal.com/95941) `/<\/?[\w\s]*>|<.+[\W]>/`
- [带属性的元素](https://www.regexpal.com/95941) `/<\/?[\w\s]*>|<.+[\W]>/`
#### 11\. JavaScript 处理器
* [内联 JS 处理器](https://www.regexpal.com/?fam=104055) `/\bon\w+=\S+(?=.*>)/`
* [带元素的内联 JS 处理器](https://www.regexpal.com/94641) `/(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/`
- [内联 JS 处理器](https://www.regexpal.com/?fam=104055) `/\bon\w+=\S+(?=.*>)/`
- [带元素的内联 JS 处理器](https://www.regexpal.com/94641) `/(?:<[^>]+\s)(on\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/`
#### 12\. Slug
* [Slug](https://www.regexpal.com/?fam=104056) `/^[a-z0-9]+(?:-[a-z0-9]+)*$/`
- [Slug](https://www.regexpal.com/?fam=104056) `/^[a-z0-9]+(?:-[a-z0-9]+)*$/`
#### 13\. 匹配字符串中的重复项
* [搜索重复项](https://www.regexpal.com/?fam=104060) `/(\b\w+\b)(?=.*\b\1\b)/`
- [搜索重复项](https://www.regexpal.com/?fam=104060) `/(\b\w+\b)(?=.*\b\1\b)/`
#### 14\. 电话号码
* [国际电话号码](https://www.regexpal.com/?fam=99127) – 带可选的国家代码/分机号
- [国际电话号码](https://www.regexpal.com/?fam=99127) – 带可选的国家代码/分机号
```
`/* International Phone Numbers */`
/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:``#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/
@@ -123,19 +127,19 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
#### 15\. 文件路径
* [带文件名和扩展名的文件路径](https://www.regexpal.com/?fam=104047)
- [带文件名和扩展名的文件路径](https://www.regexpal.com/?fam=104047)
```
/((\\/|\\\\|\\/\\/|https?:\\\\\\\\|https?:\\/\\/)\[a-z0-9 \_@\\-^!#$%&+={}.\\/\\\\\\\[\\\]\]+)+\\.\[a-z\]+$/
```
* 带可选文件名、扩展名的文件路径
- 带可选文件名、扩展名的文件路径
```
/^(.+)/(\[^/\]+)$/
```
* [带 3 字符扩展名的文件名](https://www.regexpal.com/?fam=104048)
- [带 3 字符扩展名的文件名](https://www.regexpal.com/?fam=104048)
```
/^\[\\w,\\s-\]+\\.\[A-Za-z\]{3}$/
@@ -153,7 +157,7 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
#### 3\. 身份证件
* 社会保障号 – [参考](https://www.codeproject.com/Articles/651609/Validating-Social-Security-Numbers-through-Regular)
- 社会保障号 – [参考](https://www.codeproject.com/Articles/651609/Validating-Social-Security-Numbers-through-Regular)
```
/\* can use either hypen(-) or space( ) character as separator \*/
@@ -161,14 +165,15 @@ _注意:_ **仅**在没有其他选择时才使用正则表达式验证电话
/^((?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}-(?!00)\\d{2}-(?!0{4})\\d{4})|((?!219 09 9999|078 05 1120)(?!666|000|9\\d{2})\\d{3} (?!00)\\d{2} (?!0{4})\\d{4})|((?!219099999|078051120)(?!666|000|9\\d{2})\\d{3}(?!00)\\d{2}(?!0{4})\\d{4})$/
```
* 护照 – `/^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$/`
- 护照 – `/^[A-PR-WY][1-9]\d\s?\d{4}[1-9]$/`
#### 参考文献
* [https://www.codeproject.com/validate-passport-number](https://www.codeproject.com/Questions/1046445/How-to-validate-passport-number-using-javascript)
* [https://gist.github.com/](https://gist.github.com/nerdsrescueme/1237767)
* [https://code.tutsplus.com/regular-expressions](https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149)
* [https://www.regular-expressions.info](https://www.regular-expressions.info/)
* [http://www.regexlib.com/](http://www.regexlib.com/)
* [https://projects.lukehaas.me/regexhub/](https://projects.lukehaas.me/regexhub/)
* [http://wiki.zoolz.com/commonly-used-regular-expressions/](http://wiki.zoolz.com/commonly-used-regular-expressions/)
* [https://www.smashingmagazine.com/advanced-regular-expressions/](https://www.smashingmagazine.com/2009/05/introduction-to-advanced-regular-expressions/)
- [https://www.codeproject.com/validate-passport-number](https://www.codeproject.com/Questions/1046445/How-to-validate-passport-number-using-javascript)
- [https://gist.github.com/](https://gist.github.com/nerdsrescueme/1237767)
- [https://code.tutsplus.com/regular-expressions](https://code.tutsplus.com/tutorials/8-regular-expressions-you-should-know--net-6149)
- [https://www.regular-expressions.info](https://www.regular-expressions.info/)
- [http://www.regexlib.com/](http://www.regexlib.com/)
- [https://projects.lukehaas.me/regexhub/](https://projects.lukehaas.me/regexhub/)
- [http://wiki.zoolz.com/commonly-used-regular-expressions/](http://wiki.zoolz.com/commonly-used-regular-expressions/)
- [https://www.smashingmagazine.com/advanced-regular-expressions/](https://www.smashingmagazine.com/2009/05/introduction-to-advanced-regular-expressions/)
+26 -9
View File
@@ -8,25 +8,42 @@ const { t } = useI18n();
const cookieHeader = useQueryParam({ tool: 'cookies-parser', name: 'cookies', defaultValue: '' });
const parsedCookies = computed(() => {
return (cookieHeader.value || '').replace(/^Cookie:\s*/, '').split('; ').map((cookie) => {
const [name, ...values] = cookie.split('=');
return { name, value: decodeURIComponent(values?.join('=') || '') };
});
return (cookieHeader.value || '')
.replace(/^Cookie:\s*/, '')
.split('; ')
.map((cookie) => {
const [name, ...values] = cookie.split('=');
return { name, value: decodeURIComponent(values?.join('=') || '') };
});
});
</script>
<template>
<n-card :title="t('tools.cookies-parser.texts.title-cookie-parser')">
<n-space vertical>
<n-input v-model:value="cookieHeader" :placeholder="t('tools.cookies-parser.texts.placeholder-enter-cookie-header')" type="text" />
<n-input
v-model:value="cookieHeader"
:placeholder="t('tools.cookies-parser.texts.placeholder-enter-cookie-header')"
type="text"
/>
</n-space>
<n-p>
{{ t('tools.cookies-parser.texts.tag-tip-navigate-to-a-website-to-test-open-f12-console-and-run') }}<n-tag :bordered="false">
<code>{{ t('tools.cookies-parser.texts.tag-window-copy-document-cookie') }}</code>
</n-tag>{{ t('tools.cookies-parser.texts.tag-this-will-copy-the-cookie-string-to-your-clipboard-note-this-will-only-copy-cookies-available-to-javascript-http-only-and-secure-cookies-will-be-omitted') }}
{{ t('tools.cookies-parser.texts.tag-tip-navigate-to-a-website-to-test-open-f12-console-and-run')
}}<n-tag :bordered="false">
<code>{{ t('tools.cookies-parser.texts.tag-window-copy-document-cookie') }}</code> </n-tag
>{{
t(
'tools.cookies-parser.texts.tag-this-will-copy-the-cookie-string-to-your-clipboard-note-this-will-only-copy-cookies-available-to-javascript-http-only-and-secure-cookies-will-be-omitted',
)
}}
</n-p>
<n-table v-if="parsedCookies.length">
<thead><tr><th>{{ t('tools.cookies-parser.texts.tag-name') }}</th><th>{{ t('tools.cookies-parser.texts.tag-value') }}</th></tr></thead>
<thead>
<tr>
<th>{{ t('tools.cookies-parser.texts.tag-name') }}</th>
<th>{{ t('tools.cookies-parser.texts.tag-value') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="cookie in parsedCookies" :key="cookie.name">
<td>
+3 -3
View File
@@ -1,3 +1,3 @@
declare module "vue3-flip-countdown" {
export function Countdown(): any;
}
declare module 'vue3-flip-countdown' {
export function Countdown(): any;
}
@@ -101,7 +101,7 @@ describe('crc-calculator', () => {
it('re-encodes every checksum of "Hello, World!" as the ui does', () => {
const hashes = getCRCs('Hello, World!');
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([
expect(algoNames.map((algo) => formatHexWithEncoding(hashes[algo], 'Hex'))).toEqual([
'69',
'87',
'9c',
@@ -116,7 +116,7 @@ describe('crc-calculator', () => {
'19270120',
'13b53c2f',
]);
expect(algoNames.map(algo => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([
expect(algoNames.map((algo) => formatHexWithEncoding(hashes[algo], 'Base64'))).toEqual([
'aQ==',
'hw==',
'nA==',
+6 -2
View File
@@ -5,7 +5,10 @@ export const tool = defineTool({
name: t('tools.crc-calculator.title'),
path: '/crc-calculator',
description: t('tools.crc-calculator.description'),
keywords: ['crc', 'checksum', 'crc1',
keywords: [
'crc',
'checksum',
'crc1',
'crc8',
'crc8 1-wire',
'crc8 dvb-s2',
@@ -17,7 +20,8 @@ export const tool = defineTool({
'crc24',
'crc32',
'crc32 mpeg-2',
'crcjam'],
'crcjam',
],
component: () => import('./crc-calculator.vue'),
icon: defineAsyncComponent(() => import('@vicons/tabler/es/EyeOff')),
createdAt: new Date('2024-05-11'),
@@ -15,7 +15,7 @@ const parsed = computed(() => {
</script>
<template>
<div style="max-width: 600px;">
<div style="max-width: 600px">
<c-input-text
v-model:value="cardNumber"
:label="t('tools.credit-card-checker.texts.label-credit-card-number')"
@@ -27,13 +27,48 @@ const parsed = computed(() => {
<n-alert v-if="parsed && !parsed.validates" type="error">
{{ t('tools.credit-card-checker.texts.tag-invlid-credit-card-number') }}
</n-alert>
<n-card v-if="parsed && parsed.validates" :title="t('tools.credit-card-checker.texts.title-credit-card-number-info')">
<input-copyable :label="t('tools.credit-card-checker.texts.label-formatted')" label-position="left" label-width="150px" mb-1 :value="parsed.formatted" />
<input-copyable :label="t('tools.credit-card-checker.texts.label-pan-truncated')" label-position="left" label-width="150px" mb-1 :value="parsed.truncate" />
<input-copyable :label="t('tools.credit-card-checker.texts.label-scheme')" label-position="left" label-width="150px" mb-1 :value="parsed.scheme || 'Unknown'" />
<input-copyable :label="t('tools.credit-card-checker.texts.label-major-industry-identifier')" mb-1 :value="parsed.mii" />
<input-copyable :label="t('tools.credit-card-checker.texts.label-issuer-identifier-number')" mb-1 :value="parsed.iin" />
<input-copyable :label="t('tools.credit-card-checker.texts.label-cvv-length')" label-position="left" label-width="150px" mb-1 :value="parsed.cvv" />
<n-card
v-if="parsed && parsed.validates"
:title="t('tools.credit-card-checker.texts.title-credit-card-number-info')"
>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-formatted')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.formatted"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-pan-truncated')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.truncate"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-scheme')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.scheme || 'Unknown'"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-major-industry-identifier')"
mb-1
:value="parsed.mii"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-issuer-identifier-number')"
mb-1
:value="parsed.iin"
/>
<input-copyable
:label="t('tools.credit-card-checker.texts.label-cvv-length')"
label-position="left"
label-width="150px"
mb-1
:value="parsed.cvv"
/>
</n-card>
</div>
</template>
+10 -10
View File
@@ -1,11 +1,11 @@
declare module 'creditcard' {
export function parse(creditCardNumber: string): {
formatted: string
truncate: string
scheme: string
mii: string
iin: string
validates: boolean
cvv: number
}
}
export function parse(creditCardNumber: string): {
formatted: string;
truncate: string;
scheme: string;
mii: string;
iin: string;
validates: boolean;
cvv: number;
};
}
@@ -11,7 +11,7 @@ function looksLikeAwsExpression(cronExpression: string) {
return /(?:^|\s)\?(?:\s|$)/.test(cronExpression);
}
export function getLastExecutionTimes(cronExpression: string, tz?: string | undefined, count: number = 5) {
export function getLastExecutionTimes(cronExpression: string, tz?: string, count: number = 5) {
const cronType = getCronType(cronExpression);
if (cronType === 'standard') {
@@ -46,8 +46,7 @@ function isStandardExpression(cronExpression: string) {
CronExpressionParser.parse(cronExpression);
cronstrue.toString(cronExpression, { throwExceptionOnParseError: true });
return true;
}
catch (_) {
} catch (_) {
return false;
}
}
@@ -57,8 +56,7 @@ function isAwsExpression(cronExpression: string) {
const parsed = new EventCronParser(cronExpression);
parsed.validate();
return true;
}
catch (_) {
} catch (_) {
return false;
}
}
+2 -2
View File
@@ -1,3 +1,3 @@
declare module "get-timezone-offset" {
export default function(timeZoneName: string, date: Date);
declare module 'get-timezone-offset' {
export default function (timeZoneName: string, date: Date);
}
+2 -4
View File
@@ -11,8 +11,7 @@ export function getViewportDimensions(
width: maxWidth,
height: maxWidth / ratio,
};
}
else {
} else {
return {
width: maxHeight * ratio,
height: maxHeight,
@@ -41,8 +40,7 @@ export function getBaseDimensions(
width: vH * iRatio,
height: vH,
};
}
else {
} else {
// Portrait relative to viewport
return {
width: vW,
Loaded 100 of 830 files, more files were not shown because too many files have changed in this diff. Show more