Просмотр исходного кода

Merge branch 'master' into support/156162-172236-openai-feature-exluding-client-dir-biome

Futa Arai 6 месяцев назад
Родитель
Сommit
a25d69051e
26 измененных файлов с 698 добавлено и 477 удалено
  1. 2 0
      apps/app/.eslintrc.js
  2. 18 23
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginCard.tsx
  3. 22 14
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginDeleteModal.tsx
  4. 49 33
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginInstallerForm.tsx
  5. 38 28
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginsExtensionPageContents.tsx
  6. 11 8
      apps/app/src/features/growi-plugin/client/components/GrowiPluginsActivator.tsx
  7. 30 26
      apps/app/src/features/growi-plugin/client/stores/admin-plugins.tsx
  8. 1 5
      apps/app/src/features/growi-plugin/client/utils/growi-facade-utils.ts
  9. 30 25
      apps/app/src/features/growi-plugin/interfaces/growi-plugin.ts
  10. 19 18
      apps/app/src/features/growi-plugin/server/models/growi-plugin.integ.ts
  11. 45 20
      apps/app/src/features/growi-plugin/server/models/growi-plugin.ts
  12. 11 9
      apps/app/src/features/growi-plugin/server/models/vo/github-url.spec.ts
  13. 13 10
      apps/app/src/features/growi-plugin/server/models/vo/github-url.ts
  14. 62 36
      apps/app/src/features/growi-plugin/server/routes/apiv3/admin/index.ts
  15. 11 3
      apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-template-plugin-meta.ts
  16. 4 1
      apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-theme-plugin-meta.ts
  17. 42 25
      apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.integ.ts
  18. 190 123
      apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.ts
  19. 14 12
      apps/app/src/features/rate-limiter/config/index.ts
  20. 10 8
      apps/app/src/features/rate-limiter/middleware/consume-points.integ.ts
  21. 15 5
      apps/app/src/features/rate-limiter/middleware/consume-points.ts
  22. 26 22
      apps/app/src/features/rate-limiter/middleware/factory.ts
  23. 4 3
      apps/app/src/features/rate-limiter/middleware/rate-limiter-factory.ts
  24. 30 17
      apps/app/src/features/rate-limiter/utils/config-generator.ts
  25. 1 1
      apps/app/src/server/service/customize.ts
  26. 0 2
      biome.json

+ 2 - 0
apps/app/.eslintrc.js

