Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b697c419a7 | ||
|
|
c87fb96195 | ||
|
|
d55f51a69b | ||
|
|
fe01a5a28f | ||
|
|
e5f1af9606 | ||
|
|
d5256a290f | ||
|
|
d1d50d19e0 | ||
|
|
32b5583432 | ||
|
|
5fbe801d35 | ||
|
|
3c11797c6d | ||
|
|
10242d5f14 | ||
|
|
0455187a68 |
@@ -111,10 +111,5 @@ jobs:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
- run: pnpm i --frozen-lockfile
|
||||
- run: pnpm --filter misskey-js run build
|
||||
if: ${{ matrix.workspace == 'backend' || matrix.workspace == 'frontend' || matrix.workspace == 'sw' }}
|
||||
- run: pnpm --filter misskey-reversi run build
|
||||
if: ${{ matrix.workspace == 'backend' || matrix.workspace == 'frontend' }}
|
||||
- run: pnpm --filter misskey-bubble-game run build
|
||||
if: ${{ matrix.workspace == 'frontend' }}
|
||||
- run: pnpm --filter "${{ matrix.workspace }}^..." run build
|
||||
- run: pnpm --filter ${{ matrix.workspace }} run typecheck
|
||||
|
||||
@@ -3,10 +3,12 @@ name: Lint
|
||||
on:
|
||||
push:
|
||||
paths:
|
||||
- packages/i18n/**
|
||||
- locales/**
|
||||
- .github/workflows/locale.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- packages/i18n/**
|
||||
- locales/**
|
||||
- .github/workflows/locale.yml
|
||||
jobs:
|
||||
@@ -14,15 +16,18 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
continue-on-error: true
|
||||
steps:
|
||||
- uses: actions/checkout@v4.3.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: true
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4.2.0
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version-file: '.node-version'
|
||||
cache: 'pnpm'
|
||||
- run: pnpm i --frozen-lockfile
|
||||
- run: cd locales && node verify.js
|
||||
- uses: actions/checkout@v4.3.0
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: true
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4.2.0
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version-file: ".node-version"
|
||||
cache: "pnpm"
|
||||
- run: pnpm i --frozen-lockfile
|
||||
- run: pnpm --filter i18n build
|
||||
- name: Verify Locales
|
||||
working-directory: ./packages/i18n
|
||||
run: pnpm run verify
|
||||
|
||||
@@ -24,6 +24,7 @@ COPY --link ["packages/frontend-shared/package.json", "./packages/frontend-share
|
||||
COPY --link ["packages/frontend/package.json", "./packages/frontend/"]
|
||||
COPY --link ["packages/frontend-embed/package.json", "./packages/frontend-embed/"]
|
||||
COPY --link ["packages/frontend-builder/package.json", "./packages/frontend-builder/"]
|
||||
COPY --link ["packages/i18n/package.json", "./packages/i18n/"]
|
||||
COPY --link ["packages/icons-subsetter/package.json", "./packages/icons-subsetter/"]
|
||||
COPY --link ["packages/sw/package.json", "./packages/sw/"]
|
||||
COPY --link ["packages/misskey-js/package.json", "./packages/misskey-js/"]
|
||||
@@ -101,6 +102,7 @@ COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-js/
|
||||
COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-reversi/built ./packages/misskey-reversi/built
|
||||
COPY --chown=misskey:misskey --from=native-builder /misskey/packages/misskey-bubble-game/built ./packages/misskey-bubble-game/built
|
||||
COPY --chown=misskey:misskey --from=native-builder /misskey/packages/backend/built ./packages/backend/built
|
||||
COPY --chown=misskey:misskey --from=native-builder /misskey/packages/i18n/built ./packages/i18n/built
|
||||
COPY --chown=misskey:misskey --from=native-builder /misskey/fluent-emojis /misskey/fluent-emojis
|
||||
COPY --chown=misskey:misskey . ./
|
||||
|
||||
|
||||
+17
-17
@@ -128,7 +128,7 @@ pinnedNote: "Nota fijada"
|
||||
pinned: "Fijar al perfil"
|
||||
you: "Tú"
|
||||
clickToShow: "Haz clic para verlo"
|
||||
sensitive: "Marcado como sensible"
|
||||
sensitive: "Marcado como sensible (NSFW)"
|
||||
add: "Agregar"
|
||||
reaction: "Reacción"
|
||||
reactions: "Reacciones"
|
||||
@@ -143,7 +143,7 @@ rememberNoteVisibility: "Recordar visibilidad"
|
||||
attachCancel: "Quitar adjunto"
|
||||
deleteFile: "Eliminar archivo"
|
||||
markAsSensitive: "Marcar como sensible"
|
||||
unmarkAsSensitive: "Desmarcar como sensible"
|
||||
unmarkAsSensitive: "No marcar como sensible"
|
||||
enterFileName: "Introduce el nombre del archivo"
|
||||
mute: "Silenciar"
|
||||
unmute: "Dejar de silenciar"
|
||||
@@ -353,7 +353,7 @@ emptyFolder: "La carpeta está vacía"
|
||||
dropHereToUpload: "Arrastra los archivos aquí para subirlos."
|
||||
unableToDelete: "No se puede borrar"
|
||||
inputNewFileName: "Ingrese un nuevo nombre de archivo"
|
||||
inputNewDescription: "Ingrese nueva descripción"
|
||||
inputNewDescription: "Introducir un nuevo texto alternativo"
|
||||
inputNewFolderName: "Ingrese un nuevo nombre de la carpeta"
|
||||
circularReferenceFolder: "La carpeta de destino es una sub-carpeta de la carpeta que quieres mover."
|
||||
hasChildFilesOrFolders: "No se puede borrar esta carpeta. No está vacía."
|
||||
@@ -706,7 +706,7 @@ userSaysSomethingAbout: "{name} dijo algo sobre {word}"
|
||||
makeActive: "Activar"
|
||||
display: "Apariencia"
|
||||
copy: "Copiar"
|
||||
copiedToClipboard: "Texto copiado al portapapeles"
|
||||
copiedToClipboard: "Copiado al portapapeles"
|
||||
metrics: "Métricas"
|
||||
overview: "Resumen"
|
||||
logs: "Registros"
|
||||
@@ -715,7 +715,7 @@ database: "Base de datos"
|
||||
channel: "Canal"
|
||||
create: "Crear"
|
||||
notificationSetting: "Ajustes de Notificaciones"
|
||||
notificationSettingDesc: "Por favor elija el tipo de notificación a mostrar"
|
||||
notificationSettingDesc: "Por favor elige el tipo de notificación a mostrar"
|
||||
useGlobalSetting: "Usar ajustes globales"
|
||||
useGlobalSettingDesc: "Al activarse, se usará la configuración de notificaciones de la cuenta, al desactivarse se pueden hacer configuraciones particulares."
|
||||
other: "Otro"
|
||||
@@ -747,7 +747,7 @@ system: "Sistema"
|
||||
switchUi: "Cambiar interfaz de usuario"
|
||||
desktop: "Escritorio"
|
||||
clip: "Clip"
|
||||
createNew: "Crear"
|
||||
createNew: "Crear Nuevo"
|
||||
optional: "Opcional"
|
||||
createNewClip: "Crear clip nuevo"
|
||||
unclip: "Quitar clip"
|
||||
@@ -1203,8 +1203,8 @@ iHaveReadXCarefullyAndAgree: "He leído el texto {x} y estoy de acuerdo"
|
||||
dialog: "Diálogo"
|
||||
icon: "Avatar"
|
||||
forYou: "Para ti"
|
||||
currentAnnouncements: "Anuncios actuales"
|
||||
pastAnnouncements: "Anuncios anteriores"
|
||||
currentAnnouncements: "Avisos actuales"
|
||||
pastAnnouncements: "Avisos anteriores"
|
||||
youHaveUnreadAnnouncements: "Hay anuncios sin leer"
|
||||
useSecurityKey: "Por favor, sigue las instrucciones de tu dispositivo o navegador para usar tu clave de seguridad o tu clave de paso."
|
||||
replies: "Responder"
|
||||
@@ -1412,8 +1412,8 @@ _imageEditing:
|
||||
filename: "Nombre de archivo"
|
||||
filename_without_ext: "Nombre del archivo sin la extensión"
|
||||
year: "Año de rodaje"
|
||||
month: "Mes de rodaje"
|
||||
day: "Día de rodaje"
|
||||
month: "Mes de la fotografía"
|
||||
day: "Día de la fotografía"
|
||||
hour: "Hora"
|
||||
minute: "Minuto"
|
||||
second: "Segundo"
|
||||
@@ -1427,9 +1427,9 @@ _imageEditing:
|
||||
gps_lat: "Latitud"
|
||||
gps_long: "Longitud"
|
||||
_imageFrameEditor:
|
||||
title: "Edición de Fotograma"
|
||||
title: "Edición de Fotos"
|
||||
tip: "Decora tus imágenes con marcos y etiquetas que contengan metadatos."
|
||||
header: "Cabezal"
|
||||
header: "Título"
|
||||
footer: "Pie de página"
|
||||
borderThickness: "Ancho del borde"
|
||||
labelThickness: "Ancho de la etiqueta"
|
||||
@@ -1456,8 +1456,8 @@ _compression:
|
||||
medium: "Tamaño mediano"
|
||||
small: "Tamaño pequeño"
|
||||
_order:
|
||||
newest: "Los más recientes primero"
|
||||
oldest: "Los más antiguos primero"
|
||||
newest: "Más reciente primero"
|
||||
oldest: "Más antiguos primero"
|
||||
_chat:
|
||||
messages: "Mensajes"
|
||||
noMessagesYet: "Aún no hay mensajes"
|
||||
@@ -1685,7 +1685,7 @@ _initialTutorial:
|
||||
followers: "Visible solo para seguidores. Sólo tus seguidores podrán ver la nota, y no podrá ser renotada por otras personas."
|
||||
direct: "Visible sólo para usuarios específicos, y el destinatario será notificado. Puede usarse como alternativa a la mensajería directa."
|
||||
doNotSendConfidencialOnDirect1: "¡Ten cuidado cuando vayas a enviar información sensible!"
|
||||
doNotSendConfidencialOnDirect2: "Los administradores del servidor pueden leer lo que escribes. Ten cuidado cuando envíes información sensible en notas directas en servidores no confiables."
|
||||
doNotSendConfidencialOnDirect2: "Los administradores del servidor, también llamado instancia, pueden leer lo que escribes. Ten cuidado cuando envíes información sensible en notas directas en servidores o instancias no confiables."
|
||||
localOnly: "Publicando con esta opción seleccionada, la nota no se federará hacia otros servidores. Los usuarios de otros servidores no podrán ver estas notas directamente, sin importar los ajustes seleccionados más arriba."
|
||||
_cw:
|
||||
title: "Alerta de contenido (CW)"
|
||||
@@ -2299,7 +2299,7 @@ _theme:
|
||||
indicator: "Indicador"
|
||||
panel: "Panel"
|
||||
shadow: "Sombra"
|
||||
header: "Cabezal"
|
||||
header: "Título"
|
||||
navBg: "Fondo de la barra lateral"
|
||||
navFg: "Texto de la barra lateral"
|
||||
navActive: "Texto de la barra lateral (activo)"
|
||||
@@ -2771,7 +2771,7 @@ _notification:
|
||||
follow: "Siguiendo"
|
||||
mention: "Menciones"
|
||||
reply: "Respuestas"
|
||||
renote: "Renotar"
|
||||
renote: "Renotas"
|
||||
quote: "Citar"
|
||||
reaction: "Reacción"
|
||||
pollEnded: "La encuesta terminó"
|
||||
|
||||
@@ -1,232 +0,0 @@
|
||||
import * as fs from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname } from 'node:path';
|
||||
import * as yaml from 'js-yaml';
|
||||
import ts from 'typescript';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const parameterRegExp = /\{(\w+)\}/g;
|
||||
|
||||
function createMemberType(item) {
|
||||
if (typeof item !== 'string') {
|
||||
return ts.factory.createTypeLiteralNode(createMembers(item));
|
||||
}
|
||||
const parameters = Array.from(
|
||||
item.matchAll(parameterRegExp),
|
||||
([, parameter]) => parameter,
|
||||
);
|
||||
return parameters.length
|
||||
? ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('ParameterizedString'),
|
||||
[
|
||||
ts.factory.createUnionTypeNode(
|
||||
parameters.map((parameter) =>
|
||||
ts.factory.createStringLiteral(parameter),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
|
||||
}
|
||||
|
||||
function createMembers(record) {
|
||||
return Object.entries(record).map(([k, v]) => {
|
||||
const node = ts.factory.createPropertySignature(
|
||||
undefined,
|
||||
ts.factory.createStringLiteral(k),
|
||||
undefined,
|
||||
createMemberType(v),
|
||||
);
|
||||
if (typeof v === 'string') {
|
||||
ts.addSyntheticLeadingComment(
|
||||
node,
|
||||
ts.SyntaxKind.MultiLineCommentTrivia,
|
||||
`*
|
||||
* ${v.replace(/\n/g, '\n * ')}
|
||||
`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
|
||||
export default function generateDTS() {
|
||||
const locale = yaml.load(fs.readFileSync(`${__dirname}/ja-JP.yml`, 'utf-8'));
|
||||
const members = createMembers(locale);
|
||||
const elements = [
|
||||
ts.factory.createVariableStatement(
|
||||
[ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)],
|
||||
ts.factory.createVariableDeclarationList(
|
||||
[
|
||||
ts.factory.createVariableDeclaration(
|
||||
ts.factory.createIdentifier('kParameters'),
|
||||
undefined,
|
||||
ts.factory.createTypeOperatorNode(
|
||||
ts.SyntaxKind.UniqueKeyword,
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.SymbolKeyword),
|
||||
),
|
||||
undefined,
|
||||
),
|
||||
],
|
||||
ts.NodeFlags.Const,
|
||||
),
|
||||
),
|
||||
ts.factory.createTypeAliasDeclaration(
|
||||
[ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
|
||||
ts.factory.createIdentifier('ParameterizedString'),
|
||||
[
|
||||
ts.factory.createTypeParameterDeclaration(
|
||||
undefined,
|
||||
ts.factory.createIdentifier('T'),
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
||||
),
|
||||
],
|
||||
ts.factory.createIntersectionTypeNode([
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
||||
ts.factory.createTypeLiteralNode([
|
||||
ts.factory.createPropertySignature(
|
||||
undefined,
|
||||
ts.factory.createComputedPropertyName(
|
||||
ts.factory.createIdentifier('kParameters'),
|
||||
),
|
||||
undefined,
|
||||
ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('T'),
|
||||
undefined,
|
||||
),
|
||||
),
|
||||
])
|
||||
]),
|
||||
),
|
||||
ts.factory.createInterfaceDeclaration(
|
||||
[ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
|
||||
ts.factory.createIdentifier('ILocale'),
|
||||
undefined,
|
||||
undefined,
|
||||
[
|
||||
ts.factory.createIndexSignature(
|
||||
undefined,
|
||||
[
|
||||
ts.factory.createParameterDeclaration(
|
||||
undefined,
|
||||
undefined,
|
||||
ts.factory.createIdentifier('_'),
|
||||
undefined,
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
||||
undefined,
|
||||
),
|
||||
],
|
||||
ts.factory.createUnionTypeNode([
|
||||
ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword),
|
||||
ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('ParameterizedString'),
|
||||
),
|
||||
ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('ILocale'),
|
||||
undefined,
|
||||
),
|
||||
]),
|
||||
),
|
||||
],
|
||||
),
|
||||
ts.factory.createInterfaceDeclaration(
|
||||
[ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
|
||||
ts.factory.createIdentifier('Locale'),
|
||||
undefined,
|
||||
[
|
||||
ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [
|
||||
ts.factory.createExpressionWithTypeArguments(
|
||||
ts.factory.createIdentifier('ILocale'),
|
||||
undefined,
|
||||
),
|
||||
]),
|
||||
],
|
||||
members,
|
||||
),
|
||||
ts.factory.createVariableStatement(
|
||||
[ts.factory.createToken(ts.SyntaxKind.DeclareKeyword)],
|
||||
ts.factory.createVariableDeclarationList(
|
||||
[
|
||||
ts.factory.createVariableDeclaration(
|
||||
ts.factory.createIdentifier('locales'),
|
||||
undefined,
|
||||
ts.factory.createTypeLiteralNode([
|
||||
ts.factory.createIndexSignature(
|
||||
undefined,
|
||||
[
|
||||
ts.factory.createParameterDeclaration(
|
||||
undefined,
|
||||
undefined,
|
||||
ts.factory.createIdentifier('lang'),
|
||||
undefined,
|
||||
ts.factory.createKeywordTypeNode(
|
||||
ts.SyntaxKind.StringKeyword,
|
||||
),
|
||||
undefined,
|
||||
),
|
||||
],
|
||||
ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('Locale'),
|
||||
undefined,
|
||||
),
|
||||
),
|
||||
]),
|
||||
undefined,
|
||||
),
|
||||
],
|
||||
ts.NodeFlags.Const,
|
||||
),
|
||||
),
|
||||
ts.factory.createFunctionDeclaration(
|
||||
[ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)],
|
||||
undefined,
|
||||
ts.factory.createIdentifier('build'),
|
||||
undefined,
|
||||
[],
|
||||
ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('Locale'),
|
||||
undefined,
|
||||
),
|
||||
undefined,
|
||||
),
|
||||
ts.factory.createExportDefault(ts.factory.createIdentifier('locales')),
|
||||
];
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.MultiLineCommentTrivia,
|
||||
' eslint-disable ',
|
||||
true,
|
||||
);
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.SingleLineCommentTrivia,
|
||||
' This file is generated by locales/generateDTS.js',
|
||||
true,
|
||||
);
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.SingleLineCommentTrivia,
|
||||
' Do not edit this file directly.',
|
||||
true,
|
||||
);
|
||||
const printed = ts
|
||||
.createPrinter({
|
||||
newLine: ts.NewLineKind.LineFeed,
|
||||
})
|
||||
.printList(
|
||||
ts.ListFormat.MultiLine,
|
||||
ts.factory.createNodeArray(elements),
|
||||
ts.createSourceFile(
|
||||
'index.d.ts',
|
||||
'',
|
||||
ts.ScriptTarget.ESNext,
|
||||
true,
|
||||
ts.ScriptKind.TS,
|
||||
),
|
||||
);
|
||||
|
||||
fs.writeFileSync(`${__dirname}/index.d.ts`, printed, 'utf-8');
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
/**
|
||||
* Languages Loader
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import * as yaml from 'js-yaml';
|
||||
|
||||
const merge = (...args) => args.reduce((a, c) => ({
|
||||
...a,
|
||||
...c,
|
||||
...Object.entries(a)
|
||||
.filter(([k]) => c && typeof c[k] === 'object')
|
||||
.reduce((a, [k, v]) => (a[k] = merge(v, c[k]), a), {})
|
||||
}), {});
|
||||
|
||||
const languages = [
|
||||
'ar-SA',
|
||||
'ca-ES',
|
||||
'cs-CZ',
|
||||
'da-DK',
|
||||
'de-DE',
|
||||
'en-US',
|
||||
'es-ES',
|
||||
'fr-FR',
|
||||
'id-ID',
|
||||
'it-IT',
|
||||
'ja-JP',
|
||||
'ja-KS',
|
||||
'kab-KAB',
|
||||
'kn-IN',
|
||||
'ko-KR',
|
||||
'nl-NL',
|
||||
'no-NO',
|
||||
'pl-PL',
|
||||
'pt-PT',
|
||||
'ru-RU',
|
||||
'sk-SK',
|
||||
'th-TH',
|
||||
'tr-TR',
|
||||
'ug-CN',
|
||||
'uk-UA',
|
||||
'vi-VN',
|
||||
'zh-CN',
|
||||
'zh-TW',
|
||||
];
|
||||
|
||||
const primaries = {
|
||||
'en': 'US',
|
||||
'ja': 'JP',
|
||||
'zh': 'CN',
|
||||
};
|
||||
|
||||
// 何故か文字列にバックスペース文字が混入することがあり、YAMLが壊れるので取り除く
|
||||
const clean = (text) => text.replace(new RegExp(String.fromCodePoint(0x08), 'g'), '');
|
||||
|
||||
export function build() {
|
||||
// vitestの挙動を調整するため、一度ローカル変数化する必要がある
|
||||
// https://github.com/vitest-dev/vitest/issues/3988#issuecomment-1686599577
|
||||
// https://github.com/misskey-dev/misskey/pull/14057#issuecomment-2192833785
|
||||
const metaUrl = import.meta.url;
|
||||
const locales = languages.reduce((a, c) => (a[c] = yaml.load(clean(fs.readFileSync(new URL(`${c}.yml`, metaUrl), 'utf-8'))) || {}, a), {});
|
||||
|
||||
// 空文字列が入ることがあり、フォールバックが動作しなくなるのでプロパティごと消す
|
||||
const removeEmpty = (obj) => {
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
if (v === '') {
|
||||
delete obj[k];
|
||||
} else if (typeof v === 'object') {
|
||||
removeEmpty(v);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
removeEmpty(locales);
|
||||
|
||||
return Object.entries(locales)
|
||||
.reduce((a, [k, v]) => (a[k] = (() => {
|
||||
const [lang] = k.split('-');
|
||||
switch (k) {
|
||||
case 'ja-JP': return v;
|
||||
case 'ja-KS':
|
||||
case 'en-US': return merge(locales['ja-JP'], v);
|
||||
default: return merge(
|
||||
locales['ja-JP'],
|
||||
locales['en-US'],
|
||||
locales[`${lang}-${primaries[lang]}`] ?? {},
|
||||
v
|
||||
);
|
||||
}
|
||||
})(), a), {});
|
||||
}
|
||||
|
||||
export default build();
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"type": "module"
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import locales from './index.js';
|
||||
|
||||
let valid = true;
|
||||
|
||||
function writeError(type, lang, tree, data) {
|
||||
process.stderr.write(JSON.stringify({ type, lang, tree, data }));
|
||||
process.stderr.write('\n');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
function verify(expected, actual, lang, trace) {
|
||||
for (let key in expected) {
|
||||
if (!Object.prototype.hasOwnProperty.call(actual, key)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof expected[key] === 'object') {
|
||||
if (typeof actual[key] !== 'object') {
|
||||
writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'object', actual: typeof actual[key] });
|
||||
continue;
|
||||
}
|
||||
verify(expected[key], actual[key], lang, trace ? `${trace}.${key}` : key);
|
||||
} else if (typeof expected[key] === 'string') {
|
||||
switch (typeof actual[key]) {
|
||||
case 'object':
|
||||
writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'string', actual: 'object' });
|
||||
break;
|
||||
case 'undefined':
|
||||
continue;
|
||||
case 'string':
|
||||
const expectedParameters = new Set(expected[key].match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1)));
|
||||
const actualParameters = new Set(actual[key].match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1)));
|
||||
for (let parameter of expectedParameters) {
|
||||
if (!actualParameters.has(parameter)) {
|
||||
writeError('missing_parameter', lang, trace ? `${trace}.${key}` : key, { parameter });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { ['ja-JP']: original, ...verifiees } = locales;
|
||||
|
||||
for (let lang in verifiees) {
|
||||
if (!Object.prototype.hasOwnProperty.call(locales, lang)) {
|
||||
continue;
|
||||
}
|
||||
verify(original, verifiees[lang], lang);
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
process.exit(1);
|
||||
}
|
||||
+2
-2
@@ -877,7 +877,7 @@ noInquiryUrlWarning: "尚未设置联络地址。"
|
||||
noBotProtectionWarning: "尚未设置 Bot 防御。"
|
||||
configure: "设置"
|
||||
postToGallery: "创建新图集"
|
||||
postToHashtag: "投稿到这个标签"
|
||||
postToHashtag: "发布至该话题"
|
||||
gallery: "图集"
|
||||
recentPosts: "最新发布"
|
||||
popularPosts: "热门投稿"
|
||||
@@ -3146,7 +3146,7 @@ _selfXssPrevention:
|
||||
description3: "详情请看这里。{link}"
|
||||
_followRequest:
|
||||
recieved: "收到的请求"
|
||||
sent: "已发送的请求"
|
||||
sent: "发送的请求"
|
||||
_remoteLookupErrors:
|
||||
_federationNotAllowed:
|
||||
title: "无法与此服务器通信"
|
||||
|
||||
+12
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "misskey",
|
||||
"version": "2025.11.2-alpha.0",
|
||||
"version": "2025.11.2-alpha.1",
|
||||
"codename": "nasubi",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -8,21 +8,24 @@
|
||||
},
|
||||
"packageManager": "pnpm@10.22.0",
|
||||
"workspaces": [
|
||||
"packages/frontend-shared",
|
||||
"packages/frontend",
|
||||
"packages/frontend-embed",
|
||||
"packages/icons-subsetter",
|
||||
"packages/backend",
|
||||
"packages/sw",
|
||||
"packages/misskey-js",
|
||||
"packages/i18n",
|
||||
"packages/misskey-reversi",
|
||||
"packages/misskey-bubble-game"
|
||||
"packages/misskey-bubble-game",
|
||||
"packages/icons-subsetter",
|
||||
"packages/frontend-shared",
|
||||
"packages/frontend-builder",
|
||||
"packages/sw",
|
||||
"packages/backend",
|
||||
"packages/frontend",
|
||||
"packages/frontend-embed"
|
||||
],
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build-pre": "node ./scripts/build-pre.js",
|
||||
"build-assets": "node ./scripts/build-assets.mjs",
|
||||
"build": "pnpm build-pre && pnpm -r build && pnpm build-assets",
|
||||
"minify-node-modules": "node ./scripts/minify-node-modules.mjs",
|
||||
"build-storybook": "pnpm --filter frontend build-storybook",
|
||||
"build-misskey-js-with-types": "pnpm build-pre && pnpm --filter backend... --filter=!misskey-js build && pnpm --filter backend generate-api-json --no-build && ncp packages/backend/built/api.json packages/misskey-js/generator/api.json && pnpm --filter misskey-js update-autogen-code && pnpm --filter misskey-js build && pnpm --filter misskey-js api",
|
||||
"start": "pnpm check:connect && cd packages/backend && node ./built/boot/entry.js",
|
||||
@@ -68,6 +71,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "9.39.1",
|
||||
"i18n": "workspace:*",
|
||||
"@misskey-dev/eslint-plugin": "2.2.0",
|
||||
"@types/js-yaml": "4.0.9",
|
||||
"@types/node": "24.10.1",
|
||||
|
||||
@@ -10,8 +10,6 @@ import * as os from 'node:os';
|
||||
import cluster from 'node:cluster';
|
||||
import chalk from 'chalk';
|
||||
import chalkTemplate from 'chalk-template';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { nodeProfilingIntegration } from '@sentry/profiling-node';
|
||||
import Logger from '@/logger.js';
|
||||
import { loadConfig } from '@/config.js';
|
||||
import type { Config } from '@/config.js';
|
||||
@@ -74,6 +72,9 @@ export async function masterMain() {
|
||||
bootLogger.succ('Misskey initialized');
|
||||
|
||||
if (config.sentryForBackend) {
|
||||
const Sentry = await import('@sentry/node');
|
||||
const { nodeProfilingIntegration } = await import('@sentry/profiling-node');
|
||||
|
||||
Sentry.init({
|
||||
integrations: [
|
||||
...(config.sentryForBackend.enableNodeProfiling ? [nodeProfilingIntegration()] : []),
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
*/
|
||||
|
||||
import cluster from 'node:cluster';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { nodeProfilingIntegration } from '@sentry/profiling-node';
|
||||
import { envOption } from '@/env.js';
|
||||
import { loadConfig } from '@/config.js';
|
||||
import { jobQueue, server } from './common.js';
|
||||
@@ -17,6 +15,9 @@ export async function workerMain() {
|
||||
const config = loadConfig();
|
||||
|
||||
if (config.sentryForBackend) {
|
||||
const Sentry = await import('@sentry/node');
|
||||
const { nodeProfilingIntegration } = await import('@sentry/profiling-node');
|
||||
|
||||
Sentry.init({
|
||||
integrations: [
|
||||
...(config.sentryForBackend.enableNodeProfiling ? [nodeProfilingIntegration()] : []),
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as Redis from 'ioredis';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { acquireApObjectLock, acquireChartInsertLock } from '@/misc/distributed-lock.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
|
||||
@Injectable()
|
||||
export class AppLockService {
|
||||
constructor(
|
||||
@Inject(DI.redis)
|
||||
private redisClient: Redis.Redis,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get AP Object lock
|
||||
* @param uri AP object ID
|
||||
* @returns Unlock function
|
||||
*/
|
||||
@bindThis
|
||||
public getApLock(uri: string): Promise<() => Promise<void>> {
|
||||
return acquireApObjectLock(this.redisClient, uri);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get chart insert lock
|
||||
* @param lockKey Lock key
|
||||
* @returns Unlock function
|
||||
*/
|
||||
@bindThis
|
||||
public getChartInsertLock(lockKey: string): Promise<() => Promise<void>> {
|
||||
return acquireChartInsertLock(this.redisClient, lockKey);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import { ChannelMutingService } from '@/core/ChannelMutingService.js';
|
||||
import { AccountMoveService } from './AccountMoveService.js';
|
||||
import { AccountUpdateService } from './AccountUpdateService.js';
|
||||
import { AiService } from './AiService.js';
|
||||
import { AppLockService } from './AppLockService.js';
|
||||
import { AnnouncementService } from './AnnouncementService.js';
|
||||
import { AntennaService } from './AntennaService.js';
|
||||
import { AchievementService } from './AchievementService.js';
|
||||
@@ -164,7 +163,6 @@ const $AbuseReportNotificationService: Provider = { provide: 'AbuseReportNotific
|
||||
const $AccountMoveService: Provider = { provide: 'AccountMoveService', useExisting: AccountMoveService };
|
||||
const $AccountUpdateService: Provider = { provide: 'AccountUpdateService', useExisting: AccountUpdateService };
|
||||
const $AiService: Provider = { provide: 'AiService', useExisting: AiService };
|
||||
const $AppLockService: Provider = { provide: 'AppLockService', useExisting: AppLockService };
|
||||
const $AnnouncementService: Provider = { provide: 'AnnouncementService', useExisting: AnnouncementService };
|
||||
const $AntennaService: Provider = { provide: 'AntennaService', useExisting: AntennaService };
|
||||
const $AchievementService: Provider = { provide: 'AchievementService', useExisting: AchievementService };
|
||||
@@ -318,7 +316,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
|
||||
AccountMoveService,
|
||||
AccountUpdateService,
|
||||
AiService,
|
||||
AppLockService,
|
||||
AnnouncementService,
|
||||
AntennaService,
|
||||
AchievementService,
|
||||
@@ -468,7 +465,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
|
||||
$AccountMoveService,
|
||||
$AccountUpdateService,
|
||||
$AiService,
|
||||
$AppLockService,
|
||||
$AnnouncementService,
|
||||
$AntennaService,
|
||||
$AchievementService,
|
||||
@@ -619,7 +615,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
|
||||
AccountMoveService,
|
||||
AccountUpdateService,
|
||||
AiService,
|
||||
AppLockService,
|
||||
AnnouncementService,
|
||||
AntennaService,
|
||||
AchievementService,
|
||||
@@ -768,7 +763,6 @@ const $ApQuestionService: Provider = { provide: 'ApQuestionService', useExisting
|
||||
$AccountMoveService,
|
||||
$AccountUpdateService,
|
||||
$AiService,
|
||||
$AppLockService,
|
||||
$AnnouncementService,
|
||||
$AntennaService,
|
||||
$AchievementService,
|
||||
|
||||
@@ -202,7 +202,7 @@ export class NotificationService implements OnApplicationShutdown {
|
||||
}
|
||||
|
||||
// TODO
|
||||
//const locales = await import('../../../../locales/index.js');
|
||||
//const locales = await import('i18n');
|
||||
|
||||
// TODO: locale ファイルをクライアント用とサーバー用で分けたい
|
||||
|
||||
@@ -271,7 +271,7 @@ export class NotificationService implements OnApplicationShutdown {
|
||||
let untilTime = untilId ? this.toXListId(untilId) : null;
|
||||
|
||||
let notifications: MiNotification[];
|
||||
for (;;) {
|
||||
for (; ;) {
|
||||
let notificationsRes: [id: string, fields: string[]][];
|
||||
|
||||
// sinceidのみの場合は古い順、そうでない場合は新しい順。 QueryService.makePaginationQueryも参照
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import { In } from 'typeorm';
|
||||
import * as Redis from 'ioredis';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type { Config } from '@/config.js';
|
||||
import { UserFollowingService } from '@/core/UserFollowingService.js';
|
||||
@@ -14,6 +15,7 @@ import { NotePiningService } from '@/core/NotePiningService.js';
|
||||
import { UserBlockingService } from '@/core/UserBlockingService.js';
|
||||
import { NoteDeleteService } from '@/core/NoteDeleteService.js';
|
||||
import { NoteCreateService } from '@/core/NoteCreateService.js';
|
||||
import { acquireApObjectLock } from '@/misc/distributed-lock.js';
|
||||
import { concat, toArray, toSingle, unique } from '@/misc/prelude/array.js';
|
||||
import type Logger from '@/logger.js';
|
||||
import { IdService } from '@/core/IdService.js';
|
||||
@@ -28,7 +30,6 @@ import type { MiRemoteUser } from '@/models/User.js';
|
||||
import { GlobalEventService } from '@/core/GlobalEventService.js';
|
||||
import { AbuseReportService } from '@/core/AbuseReportService.js';
|
||||
import { IdentifiableError } from '@/misc/identifiable-error.js';
|
||||
import { AppLockService } from '@/core/AppLockService.js';
|
||||
import { getApHrefNullable, getApId, getApIds, getApType, isAccept, isActor, isAdd, isAnnounce, isBlock, isCollection, isCollectionOrOrderedCollection, isCreate, isDelete, isFlag, isFollow, isLike, isMove, isPost, isReject, isRemove, isTombstone, isUndo, isUpdate, validActor, validPost } from './type.js';
|
||||
import { ApNoteService } from './models/ApNoteService.js';
|
||||
import { ApLoggerService } from './ApLoggerService.js';
|
||||
@@ -48,6 +49,9 @@ export class ApInboxService {
|
||||
@Inject(DI.config)
|
||||
private config: Config,
|
||||
|
||||
@Inject(DI.redis)
|
||||
private redisClient: Redis.Redis,
|
||||
|
||||
@Inject(DI.usersRepository)
|
||||
private usersRepository: UsersRepository,
|
||||
|
||||
@@ -81,7 +85,6 @@ export class ApInboxService {
|
||||
private apQuestionService: ApQuestionService,
|
||||
private queueService: QueueService,
|
||||
private globalEventService: GlobalEventService,
|
||||
private appLockService: AppLockService,
|
||||
) {
|
||||
this.logger = this.apLoggerService.logger;
|
||||
}
|
||||
@@ -308,7 +311,7 @@ export class ApInboxService {
|
||||
// アナウンス先が許可されているかチェック
|
||||
if (!this.utilityService.isFederationAllowedUri(uri)) return;
|
||||
|
||||
const unlock = await this.appLockService.getApLock(uri);
|
||||
const unlock = await acquireApObjectLock(this.redisClient, uri);
|
||||
|
||||
try {
|
||||
// 既に同じURIを持つものが登録されていないかチェック
|
||||
@@ -435,7 +438,7 @@ export class ApInboxService {
|
||||
}
|
||||
}
|
||||
|
||||
const unlock = await this.appLockService.getApLock(uri);
|
||||
const unlock = await acquireApObjectLock(this.redisClient, uri);
|
||||
|
||||
try {
|
||||
const exist = await this.apNoteService.fetchNote(note);
|
||||
@@ -519,7 +522,7 @@ export class ApInboxService {
|
||||
private async deleteNote(actor: MiRemoteUser, uri: string): Promise<string> {
|
||||
this.logger.info(`Deleting the Note: ${uri}`);
|
||||
|
||||
const unlock = await this.appLockService.getApLock(uri);
|
||||
const unlock = await acquireApObjectLock(this.redisClient, uri);
|
||||
|
||||
try {
|
||||
const note = await this.apDbResolverService.getNoteFromApId(uri);
|
||||
|
||||
@@ -5,11 +5,13 @@
|
||||
|
||||
import { forwardRef, Inject, Injectable } from '@nestjs/common';
|
||||
import { In } from 'typeorm';
|
||||
import * as Redis from 'ioredis';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type { PollsRepository, EmojisRepository, MiMeta } from '@/models/_.js';
|
||||
import type { Config } from '@/config.js';
|
||||
import type { MiRemoteUser } from '@/models/User.js';
|
||||
import type { MiNote } from '@/models/Note.js';
|
||||
import { acquireApObjectLock } from '@/misc/distributed-lock.js';
|
||||
import { toArray, toSingle, unique } from '@/misc/prelude/array.js';
|
||||
import type { MiEmoji } from '@/models/Emoji.js';
|
||||
import type { MiDriveFile } from '@/models/DriveFile.js';
|
||||
@@ -22,7 +24,6 @@ import { UtilityService } from '@/core/UtilityService.js';
|
||||
import { bindThis } from '@/decorators.js';
|
||||
import { checkHttps } from '@/misc/check-https.js';
|
||||
import { IdentifiableError } from '@/misc/identifiable-error.js';
|
||||
import { AppLockService } from '@/core/AppLockService.js';
|
||||
import { getOneApId, getApId, getOneApHrefNullable, validPost, isEmoji, getApType } from '../type.js';
|
||||
import { ApLoggerService } from '../ApLoggerService.js';
|
||||
import { ApMfmService } from '../ApMfmService.js';
|
||||
@@ -48,6 +49,9 @@ export class ApNoteService {
|
||||
@Inject(DI.meta)
|
||||
private meta: MiMeta,
|
||||
|
||||
@Inject(DI.redis)
|
||||
private redisClient: Redis.Redis,
|
||||
|
||||
@Inject(DI.pollsRepository)
|
||||
private pollsRepository: PollsRepository,
|
||||
|
||||
@@ -71,7 +75,6 @@ export class ApNoteService {
|
||||
private noteCreateService: NoteCreateService,
|
||||
private apDbResolverService: ApDbResolverService,
|
||||
private apLoggerService: ApLoggerService,
|
||||
private appLockService: AppLockService,
|
||||
) {
|
||||
this.logger = this.apLoggerService.logger;
|
||||
}
|
||||
@@ -354,7 +357,7 @@ export class ApNoteService {
|
||||
throw new StatusError('blocked host', 451);
|
||||
}
|
||||
|
||||
const unlock = await this.appLockService.getApLock(uri);
|
||||
const unlock = await acquireApObjectLock(this.redisClient, uri);
|
||||
|
||||
try {
|
||||
//#region このサーバーに既に登録されていたらそれを返す
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
|
||||
import { Inject, Injectable, OnApplicationShutdown } from '@nestjs/common';
|
||||
import * as Bull from 'bullmq';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import type { Config } from '@/config.js';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import type Logger from '@/logger.js';
|
||||
@@ -157,6 +156,13 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
};
|
||||
}
|
||||
|
||||
let Sentry: typeof import('@sentry/node') | undefined;
|
||||
if (Sentry != null) {
|
||||
import('@sentry/node').then((mod) => {
|
||||
Sentry = mod;
|
||||
});
|
||||
}
|
||||
|
||||
//#region system
|
||||
{
|
||||
const processer = (job: Bull.Job) => {
|
||||
@@ -175,7 +181,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
};
|
||||
|
||||
this.systemQueueWorker = new Bull.Worker(QUEUE.SYSTEM, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: System: ' + job.name }, () => processer(job));
|
||||
} else {
|
||||
return processer(job);
|
||||
@@ -192,7 +198,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) id=${job.id}`))
|
||||
.on('failed', (job, err: Error) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) id=${job?.id ?? '?'}`, { job: renderJob(job), e: renderError(err) });
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: System: ${job?.name ?? '?'}: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -232,7 +238,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
};
|
||||
|
||||
this.dbQueueWorker = new Bull.Worker(QUEUE.DB, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: DB: ' + job.name }, () => processer(job));
|
||||
} else {
|
||||
return processer(job);
|
||||
@@ -249,7 +255,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) id=${job.id}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) id=${job?.id ?? '?'}`, { job: renderJob(job), e: renderError(err) });
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: DB: ${job?.name ?? '?'}: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -264,7 +270,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region deliver
|
||||
{
|
||||
this.deliverQueueWorker = new Bull.Worker(QUEUE.DELIVER, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: Deliver' }, () => this.deliverProcessorService.process(job));
|
||||
} else {
|
||||
return this.deliverProcessorService.process(job);
|
||||
@@ -289,7 +295,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) ${getJobInfo(job, true)} to=${job.data.to}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) ${getJobInfo(job)} to=${job ? job.data.to : '-'}`);
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: Deliver: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -304,7 +310,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region inbox
|
||||
{
|
||||
this.inboxQueueWorker = new Bull.Worker(QUEUE.INBOX, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: Inbox' }, () => this.inboxProcessorService.process(job));
|
||||
} else {
|
||||
return this.inboxProcessorService.process(job);
|
||||
@@ -329,7 +335,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) ${getJobInfo(job, true)}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) ${getJobInfo(job)} activity=${job ? (job.data.activity ? job.data.activity.id : 'none') : '-'}`, { job: renderJob(job), e: renderError(err) });
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: Inbox: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -344,7 +350,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region user-webhook deliver
|
||||
{
|
||||
this.userWebhookDeliverQueueWorker = new Bull.Worker(QUEUE.USER_WEBHOOK_DELIVER, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: UserWebhookDeliver' }, () => this.userWebhookDeliverProcessorService.process(job));
|
||||
} else {
|
||||
return this.userWebhookDeliverProcessorService.process(job);
|
||||
@@ -369,7 +375,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) ${getJobInfo(job, true)} to=${job.data.to}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) ${getJobInfo(job)} to=${job ? job.data.to : '-'}`);
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: UserWebhookDeliver: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -384,7 +390,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region system-webhook deliver
|
||||
{
|
||||
this.systemWebhookDeliverQueueWorker = new Bull.Worker(QUEUE.SYSTEM_WEBHOOK_DELIVER, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: SystemWebhookDeliver' }, () => this.systemWebhookDeliverProcessorService.process(job));
|
||||
} else {
|
||||
return this.systemWebhookDeliverProcessorService.process(job);
|
||||
@@ -409,7 +415,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) ${getJobInfo(job, true)} to=${job.data.to}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) ${getJobInfo(job)} to=${job ? job.data.to : '-'}`);
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: SystemWebhookDeliver: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -434,7 +440,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
};
|
||||
|
||||
this.relationshipQueueWorker = new Bull.Worker(QUEUE.RELATIONSHIP, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: Relationship: ' + job.name }, () => processer(job));
|
||||
} else {
|
||||
return processer(job);
|
||||
@@ -456,7 +462,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) id=${job.id}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) id=${job?.id ?? '?'}`, { job: renderJob(job), e: renderError(err) });
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: Relationship: ${job?.name ?? '?'}: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -479,7 +485,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
};
|
||||
|
||||
this.objectStorageQueueWorker = new Bull.Worker(QUEUE.OBJECT_STORAGE, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: ObjectStorage: ' + job.name }, () => processer(job));
|
||||
} else {
|
||||
return processer(job);
|
||||
@@ -497,7 +503,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
.on('completed', (job, result) => logger.debug(`completed(${result}) id=${job.id}`))
|
||||
.on('failed', (job, err) => {
|
||||
logger.error(`failed(${err.name}: ${err.message}) id=${job?.id ?? '?'}`, { job: renderJob(job), e: renderError(err) });
|
||||
if (config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
Sentry.captureMessage(`Queue: ObjectStorage: ${job?.name ?? '?'}: ${err.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
extra: { job, err },
|
||||
@@ -512,7 +518,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region ended poll notification
|
||||
{
|
||||
this.endedPollNotificationQueueWorker = new Bull.Worker(QUEUE.ENDED_POLL_NOTIFICATION, (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: EndedPollNotification' }, () => this.endedPollNotificationProcessorService.process(job));
|
||||
} else {
|
||||
return this.endedPollNotificationProcessorService.process(job);
|
||||
@@ -527,7 +533,7 @@ export class QueueProcessorService implements OnApplicationShutdown {
|
||||
//#region post scheduled note
|
||||
{
|
||||
this.postScheduledNoteQueueWorker = new Bull.Worker(QUEUE.POST_SCHEDULED_NOTE, async (job) => {
|
||||
if (this.config.sentryForBackend) {
|
||||
if (Sentry != null) {
|
||||
return Sentry.startSpan({ name: 'Queue: PostScheduledNote' }, () => this.postScheduledNoteProcessorService.process(job));
|
||||
} else {
|
||||
return this.postScheduledNoteProcessorService.process(job);
|
||||
|
||||
@@ -7,7 +7,6 @@ import { randomUUID } from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as stream from 'node:stream/promises';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import * as Sentry from '@sentry/node';
|
||||
import { DI } from '@/di-symbols.js';
|
||||
import { getIpHash } from '@/misc/get-ip-hash.js';
|
||||
import type { MiLocalUser, MiUser } from '@/models/User.js';
|
||||
@@ -37,6 +36,7 @@ export class ApiCallService implements OnApplicationShutdown {
|
||||
private logger: Logger;
|
||||
private userIpHistories: Map<MiUser['id'], Set<string>>;
|
||||
private userIpHistoriesClearIntervalId: NodeJS.Timeout;
|
||||
private Sentry: typeof import('@sentry/node') | null = null;
|
||||
|
||||
constructor(
|
||||
@Inject(DI.meta)
|
||||
@@ -59,6 +59,12 @@ export class ApiCallService implements OnApplicationShutdown {
|
||||
this.userIpHistoriesClearIntervalId = setInterval(() => {
|
||||
this.userIpHistories.clear();
|
||||
}, 1000 * 60 * 60);
|
||||
|
||||
if (this.config.sentryForBackend) {
|
||||
import('@sentry/node').then((Sentry) => {
|
||||
this.Sentry = Sentry;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#sendApiError(reply: FastifyReply, err: ApiError): void {
|
||||
@@ -120,8 +126,8 @@ export class ApiCallService implements OnApplicationShutdown {
|
||||
},
|
||||
});
|
||||
|
||||
if (this.config.sentryForBackend) {
|
||||
Sentry.captureMessage(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
||||
if (this.Sentry != null) {
|
||||
this.Sentry.captureMessage(`Internal error occurred in ${ep.name}: ${err.message}`, {
|
||||
level: 'error',
|
||||
user: {
|
||||
id: userId,
|
||||
@@ -432,8 +438,8 @@ export class ApiCallService implements OnApplicationShutdown {
|
||||
}
|
||||
|
||||
// API invoking
|
||||
if (this.config.sentryForBackend) {
|
||||
return await Sentry.startSpan({
|
||||
if (this.Sentry != null) {
|
||||
return await this.Sentry.startSpan({
|
||||
name: 'API: ' + ep.name,
|
||||
}, () => ep.exec(data, user, token, file, request.ip, request.headers)
|
||||
.catch((err: Error) => this.#onExecError(ep, data, err, user?.id)));
|
||||
|
||||
@@ -10,7 +10,7 @@ import { collectModifications } from './locale-inliner/collect-modifications.js'
|
||||
import { applyWithLocale } from './locale-inliner/apply-with-locale.js';
|
||||
import { blankLogger } from './logger.js';
|
||||
import type { Logger } from './logger.js';
|
||||
import type { Locale } from '../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
import type { Manifest as ViteManifest } from 'vite';
|
||||
|
||||
export class LocaleInliner {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import MagicString from 'magic-string';
|
||||
import { assertNever } from '../utils.js';
|
||||
import type { Locale, ILocale } from '../../../locales/index.js';
|
||||
import type { ILocale, Locale } from 'i18n';
|
||||
import type { TextModification } from '../locale-inliner.js';
|
||||
import type { Logger } from '../logger.js';
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"i18n": "workspace:*",
|
||||
"estree-walker": "3.0.3",
|
||||
"magic-string": "0.30.21",
|
||||
"vite": "7.2.2"
|
||||
"vite": "7.2.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as fs from 'fs/promises';
|
||||
import url from 'node:url';
|
||||
import path from 'node:path';
|
||||
import { execa } from 'execa';
|
||||
import locales from '../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
import { LocaleInliner } from '../frontend-builder/locale-inliner.js'
|
||||
import { createLogger } from '../frontend-builder/logger';
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@discordapp/twemoji": "16.0.1",
|
||||
"i18n": "workspace:*",
|
||||
"@rollup/plugin-json": "6.1.0",
|
||||
"@rollup/plugin-replace": "6.0.3",
|
||||
"@rollup/pluginutils": "5.3.0",
|
||||
@@ -27,14 +28,14 @@
|
||||
"misskey-js": "workspace:*",
|
||||
"punycode.js": "2.3.1",
|
||||
"rollup": "4.53.3",
|
||||
"sass": "1.94.1",
|
||||
"sass": "1.94.2",
|
||||
"shiki": "3.15.0",
|
||||
"tinycolor2": "1.6.0",
|
||||
"tsc-alias": "1.8.16",
|
||||
"tsconfig-paths": "4.2.0",
|
||||
"typescript": "5.9.3",
|
||||
"uuid": "13.0.0",
|
||||
"vite": "7.2.2",
|
||||
"vite": "7.2.4",
|
||||
"vue": "3.5.24"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -49,12 +50,12 @@
|
||||
"@types/ws": "8.18.1",
|
||||
"@typescript-eslint/eslint-plugin": "8.47.0",
|
||||
"@typescript-eslint/parser": "8.47.0",
|
||||
"@vitest/coverage-v8": "3.2.4",
|
||||
"@vitest/coverage-v8": "4.0.13",
|
||||
"@vue/runtime-core": "3.5.24",
|
||||
"acorn": "8.15.0",
|
||||
"cross-env": "10.1.0",
|
||||
"eslint-plugin-import": "2.32.0",
|
||||
"eslint-plugin-vue": "10.5.1",
|
||||
"eslint-plugin-vue": "10.6.0",
|
||||
"fast-glob": "3.3.3",
|
||||
"happy-dom": "20.0.10",
|
||||
"intersection-observer": "0.12.2",
|
||||
@@ -62,11 +63,11 @@
|
||||
"msw": "2.12.2",
|
||||
"nodemon": "3.1.11",
|
||||
"prettier": "3.6.2",
|
||||
"start-server-and-test": "2.1.2",
|
||||
"start-server-and-test": "2.1.3",
|
||||
"tsx": "4.20.6",
|
||||
"vite-plugin-turbosnap": "1.0.3",
|
||||
"vue-component-type-helpers": "3.1.4",
|
||||
"vue-component-type-helpers": "3.1.5",
|
||||
"vue-eslint-parser": "10.2.0",
|
||||
"vue-tsc": "3.1.4"
|
||||
"vue-tsc": "3.1.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
<script setup lang="ts" generic="T extends string | ParameterizedString">
|
||||
import { computed, h } from 'vue';
|
||||
import type { ParameterizedString } from '../../../../locales/index.js';
|
||||
import type { ParameterizedString } from 'i18n';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
src: T;
|
||||
@@ -25,7 +25,7 @@ const slots = defineSlots<T extends ParameterizedString<infer R> ? { [K in R]: (
|
||||
const parsed = computed(() => {
|
||||
let str = props.src as string;
|
||||
const value: (string | { arg: string; })[] = [];
|
||||
for (;;) {
|
||||
for (; ;) {
|
||||
const nextBracketOpen = str.indexOf('{');
|
||||
const nextBracketClose = str.indexOf('}');
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { markRaw } from 'vue';
|
||||
import { I18n } from '@@/js/i18n.js';
|
||||
import { locale } from '@@/js/locale.js';
|
||||
import type { Locale } from '../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
|
||||
export const i18n = markRaw(new I18n<Locale>(locale, _DEV_));
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import path from 'path';
|
||||
import pluginVue from '@vitejs/plugin-vue';
|
||||
import { type UserConfig, defineConfig } from 'vite';
|
||||
import { defineConfig, type UserConfig } from 'vite';
|
||||
import * as yaml from 'js-yaml';
|
||||
import { promises as fsp } from 'fs';
|
||||
|
||||
import locales from '../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
import meta from '../../package.json';
|
||||
import packageInfo from './package.json' with { type: 'json' };
|
||||
import pluginJson5 from './vite.json5.js';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import type { ILocale, ParameterizedString } from '../../../locales/index.js';
|
||||
import type { ILocale, ParameterizedString } from 'i18n';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
type TODO = any;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { lang, version } from '@@/js/config.js';
|
||||
import type { Locale } from '../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
|
||||
// ここはビルド時に const locale = JSON.parse("...") みたいな感じで置き換えられるので top-level await は消える
|
||||
export let locale: Locale = await window.fetch(`/assets/locales/${lang}.${version}.json`).then(r => r.json(), () => null);
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import type { Locale } from '../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
|
||||
type BootLoaderLocaleBody = Locale['_bootErrors'] & { reload: Locale['reload'] };
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
"@typescript-eslint/eslint-plugin": "8.47.0",
|
||||
"@typescript-eslint/parser": "8.47.0",
|
||||
"esbuild": "0.27.0",
|
||||
"eslint-plugin-vue": "10.5.1",
|
||||
"eslint-plugin-vue": "10.6.0",
|
||||
"nodemon": "3.1.11",
|
||||
"typescript": "5.9.3",
|
||||
"vue-eslint-parser": "10.2.0"
|
||||
@@ -34,6 +34,7 @@
|
||||
"js-built"
|
||||
],
|
||||
"dependencies": {
|
||||
"i18n": "workspace:*",
|
||||
"misskey-js": "workspace:*",
|
||||
"vue": "3.5.24"
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
import locales from '../../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
|
||||
await writeFile(
|
||||
new URL('locale.ts', import.meta.url),
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as fs from 'fs/promises';
|
||||
import url from 'node:url';
|
||||
import path from 'node:path';
|
||||
import { execa } from 'execa';
|
||||
import locales from '../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
import { LocaleInliner } from '../frontend-builder/locale-inliner.js'
|
||||
import { createLogger } from '../frontend-builder/logger';
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import path from 'node:path'
|
||||
import locales from '../../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
|
||||
const localesDir = path.resolve(__dirname, '../../../locales')
|
||||
|
||||
@@ -13,14 +13,14 @@ const localesDir = path.resolve(__dirname, '../../../locales')
|
||||
* @returns {import('vite').Plugin}
|
||||
*/
|
||||
export default function pluginWatchLocales() {
|
||||
return {
|
||||
name: 'watch-locales',
|
||||
return {
|
||||
name: 'watch-locales',
|
||||
|
||||
configureServer(server) {
|
||||
const localeYmlPaths = Object.keys(locales).map(locale => path.join(localesDir, `${locale}.yml`));
|
||||
configureServer(server) {
|
||||
const localeYmlPaths = Object.keys(locales).map(locale => path.join(localesDir, `${locale}.yml`));
|
||||
|
||||
// watcherにパスを追加
|
||||
server.watcher.add(localeYmlPaths);
|
||||
// watcherにパスを追加
|
||||
server.watcher.add(localeYmlPaths);
|
||||
|
||||
server.watcher.on('change', (filePath) => {
|
||||
if (localeYmlPaths.includes(filePath)) {
|
||||
@@ -31,6 +31,6 @@ export default function pluginWatchLocales() {
|
||||
})
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
"@discordapp/twemoji": "16.0.1",
|
||||
"@github/webauthn-json": "2.1.1",
|
||||
"@mcaptcha/vanilla-glue": "0.1.0-alpha-3",
|
||||
"i18n": "workspace:*",
|
||||
"@misskey-dev/browser-image-resizer": "2024.1.0",
|
||||
"@rollup/plugin-json": "6.1.0",
|
||||
"@rollup/plugin-replace": "6.0.3",
|
||||
@@ -58,7 +59,7 @@
|
||||
"json5": "2.2.3",
|
||||
"magic-string": "0.30.21",
|
||||
"matter-js": "0.20.0",
|
||||
"mediabunny": "1.25.0",
|
||||
"mediabunny": "1.25.1",
|
||||
"mfm-js": "0.25.0",
|
||||
"misskey-bubble-game": "workspace:*",
|
||||
"misskey-js": "workspace:*",
|
||||
@@ -69,7 +70,7 @@
|
||||
"qr-scanner": "1.4.2",
|
||||
"rollup": "4.53.3",
|
||||
"sanitize-html": "2.17.0",
|
||||
"sass": "1.94.1",
|
||||
"sass": "1.94.2",
|
||||
"shiki": "3.15.0",
|
||||
"strict-event-emitter-types": "2.0.0",
|
||||
"textarea-caret": "3.1.0",
|
||||
@@ -80,7 +81,7 @@
|
||||
"tsconfig-paths": "4.2.0",
|
||||
"typescript": "5.9.3",
|
||||
"v-code-diff": "1.13.1",
|
||||
"vite": "7.2.2",
|
||||
"vite": "7.2.4",
|
||||
"vue": "3.5.24",
|
||||
"vuedraggable": "next",
|
||||
"wanakana": "5.3.1"
|
||||
@@ -89,7 +90,7 @@
|
||||
"@misskey-dev/summaly": "5.2.5",
|
||||
"@storybook/addon-essentials": "8.6.14",
|
||||
"@storybook/addon-interactions": "8.6.14",
|
||||
"@storybook/addon-links": "9.1.16",
|
||||
"@storybook/addon-links": "10.0.8",
|
||||
"@storybook/addon-mdx-gfm": "8.6.14",
|
||||
"@storybook/addon-storysource": "8.6.14",
|
||||
"@storybook/blocks": "8.6.14",
|
||||
@@ -97,13 +98,13 @@
|
||||
"@storybook/core-events": "8.6.14",
|
||||
"@storybook/manager-api": "8.6.14",
|
||||
"@storybook/preview-api": "8.6.14",
|
||||
"@storybook/react": "9.1.16",
|
||||
"@storybook/react-vite": "9.1.16",
|
||||
"@storybook/react": "10.0.8",
|
||||
"@storybook/react-vite": "10.0.8",
|
||||
"@storybook/test": "8.6.14",
|
||||
"@storybook/theming": "8.6.14",
|
||||
"@storybook/types": "8.6.14",
|
||||
"@storybook/vue3": "9.1.16",
|
||||
"@storybook/vue3-vite": "9.1.16",
|
||||
"@storybook/vue3": "10.0.8",
|
||||
"@storybook/vue3-vite": "10.0.8",
|
||||
"@tabler/icons-webfont": "3.35.0",
|
||||
"@testing-library/vue": "8.1.0",
|
||||
"@types/canvas-confetti": "1.9.0",
|
||||
@@ -119,14 +120,14 @@
|
||||
"@types/ws": "8.18.1",
|
||||
"@typescript-eslint/eslint-plugin": "8.47.0",
|
||||
"@typescript-eslint/parser": "8.47.0",
|
||||
"@vitest/coverage-v8": "3.2.4",
|
||||
"@vitest/coverage-v8": "4.0.13",
|
||||
"@vue/compiler-core": "3.5.24",
|
||||
"@vue/runtime-core": "3.5.24",
|
||||
"acorn": "8.15.0",
|
||||
"cross-env": "10.1.0",
|
||||
"cypress": "15.6.0",
|
||||
"cypress": "15.7.0",
|
||||
"eslint-plugin-import": "2.32.0",
|
||||
"eslint-plugin-vue": "10.5.1",
|
||||
"eslint-plugin-vue": "10.6.0",
|
||||
"fast-glob": "3.3.3",
|
||||
"happy-dom": "20.0.10",
|
||||
"intersection-observer": "0.12.2",
|
||||
@@ -139,16 +140,16 @@
|
||||
"react": "19.2.0",
|
||||
"react-dom": "19.2.0",
|
||||
"seedrandom": "3.0.5",
|
||||
"start-server-and-test": "2.1.2",
|
||||
"storybook": "9.1.16",
|
||||
"start-server-and-test": "2.1.3",
|
||||
"storybook": "10.0.8",
|
||||
"storybook-addon-misskey-theme": "github:misskey-dev/storybook-addon-misskey-theme",
|
||||
"tsx": "4.20.6",
|
||||
"vite-plugin-glsl": "1.5.4",
|
||||
"vite-plugin-turbosnap": "1.0.3",
|
||||
"vitest": "3.2.4",
|
||||
"vitest": "4.0.13",
|
||||
"vitest-fetch-mock": "0.4.5",
|
||||
"vue-component-type-helpers": "3.1.4",
|
||||
"vue-component-type-helpers": "3.1.5",
|
||||
"vue-eslint-parser": "10.2.0",
|
||||
"vue-tsc": "3.1.4"
|
||||
"vue-tsc": "3.1.5"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
<script setup lang="ts" generic="T extends string | ParameterizedString">
|
||||
import { computed, h } from 'vue';
|
||||
import type { ParameterizedString } from '../../../../../locales/index.js';
|
||||
import type { ParameterizedString } from 'i18n';
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
src: T;
|
||||
@@ -25,7 +25,7 @@ const slots = defineSlots<T extends ParameterizedString<infer R> ? { [K in R]: (
|
||||
const parsed = computed(() => {
|
||||
let str = props.src as string;
|
||||
const value: (string | { arg: string; })[] = [];
|
||||
for (;;) {
|
||||
for (; ;) {
|
||||
const nextBracketOpen = str.indexOf('{');
|
||||
const nextBracketClose = str.indexOf('}');
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
import { markRaw } from 'vue';
|
||||
import { I18n } from '@@/js/i18n.js';
|
||||
import { locale } from '@@/js/locale.js';
|
||||
import type { Locale } from '../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
|
||||
export const i18n = markRaw(new I18n<Locale>(locale, _DEV_));
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@ import { aiScriptReadline, createAiScriptEnv } from '@/aiscript/api.js';
|
||||
import { errors, Interpreter, Parser, values } from '@syuilo/aiscript';
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
describe,
|
||||
@@ -80,8 +79,9 @@ describe('AiScript common API', () => {
|
||||
});
|
||||
|
||||
describe('readline', () => {
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test.sequential('ok', async () => {
|
||||
@@ -176,8 +176,9 @@ describe('AiScript common API', () => {
|
||||
});
|
||||
|
||||
describe('dialog', () => {
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test.sequential('ok', async () => {
|
||||
@@ -215,8 +216,9 @@ describe('AiScript common API', () => {
|
||||
});
|
||||
|
||||
describe('confirm', () => {
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test.sequential('ok', async () => {
|
||||
@@ -272,8 +274,9 @@ describe('AiScript common API', () => {
|
||||
});
|
||||
|
||||
describe('api', () => {
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test.sequential('successful', async () => {
|
||||
@@ -347,7 +350,7 @@ describe('AiScript common API', () => {
|
||||
miLocalStorage.removeItem('aiscript:widget:key');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
beforeEach(() => {
|
||||
miLocalStorage.removeItem('aiscript:widget:key');
|
||||
});
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { I18n } from '../../frontend-shared/js/i18n.js'; // @@で参照できなかったので
|
||||
import type { ParameterizedString } from '../../../locales/index.js';
|
||||
import type { ParameterizedString } from 'i18n';
|
||||
|
||||
// TODO: このテストはfrontend-sharedに移動する
|
||||
|
||||
|
||||
@@ -7,13 +7,13 @@ import { vi } from 'vitest';
|
||||
import createFetchMock from 'vitest-fetch-mock';
|
||||
import type { Ref } from 'vue';
|
||||
import { ref } from 'vue';
|
||||
// Set i18n
|
||||
import locales from 'i18n';
|
||||
import { updateI18n } from '@/i18n.js';
|
||||
|
||||
const fetchMocker = createFetchMock(vi);
|
||||
fetchMocker.enableMocks();
|
||||
|
||||
// Set i18n
|
||||
import locales from '../../../locales/index.js';
|
||||
import { updateI18n } from '@/i18n.js';
|
||||
updateI18n(locales['en-US']);
|
||||
|
||||
// XXX: misskey-js panics if WebSocket is not defined
|
||||
|
||||
@@ -2,18 +2,18 @@ import path from 'path';
|
||||
import pluginReplace from '@rollup/plugin-replace';
|
||||
import pluginVue from '@vitejs/plugin-vue';
|
||||
import pluginGlsl from 'vite-plugin-glsl';
|
||||
import { defineConfig } from 'vite';
|
||||
import type { UserConfig } from 'vite';
|
||||
import { defineConfig } from 'vite';
|
||||
import * as yaml from 'js-yaml';
|
||||
import { promises as fsp } from 'fs';
|
||||
|
||||
import locales from '../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
import meta from '../../package.json';
|
||||
import packageInfo from './package.json' with { type: 'json' };
|
||||
import pluginUnwindCssModuleClassName from './lib/rollup-plugin-unwind-css-module-class-name.js';
|
||||
import pluginJson5 from './vite.json5.js';
|
||||
import pluginCreateSearchIndex from './lib/vite-plugin-create-search-index.js';
|
||||
import type { Options as SearchIndexOptions } from './lib/vite-plugin-create-search-index.js';
|
||||
import pluginCreateSearchIndex from './lib/vite-plugin-create-search-index.js';
|
||||
import pluginWatchLocales from './lib/vite-plugin-watch-locales.js';
|
||||
import { pluginRemoveUnrefI18n } from '../frontend-builder/rollup-plugin-remove-unref-i18n.js';
|
||||
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Misskey i18n
|
||||
|
||||
Misskey の言語ファイル本体 (ja-JP.yml など) はリポジトリ直下の `/locales` に置かれており、そこから Crowdin 連携やビルド資産が生成されます。
|
||||
|
||||
このパッケージは Misskey モノレポ内で、これらの言語ファイルを共通で扱うためのヘルパー群や型情報をまとめる位置づけです。バックエンド / フロントエンド / Service Worker など各パッケージが同じ翻訳データと型定義を利用できるようにすることを目的としており、npm での外部配布は想定していません。
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import fs from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { watch as chokidarWatch } from 'chokidar';
|
||||
import * as esbuild from 'esbuild';
|
||||
import { build } from 'esbuild';
|
||||
import { execa } from 'execa';
|
||||
import { globSync } from 'glob';
|
||||
import { generateLocaleInterface } from './scripts/generateLocaleInterface.js';
|
||||
import type { BuildOptions, BuildResult, Plugin, PluginBuild } from 'esbuild';
|
||||
|
||||
const _filename = fileURLToPath(import.meta.url);
|
||||
const _dirname = dirname(_filename);
|
||||
const _package = JSON.parse(fs.readFileSync(_dirname + '/package.json', 'utf-8'));
|
||||
const _rootPackageDir = resolve(_dirname, '../../');
|
||||
const _rootPackage = JSON.parse(fs.readFileSync(resolve(_rootPackageDir, 'package.json'), 'utf-8'));
|
||||
const _frontendLocalesDir = resolve(_dirname, '../../built/_frontend_dist_/locales');
|
||||
const _localesDir = resolve(_rootPackageDir, 'locales');
|
||||
|
||||
const entryPoints = globSync('./src/**/**.{ts,tsx}');
|
||||
|
||||
const options: BuildOptions = {
|
||||
entryPoints,
|
||||
minify: process.env.NODE_ENV === 'production',
|
||||
sourceRoot: 'src',
|
||||
outdir: './built',
|
||||
target: 'es2022',
|
||||
platform: 'node',
|
||||
format: 'esm',
|
||||
sourcemap: 'linked',
|
||||
};
|
||||
|
||||
// コマンドライン引数を取得
|
||||
const args = process.argv.slice(2).map(arg => arg.toLowerCase());
|
||||
|
||||
// built配下をすべて削除する
|
||||
if (!args.includes('--no-clean')) {
|
||||
fs.rmSync('./built', { recursive: true, force: true });
|
||||
}
|
||||
|
||||
if (args.includes('--watch')) {
|
||||
await watchSrc();
|
||||
} else {
|
||||
await buildSrc();
|
||||
}
|
||||
|
||||
function copyLocales(): void {
|
||||
const srcDir = _localesDir;
|
||||
const destDir = resolve(_dirname, 'built/locales');
|
||||
|
||||
fs.mkdirSync(destDir, { recursive: true });
|
||||
|
||||
const files = fs.readdirSync(srcDir).filter(f => f.endsWith('.yml'));
|
||||
for (const file of files) {
|
||||
fs.copyFileSync(resolve(srcDir, file), resolve(destDir, file));
|
||||
}
|
||||
console.log(`[${_package.name}] locales copied (${files.length} files).`);
|
||||
}
|
||||
|
||||
/**
|
||||
* フロントエンド用の locale JSON を書き出す
|
||||
* Service Worker が HTTP 経由で取得するために必要
|
||||
*/
|
||||
async function writeFrontendLocalesJson(): Promise<void> {
|
||||
// 動的 import でビルド済みモジュールから読み込み(循環参照回避)
|
||||
const { writeFrontendLocalesJson: write } = await import('./built/index.js');
|
||||
await write(_frontendLocalesDir, _rootPackage.version);
|
||||
console.log(`[${_package.name}] frontend locales JSON written to ${_frontendLocalesDir}`);
|
||||
}
|
||||
|
||||
async function buildSrc(): Promise<void> {
|
||||
console.log(`[${_package.name}] start building...`);
|
||||
|
||||
await generateLocaleInterface(_localesDir);
|
||||
|
||||
await build(options)
|
||||
.then(() => {
|
||||
console.log(`[${_package.name}] build succeeded.`);
|
||||
})
|
||||
.catch((err) => {
|
||||
process.stderr.write(err.stderr);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
copyLocales();
|
||||
await writeFrontendLocalesJson();
|
||||
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
console.log(`[${_package.name}] skip building d.ts because NODE_ENV is production.`);
|
||||
} else {
|
||||
await buildDts();
|
||||
}
|
||||
|
||||
console.log(`[${_package.name}] finish building.`);
|
||||
}
|
||||
|
||||
function buildDts(): Promise<unknown> {
|
||||
return execa(
|
||||
'tsc',
|
||||
[
|
||||
'--project', 'tsconfig.json',
|
||||
'--rootDir', 'src',
|
||||
'--outDir', 'built',
|
||||
'--declaration', 'true',
|
||||
'--emitDeclarationOnly', 'true',
|
||||
],
|
||||
{
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
async function watchSrc(): Promise<void> {
|
||||
const localesWatcher = chokidarWatch(_localesDir, {
|
||||
ignoreInitial: true,
|
||||
});
|
||||
localesWatcher.on('all', async (event, path) => {
|
||||
if (!path.endsWith('.yml')) return;
|
||||
console.log(`[${_package.name}] locales changed: ${event} ${path}`);
|
||||
copyLocales();
|
||||
await writeFrontendLocalesJson();
|
||||
await generateLocaleInterface(_localesDir);
|
||||
});
|
||||
|
||||
const plugins: Plugin[] = [{
|
||||
name: 'gen-dts',
|
||||
setup(build: PluginBuild) {
|
||||
build.onStart(() => {
|
||||
console.log(`[${_package.name}] detect changed...`);
|
||||
});
|
||||
build.onEnd(async (result: BuildResult) => {
|
||||
if (result.errors.length > 0) {
|
||||
console.error(`[${_package.name}] watch build failed:`, result);
|
||||
return;
|
||||
}
|
||||
await buildDts();
|
||||
});
|
||||
},
|
||||
}];
|
||||
|
||||
console.log(`[${_package.name}] start watching...`);
|
||||
|
||||
const context = await esbuild.context({ ...options, plugins });
|
||||
await context.watch();
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
process.on('SIGHUP', resolve);
|
||||
process.on('SIGINT', resolve);
|
||||
process.on('SIGTERM', resolve);
|
||||
process.on('uncaughtException', reject);
|
||||
process.on('exit', resolve);
|
||||
}).finally(async () => {
|
||||
await context.dispose();
|
||||
await localesWatcher.close();
|
||||
console.log(`[${_package.name}] finish watching.`);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import tsParser from '@typescript-eslint/parser';
|
||||
import sharedConfig from '../shared/eslint.config.js';
|
||||
|
||||
// eslint-disable-next-line import/no-default-export
|
||||
export default [
|
||||
...sharedConfig,
|
||||
{
|
||||
ignores: [
|
||||
'**/node_modules',
|
||||
'built',
|
||||
'coverage',
|
||||
'vitest.config.ts',
|
||||
'test',
|
||||
'test-d',
|
||||
'generator',
|
||||
],
|
||||
},
|
||||
{
|
||||
files: ['**/*.ts', '**/*.tsx'],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
parser: tsParser,
|
||||
project: ['./tsconfig.eslint.json'],
|
||||
sourceType: 'module',
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['src/autogen/**/*.ts', 'src/autogen/**/*.tsx'],
|
||||
rules: {
|
||||
'@stylistic/indent': 'off',
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "i18n",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
"main": "./built/index.js",
|
||||
"types": "./built/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./built/index.d.ts",
|
||||
"import": "./built/index.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"generate": "tsx scripts/generateLocaleInterface.ts",
|
||||
"verify": "tsx scripts/verify.ts",
|
||||
"build": "tsx ./build.ts",
|
||||
"watch": "nodemon -w package.json -e json --exec \"tsx ./build.ts --watch\"",
|
||||
"tsd": "tsd",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"lint": "pnpm typecheck && pnpm eslint",
|
||||
"lint:fix": "pnpm eslint --fix"
|
||||
},
|
||||
"files": [
|
||||
"built"
|
||||
],
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "4.0.9",
|
||||
"@types/node": "24.10.1",
|
||||
"@typescript-eslint/eslint-plugin": "8.47.0",
|
||||
"@typescript-eslint/parser": "8.47.0",
|
||||
"chokidar": "4.0.3",
|
||||
"esbuild": "0.27.0",
|
||||
"execa": "9.6.0",
|
||||
"glob": "11.1.0",
|
||||
"nodemon": "3.1.11",
|
||||
"tsx": "4.20.6",
|
||||
"typescript": "5.9.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "4.1.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import * as yaml from 'js-yaml';
|
||||
import ts from 'typescript';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = dirname(__filename);
|
||||
const parameterRegExp = /\{(\w+)\}/g;
|
||||
|
||||
interface LocaleRecord {
|
||||
[key: string]: string | LocaleRecord;
|
||||
}
|
||||
|
||||
function createMemberType(item: string | LocaleRecord): ts.TypeNode {
|
||||
if (typeof item !== 'string') {
|
||||
return ts.factory.createTypeLiteralNode(createMembers(item));
|
||||
}
|
||||
const parameters = Array.from(
|
||||
item.matchAll(parameterRegExp),
|
||||
([, parameter]) => parameter,
|
||||
);
|
||||
return parameters.length
|
||||
? ts.factory.createTypeReferenceNode(
|
||||
ts.factory.createIdentifier('ParameterizedString'),
|
||||
[
|
||||
ts.factory.createUnionTypeNode(
|
||||
parameters.map((parameter) =>
|
||||
ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(parameter)),
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
|
||||
}
|
||||
|
||||
function createMembers(record: LocaleRecord): ts.TypeElement[] {
|
||||
return Object.entries(record).map(([k, v]) => {
|
||||
const node = ts.factory.createPropertySignature(
|
||||
undefined,
|
||||
ts.factory.createStringLiteral(k),
|
||||
undefined,
|
||||
createMemberType(v),
|
||||
);
|
||||
if (typeof v === 'string') {
|
||||
ts.addSyntheticLeadingComment(
|
||||
node,
|
||||
ts.SyntaxKind.MultiLineCommentTrivia,
|
||||
`*
|
||||
* ${v.replace(/\n/g, '\n * ')}
|
||||
`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
return node;
|
||||
});
|
||||
}
|
||||
|
||||
export async function generateLocaleInterface(localesDir: string): Promise<void> {
|
||||
const locale = yaml.load(fs.readFileSync(`${localesDir}/ja-JP.yml`, 'utf-8').toString()) as LocaleRecord;
|
||||
const members = createMembers(locale);
|
||||
|
||||
const elements: ts.Statement[] = [
|
||||
ts.factory.createImportDeclaration(
|
||||
undefined,
|
||||
ts.factory.createImportClause(
|
||||
false,
|
||||
undefined,
|
||||
ts.factory.createNamedImports([
|
||||
ts.factory.createImportSpecifier(
|
||||
true,
|
||||
undefined,
|
||||
ts.factory.createIdentifier('ILocale'),
|
||||
),
|
||||
ts.factory.createImportSpecifier(
|
||||
true,
|
||||
undefined,
|
||||
ts.factory.createIdentifier('ParameterizedString'),
|
||||
),
|
||||
]),
|
||||
),
|
||||
ts.factory.createStringLiteral('../types.js'),
|
||||
undefined,
|
||||
),
|
||||
ts.factory.createInterfaceDeclaration(
|
||||
[ts.factory.createToken(ts.SyntaxKind.ExportKeyword)],
|
||||
ts.factory.createIdentifier('Locale'),
|
||||
undefined,
|
||||
[
|
||||
ts.factory.createHeritageClause(ts.SyntaxKind.ExtendsKeyword, [
|
||||
ts.factory.createExpressionWithTypeArguments(
|
||||
ts.factory.createIdentifier('ILocale'),
|
||||
undefined,
|
||||
),
|
||||
]),
|
||||
],
|
||||
members,
|
||||
),
|
||||
];
|
||||
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.MultiLineCommentTrivia,
|
||||
' eslint-disable ',
|
||||
true,
|
||||
);
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.SingleLineCommentTrivia,
|
||||
' This file is generated by scripts/generateLocaleInterface.ts',
|
||||
true,
|
||||
);
|
||||
ts.addSyntheticLeadingComment(
|
||||
elements[0],
|
||||
ts.SyntaxKind.SingleLineCommentTrivia,
|
||||
' Do not edit this file directly.',
|
||||
true,
|
||||
);
|
||||
|
||||
const printed = ts
|
||||
.createPrinter({
|
||||
newLine: ts.NewLineKind.LineFeed,
|
||||
})
|
||||
.printList(
|
||||
ts.ListFormat.MultiLine,
|
||||
ts.factory.createNodeArray(elements),
|
||||
ts.createSourceFile(
|
||||
'locale.ts',
|
||||
'',
|
||||
ts.ScriptTarget.ESNext,
|
||||
true,
|
||||
ts.ScriptKind.TS,
|
||||
),
|
||||
);
|
||||
|
||||
const autogenDir = `${__dirname}/../src/autogen`;
|
||||
fs.mkdirSync(autogenDir, { recursive: true });
|
||||
|
||||
// 一瞬ファイルが存在しなくなって途切れる→不安定になるらしいので、リネームで対処
|
||||
fs.writeFileSync(`${autogenDir}/_locale.ts`, printed, 'utf-8');
|
||||
fs.renameSync(`${autogenDir}/_locale.ts`, `${autogenDir}/locale.ts`);
|
||||
}
|
||||
|
||||
// スクリプトとして直接実行された場合
|
||||
const isMain = import.meta.url === `file://${process.argv[1]}`;
|
||||
if (isMain) {
|
||||
await generateLocaleInterface(resolve(__dirname, '../../../locales'));
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
let valid = true;
|
||||
|
||||
interface LocaleRecord {
|
||||
[key: string]: string | LocaleRecord;
|
||||
}
|
||||
|
||||
interface ErrorData {
|
||||
expected?: string;
|
||||
actual?: string;
|
||||
parameter?: string;
|
||||
}
|
||||
|
||||
function writeError(type: string, lang: string, tree: string, data: ErrorData): void {
|
||||
process.stderr.write(JSON.stringify({ type, lang, tree, data }));
|
||||
process.stderr.write('\n');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
function verify(expected: LocaleRecord, actual: LocaleRecord, lang: string, trace?: string): void {
|
||||
for (const key in expected) {
|
||||
if (!Object.prototype.hasOwnProperty.call(actual, key)) {
|
||||
continue;
|
||||
}
|
||||
if (typeof expected[key] === 'object') {
|
||||
if (typeof actual[key] !== 'object') {
|
||||
writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'object', actual: typeof actual[key] });
|
||||
continue;
|
||||
}
|
||||
verify(expected[key] as LocaleRecord, actual[key] as LocaleRecord, lang, trace ? `${trace}.${key}` : key);
|
||||
} else if (typeof expected[key] === 'string') {
|
||||
switch (typeof actual[key]) {
|
||||
case 'object':
|
||||
writeError('mismatched_type', lang, trace ? `${trace}.${key}` : key, { expected: 'string', actual: 'object' });
|
||||
break;
|
||||
case 'undefined':
|
||||
continue;
|
||||
case 'string': {
|
||||
const expectedParameters = new Set((expected[key] as string).match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1)));
|
||||
const actualParameters = new Set((actual[key] as string).match(/\{[^}]+\}/g)?.map((s) => s.slice(1, -1)));
|
||||
for (const parameter of expectedParameters) {
|
||||
if (!actualParameters.has(parameter)) {
|
||||
writeError('missing_parameter', lang, trace ? `${trace}.${key}` : key, { parameter });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// index.tsはtsのまま動かすことを想定していない(ビルド成果物を外部に公開する).
|
||||
// よってビルド後のものを検証する
|
||||
const locales = await import('../built/index.js');
|
||||
const { 'ja-JP': original, ...verifiees } = locales as unknown as Record<string, LocaleRecord>;
|
||||
|
||||
for (const lang in verifiees) {
|
||||
if (!Object.prototype.hasOwnProperty.call(locales, lang)) {
|
||||
continue;
|
||||
}
|
||||
verify(original, verifiees[lang], lang);
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -1,13 +1,7 @@
|
||||
/* eslint-disable */
|
||||
// This file is generated by locales/generateDTS.js
|
||||
// This file is generated by scripts/generateLocaleInterface.ts
|
||||
// Do not edit this file directly.
|
||||
declare const kParameters: unique symbol;
|
||||
export type ParameterizedString<T extends string = string> = string & {
|
||||
[kParameters]: T;
|
||||
};
|
||||
export interface ILocale {
|
||||
[_: string]: string | ParameterizedString | ILocale;
|
||||
}
|
||||
import { type ILocale, type ParameterizedString } from "../types.js";
|
||||
export interface Locale extends ILocale {
|
||||
/**
|
||||
* 日本語
|
||||
@@ -13089,8 +13083,3 @@ export interface Locale extends ILocale {
|
||||
"mfm": string;
|
||||
};
|
||||
}
|
||||
declare const locales: {
|
||||
[lang: string]: Locale;
|
||||
};
|
||||
export function build(): Locale;
|
||||
export default locales;
|
||||
@@ -0,0 +1,166 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
/**
|
||||
* Languages Loader
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs';
|
||||
import * as yaml from 'js-yaml';
|
||||
import type { Locale } from './autogen/locale.js';
|
||||
import type { ILocale, ParameterizedString } from './types.js';
|
||||
|
||||
const languages = [
|
||||
'ar-SA',
|
||||
'ca-ES',
|
||||
'cs-CZ',
|
||||
'da-DK',
|
||||
'de-DE',
|
||||
'en-US',
|
||||
'es-ES',
|
||||
'fr-FR',
|
||||
'id-ID',
|
||||
'it-IT',
|
||||
'ja-JP',
|
||||
'ja-KS',
|
||||
'kab-KAB',
|
||||
'kn-IN',
|
||||
'ko-KR',
|
||||
'nl-NL',
|
||||
'no-NO',
|
||||
'pl-PL',
|
||||
'pt-PT',
|
||||
'ru-RU',
|
||||
'sk-SK',
|
||||
'th-TH',
|
||||
'tr-TR',
|
||||
'ug-CN',
|
||||
'uk-UA',
|
||||
'vi-VN',
|
||||
'zh-CN',
|
||||
'zh-TW',
|
||||
] as const;
|
||||
|
||||
type Language = typeof languages[number];
|
||||
|
||||
const primaries = {
|
||||
'en': 'US',
|
||||
'ja': 'JP',
|
||||
'zh': 'CN',
|
||||
} as const satisfies Record<string, string>;
|
||||
|
||||
type PrimaryLang = keyof typeof primaries;
|
||||
|
||||
type Locales = Record<Language, ILocale>;
|
||||
|
||||
/**
|
||||
* オブジェクトを再帰的にマージする
|
||||
*/
|
||||
function merge<T extends ILocale>(...args: (T | ILocale | undefined)[]): T {
|
||||
return args.reduce<ILocale>((a, c) => ({
|
||||
...a,
|
||||
...c,
|
||||
...Object.entries(a)
|
||||
.filter(([k]) => c && typeof c[k] === 'object')
|
||||
.reduce<Record<string, ILocale[string]>>((acc, [k, v]) => {
|
||||
acc[k] = merge(v as ILocale, (c as ILocale)[k] as ILocale);
|
||||
return acc;
|
||||
}, {}),
|
||||
}), {} as ILocale) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 何故か文字列にバックスペース文字が混入することがあり、YAMLが壊れるので取り除く
|
||||
*/
|
||||
function clean (text: string) {
|
||||
return text.replace(new RegExp(String.fromCodePoint(0x08), 'g'), '');
|
||||
}
|
||||
|
||||
/**
|
||||
* 空文字列が入ることがあり、フォールバックが動作しなくなるのでプロパティごと消す
|
||||
*/
|
||||
function removeEmpty<T extends ILocale>(obj: T): T {
|
||||
for (const [k, v] of Object.entries(obj)) {
|
||||
if (v === '') {
|
||||
delete obj[k];
|
||||
} else if (typeof v === 'object') {
|
||||
removeEmpty(v as ILocale);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function build(): Record<Language, Locale> {
|
||||
// vitestの挙動を調整するため、一度ローカル変数化する必要がある
|
||||
// https://github.com/vitest-dev/vitest/issues/3988#issuecomment-1686599577
|
||||
// https://github.com/misskey-dev/misskey/pull/14057#issuecomment-2192833785
|
||||
const metaUrl = import.meta.url;
|
||||
const locales = languages.reduce<Locales>((a, lang) => {
|
||||
a[lang] = (yaml.load(clean(fs.readFileSync(new URL(`./locales/${lang}.yml`, metaUrl), 'utf-8'))) ?? {}) as ILocale;
|
||||
return a;
|
||||
}, {} as Locales);
|
||||
|
||||
removeEmpty(locales);
|
||||
|
||||
return Object.entries(locales).reduce<Record<Language, Locale>>((a, [k, v]) => {
|
||||
const lang = k.split('-')[0];
|
||||
const key = k as Language;
|
||||
|
||||
switch (key) {
|
||||
case 'ja-JP':
|
||||
a[key] = v as Locale;
|
||||
break;
|
||||
case 'ja-KS':
|
||||
case 'en-US':
|
||||
a[key] = merge<Locale>(locales['ja-JP'] as Locale, v);
|
||||
break;
|
||||
default: {
|
||||
const primaryLang = lang as PrimaryLang;
|
||||
const primaryKey = (lang in primaries ? `${lang}-${primaries[primaryLang]}` : undefined) as Language | undefined;
|
||||
a[key] = merge<Locale>(
|
||||
locales['ja-JP'] as Locale,
|
||||
locales['en-US'],
|
||||
primaryKey ? locales[primaryKey] : {},
|
||||
v,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return a;
|
||||
}, {} as Record<Language, Locale>);
|
||||
}
|
||||
|
||||
const locales = build() as {
|
||||
[lang: string]: Locale;
|
||||
};
|
||||
|
||||
/**
|
||||
* フロントエンド用の locale JSON を書き出す
|
||||
* Service Worker が HTTP 経由で取得するために必要
|
||||
* @param destDir 出力先ディレクトリ(例: built/_frontend_dist_/locales)
|
||||
* @param version バージョン文字列(ファイル名とJSON内に埋め込まれる)
|
||||
*/
|
||||
async function writeFrontendLocalesJson(destDir: string, version: string): Promise<void> {
|
||||
const { mkdir, writeFile } = await import('node:fs/promises');
|
||||
const { resolve } = await import('node:path');
|
||||
|
||||
await mkdir(destDir, { recursive: true });
|
||||
|
||||
const builtLocales = build();
|
||||
const v = { '_version_': version };
|
||||
|
||||
for (const [lang, locale] of Object.entries(builtLocales)) {
|
||||
await writeFile(
|
||||
resolve(destDir, `${lang}.${version}.json`),
|
||||
JSON.stringify({ ...locale, ...v }),
|
||||
'utf-8',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export { locales, build, writeFrontendLocalesJson };
|
||||
export type { Language, Locale, ILocale, ParameterizedString };
|
||||
export default locales;
|
||||
@@ -0,0 +1,14 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
declare const kParameters: unique symbol;
|
||||
|
||||
export type ParameterizedString<T extends string = string> = string & {
|
||||
[kParameters]: T;
|
||||
};
|
||||
|
||||
export interface ILocale {
|
||||
[_: string]: string | ParameterizedString | ILocale;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"include": [
|
||||
"src/**/*.ts",
|
||||
"scripts/**/*.ts",
|
||||
"build.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"type": "module",
|
||||
"name": "misskey-js",
|
||||
"version": "2025.11.2-alpha.0",
|
||||
"version": "2025.11.2-alpha.1",
|
||||
"description": "Misskey SDK for JavaScript",
|
||||
"license": "MIT",
|
||||
"main": "./built/index.js",
|
||||
|
||||
@@ -7,8 +7,9 @@
|
||||
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as esbuild from 'esbuild';
|
||||
import locales from '../../locales/index.js';
|
||||
import locales from 'i18n';
|
||||
import meta from '../../package.json' with { type: 'json' };
|
||||
|
||||
const watch = process.argv[2]?.includes('watch');
|
||||
|
||||
const __dirname = fileURLToPath(new URL('.', import.meta.url));
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"lint": "pnpm typecheck && pnpm eslint"
|
||||
},
|
||||
"dependencies": {
|
||||
"i18n": "workspace:*",
|
||||
"esbuild": "0.27.0",
|
||||
"idb-keyval": "6.2.2",
|
||||
"misskey-js": "workspace:*"
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
*/
|
||||
import { get, set } from 'idb-keyval';
|
||||
import { I18n } from '@@/js/i18n.js';
|
||||
import type { Locale } from '../../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
|
||||
class SwLang {
|
||||
public cacheName = `mk-cache-${_VERSION_}`;
|
||||
|
||||
@@ -7,7 +7,7 @@ import { get } from 'idb-keyval';
|
||||
import * as Misskey from 'misskey-js';
|
||||
import type { PushNotificationDataMap } from '@/types.js';
|
||||
import type { I18n } from '@@/js/i18n.js';
|
||||
import type { Locale } from '../../../locales/index.js';
|
||||
import type { Locale } from 'i18n';
|
||||
import { createEmptyNotification, createNotification } from '@/scripts/create-notification.js';
|
||||
import { swLang } from '@/scripts/lang.js';
|
||||
import * as swos from '@/scripts/operations.js';
|
||||
|
||||
Generated
+634
-626
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ packages:
|
||||
- packages/frontend
|
||||
- packages/frontend-builder
|
||||
- packages/frontend-embed
|
||||
- packages/i18n
|
||||
- packages/icons-subsetter
|
||||
- packages/sw
|
||||
- packages/misskey-js
|
||||
|
||||
+34
-63
@@ -11,9 +11,7 @@ import * as yaml from 'js-yaml';
|
||||
import postcss from 'postcss';
|
||||
import * as terser from 'terser';
|
||||
|
||||
import { build as buildLocales } from '../locales/index.js';
|
||||
import generateDTS from '../locales/generateDTS.js';
|
||||
import meta from '../package.json' with { type: "json" };
|
||||
import { locales } from 'i18n';
|
||||
import buildTarball from './tarball.mjs';
|
||||
|
||||
const configDir = fileURLToPath(new URL('../.config', import.meta.url));
|
||||
@@ -23,86 +21,59 @@ const configPath = process.env.MISSKEY_CONFIG_YML
|
||||
? path.resolve(configDir, 'test.yml')
|
||||
: path.resolve(configDir, 'default.yml');
|
||||
|
||||
let locales = buildLocales();
|
||||
|
||||
async function loadConfig() {
|
||||
return fs.readFile(configPath, 'utf-8').then(data => yaml.load(data)).catch(() => null);
|
||||
}
|
||||
|
||||
async function copyFrontendFonts() {
|
||||
await fs.cp('./packages/frontend/node_modules/three/examples/fonts', './built/_frontend_dist_/fonts', { dereference: true, recursive: true });
|
||||
}
|
||||
|
||||
async function copyFrontendLocales() {
|
||||
generateDTS();
|
||||
|
||||
await fs.mkdir('./built/_frontend_dist_/locales', { recursive: true });
|
||||
|
||||
const v = { '_version_': meta.version };
|
||||
|
||||
for (const [lang, locale] of Object.entries(locales)) {
|
||||
await fs.writeFile(`./built/_frontend_dist_/locales/${lang}.${meta.version}.json`, JSON.stringify({ ...locale, ...v }), 'utf-8');
|
||||
}
|
||||
await fs.cp('./packages/frontend/node_modules/three/examples/fonts', './built/_frontend_dist_/fonts', { dereference: true, recursive: true });
|
||||
}
|
||||
|
||||
async function copyBackendViews() {
|
||||
await fs.cp('./packages/backend/src/server/web/views', './packages/backend/built/server/web/views', { recursive: true });
|
||||
await fs.cp('./packages/backend/src/server/web/views', './packages/backend/built/server/web/views', { recursive: true });
|
||||
}
|
||||
|
||||
async function buildBackendScript() {
|
||||
await fs.mkdir('./packages/backend/built/server/web', { recursive: true });
|
||||
await fs.mkdir('./packages/backend/built/server/web', { recursive: true });
|
||||
|
||||
for (const file of [
|
||||
'./packages/backend/src/server/web/boot.js',
|
||||
'./packages/backend/src/server/web/boot.embed.js',
|
||||
'./packages/backend/src/server/web/bios.js',
|
||||
'./packages/backend/src/server/web/cli.js',
|
||||
'./packages/backend/src/server/web/error.js',
|
||||
]) {
|
||||
let source = await fs.readFile(file, { encoding: 'utf-8' });
|
||||
source = source.replaceAll('LANGS', JSON.stringify(Object.keys(locales)));
|
||||
const { code } = await terser.minify(source, { toplevel: true });
|
||||
await fs.writeFile(`./packages/backend/built/server/web/${path.basename(file)}`, code);
|
||||
}
|
||||
for (const file of [
|
||||
'./packages/backend/src/server/web/boot.js',
|
||||
'./packages/backend/src/server/web/boot.embed.js',
|
||||
'./packages/backend/src/server/web/bios.js',
|
||||
'./packages/backend/src/server/web/cli.js',
|
||||
'./packages/backend/src/server/web/error.js',
|
||||
]) {
|
||||
let source = await fs.readFile(file, { encoding: 'utf-8' });
|
||||
source = source.replaceAll('LANGS', JSON.stringify(Object.keys(locales)));
|
||||
const { code } = await terser.minify(source, { toplevel: true });
|
||||
await fs.writeFile(`./packages/backend/built/server/web/${path.basename(file)}`, code);
|
||||
}
|
||||
}
|
||||
|
||||
async function buildBackendStyle() {
|
||||
await fs.mkdir('./packages/backend/built/server/web', { recursive: true });
|
||||
await fs.mkdir('./packages/backend/built/server/web', { recursive: true });
|
||||
|
||||
for (const file of [
|
||||
'./packages/backend/src/server/web/style.css',
|
||||
'./packages/backend/src/server/web/style.embed.css',
|
||||
'./packages/backend/src/server/web/bios.css',
|
||||
'./packages/backend/src/server/web/cli.css',
|
||||
'./packages/backend/src/server/web/error.css'
|
||||
]) {
|
||||
const source = await fs.readFile(file, { encoding: 'utf-8' });
|
||||
const { css } = await postcss([cssnano({ zindex: false })]).process(source, { from: undefined });
|
||||
await fs.writeFile(`./packages/backend/built/server/web/${path.basename(file)}`, css);
|
||||
}
|
||||
for (const file of [
|
||||
'./packages/backend/src/server/web/style.css',
|
||||
'./packages/backend/src/server/web/style.embed.css',
|
||||
'./packages/backend/src/server/web/bios.css',
|
||||
'./packages/backend/src/server/web/cli.css',
|
||||
'./packages/backend/src/server/web/error.css'
|
||||
]) {
|
||||
const source = await fs.readFile(file, { encoding: 'utf-8' });
|
||||
const { css } = await postcss([cssnano({ zindex: false })]).process(source, { from: undefined });
|
||||
await fs.writeFile(`./packages/backend/built/server/web/${path.basename(file)}`, css);
|
||||
}
|
||||
}
|
||||
|
||||
async function build() {
|
||||
await Promise.all([
|
||||
copyFrontendFonts(),
|
||||
copyFrontendLocales(),
|
||||
copyBackendViews(),
|
||||
buildBackendScript(),
|
||||
buildBackendStyle(),
|
||||
await Promise.all([
|
||||
copyFrontendFonts(),
|
||||
copyBackendViews(),
|
||||
buildBackendScript(),
|
||||
buildBackendStyle(),
|
||||
loadConfig().then(config => config?.publishTarballInsteadOfProvideRepositoryUrl && buildTarball()),
|
||||
]);
|
||||
]);
|
||||
}
|
||||
|
||||
await build();
|
||||
|
||||
if (process.argv.includes('--watch')) {
|
||||
const watcher = fs.watch('./locales');
|
||||
for await (const event of watcher) {
|
||||
const filename = event.filename?.replaceAll('\\', '/');
|
||||
if (/^[a-z]+-[A-Z]+\.yml/.test(filename)) {
|
||||
console.log(`update ${filename} ...`)
|
||||
locales = buildLocales();
|
||||
await copyFrontendLocales()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,9 @@ const fs = require('fs');
|
||||
fs.rmSync(__dirname + '/../packages/sw/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/sw/node_modules', { recursive: true, force: true });
|
||||
|
||||
fs.rmSync(__dirname + '/../packages/i18n/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/i18n/node_modules', { recursive: true, force: true });
|
||||
|
||||
fs.rmSync(__dirname + '/../packages/misskey-js/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/misskey-js/node_modules', { recursive: true, force: true });
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ const fs = require('fs');
|
||||
fs.rmSync(__dirname + '/../packages/frontend/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/frontend-embed/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/icons-subsetter/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/i18n/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/sw/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/misskey-js/built', { recursive: true, force: true });
|
||||
fs.rmSync(__dirname + '/../packages/misskey-reversi/built', { recursive: true, force: true });
|
||||
|
||||
@@ -16,6 +16,13 @@ await execa('pnpm', ['clean'], {
|
||||
stderr: process.stderr,
|
||||
});
|
||||
|
||||
// アセットのビルドで依存しているので一番最初に必要
|
||||
await execa('pnpm', ['--filter', 'i18n', 'build'], {
|
||||
cwd: _dirname + '/../',
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
});
|
||||
|
||||
await Promise.all([
|
||||
execa('pnpm', ['build-pre'], {
|
||||
cwd: _dirname + '/../',
|
||||
@@ -38,6 +45,11 @@ await Promise.all([
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
}),
|
||||
execa('pnpm', ['--filter', 'misskey-js', 'build'], {
|
||||
cwd: _dirname + '/../',
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
}),
|
||||
]);
|
||||
|
||||
execa('pnpm', ['build-pre', '--watch'], {
|
||||
@@ -88,6 +100,12 @@ execa('pnpm', ['--filter', 'misskey-js', 'watch', '--no-clean'], {
|
||||
stderr: process.stderr,
|
||||
});
|
||||
|
||||
execa('pnpm', ['--filter', 'i18n', 'watch', '--no-clean'], {
|
||||
cwd: _dirname + '/../',
|
||||
stdout: process.stdout,
|
||||
stderr: process.stderr,
|
||||
});
|
||||
|
||||
execa('pnpm', ['--filter', 'misskey-reversi', 'watch', '--no-clean'], {
|
||||
cwd: _dirname + '/../',
|
||||
stdout: process.stdout,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: syuilo and misskey-project
|
||||
* SPDX-License-Identifier: AGPL-3.0-only
|
||||
*/
|
||||
|
||||
/**
|
||||
* This script minifies JavaScript files in node_modules to reduce memory usage.
|
||||
* V8 keeps script source code in memory, so minifying reduces memory consumption.
|
||||
*
|
||||
* Usage:
|
||||
* node scripts/minify-node-modules.mjs
|
||||
*
|
||||
* Environment variables:
|
||||
* MISSKEY_MINIFY_NODE_MODULES - Set to 'true' to enable minification (default: true in production)
|
||||
* NODE_ENV - When set to 'development', minification is skipped
|
||||
*/
|
||||
|
||||
import * as fs from 'node:fs/promises';
|
||||
import * as path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as esbuild from 'esbuild';
|
||||
import glob from 'fast-glob';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
const rootDir = path.resolve(__dirname, '..');
|
||||
|
||||
// Configuration constants
|
||||
const BATCH_SIZE = 100;
|
||||
const MIN_FILE_SIZE_BYTES = 50;
|
||||
|
||||
/** @type {import('esbuild').TransformOptions} */
|
||||
const esbuildOptions = {
|
||||
loader: 'js',
|
||||
minifyWhitespace: true,
|
||||
minifyIdentifiers: true,
|
||||
minifySyntax: true,
|
||||
};
|
||||
|
||||
console.log('Minifying node_modules JavaScript files...');
|
||||
|
||||
const pnpmDir = path.join(rootDir, 'node_modules', '.pnpm');
|
||||
|
||||
// Check if pnpm directory exists
|
||||
try {
|
||||
await fs.access(pnpmDir);
|
||||
} catch {
|
||||
console.log('No pnpm node_modules found, skipping minification');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
// Find all JavaScript files in node_modules/.pnpm
|
||||
// Use followSymbolicLinks: false to avoid following symlinks to workspace packages
|
||||
const jsFiles = await glob('**/*.js', {
|
||||
cwd: pnpmDir,
|
||||
absolute: true,
|
||||
followSymbolicLinks: false,
|
||||
ignore: [
|
||||
// Ignore already minified files
|
||||
'**/*.min.js',
|
||||
// Ignore source maps
|
||||
'**/*.js.map',
|
||||
// Ignore TypeScript declaration files that might be named .js
|
||||
'**/*.d.js',
|
||||
// Ignore workspace package symlinks
|
||||
'node_modules/i18n/**',
|
||||
'node_modules/backend/**',
|
||||
'node_modules/frontend/**',
|
||||
'node_modules/frontend-embed/**',
|
||||
'node_modules/frontend-shared/**',
|
||||
'node_modules/frontend-builder/**',
|
||||
'node_modules/icons-subsetter/**',
|
||||
'node_modules/sw/**',
|
||||
'node_modules/misskey-js/**',
|
||||
'node_modules/misskey-js-type-generator/**',
|
||||
'node_modules/misskey-reversi/**',
|
||||
'node_modules/misskey-bubble-game/**',
|
||||
],
|
||||
});
|
||||
|
||||
console.log(`Found ${jsFiles.length} JavaScript files to minify`);
|
||||
|
||||
// Process files in parallel batches for efficiency
|
||||
let processed = 0;
|
||||
let errors = 0;
|
||||
|
||||
for (let i = 0; i < jsFiles.length; i += BATCH_SIZE) {
|
||||
const batch = jsFiles.slice(i, i + BATCH_SIZE);
|
||||
|
||||
await Promise.all(batch.map(async (filePath) => {
|
||||
try {
|
||||
const content = await fs.readFile(filePath, 'utf-8');
|
||||
|
||||
// Skip empty files or very small files (likely not worth minifying)
|
||||
if (content.length < MIN_FILE_SIZE_BYTES) {
|
||||
processed++;
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await esbuild.transform(content, esbuildOptions);
|
||||
|
||||
await fs.writeFile(filePath, result.code);
|
||||
processed++;
|
||||
} catch (err) {
|
||||
// Some files may have syntax that esbuild doesn't handle well, skip them
|
||||
errors++;
|
||||
if (process.env.DEBUG) {
|
||||
console.error(`Failed to minify ${filePath}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// Progress update every 10 batches
|
||||
if ((i / BATCH_SIZE) % 10 === 0) {
|
||||
console.log(`Progress: ${processed}/${jsFiles.length} files processed...`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Minification complete: ${processed} files processed, ${errors} files skipped due to errors`);
|
||||
Reference in New Issue
Block a user