@@ -39,11 +39,13 @@ module.exports = {
     'src/features/plantuml/**',
     'src/features/external-user-group/**',
     'src/features/page-bulk-export/**',
+    'src/features/growi-plugin/**',
     'src/features/opentelemetry/**',
     'src/features/openai/docs/**',
     'src/features/openai/interfaces/**',
     'src/features/openai/server/**',
     'src/features/openai/utils/**',
+    'src/features/rate-limiter/**',
     'src/stores-universal/**',
     'src/interfaces/**',
     'src/utils/**',

+ 18 - 23
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginCard.tsx

@@ -1,34 +1,31 @@
-import React, { useState, type JSX } from 'react';
+import Link from 'next/link';
 
 import { useTranslation } from 'next-i18next';
-import Link from 'next/link';
+import React, { type JSX, useState } from 'react';
 
 import { apiv3Put } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
 import styles from './PluginCard.module.scss';
 
 type Props = {
-  id: string,
-  name: string,
-  url: string,
-  isEnabled: boolean,
-  desc?: string,
-  onDelete: () => void,
-}
+  id: string;
+  name: string;
+  url: string;
+  isEnabled: boolean;
+  desc?: string;
+  onDelete: () => void;
+};
 
 export const PluginCard = (props: Props): JSX.Element => {
-
-  const {
-    id, name, url, isEnabled, desc,
-  } = props;
+  const { id, name, url, isEnabled, desc } = props;
 
   const { t } = useTranslation('admin');
 
   const PluginCardButton = (): JSX.Element => {
     const [_isEnabled, setIsEnabled] = useState<boolean>(isEnabled);
 
-    const onChangeHandler = async() => {
+    const onChangeHandler = async () => {
       try {
         if (_isEnabled) {
           const reqUrl = `/plugins/${id}/deactivate`;
@@ -36,16 +33,14 @@ export const PluginCard = (props: Props): JSX.Element => {
           setIsEnabled(!_isEnabled);
           const pluginName = res.data.pluginName;
           toastSuccess(t('toaster.deactivate_plugin_success', { pluginName }));
-        }
-        else {
+        } else {
           const reqUrl = `/plugins/${id}/activate`;
           const res = await apiv3Put(reqUrl);
           setIsEnabled(!_isEnabled);
           const pluginName = res.data.pluginName;
           toastSuccess(t('toaster.activate_plugin_success', { pluginName }));
         }
-      }
-      catch (err) {
+      } catch (err) {
         toastError(err);
       }
     };
@@ -69,7 +64,6 @@ export const PluginCard = (props: Props): JSX.Element => {
   };
 
   const PluginDeleteButton = (): JSX.Element => {
-
     return (
       <div>
         <button
@@ -89,7 +83,9 @@ export const PluginCard = (props: Props): JSX.Element => {
         <div className="row mb-3">
           <div className="col-9">
             <h2 className="card-title h3 border-bottom pb-2 mb-3">
-              <Link href={`${url}`} legacyBehavior>{name}</Link>
+              <Link href={`${url}`} legacyBehavior>
+                {name}
+              </Link>
             </h2>
             <p className="card-text text-muted">{desc}</p>
           </div>
@@ -104,8 +100,7 @@ export const PluginCard = (props: Props): JSX.Element => {
         </div>
       </div>
       <div className="card-footer px-5 border-top-0">
-        <p className="d-flex justify-content-between align-self-center mb-0">
-        </p>
+        <p className="d-flex justify-content-between align-self-center mb-0"></p>
       </div>
     </div>
   );

+ 22 - 14
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginDeleteModal.tsx

@@ -1,21 +1,23 @@
-import React, { useCallback } from 'react';
+import Link from 'next/link';
 
 import { useTranslation } from 'next-i18next';
-import Link from 'next/link';
-import {
-  Button, Modal, ModalHeader, ModalBody, ModalFooter,
-} from 'reactstrap';
+import type React from 'react';
+import { useCallback } from 'react';
+import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
 
 import { apiv3Delete } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
-import { useSWRxAdminPlugins, usePluginDeleteModal } from '../../../stores/admin-plugins';
+import {
+  usePluginDeleteModal,
+  useSWRxAdminPlugins,
+} from '../../../stores/admin-plugins';
 
 export const PluginDeleteModal: React.FC = () => {
-
   const { t } = useTranslation('admin');
   const { mutate } = useSWRxAdminPlugins();
-  const { data: pluginDeleteModalData, close: closePluginDeleteModal } = usePluginDeleteModal();
+  const { data: pluginDeleteModalData, close: closePluginDeleteModal } =
+    usePluginDeleteModal();
   const isOpen = pluginDeleteModalData?.isOpen;
   const id = pluginDeleteModalData?.id;
   const name = pluginDeleteModalData?.name;
@@ -25,7 +27,7 @@ export const PluginDeleteModal: React.FC = () => {
     closePluginDeleteModal();
   }, [closePluginDeleteModal]);
 
-  const onClickDeleteButtonHandler = useCallback(async() => {
+  const onClickDeleteButtonHandler = useCallback(async () => {
     const reqUrl = `/plugins/${id}/remove`;
 
     try {
@@ -34,15 +36,19 @@ export const PluginDeleteModal: React.FC = () => {
       closePluginDeleteModal();
       toastSuccess(t('toaster.remove_plugin_success', { pluginName }));
       mutate();
-    }
-    catch (err) {
+    } catch (err) {
       toastError(err);
     }
   }, [id, closePluginDeleteModal, t, mutate]);
 
   return (
     <Modal isOpen={isOpen} toggle={toggleHandler}>
-      <ModalHeader tag="h4" toggle={toggleHandler} className="text-danger" name={name}>
+      <ModalHeader
+        tag="h4"
+        toggle={toggleHandler}
+        className="text-danger"
+        name={name}
+      >
         <span>
           <span className="material-symbols-outlined">delete_forever</span>
           {t('plugins.confirm')}
@@ -50,7 +56,9 @@ export const PluginDeleteModal: React.FC = () => {
       </ModalHeader>
       <ModalBody>
         <div className="card well mt-2 p-2" key={id}>
-          <Link href={`${url}`} legacyBehavior>{name}</Link>
+          <Link href={`${url}`} legacyBehavior>
+            {name}
+          </Link>
         </div>
       </ModalBody>
       <ModalFooter>

+ 49 - 33
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginInstallerForm.tsx

@@ -1,9 +1,8 @@
-import React, { useCallback, type JSX } from 'react';
-
 import { useTranslation } from 'next-i18next';
+import React, { type JSX, useCallback } from 'react';
 
 import { apiv3Post } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
 import type { IGrowiPluginOrigin } from '../../../../interfaces';
 import { useSWRxAdminPlugins } from '../../../stores/admin-plugins';
@@ -12,40 +11,46 @@ export const PluginInstallerForm = (): JSX.Element => {
   const { mutate } = useSWRxAdminPlugins();
   const { t } = useTranslation('admin');
 
-  const submitHandler = useCallback(async(e) => {
-    e.preventDefault();
+  const submitHandler = useCallback(
+    async (e) => {
+      e.preventDefault();
 
-    const formData = e.target.elements;
+      const formData = e.target.elements;
 
-    const {
-      'pluginInstallerForm[url]': { value: url },
-      'pluginInstallerForm[ghBranch]': { value: ghBranch },
-      // 'pluginInstallerForm[ghTag]': { value: ghTag },
-    } = formData;
+      const {
+        'pluginInstallerForm[url]': { value: url },
+        'pluginInstallerForm[ghBranch]': { value: ghBranch },
+        // 'pluginInstallerForm[ghTag]': { value: ghTag },
+      } = formData;
 
-    const pluginInstallerForm: IGrowiPluginOrigin = {
-      url,
-      ghBranch: ghBranch || 'main',
-      // ghTag,
-    };
+      const pluginInstallerForm: IGrowiPluginOrigin = {
+        url,
+        ghBranch: ghBranch || 'main',
+        // ghTag,
+      };
 
-    try {
-      const res = await apiv3Post('/plugins', { pluginInstallerForm });
-      const pluginName = res.data.pluginName;
-      toastSuccess(t('toaster.install_plugin_success', { pluginName }));
-    }
-    catch (e) {
-      toastError(e);
-    }
-    finally {
-      mutate();
-    }
-  }, [mutate, t]);
+      try {
+        const res = await apiv3Post('/plugins', { pluginInstallerForm });
+        const pluginName = res.data.pluginName;
+        toastSuccess(t('toaster.install_plugin_success', { pluginName }));
+      } catch (e) {
+        toastError(e);
+      } finally {
+        mutate();
+      }
+    },
+    [mutate, t],
+  );
 
   return (
-    <form role="form" onSubmit={submitHandler}>
+    <form onSubmit={submitHandler}>
       <div className="row">
-        <label className="text-start text-md-end col-md-3 col-form-label">{t('plugins.form.label_url')}</label>
+        <label
+          className="text-start text-md-end col-md-3 col-form-label"
+          htmlFor="repoUrl"
+        >
+          {t('plugins.form.label_url')}
+        </label>
         <div className="col-md-6">
           <input
             className="form-control"
@@ -53,26 +58,37 @@ export const PluginInstallerForm = (): JSX.Element => {
             name="pluginInstallerForm[url]"
             placeholder="https://github.com/growilabs/growi-plugins-example"
             required
+            id="repoUrl"
           />
           <p className="form-text text-muted">{t('plugins.form.desc_url')}</p>
         </div>
       </div>
       <div className="row">
-        <label className="text-start text-md-end col-md-3 col-form-label">{t('plugins.form.label_branch')}</label>
+        <label
+          className="text-start text-md-end col-md-3 col-form-label"
+          htmlFor="branchName"
+        >
+          {t('plugins.form.label_branch')}
+        </label>
         <div className="col-md-6">
           <input
             className="form-control col-md-3"
             type="text"
             name="pluginInstallerForm[ghBranch]"
             placeholder="main"
+            id="branchName"
           />
-          <p className="form-text text-muted">{t('plugins.form.desc_branch')}</p>
+          <p className="form-text text-muted">
+            {t('plugins.form.desc_branch')}
+          </p>
         </div>
       </div>
 
       <div className="row my-3">
         <div className="mx-auto">
-          <button type="submit" className="btn btn-primary">{t('plugins.install')}</button>
+          <button type="submit" className="btn btn-primary">
+            {t('plugins.install')}
+          </button>
         </div>
       </div>
     </form>

+ 38 - 28
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginsExtensionPageContents.tsx

@@ -1,10 +1,13 @@
-import React, { type JSX } from 'react';
+import dynamic from 'next/dynamic';
 
 import { useTranslation } from 'next-i18next';
-import dynamic from 'next/dynamic';
+import React, { type JSX } from 'react';
 import { Spinner } from 'reactstrap';
 
-import { useSWRxAdminPlugins, usePluginDeleteModal } from '../../../stores/admin-plugins';
+import {
+  usePluginDeleteModal,
+  useSWRxAdminPlugins,
+} from '../../../stores/admin-plugins';
 
 import { PluginCard } from './PluginCard';
 import { PluginInstallerForm } from './PluginInstallerForm';
@@ -19,8 +22,10 @@ const Loading = (): JSX.Element => {
 
 export const PluginsExtensionPageContents = (): JSX.Element => {
   const { t } = useTranslation('admin');
-  const PluginDeleteModal = dynamic(() => import('./PluginDeleteModal')
-    .then(mod => mod.PluginDeleteModal), { ssr: false });
+  const PluginDeleteModal = dynamic(
+    () => import('./PluginDeleteModal').then((mod) => mod.PluginDeleteModal),
+    { ssr: false },
+  );
   const { data, mutate } = useSWRxAdminPlugins();
   const { open: openPluginDeleteModal } = usePluginDeleteModal();
 
@@ -28,7 +33,9 @@ export const PluginsExtensionPageContents = (): JSX.Element => {
     <div>
       <div className="row mb-5">
         <div className="col-lg-12">
-          <h2 className="admin-setting-header">{t('plugins.plugin_installer')}</h2>
+          <h2 className="admin-setting-header">
+            {t('plugins.plugin_installer')}
+          </h2>
           <PluginInstallerForm />
         </div>
       </div>
@@ -37,34 +44,37 @@ export const PluginsExtensionPageContents = (): JSX.Element => {
         <div className="col-lg-12">
           <h2 className="admin-setting-header">
             {t('plugins.plugin_card')}
-            <button type="button" className="btn btn-sm ms-auto grw-btn-reload" onClick={() => mutate()}>
+            <button
+              type="button"
+              className="btn btn-sm ms-auto grw-btn-reload"
+              onClick={() => mutate()}
+            >
               <span className="material-symbols-outlined">refresh</span>
             </button>
           </h2>
-          {data?.plugins == null
-            ? <Loading />
-            : (
-              <div className="d-grid gap-5">
-                { data.plugins.length === 0 && (
-                  <div>{t('plugins.plugin_is_not_installed')}</div>
-                )}
-                {data.plugins.map(plugin => (
-                  <PluginCard
-                    key={plugin._id}
-                    id={plugin._id}
-                    name={plugin.meta.name}
-                    url={plugin.origin.url}
-                    isEnabled={plugin.isEnabled}
-                    desc={plugin.meta.desc}
-                    onDelete={() => openPluginDeleteModal(plugin)}
-                  />
-                ))}
-              </div>
-            )}
+          {data?.plugins == null ? (
+            <Loading />
+          ) : (
+            <div className="d-grid gap-5">
+              {data.plugins.length === 0 && (
+                <div>{t('plugins.plugin_is_not_installed')}</div>
+              )}
+              {data.plugins.map((plugin) => (
+                <PluginCard
+                  key={plugin._id}
+                  id={plugin._id}
+                  name={plugin.meta.name}
+                  url={plugin.origin.url}
+                  isEnabled={plugin.isEnabled}
+                  desc={plugin.meta.desc}
+                  onDelete={() => openPluginDeleteModal(plugin)}
+                />
+              ))}
+            </div>
+          )}
         </div>
       </div>
       <PluginDeleteModal />
-
     </div>
   );
 };

+ 11 - 8
apps/app/src/features/growi-plugin/client/components/GrowiPluginsActivator.tsx

@@ -1,14 +1,17 @@
-import React, { useEffect, type JSX } from 'react';
+import React, { type JSX, useEffect } from 'react';
 
-import { initializeGrowiFacade, registerGrowiFacade } from '../utils/growi-facade-utils';
+import {
+  initializeGrowiFacade,
+  registerGrowiFacade,
+} from '../utils/growi-facade-utils';
 
 declare global {
   // eslint-disable-next-line vars-on-top, no-var
   var pluginActivators: {
     [key: string]: {
-      activate: () => void,
-      deactivate: () => void,
-    },
+      activate: () => void;
+      deactivate: () => void;
+    };
   };
 }
 
@@ -16,7 +19,9 @@ async function activateAll(): Promise<void> {
   initializeGrowiFacade();
 
   // register renderer options to facade
-  const { generateViewOptions, generatePreviewOptions } = await import('~/client/services/renderer/renderer');
+  const { generateViewOptions, generatePreviewOptions } = await import(
+    '~/client/services/renderer/renderer'
+  );
   registerGrowiFacade({
     markdownRenderer: {
       optionsGenerators: {
@@ -36,9 +41,7 @@ async function activateAll(): Promise<void> {
   });
 }
 
-
 export const GrowiPluginsActivator = (): JSX.Element => {
-
   useEffect(() => {
     activateAll();
   }, []);

+ 30 - 26
apps/app/src/features/growi-plugin/client/stores/admin-plugins.tsx

@@ -7,40 +7,40 @@ import { useStaticSWR } from '~/stores/use-static-swr';
 import type { IGrowiPluginHasId } from '../../interfaces';
 
 type Plugins = {
-  plugins: IGrowiPluginHasId[]
-}
+  plugins: IGrowiPluginHasId[];
+};
 
 export const useSWRxAdminPlugins = (): SWRResponse<Plugins, Error> => {
-  return useSWR(
-    '/plugins',
-    async(endpoint) => {
-      try {
-        const res = await apiv3Get<Plugins>(endpoint);
-        return res.data;
-      }
-      catch (err) {
-        throw new Error(err);
-      }
-    },
-  );
+  return useSWR('/plugins', async (endpoint) => {
+    try {
+      const res = await apiv3Get<Plugins>(endpoint);
+      return res.data;
+    } catch (err) {
+      throw new Error(err);
+    }
+  });
 };
 
 /*
  * PluginDeleteModal
  */
 type PluginDeleteModalStatus = {
-  isOpen: boolean,
-  id: string,
-  name: string,
-  url: string,
-}
+  isOpen: boolean;
+  id: string;
+  name: string;
+  url: string;
+};
 
 type PluginDeleteModalUtils = {
-  open(plugin: IGrowiPluginHasId): Promise<void>,
-  close(): Promise<void>,
-}
+  open(plugin: IGrowiPluginHasId): Promise<void>;
+  close(): Promise<void>;
+};
 
-export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Error> & PluginDeleteModalUtils => {
+export const usePluginDeleteModal = (): SWRResponse<
+  PluginDeleteModalStatus,
+  Error
+> &
+  PluginDeleteModalUtils => {
   const initialStatus: PluginDeleteModalStatus = {
     isOpen: false,
     id: '',
@@ -48,10 +48,14 @@ export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Err
     url: '',
   };
 
-  const swrResponse = useStaticSWR<PluginDeleteModalStatus, Error>('pluginDeleteModal', undefined, { fallbackData: initialStatus });
+  const swrResponse = useStaticSWR<PluginDeleteModalStatus, Error>(
+    'pluginDeleteModal',
+    undefined,
+    { fallbackData: initialStatus },
+  );
   const { mutate } = swrResponse;
 
-  const open = async(plugin) => {
+  const open = async (plugin) => {
     mutate({
       isOpen: true,
       id: plugin._id,
@@ -60,7 +64,7 @@ export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Err
     });
   };
 
-  const close = async() => {
+  const close = async () => {
     mutate(initialStatus);
   };
 

+ 1 - 5
apps/app/src/features/growi-plugin/client/utils/growi-facade-utils.ts

@@ -7,7 +7,6 @@ declare global {
   var growiFacade: GrowiFacade;
 }
 
-
 export const initializeGrowiFacade = (): void => {
   if (isServer()) {
     return;
@@ -33,8 +32,5 @@ export const registerGrowiFacade = (addedFacade: GrowiFacade): void => {
     throw new Error('This method is available only in client.');
   }
 
-  window.growiFacade = deepmerge(
-    getGrowiFacade(),
-    addedFacade,
-  );
+  window.growiFacade = deepmerge(getGrowiFacade(), addedFacade);
 };

+ 30 - 25
apps/app/src/features/growi-plugin/interfaces/growi-plugin.ts

@@ -1,39 +1,44 @@
-import type { GrowiPluginType, GrowiThemeMetadata, HasObjectId } from '@growi/core';
+import type {
+  GrowiPluginType,
+  GrowiThemeMetadata,
+  HasObjectId,
+} from '@growi/core';
 import type { TemplateSummary } from '@growi/pluginkit/dist/v4';
 
 export type IGrowiPluginOrigin = {
-  url: string,
-  ghBranch?: string,
-  ghTag?: string,
-}
+  url: string;
+  ghBranch?: string;
+  ghTag?: string;
+};
 
 export type IGrowiPlugin<M extends IGrowiPluginMeta = IGrowiPluginMeta> = {
-  isEnabled: boolean,
-  installedPath: string,
-  organizationName: string,
-  origin: IGrowiPluginOrigin,
-  meta: M,
-}
+  isEnabled: boolean;
+  installedPath: string;
+  organizationName: string;
+  origin: IGrowiPluginOrigin;
+  meta: M;
+};
 
 export type IGrowiPluginMeta = {
-  name: string,
-  types: GrowiPluginType[],
-  desc?: string,
-  author?: string,
-}
+  name: string;
+  types: GrowiPluginType[];
+  desc?: string;
+  author?: string;
+};
 
 export type IGrowiThemePluginMeta = IGrowiPluginMeta & {
-  themes: GrowiThemeMetadata[],
-}
+  themes: GrowiThemeMetadata[];
+};
 
 export type IGrowiTemplatePluginMeta = IGrowiPluginMeta & {
-  templateSummaries: TemplateSummary[],
-}
+  templateSummaries: TemplateSummary[];
+};
 
-export type IGrowiPluginMetaByType<T extends GrowiPluginType = any> = T extends 'theme'
-  ? IGrowiThemePluginMeta
-  : T extends 'template'
-    ? IGrowiTemplatePluginMeta
-    : IGrowiPluginMeta;
+export type IGrowiPluginMetaByType<T extends GrowiPluginType = any> =
+  T extends 'theme'
+    ? IGrowiThemePluginMeta
+    : T extends 'template'
+      ? IGrowiTemplatePluginMeta
+      : IGrowiPluginMeta;
 
 export type IGrowiPluginHasId = IGrowiPlugin & HasObjectId;

+ 19 - 18
apps/app/src/features/growi-plugin/server/models/growi-plugin.integ.ts

@@ -3,8 +3,7 @@ import { GrowiPluginType } from '@growi/core';
 import { GrowiPlugin } from './growi-plugin';
 
 describe('GrowiPlugin find methods', () => {
-
-  beforeAll(async() => {
+  beforeAll(async () => {
     await GrowiPlugin.insertMany([
       {
         isEnabled: false,
@@ -57,16 +56,16 @@ describe('GrowiPlugin find methods', () => {
     ]);
   });
 
-  afterAll(async() => {
+  afterAll(async () => {
     await GrowiPlugin.deleteMany({});
   });
 
   describe.concurrent('.findEnabledPlugins', () => {
-    it('shoud returns documents which isEnabled is true', async() => {
+    it('shoud returns documents which isEnabled is true', async () => {
       // when
       const results = await GrowiPlugin.findEnabledPlugins();
 
-      const pluginNames = results.map(p => p.meta.name);
+      const pluginNames = results.map((p) => p.meta.name);
 
       // then
       expect(results.length === 2).toBeTruthy();
@@ -76,24 +75,23 @@ describe('GrowiPlugin find methods', () => {
   });
 
   describe.concurrent('.findEnabledPluginsByType', () => {
-    it("shoud returns documents which type is 'template'", async() => {
+    it("shoud returns documents which type is 'template'", async () => {
       // when
-      const results = await GrowiPlugin.findEnabledPluginsByType(GrowiPluginType.Template);
+      const results = await GrowiPlugin.findEnabledPluginsByType(
+        GrowiPluginType.Template,
+      );
 
-      const pluginNames = results.map(p => p.meta.name);
+      const pluginNames = results.map((p) => p.meta.name);
 
       // then
       expect(results.length === 1).toBeTruthy();
       expect(pluginNames.includes('@growi/growi-plugin-example2')).toBeTruthy();
     });
   });
-
 });
 
-
 describe('GrowiPlugin activate/deactivate', () => {
-
-  beforeAll(async() => {
+  beforeAll(async () => {
     await GrowiPlugin.insertMany([
       {
         isEnabled: false,
@@ -110,12 +108,12 @@ describe('GrowiPlugin activate/deactivate', () => {
     ]);
   });
 
-  afterAll(async() => {
+  afterAll(async () => {
     await GrowiPlugin.deleteMany({});
   });
 
   describe('.activatePlugin', () => {
-    it('shoud update the property "isEnabled" to true', async() => {
+    it('shoud update the property "isEnabled" to true', async () => {
       // setup
       const plugin = await GrowiPlugin.findOne({});
       assert(plugin != null);
@@ -124,7 +122,9 @@ describe('GrowiPlugin activate/deactivate', () => {
 
       // when
       const result = await GrowiPlugin.activatePlugin(plugin._id);
-      const pluginAfterActivated = await GrowiPlugin.findOne({ _id: plugin._id });
+      const pluginAfterActivated = await GrowiPlugin.findOne({
+        _id: plugin._id,
+      });
 
       // then
       expect(result).toEqual('@growi/growi-plugin-example1'); // equals to meta.name
@@ -135,7 +135,7 @@ describe('GrowiPlugin activate/deactivate', () => {
   });
 
   describe('.deactivatePlugin', () => {
-    it('shoud update the property "isEnabled" to true', async() => {
+    it('shoud update the property "isEnabled" to true', async () => {
       // setup
       const plugin = await GrowiPlugin.findOne({});
       assert(plugin != null);
@@ -144,7 +144,9 @@ describe('GrowiPlugin activate/deactivate', () => {
 
       // when
       const result = await GrowiPlugin.deactivatePlugin(plugin._id);
-      const pluginAfterActivated = await GrowiPlugin.findOne({ _id: plugin._id });
+      const pluginAfterActivated = await GrowiPlugin.findOne({
+        _id: plugin._id,
+      });
 
       // then
       expect(result).toEqual('@growi/growi-plugin-example1'); // equals to meta.name
@@ -153,5 +155,4 @@ describe('GrowiPlugin activate/deactivate', () => {
       expect(pluginAfterActivated.isEnabled).toBeFalsy(); // isEnabled: false
     });
   });
-
 });

+ 45 - 20
apps/app/src/features/growi-plugin/server/models/growi-plugin.ts

@@ -1,25 +1,35 @@
 import { GrowiPluginType } from '@growi/core';
-import {
-  Schema, type Model, type Document, type Types,
-} from 'mongoose';
+import { type Document, type Model, Schema, type Types } from 'mongoose';
 
 import { getOrCreateModel } from '~/server/util/mongoose-utils';
 
 import type {
-  IGrowiPlugin, IGrowiPluginMeta, IGrowiPluginMetaByType, IGrowiPluginOrigin, IGrowiTemplatePluginMeta, IGrowiThemePluginMeta,
+  IGrowiPlugin,
+  IGrowiPluginMeta,
+  IGrowiPluginMetaByType,
+  IGrowiPluginOrigin,
+  IGrowiTemplatePluginMeta,
+  IGrowiThemePluginMeta,
 } from '../../interfaces';
 
-export interface IGrowiPluginDocument<M extends IGrowiPluginMeta = IGrowiPluginMeta> extends IGrowiPlugin<M>, Document {
-  metaJson: IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta,
+export interface IGrowiPluginDocument<
+  M extends IGrowiPluginMeta = IGrowiPluginMeta,
+> extends IGrowiPlugin<M>,
+    Document {
+  metaJson: IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta;
 }
 export interface IGrowiPluginModel extends Model<IGrowiPluginDocument> {
-  findEnabledPlugins(): Promise<IGrowiPluginDocument[]>
-  findEnabledPluginsByType<T extends GrowiPluginType>(type: T): Promise<IGrowiPluginDocument<IGrowiPluginMetaByType<T>>[]>
-  activatePlugin(id: Types.ObjectId): Promise<string>
-  deactivatePlugin(id: Types.ObjectId): Promise<string>
+  findEnabledPlugins(): Promise<IGrowiPluginDocument[]>;
+  findEnabledPluginsByType<T extends GrowiPluginType>(
+    type: T,
+  ): Promise<IGrowiPluginDocument<IGrowiPluginMetaByType<T>>[]>;
+  activatePlugin(id: Types.ObjectId): Promise<string>;
+  deactivatePlugin(id: Types.ObjectId): Promise<string>;
 }
 
-const growiPluginMetaSchema = new Schema<IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta>({
+const growiPluginMetaSchema = new Schema<
+  IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta
+>({
   name: { type: String, required: true },
   types: {
     type: [String],
@@ -46,21 +56,28 @@ const growiPluginSchema = new Schema<IGrowiPluginDocument, IGrowiPluginModel>({
   meta: growiPluginMetaSchema,
 });
 
-growiPluginSchema.statics.findEnabledPlugins = async function(): Promise<IGrowiPlugin[]> {
+growiPluginSchema.statics.findEnabledPlugins = async function (): Promise<
+  IGrowiPlugin[]
+> {
   return this.find({ isEnabled: true }).lean();
 };
 
-growiPluginSchema.statics.findEnabledPluginsByType = async function<T extends GrowiPluginType>(
-    type: T,
-): Promise<IGrowiPlugin<IGrowiPluginMetaByType<T>>[]> {
+growiPluginSchema.statics.findEnabledPluginsByType = async function <
+  T extends GrowiPluginType,
+>(type: T): Promise<IGrowiPlugin<IGrowiPluginMetaByType<T>>[]> {
   return this.find({
     isEnabled: true,
     'meta.types': { $in: type },
   }).lean();
 };
 
-growiPluginSchema.statics.activatePlugin = async function(id: Types.ObjectId): Promise<string> {
-  const growiPlugin = await this.findOneAndUpdate({ _id: id }, { isEnabled: true });
+growiPluginSchema.statics.activatePlugin = async function (
+  id: Types.ObjectId,
+): Promise<string> {
+  const growiPlugin = await this.findOneAndUpdate(
+    { _id: id },
+    { isEnabled: true },
+  );
   if (growiPlugin == null) {
     const message = 'No plugin found for this ID.';
     throw new Error(message);
@@ -69,8 +86,13 @@ growiPluginSchema.statics.activatePlugin = async function(id: Types.ObjectId): P
   return pluginName;
 };
 
-growiPluginSchema.statics.deactivatePlugin = async function(id: Types.ObjectId): Promise<string> {
-  const growiPlugin = await this.findOneAndUpdate({ _id: id }, { isEnabled: false });
+growiPluginSchema.statics.deactivatePlugin = async function (
+  id: Types.ObjectId,
+): Promise<string> {
+  const growiPlugin = await this.findOneAndUpdate(
+    { _id: id },
+    { isEnabled: false },
+  );
   if (growiPlugin == null) {
     const message = 'No plugin found for this ID.';
     throw new Error(message);
@@ -79,4 +101,7 @@ growiPluginSchema.statics.deactivatePlugin = async function(id: Types.ObjectId):
   return pluginName;
 };
 
-export const GrowiPlugin = getOrCreateModel<IGrowiPluginDocument, IGrowiPluginModel>('GrowiPlugin', growiPluginSchema);
+export const GrowiPlugin = getOrCreateModel<
+  IGrowiPluginDocument,
+  IGrowiPluginModel
+>('GrowiPlugin', growiPluginSchema);

+ 11 - 9
apps/app/src/features/growi-plugin/server/models/vo/github-url.spec.ts

@@ -1,7 +1,6 @@
 import { GitHubUrl } from './github-url';
 
 describe('GitHubUrl Constructor throws an error when the url string is', () => {
-
   it.concurrent.each`
     url
     ${'//example.com/org/repos'}
@@ -14,11 +13,9 @@ describe('GitHubUrl Constructor throws an error when the url string is', () => {
     // then
     expect(caller).toThrowError(`The specified URL is invalid. : url='${url}'`);
   });
-
 });
 
 describe('The constructor is successfully processed', () => {
-
   it('with http schemed url', () => {
     // when
     const githubUrl = new GitHubUrl('http://github.com/org/repos');
@@ -51,7 +48,6 @@ describe('The constructor is successfully processed', () => {
     expect(githubUrl.reposName).toEqual('repos');
     expect(githubUrl.branchName).toEqual('fix/bug');
   });
-
 });
 
 describe('archiveUrl()', () => {
@@ -63,12 +59,13 @@ describe('archiveUrl()', () => {
     const { archiveUrl } = githubUrl;
 
     // then
-    expect(archiveUrl).toEqual('https://github.com/org/repos/archive/refs/heads/fix%2Fbug.zip');
+    expect(archiveUrl).toEqual(
+      'https://github.com/org/repos/archive/refs/heads/fix%2Fbug.zip',
+    );
   });
 });
 
 describe('extractedArchiveDirName()', () => {
-
   describe('certain characters in the branch name are converted to slashes, and if they are consecutive, they become a single hyphen', () => {
     it.concurrent.each`
       branchName
@@ -76,7 +73,10 @@ describe('extractedArchiveDirName()', () => {
       ${'a---b'}
     `("'$branchName'", ({ branchName }) => {
       // setup
-      const githubUrl = new GitHubUrl('https://github.com/org/repos', branchName);
+      const githubUrl = new GitHubUrl(
+        'https://github.com/org/repos',
+        branchName,
+      );
 
       // when
       const { extractedArchiveDirName } = githubUrl;
@@ -93,7 +93,10 @@ describe('extractedArchiveDirName()', () => {
       ${'a_b'}
     `("'$branchName'", ({ branchName }) => {
       // setup
-      const githubUrl = new GitHubUrl('https://github.com/org/repos', branchName);
+      const githubUrl = new GitHubUrl(
+        'https://github.com/org/repos',
+        branchName,
+      );
 
       // when
       const { extractedArchiveDirName } = githubUrl;
@@ -102,5 +105,4 @@ describe('extractedArchiveDirName()', () => {
       expect(extractedArchiveDirName).toEqual(branchName);
     });
   });
-
 });

+ 13 - 10
apps/app/src/features/growi-plugin/server/models/vo/github-url.ts

@@ -1,4 +1,3 @@
-
 import sanitize from 'sanitize-filename';
 
 // https://regex101.com/r/fK2rV3/1
@@ -11,7 +10,6 @@ const sanitizeSymbolsChars = new RegExp(/[^a-zA-Z0-9_.]+/g);
 const sanitizeVersionChars = new RegExp(/^v[\d]/gi);
 
 export class GitHubUrl {
-
   private _organizationName: string;
 
   private _reposName: string;
@@ -39,19 +37,26 @@ export class GitHubUrl {
   get archiveUrl(): string {
     const encodedBranchName = encodeURIComponent(this.branchName);
     const encodedTagName = encodeURIComponent(this.tagName);
-    const zipUrl = encodedTagName !== '' ? `tags/${encodedTagName}` : `heads/${encodedBranchName}`;
-    const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/${zipUrl}.zip`, 'https://github.com');
+    const zipUrl =
+      encodedTagName !== ''
+        ? `tags/${encodedTagName}`
+        : `heads/${encodedBranchName}`;
+    const ghUrl = new URL(
+      `/${this.organizationName}/${this.reposName}/archive/refs/${zipUrl}.zip`,
+      'https://github.com',
+    );
     return ghUrl.toString();
   }
 
   get extractedArchiveDirName(): string {
     const name = this._tagName !== '' ? this._tagName : this._branchName;
-    return name.replace(sanitizeVersionChars, m => m.substring(1)).replaceAll(sanitizeSymbolsChars, '-');
+    return name
+      .replace(sanitizeVersionChars, (m) => m.substring(1))
+      .replaceAll(sanitizeSymbolsChars, '-');
   }
 
   constructor(url: string, branchName = 'main', tagName = '') {
-
-    let matched;
+    let matched: RegExpMatchArray | null;
     try {
       const ghUrl = new URL(url);
 
@@ -60,8 +65,7 @@ export class GitHubUrl {
       if (ghUrl.hostname !== 'github.com' || matched == null) {
         throw new Error();
       }
-    }
-    catch (err) {
+    } catch (err) {
       throw new Error(`The specified URL is invalid. : url='${url}'`);
     }
 
@@ -71,5 +75,4 @@ export class GitHubUrl {
     this._organizationName = sanitize(matched[1]);
     this._reposName = sanitize(matched[2]);
   }
-
 }

+ 62 - 36
apps/app/src/features/growi-plugin/server/routes/apiv3/admin/index.ts

@@ -1,9 +1,8 @@
+import { SCOPE } from '@growi/core/dist/interfaces';
 import type { Request, Router } from 'express';
 import express from 'express';
 import { body, query } from 'express-validator';
 import mongoose from 'mongoose';
-
-import { SCOPE } from '@growi/core/dist/interfaces';
 import type Crowi from '~/server/crowi';
 import { accessTokenParser } from '~/server/middlewares/access-token-parser';
 import type { ApiV3Response } from '~/server/routes/apiv3/interfaces/apiv3-response';
@@ -11,7 +10,6 @@ import type { ApiV3Response } from '~/server/routes/apiv3/interfaces/apiv3-respo
 import { GrowiPlugin } from '../../../models';
 import { growiPluginService } from '../../../services';
 
-
 const ObjectID = mongoose.Types.ObjectId;
 
 /*
@@ -22,26 +20,34 @@ const validator = {
     query('id').isMongoId().withMessage('pluginId is required'),
   ],
   pluginFormValueisRequired: [
-    body('pluginInstallerForm').isString().withMessage('pluginFormValue is required'),
+    body('pluginInstallerForm')
+      .isString()
+      .withMessage('pluginFormValue is required'),
   ],
 };
 
 module.exports = (crowi: Crowi): Router => {
-  const loginRequiredStrictly = require('~/server/middlewares/login-required')(crowi);
+  const loginRequiredStrictly = require('~/server/middlewares/login-required')(
+    crowi,
+  );
   const adminRequired = require('~/server/middlewares/admin-required')(crowi);
 
   const router = express.Router();
 
-  router.get('/', accessTokenParser([SCOPE.READ.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, async(req: Request, res: ApiV3Response) => {
-    try {
-      const data = await GrowiPlugin.find({});
-      return res.apiv3({ plugins: data });
-    }
-    catch (err) {
-      return res.apiv3Err(err);
-    }
-  });
-
+  router.get(
+    '/',
+    accessTokenParser([SCOPE.READ.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    async (req: Request, res: ApiV3Response) => {
+      try {
+        const data = await GrowiPlugin.find({});
+        return res.apiv3({ plugins: data });
+      } catch (err) {
+        return res.apiv3Err(err);
+      }
+    },
+  );
 
   /**
    * @swagger
@@ -82,18 +88,23 @@ module.exports = (crowi: Crowi): Router => {
    *                   description: The name of the installed plugin
    *
    */
-  router.post('/', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginFormValueisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.post(
+    '/',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginFormValueisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { pluginInstallerForm: formValue } = req.body;
 
       try {
         const pluginName = await growiPluginService.install(formValue);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   /**
    * @swagger
@@ -123,33 +134,43 @@ module.exports = (crowi: Crowi): Router => {
    *                   type: string
    *                   description: The name of the activated plugin
    */
-  router.put('/:id/activate', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.put(
+    '/:id/activate',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await GrowiPlugin.activatePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
-
-  router.put('/:id/deactivate', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+    },
+  );
+
+  router.put(
+    '/:id/deactivate',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await GrowiPlugin.deactivatePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   /**
    * @swagger
@@ -179,19 +200,24 @@ module.exports = (crowi: Crowi): Router => {
    *                   type: string
    *                   description: The name of the removed plugin
    */
-  router.delete('/:id/remove', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.delete(
+    '/:id/remove',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await growiPluginService.deletePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   return router;
 };

+ 11 - 3
apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-template-plugin-meta.ts

@@ -1,11 +1,19 @@
 import type { GrowiPluginValidationData } from '@growi/pluginkit';
 import { scanAllTemplates } from '@growi/pluginkit/dist/v4/server/index.cjs';
 
-import type { IGrowiPlugin, IGrowiTemplatePluginMeta } from '../../../interfaces';
+import type {
+  IGrowiPlugin,
+  IGrowiTemplatePluginMeta,
+} from '../../../interfaces';
 
-export const generateTemplatePluginMeta = async(plugin: IGrowiPlugin, validationData: GrowiPluginValidationData): Promise<IGrowiTemplatePluginMeta> => {
+export const generateTemplatePluginMeta = async (
+  plugin: IGrowiPlugin,
+  validationData: GrowiPluginValidationData,
+): Promise<IGrowiTemplatePluginMeta> => {
   return {
     ...plugin.meta,
-    templateSummaries: await scanAllTemplates(validationData.projectDirRoot, { pluginId: plugin.installedPath }),
+    templateSummaries: await scanAllTemplates(validationData.projectDirRoot, {
+      pluginId: plugin.installedPath,
+    }),
   };
 };

+ 4 - 1
apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-theme-plugin-meta.ts

@@ -2,7 +2,10 @@ import type { GrowiPluginValidationData } from '@growi/pluginkit';
 
 import type { IGrowiPlugin, IGrowiThemePluginMeta } from '../../../interfaces';
 
-export const generateThemePluginMeta = async(plugin: IGrowiPlugin, validationData: GrowiPluginValidationData): Promise<IGrowiThemePluginMeta> => {
+export const generateThemePluginMeta = async (
+  plugin: IGrowiPlugin,
+  validationData: GrowiPluginValidationData,
+): Promise<IGrowiThemePluginMeta> => {
   // TODO: validate as a theme plugin
 
   return {

+ 42 - 25
apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.integ.ts

@@ -7,27 +7,34 @@ import { GrowiPlugin } from '../../models';
 import { growiPluginService } from './growi-plugin';
 
 describe('Installing a GROWI template plugin', () => {
-
-  it('install() should success', async() => {
+  it('install() should success', async () => {
     // when
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-templates-for-office',
     });
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-templates-for-office');
     expect(count).toBe(1);
-    expect(fs.existsSync(path.join(
-      PLUGIN_STORING_PATH,
-      'growilabs',
-      'growi-plugin-templates-for-office',
-    ))).toBeTruthy();
+    expect(
+      fs.existsSync(
+        path.join(
+          PLUGIN_STORING_PATH,
+          'growilabs',
+          'growi-plugin-templates-for-office',
+        ),
+      ),
+    ).toBeTruthy();
   });
 
-  it('install() should success (re-install)', async() => {
+  it('install() should success (re-install)', async () => {
     // confirm
-    const count1 = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count1 = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
     expect(count1).toBe(1);
 
     // setup
@@ -44,38 +51,46 @@ describe('Installing a GROWI template plugin', () => {
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-templates-for-office',
     });
-    const count2 = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count2 = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-templates-for-office');
     expect(count2).toBe(1);
     expect(fs.existsSync(dummyFilePath)).toBeFalsy(); // the dummy file should be removed
   });
-
 });
 
 describe('Installing a GROWI theme plugin', () => {
-
-  it('install() should success', async() => {
+  it('install() should success', async () => {
     // when
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-theme-vivid-internet',
     });
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-theme-vivid-internet' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-theme-vivid-internet',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-theme-vivid-internet');
     expect(count).toBe(1);
-    expect(fs.existsSync(path.join(
-      PLUGIN_STORING_PATH,
-      'growilabs',
-      'growi-plugin-theme-vivid-internet',
-    ))).toBeTruthy();
+    expect(
+      fs.existsSync(
+        path.join(
+          PLUGIN_STORING_PATH,
+          'growilabs',
+          'growi-plugin-theme-vivid-internet',
+        ),
+      ),
+    ).toBeTruthy();
   });
 
-  it('findThemePlugin() should return data with metadata and manifest', async() => {
+  it('findThemePlugin() should return data with metadata and manifest', async () => {
     // confirm
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-theme-vivid-internet' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-theme-vivid-internet',
+    });
     expect(count).toBe(1);
 
     // when
@@ -87,8 +102,10 @@ describe('Installing a GROWI theme plugin', () => {
     expect(results.growiPlugin).not.toBeNull();
     expect(results.themeMetadata).not.toBeNull();
     expect(results.themeHref).not.toBeNull();
-    expect(results.themeHref
-      .startsWith('/static/plugins/growilabs/growi-plugin-theme-vivid-internet/dist/assets/style-')).toBeTruthy();
+    expect(
+      results.themeHref?.startsWith(
+        '/static/plugins/growilabs/growi-plugin-theme-vivid-internet/dist/assets/style-',
+      ),
+    ).toBeTruthy();
   });
-
 });

+ 190 - 123
apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.ts

@@ -1,20 +1,24 @@
-import fs, { readFileSync } from 'fs';
-import path from 'path';
-import { pipeline } from 'stream/promises';
-
-import { GrowiPluginType } from '@growi/core';
 import type { GrowiThemeMetadata, ViteManifest } from '@growi/core';
+import { GrowiPluginType } from '@growi/core';
 import type { GrowiPluginPackageData } from '@growi/pluginkit';
-import { importPackageJson, validateGrowiDirective } from '@growi/pluginkit/dist/v4/server/index.cjs';
+import {
+  importPackageJson,
+  validateGrowiDirective,
+} from '@growi/pluginkit/dist/v4/server/index.cjs';
 // eslint-disable-next-line no-restricted-imports
 import axios from 'axios';
+import fs, { readFileSync } from 'fs';
 import type mongoose from 'mongoose';
+import path from 'path';
+import { pipeline } from 'stream/promises';
 import unzipStream from 'unzip-stream';
 
 import loggerFactory from '~/utils/logger';
 
 import type {
-  IGrowiPlugin, IGrowiPluginOrigin, IGrowiPluginMeta,
+  IGrowiPlugin,
+  IGrowiPluginMeta,
+  IGrowiPluginOrigin,
 } from '../../../interfaces';
 import { PLUGIN_EXPRESS_STATIC_DIR, PLUGIN_STORING_PATH } from '../../consts';
 import { GrowiPlugin } from '../../models';
@@ -25,12 +29,25 @@ import { generateThemePluginMeta } from './generate-theme-plugin-meta';
 
 const logger = loggerFactory('growi:plugins:plugin-utils');
 
-export type GrowiPluginResourceEntries = [installedPath: string, href: string][];
+export type GrowiPluginResourceEntries = [
+  installedPath: string,
+  href: string,
+][];
 
-function retrievePluginManifest(growiPlugin: IGrowiPlugin): ViteManifest | undefined {
+function retrievePluginManifest(
+  growiPlugin: IGrowiPlugin,
+): ViteManifest | undefined {
   // ref: https://vitejs.dev/guide/migration.html#manifest-files-are-now-generated-in-vite-directory-by-default
-  const manifestPathByVite4 = path.join(PLUGIN_STORING_PATH, growiPlugin.installedPath, 'dist/manifest.json');
-  const manifestPath = path.join(PLUGIN_STORING_PATH, growiPlugin.installedPath, 'dist/.vite/manifest.json');
+  const manifestPathByVite4 = path.join(
+    PLUGIN_STORING_PATH,
+    growiPlugin.installedPath,
+    'dist/manifest.json',
+  );
+  const manifestPath = path.join(
+    PLUGIN_STORING_PATH,
+    growiPlugin.installedPath,
+    'dist/.vite/manifest.json',
+  );
 
   const isManifestByVite4Exists = fs.existsSync(manifestPathByVite4);
   const isManifestExists = fs.existsSync(manifestPath);
@@ -46,25 +63,23 @@ function retrievePluginManifest(growiPlugin: IGrowiPlugin): ViteManifest | undef
   return JSON.parse(manifestStr);
 }
 
-
 type FindThemePluginResult = {
-  growiPlugin: IGrowiPlugin,
-  themeMetadata: GrowiThemeMetadata,
-  themeHref: string,
-}
+  growiPlugin: IGrowiPlugin;
+  themeMetadata: GrowiThemeMetadata;
+  themeHref: string | undefined;
+};
 
 export interface IGrowiPluginService {
-  install(origin: IGrowiPluginOrigin): Promise<string>
-  findThemePlugin(theme: string): Promise<FindThemePluginResult | null>
-  retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>
-  downloadNotExistPluginRepositories(): Promise<void>
+  install(origin: IGrowiPluginOrigin): Promise<string>;
+  findThemePlugin(theme: string): Promise<FindThemePluginResult | null>;
+  retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>;
+  downloadNotExistPluginRepositories(): Promise<void>;
 }
 
 export class GrowiPluginService implements IGrowiPluginService {
-
   /*
-  * Downloading a non-existent repository to the file system
-  */
+   * Downloading a non-existent repository to the file system
+   */
   async downloadNotExistPluginRepositories(): Promise<void> {
     try {
       // find all growi plugin documents
@@ -72,69 +87,93 @@ export class GrowiPluginService implements IGrowiPluginService {
 
       // if not exists repository in file system, download latest plugin repository
       for await (const growiPlugin of growiPlugins) {
-        let pluginPath :fs.PathLike|undefined;
-        let organizationName :fs.PathLike|undefined;
+        let pluginPath: fs.PathLike | undefined;
+        let organizationName: fs.PathLike | undefined;
         try {
-          pluginPath = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugin.installedPath);
-          organizationName = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugin.organizationName);
-        }
-        catch (err) {
+          pluginPath = this.joinAndValidatePath(
+            PLUGIN_STORING_PATH,
+            growiPlugin.installedPath,
+          );
+          organizationName = this.joinAndValidatePath(
+            PLUGIN_STORING_PATH,
+            growiPlugin.organizationName,
+          );
+        } catch (err) {
           logger.error(err);
           continue;
         }
         if (fs.existsSync(pluginPath)) {
-          continue;
-        }
-        else {
+        } else {
           if (!fs.existsSync(organizationName)) {
             fs.mkdirSync(organizationName);
           }
 
           // TODO: imprv Document version and repository version possibly different.
-          const ghUrl = new GitHubUrl(growiPlugin.origin.url, growiPlugin.origin.ghBranch);
+          const ghUrl = new GitHubUrl(
+            growiPlugin.origin.url,
+            growiPlugin.origin.ghBranch,
+          );
           const { reposName, archiveUrl, extractedArchiveDirName } = ghUrl;
 
-          const zipFilePath = path.join(PLUGIN_STORING_PATH, `${extractedArchiveDirName}.zip`);
+          const zipFilePath = path.join(
+            PLUGIN_STORING_PATH,
+            `${extractedArchiveDirName}.zip`,
+          );
           const unzippedPath = PLUGIN_STORING_PATH;
-          const unzippedReposPath = path.join(PLUGIN_STORING_PATH, `${reposName}-${extractedArchiveDirName}`);
+          const unzippedReposPath = path.join(
+            PLUGIN_STORING_PATH,
+            `${reposName}-${extractedArchiveDirName}`,
+          );
 
           try {
             // download github repository to local file system
             await this.download(archiveUrl, zipFilePath);
             await this.unzip(zipFilePath, unzippedPath);
             fs.renameSync(unzippedReposPath, pluginPath);
-          }
-          catch (err) {
+          } catch (err) {
             // clean up, documents are not operated
-            if (fs.existsSync(unzippedReposPath)) await fs.promises.rm(unzippedReposPath, { recursive: true });
-            if (fs.existsSync(pluginPath)) await fs.promises.rm(pluginPath, { recursive: true });
+            if (fs.existsSync(unzippedReposPath))
+              await fs.promises.rm(unzippedReposPath, { recursive: true });
+            if (fs.existsSync(pluginPath))
+              await fs.promises.rm(pluginPath, { recursive: true });
             logger.error(err);
           }
-
-          continue;
         }
       }
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
     }
   }
 
   /*
-  * Install a plugin from URL and save it in the DB and file system.
-  */
+   * Install a plugin from URL and save it in the DB and file system.
+   */
   async install(origin: IGrowiPluginOrigin): Promise<string> {
     const ghUrl = new GitHubUrl(origin.url, origin.ghBranch);
-    const {
-      organizationName, reposName, archiveUrl, extractedArchiveDirName,
-    } = ghUrl;
+    const { organizationName, reposName, archiveUrl, extractedArchiveDirName } =
+      ghUrl;
 
     const installedPath = `${organizationName}/${reposName}`;
 
-    const organizationPath = path.join(PLUGIN_STORING_PATH, organizationName);
-    const zipFilePath = path.join(organizationPath, `${reposName}-${extractedArchiveDirName}.zip`);
-    const temporaryReposPath = path.join(organizationPath, `${reposName}-${extractedArchiveDirName}`);
-    const reposPath = path.join(organizationPath, reposName);
+    const organizationPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+    );
+    const zipFilePath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      `${reposName}-${extractedArchiveDirName}.zip`,
+    );
+    const temporaryReposPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      `${reposName}-${extractedArchiveDirName}`,
+    );
+    const reposPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      reposName,
+    );
 
     if (!fs.existsSync(organizationPath)) fs.mkdirSync(organizationPath);
 
@@ -146,22 +185,27 @@ export class GrowiPluginService implements IGrowiPluginService {
       await this.unzip(zipFilePath, organizationPath);
 
       // detect plugins
-      plugins = await GrowiPluginService.detectPlugins(origin, organizationName, reposName, { packageRootPath: temporaryReposPath });
+      plugins = await GrowiPluginService.detectPlugins(
+        origin,
+        organizationName,
+        reposName,
+        { packageRootPath: temporaryReposPath },
+      );
 
       // remove the old repository from the storing path
-      if (fs.existsSync(reposPath)) await fs.promises.rm(reposPath, { recursive: true });
+      if (fs.existsSync(reposPath))
+        await fs.promises.rm(reposPath, { recursive: true });
 
       // move new repository from temporary path to storing path.
       fs.renameSync(temporaryReposPath, reposPath);
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
       throw err;
-    }
-    finally {
+    } finally {
       // clean up
       if (fs.existsSync(zipFilePath)) await fs.promises.rm(zipFilePath);
-      if (fs.existsSync(temporaryReposPath)) await fs.promises.rm(temporaryReposPath, { recursive: true });
+      if (fs.existsSync(temporaryReposPath))
+        await fs.promises.rm(temporaryReposPath, { recursive: true });
     }
 
     try {
@@ -172,10 +216,10 @@ export class GrowiPluginService implements IGrowiPluginService {
       await this.savePluginMetaData(plugins);
 
       return plugins[0].meta.name;
-    }
-    catch (err) {
+    } catch (err) {
       // uninstall
-      if (fs.existsSync(reposPath)) await fs.promises.rm(reposPath, { recursive: true });
+      if (fs.existsSync(reposPath))
+        await fs.promises.rm(reposPath, { recursive: true });
       await this.deleteOldPluginDocument(installedPath);
 
       logger.error(err);
@@ -198,16 +242,17 @@ export class GrowiPluginService implements IGrowiPluginService {
         .then((res) => {
           if (res.status === 200) {
             const file = fs.createWriteStream(filePath);
-            res.data.pipe(file)
+            res.data
+              .pipe(file)
               .on('close', () => file.close())
               .on('finish', () => {
                 return resolve();
               });
-          }
-          else {
+          } else {
             rejects(res.status);
           }
-        }).catch((err) => {
+        })
+        .catch((err) => {
           logger.error(err);
           // eslint-disable-next-line prefer-promise-reject-errors
           rejects('Failed to download file.');
@@ -215,12 +260,17 @@ export class GrowiPluginService implements IGrowiPluginService {
     });
   }
 
-  private async unzip(zipFilePath: fs.PathLike, destPath: fs.PathLike): Promise<void> {
+  private async unzip(
+    zipFilePath: fs.PathLike,
+    destPath: fs.PathLike,
+  ): Promise<void> {
     try {
       const readZipStream = fs.createReadStream(zipFilePath);
-      await pipeline(readZipStream, unzipStream.Extract({ path: destPath.toString() }));
-    }
-    catch (err) {
+      await pipeline(
+        readZipStream,
+        unzipStream.Extract({ path: destPath.toString() }),
+      );
+    } catch (err) {
       logger.error(err);
       throw new Error('Failed to unzip.');
     }
@@ -232,32 +282,44 @@ export class GrowiPluginService implements IGrowiPluginService {
 
   // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, max-len
   private static async detectPlugins(
-      origin: IGrowiPluginOrigin, ghOrganizationName: string, ghReposName: string,
-      opts?: {
-        packageRootPath?: string,
-        parentPackageData?: GrowiPluginPackageData,
-      },
+    origin: IGrowiPluginOrigin,
+    ghOrganizationName: string,
+    ghReposName: string,
+    opts?: {
+      packageRootPath?: string;
+      parentPackageData?: GrowiPluginPackageData;
+    },
   ): Promise<IGrowiPlugin[]> {
-    const packageRootPath = opts?.packageRootPath ?? path.resolve(PLUGIN_STORING_PATH, ghOrganizationName, ghReposName);
+    const packageRootPath =
+      opts?.packageRootPath ??
+      path.resolve(PLUGIN_STORING_PATH, ghOrganizationName, ghReposName);
 
     // validate
     const validationData = await validateGrowiDirective(packageRootPath);
 
-    const packageData = opts?.parentPackageData ?? importPackageJson(packageRootPath);
+    const packageData =
+      opts?.parentPackageData ?? importPackageJson(packageRootPath);
 
     const { growiPlugin } = validationData;
     const {
-      name: packageName, description: packageDesc, author: packageAuthor,
+      name: packageName,
+      description: packageDesc,
+      author: packageAuthor,
     } = packageData;
 
     // detect sub plugins for monorepo
     if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
       const plugins = await Promise.all(
-        growiPlugin.packages.map(async(subPackagePath) => {
-          return this.detectPlugins(origin, ghOrganizationName, ghReposName, {
-            packageRootPath: path.join(packageRootPath, subPackagePath),
-            parentPackageData: packageData,
-          });
+        growiPlugin.packages.map(async (subPackagePath) => {
+          return GrowiPluginService.detectPlugins(
+            origin,
+            ghOrganizationName,
+            ghReposName,
+            {
+              packageRootPath: path.join(packageRootPath, subPackagePath),
+              parentPackageData: packageData,
+            },
+          );
         }),
       );
       return plugins.flat();
@@ -310,31 +372,32 @@ export class GrowiPluginService implements IGrowiPluginService {
 
     try {
       await GrowiPlugin.deleteOne({ _id: pluginId });
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
       throw new Error('Failed to delete plugin from GrowiPlugin documents.');
     }
 
     let growiPluginsPath: fs.PathLike | undefined;
     try {
-      growiPluginsPath = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugins.installedPath);
-    }
-    catch (err) {
+      growiPluginsPath = this.joinAndValidatePath(
+        PLUGIN_STORING_PATH,
+        growiPlugins.installedPath,
+      );
+    } catch (err) {
       logger.error(err);
-      throw new Error('The installedPath for the plugin is invalid, and the plugin has already been removed.');
+      throw new Error(
+        'The installedPath for the plugin is invalid, and the plugin has already been removed.',
+      );
     }
 
     if (growiPluginsPath && fs.existsSync(growiPluginsPath)) {
       try {
         await deleteFolder(growiPluginsPath);
-      }
-      catch (err) {
+      } catch (err) {
         logger.error(err);
         throw new Error('Failed to delete plugin repository.');
       }
-    }
-    else {
+    } else {
       logger.warn(`Plugin path does not exist : ${growiPluginsPath}`);
     }
     return growiPlugins.meta.name;
@@ -346,51 +409,56 @@ export class GrowiPluginService implements IGrowiPluginService {
 
     try {
       // retrieve plugin manifests
-      const growiPlugins = await GrowiPlugin.findEnabledPluginsByType(GrowiPluginType.Theme);
+      const growiPlugins = await GrowiPlugin.findEnabledPluginsByType(
+        GrowiPluginType.Theme,
+      );
 
-      growiPlugins
-        .forEach((growiPlugin) => {
-          const themeMetadatas = growiPlugin.meta.themes;
-          const themeMetadata = themeMetadatas.find(t => t.name === theme);
+      growiPlugins.forEach((growiPlugin) => {
+        const themeMetadatas = growiPlugin.meta.themes;
+        const themeMetadata = themeMetadatas.find((t) => t.name === theme);
 
-          // found
-          if (themeMetadata != null) {
-            matchedPlugin = growiPlugin;
-            matchedThemeMetadata = themeMetadata;
-          }
-        });
-    }
-    catch (e) {
-      logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
+        // found
+        if (themeMetadata != null) {
+          matchedPlugin = growiPlugin;
+          matchedThemeMetadata = themeMetadata;
+        }
+      });
+    } catch (e) {
+      logger.error(
+        `Could not find the theme '${theme}' from GrowiPlugin documents.`,
+        e,
+      );
     }
 
     if (matchedPlugin == null || matchedThemeMetadata == null) {
       return null;
     }
 
-    let themeHref;
+    let themeHref: string | undefined;
     try {
       const manifest = retrievePluginManifest(matchedPlugin);
       if (manifest == null) {
         throw new Error('The manifest file does not exists');
       }
       themeHref = `${PLUGIN_EXPRESS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
-    }
-    catch (e) {
+    } catch (e) {
       logger.error(`Could not read manifest file for the theme '${theme}'`, e);
     }
 
-    return { growiPlugin: matchedPlugin, themeMetadata: matchedThemeMetadata, themeHref };
+    return {
+      growiPlugin: matchedPlugin,
+      themeMetadata: matchedThemeMetadata,
+      themeHref,
+    };
   }
 
   async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
-
     const entries: GrowiPluginResourceEntries = [];
 
     try {
       const growiPlugins = await GrowiPlugin.findEnabledPlugins();
 
-      growiPlugins.forEach(async(growiPlugin) => {
+      growiPlugins.forEach(async (growiPlugin) => {
         try {
           const { types } = growiPlugin.meta;
           const manifest = await retrievePluginManifest(growiPlugin);
@@ -405,35 +473,34 @@ export class GrowiPluginService implements IGrowiPluginService {
             entries.push([growiPlugin.installedPath, href]);
           }
           // add link
-          if (types.includes(GrowiPluginType.Script) || types.includes(GrowiPluginType.Style)) {
+          if (
+            types.includes(GrowiPluginType.Script) ||
+            types.includes(GrowiPluginType.Style)
+          ) {
             const href = `${PLUGIN_EXPRESS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
             entries.push([growiPlugin.installedPath, href]);
           }
-        }
-        catch (e) {
+        } catch (e) {
           logger.warn(e);
         }
       });
-    }
-    catch (e) {
+    } catch (e) {
       logger.error('Could not retrieve GrowiPlugin documents.', e);
     }
 
     return entries;
   }
 
-  private joinAndValidatePath(baseDir: string, ...paths: string[]):fs.PathLike {
+  private joinAndValidatePath(baseDir: string, ...paths: string[]): string {
     const joinedPath = path.join(baseDir, ...paths);
     if (!joinedPath.startsWith(baseDir)) {
       throw new Error(
-        'Invalid plugin path detected! Access outside of the allowed directory is not permitted.'
-        + `\nAttempted Path: ${joinedPath}`,
+        'Invalid plugin path detected! Access outside of the allowed directory is not permitted.' +
+          `\nAttempted Path: ${joinedPath}`,
       );
     }
     return joinedPath;
   }
-
 }
 
-
 export const growiPluginService = new GrowiPluginService();

+ 14 - 12
apps/app/src/features/rate-limiter/config/index.ts

@@ -1,11 +1,11 @@
 export type IApiRateLimitConfig = {
-  method: string,
-  maxRequests: number,
-  usersPerIpProspection?: number,
-}
+  method: string;
+  maxRequests: number;
+  usersPerIpProspection?: number;
+};
 export type IApiRateLimitEndpointMap = {
-  [endpoint: string]: IApiRateLimitConfig
-}
+  [endpoint: string]: IApiRateLimitConfig;
+};
 
 export const DEFAULT_MAX_REQUESTS = 500;
 export const DEFAULT_DURATION_SEC = 60;
@@ -59,12 +59,14 @@ export const defaultConfig: IApiRateLimitEndpointMap = {
 };
 
 const isDev = process.env.NODE_ENV === 'development';
-const defaultConfigWithRegExpForDev: IApiRateLimitEndpointMap = isDev ? {
-  '/__nextjs_original-stack-frame': {
-    method: 'GET',
-    maxRequests: Infinity,
-  },
-} : {};
+const defaultConfigWithRegExpForDev: IApiRateLimitEndpointMap = isDev
+  ? {
+      '/__nextjs_original-stack-frame': {
+        method: 'GET',
+        maxRequests: Infinity,
+      },
+    }
+  : {};
 
 // default config with reg exp
 export const defaultConfigWithRegExp: IApiRateLimitEndpointMap = {

+ 10 - 8
apps/app/src/features/rate-limiter/middleware/consume-points.integ.ts

@@ -1,6 +1,10 @@
 import { faker } from '@faker-js/faker';
 
-const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: string, maxRequests: number): Promise<void> => {
+const testRateLimitErrorWhenExceedingMaxRequests = async (
+  method: string,
+  key: string,
+  maxRequests: number,
+): Promise<void> => {
   // dynamic import is used because rateLimiterMongo needs to be initialized after connecting to DB
   // Issue: https://github.com/animir/node-rate-limiter-flexible/issues/216
   const { consumePoints } = await import('./consume-points');
@@ -20,8 +24,7 @@ const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: st
         throw new Error('Exception occurred');
       }
     }
-  }
-  catch (err) {
+  } catch (err) {
     // Expect rate limit error to be called
     expect(err.message).not.toBe('Exception occurred');
     // Expect rate limit error at maxRequest + 1
@@ -29,9 +32,8 @@ const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: st
   }
 };
 
-
-describe('consume-points.ts', async() => {
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 1)', async() => {
+describe('consume-points.ts', async () => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 1)', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-1';
@@ -40,7 +42,7 @@ describe('consume-points.ts', async() => {
     await testRateLimitErrorWhenExceedingMaxRequests(method, key, maxRequests);
   });
 
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 500)', async() => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 500)', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-2';
@@ -49,7 +51,7 @@ describe('consume-points.ts', async() => {
     await testRateLimitErrorWhenExceedingMaxRequests(method, key, maxRequests);
   });
 
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: {random integer between 1 and 1000})', async() => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: {random integer between 1 and 1000})', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-3';

+ 15 - 5
apps/app/src/features/rate-limiter/middleware/consume-points.ts

@@ -1,11 +1,14 @@
-import { type RateLimiterRes } from 'rate-limiter-flexible';
+import type { RateLimiterRes } from 'rate-limiter-flexible';
 
 import { DEFAULT_MAX_REQUESTS, type IApiRateLimitConfig } from '../config';
 
 import { rateLimiterFactory } from './rate-limiter-factory';
 
-export const consumePoints = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig, maxRequestsMultiplier?: number,
+export const consumePoints = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
+  maxRequestsMultiplier?: number,
 ): Promise<RateLimiterRes | undefined> => {
   if (key == null) {
     return;
@@ -14,7 +17,11 @@ export const consumePoints = async(
   let maxRequests = DEFAULT_MAX_REQUESTS;
 
   // use customizedConfig
-  if (customizedConfig != null && (customizedConfig.method.includes(method) || customizedConfig.method === 'ALL')) {
+  if (
+    customizedConfig != null &&
+    (customizedConfig.method.includes(method) ||
+      customizedConfig.method === 'ALL')
+  ) {
     maxRequests = customizedConfig.maxRequests;
   }
 
@@ -23,7 +30,10 @@ export const consumePoints = async(
     maxRequests *= maxRequestsMultiplier;
   }
 
-  const rateLimiter = rateLimiterFactory.getOrCreateRateLimiter(key, maxRequests);
+  const rateLimiter = rateLimiterFactory.getOrCreateRateLimiter(
+    key,
+    maxRequests,
+  );
 
   const pointsToConsume = 1;
   const rateLimiterRes = await rateLimiter.consume(key, pointsToConsume);

+ 26 - 22
apps/app/src/features/rate-limiter/middleware/factory.ts

@@ -1,11 +1,14 @@
 import type { IUserHasId } from '@growi/core';
 import type { Handler, Request } from 'express';
 import md5 from 'md5';
-import { type RateLimiterRes } from 'rate-limiter-flexible';
+import type { RateLimiterRes } from 'rate-limiter-flexible';
 
 import loggerFactory from '~/utils/logger';
 
-import { DEFAULT_USERS_PER_IP_PROSPECTION, type IApiRateLimitConfig } from '../config';
+import {
+  DEFAULT_USERS_PER_IP_PROSPECTION,
+  type IApiRateLimitConfig,
+} from '../config';
 import { generateApiRateLimitConfig } from '../utils/config-generator';
 
 import { consumePoints } from './consume-points';
@@ -22,10 +25,11 @@ const apiRateLimitConfig = generateApiRateLimitConfig();
 const configWithoutRegExp = apiRateLimitConfig.withoutRegExp;
 const configWithRegExp = apiRateLimitConfig.withRegExp;
 const allRegExp = new RegExp(Object.keys(configWithRegExp).join('|'));
-const keysWithRegExp = Object.keys(configWithRegExp).map(key => new RegExp(`^${key}`));
+const keysWithRegExp = Object.keys(configWithRegExp).map(
+  (key) => new RegExp(`^${key}`),
+);
 const valuesWithRegExp = Object.values(configWithRegExp);
 
-
 /**
  * consume per user per endpoint
  * @param method
@@ -33,8 +37,10 @@ const valuesWithRegExp = Object.values(configWithRegExp);
  * @param customizedConfig
  * @returns
  */
-const consumePointsByUser = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig,
+const consumePointsByUser = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
 ): Promise<RateLimiterRes | undefined> => {
   return consumePoints(method, key, customizedConfig);
 };
@@ -46,24 +52,25 @@ const consumePointsByUser = async(
  * @param customizedConfig
  * @returns
  */
-const consumePointsByIp = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig,
+const consumePointsByIp = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
 ): Promise<RateLimiterRes | undefined> => {
-  const maxRequestsMultiplier = customizedConfig?.usersPerIpProspection ?? DEFAULT_USERS_PER_IP_PROSPECTION;
+  const maxRequestsMultiplier =
+    customizedConfig?.usersPerIpProspection ?? DEFAULT_USERS_PER_IP_PROSPECTION;
   return consumePoints(method, key, customizedConfig, maxRequestsMultiplier);
 };
 
-
 export const middlewareFactory = (): Handler => {
-
-  return async(req: Request & { user?: IUserHasId }, res, next) => {
-
+  return async (req: Request & { user?: IUserHasId }, res, next) => {
     const endpoint = req.path;
 
     // determine keys
-    const keyForUser: string | null = req.user != null
-      ? md5(`${req.user._id}_${endpoint}_${req.method}`)
-      : null;
+    const keyForUser: string | null =
+      req.user != null
+        ? md5(`${req.user._id}_${endpoint}_${req.method}`)
+        : null;
     const keyForIp: string = md5(`${req.ip}_${endpoint}_${req.method}`);
 
     // determine customized config
@@ -71,8 +78,7 @@ export const middlewareFactory = (): Handler => {
     const configForEndpoint = configWithoutRegExp[endpoint];
     if (configForEndpoint) {
       customizedConfig = configForEndpoint;
-    }
-    else if (allRegExp.test(endpoint)) {
+    } else if (allRegExp.test(endpoint)) {
       keysWithRegExp.forEach((key, index) => {
         if (key.test(endpoint)) {
           customizedConfig = valuesWithRegExp[index];
@@ -84,8 +90,7 @@ export const middlewareFactory = (): Handler => {
     if (req.user != null) {
       try {
         await consumePointsByUser(req.method, keyForUser, customizedConfig);
-      }
-      catch {
+      } catch {
         logger.error(`${req.user._id}: too many request at ${endpoint}`);
         return res.sendStatus(429);
       }
@@ -94,8 +99,7 @@ export const middlewareFactory = (): Handler => {
     // check for ip
     try {
       await consumePointsByIp(req.method, keyForIp, customizedConfig);
-    }
-    catch {
+    } catch {
       logger.error(`${req.ip}: too many request at ${endpoint}`);
       return res.sendStatus(429);
     }

+ 4 - 3
apps/app/src/features/rate-limiter/middleware/rate-limiter-factory.ts

@@ -1,10 +1,12 @@
 import { connection } from 'mongoose';
-import { type IRateLimiterMongoOptions, RateLimiterMongo } from 'rate-limiter-flexible';
+import {
+  type IRateLimiterMongoOptions,
+  RateLimiterMongo,
+} from 'rate-limiter-flexible';
 
 import { DEFAULT_DURATION_SEC } from '../config';
 
 class RateLimiterFactory {
-
   private rateLimiters: Map<string, RateLimiterMongo> = new Map();
 
   getOrCreateRateLimiter(key: string, maxRequests: number): RateLimiterMongo {
@@ -24,7 +26,6 @@ class RateLimiterFactory {
 
     return rateLimiter;
   }
-
 }
 
 export const rateLimiterFactory = new RateLimiterFactory();

+ 30 - 17
apps/app/src/features/rate-limiter/utils/config-generator.ts

@@ -1,18 +1,21 @@
 import type { IApiRateLimitEndpointMap } from '../config';
-import {
-  defaultConfig, defaultConfigWithRegExp,
-} from '../config';
+import { defaultConfig, defaultConfigWithRegExp } from '../config';
 
 const envVar = process.env;
 
 // https://regex101.com/r/aNDjmI/1
 const regExp = /^API_RATE_LIMIT_(\w+)_ENDPOINT(_WITH_REGEXP)?$/;
 
-const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, targets: string[], withRegExp: boolean): IApiRateLimitEndpointMap => {
+const generateApiRateLimitConfigFromEndpoint = (
+  envVar: NodeJS.ProcessEnv,
+  targets: string[],
+  withRegExp: boolean,
+): IApiRateLimitEndpointMap => {
   const apiRateLimitConfig: IApiRateLimitEndpointMap = {};
   targets.forEach((target) => {
-
-    const endpointKey = withRegExp ? `API_RATE_LIMIT_${target}_ENDPOINT_WITH_REGEXP` : `API_RATE_LIMIT_${target}_ENDPOINT`;
+    const endpointKey = withRegExp
+      ? `API_RATE_LIMIT_${target}_ENDPOINT_WITH_REGEXP`
+      : `API_RATE_LIMIT_${target}_ENDPOINT`;
 
     const endpoint = envVar[endpointKey];
 
@@ -43,26 +46,26 @@ const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, targe
 };
 
 type ApiRateLimitConfigResult = {
-  'withoutRegExp': IApiRateLimitEndpointMap,
-  'withRegExp': IApiRateLimitEndpointMap
-}
+  withoutRegExp: IApiRateLimitEndpointMap;
+  withRegExp: IApiRateLimitEndpointMap;
+};
 
 export const generateApiRateLimitConfig = (): ApiRateLimitConfigResult => {
-
   const apiRateConfigTargets: string[] = [];
   const apiRateConfigTargetsWithRegExp: string[] = [];
   Object.keys(envVar).forEach((key) => {
     const result = key.match(regExp);
 
-    if (result == null) { return null }
+    if (result == null) {
+      return null;
+    }
 
     const target = result[1];
     const isWithRegExp = result[2] != null;
 
     if (isWithRegExp) {
       apiRateConfigTargetsWithRegExp.push(target);
-    }
-    else {
+    } else {
       apiRateConfigTargets.push(target);
     }
   });
@@ -72,17 +75,27 @@ export const generateApiRateLimitConfig = (): ApiRateLimitConfigResult => {
   apiRateConfigTargetsWithRegExp.sort();
 
   // get config
-  const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(envVar, apiRateConfigTargets, false);
-  const apiRateLimitConfigWithRegExp = generateApiRateLimitConfigFromEndpoint(envVar, apiRateConfigTargetsWithRegExp, true);
+  const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(
+    envVar,
+    apiRateConfigTargets,
+    false,
+  );
+  const apiRateLimitConfigWithRegExp = generateApiRateLimitConfigFromEndpoint(
+    envVar,
+    apiRateConfigTargetsWithRegExp,
+    true,
+  );
 
   const config = { ...defaultConfig, ...apiRateLimitConfig };
-  const configWithRegExp = { ...defaultConfigWithRegExp, ...apiRateLimitConfigWithRegExp };
+  const configWithRegExp = {
+    ...defaultConfigWithRegExp,
+    ...apiRateLimitConfigWithRegExp,
+  };
 
   const result: ApiRateLimitConfigResult = {
     withoutRegExp: config,
     withRegExp: configWithRegExp,
   };
 
-
   return result;
 };

+ 1 - 1
apps/app/src/server/service/customize.ts

@@ -36,7 +36,7 @@ class CustomizeService implements S2sMessageHandlable {
 
   theme: string;
 
-  themeHref: string;
+  themeHref: string | undefined;
 
   forcedColorScheme?: ColorScheme;
 

+ 0 - 2
biome.json

@@ -30,9 +30,7 @@
       "!apps/app/public/**",
       "!apps/app/src/client/**",
       "!apps/app/src/components/**",
-      "!apps/app/src/features/growi-plugin/**",
       "!apps/app/src/features/openai/client/**",
-      "!apps/app/src/features/rate-limiter/**",
       "!apps/app/src/models/**",
       "!apps/app/src/pages/**",
       "!apps/app/src/server/**",