\documentclass[uplatex,dvipdfmx,ja = standard,a4paper,11pt]{bxjsarticle}
\usepackage{array}
\usepackage{tabularx}
\usepackage{float}
\usepackage{mermaid}
\usepackage[hidelinks]{hyperref}
\usepackage{bxghost}	
\usepackage{bxtexlogo}
\usepackage{listings,jvlisting}
\usepackage{xcolor}

\lstset{
  basicstyle={\ttfamily},
  identifierstyle={\small},
  commentstyle={\small\itshape},
  keywordstyle={\small\bfseries},
  ndkeywordstyle={\small},
  stringstyle={\small\ttfamily},
  frame={tb},
  breaklines=true,
  columns=[l]{fullflexible},
  numbers=left,
  xrightmargin=0zw,
  xleftmargin=3zw,
  numberstyle={\scriptsize},
  stepnumber=1,
  numbersep=1zw,
  lineskip=-0.5ex
}

\makeatletter
\def\m@syu@space@char{^^`}

\def\m@syu@string#1{%
	\@tfor\m@syu@member:=#1\do{%
		\ifx\m@syu@member\m@syu@space@char %%%{} も{ }も空白とみなすために必要
			\textvisiblespace
		\else
			\ifx\m@syu@member\empty
				\textvisiblespace
			\else\m@syu@member\fi
		\fi}%
}

\def\m@syu@removespace#1{%%%% #1の空白除去を\m@syu@removedspaceに格納
	\def\m@syu@removedspace{}%
	\@tfor\m@syu@member:=#1\do{%
		\ifx\m@syu@member\empty
		\edef\m@syu@removedspace{\m@syu@removedspace\m@syu@member\m@syu@space@char}%
	\else
		\edef\m@syu@removedspace{\m@syu@removedspace\m@syu@member}%
	\fi}%
}	

\newcommand{\cmd}[2][\texttt]{\eghostguarded{#1{\symbol{92}\m@syu@string{#2}}}}
\makeatother
% 表の全幅レイアウト: 第2列を折り返し（X）
\newcolumntype{L}{>{\raggedright\arraybackslash}X}

\title{\texttt{mermaid} パッケージ（\texttt{mermaid.sty}）}
\author{安藤 遼哉（Ryoya Ando）\\\url{https://ryoya9826.github.io/}}
\date{\today}

\begin{document}
\maketitle

\begin{abstract}
\noindent
\texttt{mermaid.sty} は \texttt{shellesc} や \verb|\write18| を介して Mermaid CLI を起動し、\LaTeXe{} におけるコンパイル時に Mermaid 図をレンダリングして PDF として取り込むパッケージです。
\upLaTeX、\pdfLaTeX、\LuaLaTeX などのエンジンで利用可能です。
Mermaid 図のレンダリングには、Mermaid CLI（\texttt{mmdc} など）とヘッドレス Chromium（Puppeteer）が必要です。また、コンパイルの際は必ずシェルエスケープ（\verb|-shell-escape|）を有効にしてください。
\end{abstract}

\section{動作条件}

\noindent
\begin{tabularx}{\textwidth}{@{}>{\raggedright\arraybackslash}p{0.22\textwidth}L@{}}
  \hline
  \textbf{項目} & \textbf{条件} \\
  \hline
  フォーマット &
    \LaTeXe \\
  シェルエスケープ &
    \texttt{-shell-escape}（\texttt{shellesc} / \verb|\write18| 経由で CLI を起動） \\
  外部ツール &
    Mermaid CLI（\texttt{mmdc}）\\
  \hline
\end{tabularx}

\medskip

環境内に Mermaid CLI が存在しない場合でも、\texttt{mermaid.sty} が \texttt{mmdc} などを自動的にインストールすることはありません。
Mermaid CLI を一般的な方法でインストールするには、\textbf{Node.js} と \texttt{npm}（または \texttt{npx}）を利用します。
ただし、パッケージオプションの \texttt{Renderer} に \texttt{npx -y @mermaid-js/mermaid-cli …} のように \textbf{\texttt{npx -y}} を含むコマンドを指定した場合は、\texttt{npx} の仕様により、必要に応じてパッケージの\textbf{取得およびインストール}が動的に行われます（ネットワーク通信を伴います）。

コンパイルを実行する際、\texttt{Renderer} オプションで別のコマンドを指定しない限り、既定のレンダラである \texttt{mmdc} へのパスが通っており、実行可能である必要があります（別のコマンドを指定した場合も同様です）。
なお、Mermaid CLI はヘッドレス Chromium（Puppeteer）に依存しています。詳細は Mermaid CLI の公式ドキュメントを参照してください。

ログは \texttt{\string\typeout} で \texttt{[mermaid]} プレフィックス付きで出力されます。トラブル時は \texttt{mermaid/} 下の \texttt{.err} を確認してください。

\section{ライセンスとソース}

\LaTeX{} Project Public License（LPPL）1.3c 以降の下で配布されます。

ソースと issue: \url{https://github.com/ryoya9826/ltMermaid}

\section{使い方}

\subsection{最小構成の文書}

\begin{lstlisting}
\documentclass{article}
\usepackage{mermaid}

\begin{document}
\begin{mermaid}
flowchart LR
  A --> B
\end{mermaid}
\end{document}
\end{lstlisting}

コンパイル例:
\begin{verbatim}
pdflatex -shell-escape yourfile.tex
lualatex -shell-escape yourfile.tex
uplatex -shell-escape yourfile.tex && dvipdfmx yourfile.dvi
\end{verbatim}

\subsection{レイアウトの調整（任意）}

既定では \texttt{adjustbox} で取り込んだ図をスケールします。例:
\begin{lstlisting}
\MermaidAdjustBoxOpts{max width=0.8\linewidth,center}
\MermaidAdjustBoxOpts{max width=0.9\linewidth,center,valign=T}
\end{lstlisting}

\subsection{Beamer}

\texttt{beamer} クラスでも利用できます。\texttt{mermaid} 環境を含む各フレームには
\texttt{fragile} オプションが必要です（環境が \texttt{fancyvrb} に依存するため）。
例: \verb|\begin{frame}[fragile]{図}|。

\begin{lstlisting}
\documentclass{beamer}
\usepackage{mermaid}

\begin{document}
\begin{frame}[fragile]{Mermaid}
\begin{mermaid}
flowchart LR
  A --> B
\end{mermaid}
\end{frame}
\end{document}
\end{lstlisting}

\section{パッケージオプション（省略可能）}

\begin{itemize}
\small
\item \textbf{\texttt{Renderer}}:
  利用するレンダラコマンド。省略時は \texttt{mmdc} が使用されます。
  \texttt{npx -y @mermaid-js/mermaid-cli} のように、使用するコマンドを明示的に指定することも可能です。
\end{itemize}

\section{ユーザー命令}

\begin{itemize}
\small
\item \textbf{\cmd{MermaidRendererOptions}\texttt{\{...\}}:}
  \texttt{-i} / \texttt{-o} の前に付ける追加の CLI 引数（PDF fit 有効時は組み込みの \texttt{-f} の後に結合）。
\item \textbf{\cmd{MermaidNoPdfFit}:}
  \texttt{mmdc} の \texttt{-f} / \texttt{--pdfFit} を無効化（デフォルトでは \emph{有効}）。
\item \textbf{\cmd{MermaidAdjustBoxOpts}\texttt{\{...\}}:}
  \cmd{includegraphics} を囲む \texttt{adjustbox} のキー一式（デフォルトでは
  \texttt{max width=0.9}\cmd{linewidth}\texttt{,center}）。
\item \textbf{\cmd{MermaidGraphicsOpts}\texttt{\{...\}}:}
  \cmd{includegraphics} への追加キー（回転、\texttt{trim} など）。
  幅は通常 \cmd{MermaidAdjustBoxOpts} で指定します。
\end{itemize}

\section{出力ファイル}

中間ファイルである \texttt{.mmd} と、レンダリング結果の \texttt{.pdf} は、コンパイルを実行したディレクトリ内の \texttt{mermaid/} フォルダに書き出されます。ファイル名には \texttt{\jobname-mermaid-1.mmd} や \texttt{\jobname-mermaid-1.pdf} のように、\texttt{\jobname}（ジョブ名）と通し番号が付与されます。

\section{図の例}

\textbf{左}に入力した \texttt{mermaid} 環境のソース、
\textbf{右}にレンダリング結果を示します。

\begin{figure}[H]
\begin{minipage}[t]{0.42\textwidth}
\vspace{0pt}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
\begin{mermaid}
flowchart TB
  subgraph client["クライアント層"]
    WEB["ブラウザ / SPA"]
    CLI["CLI / バッチ"]
  end
  subgraph edge["エッジ"]
    GW{{API Gateway}}
  end
  subgraph svc["サービス層"]
    AUTH["認証"]
    API["業務 API"]
    WORK["ワーカー"]
  end
  subgraph store["データ"]
    DB[("PostgreSQL")]
    CACHE[("Redis")]
    QUEUE["ジョブキュー"]
  end
  WEB --> GW
  CLI --> GW
  GW --> AUTH
  GW --> API
  API --> WORK
  API --> DB
  API --> CACHE
  WORK --> QUEUE
  WORK --> DB
\end{mermaid}
\end{lstlisting}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.54\textwidth}
\vspace{0pt}\centering
\begin{mermaid}
flowchart TB
  subgraph client["クライアント層"]
    WEB["ブラウザ / SPA"]
    CLI["CLI / バッチ"]
  end
  subgraph edge["エッジ"]
    GW{{API Gateway}}
  end
  subgraph svc["サービス層"]
    AUTH["認証"]
    API["業務 API"]
    WORK["ワーカー"]
  end
  subgraph store["データ"]
    DB[("PostgreSQL")]
    CACHE[("Redis")]
    QUEUE["ジョブキュー"]
  end
  WEB --> GW
  CLI --> GW
  GW --> AUTH
  GW --> API
  API --> WORK
  API --> DB
  API --> CACHE
  WORK --> QUEUE
  WORK --> DB
\end{mermaid}
\end{minipage}
\caption{多層アーキテクチャ（サブグラフ・各種ノード形）}
\end{figure}

\begin{figure}[H]
\begin{minipage}[t]{0.42\textwidth}
\vspace{0pt}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
\begin{mermaid}
sequenceDiagram
  autonumber
  actor U as 利用者
  participant B as ブラウザ
  participant A as 認証API
  participant S as 業務API
  participant D as DB
  U->>B: ログイン
  B->>+A: POST /token
  A->>D: ユーザー検証
  D-->>A: レコード
  A-->>-B: JWT
  B->>+S: GET /orders（Bearer）
  S->>A: トークン検証
  A-->>S: クレーム
  S->>D: SELECT
  D-->>S: 行集合
  S-->>-B: 200 JSON
  B-->>U: 一覧表示
\end{mermaid}
\end{lstlisting}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.54\textwidth}
\vspace{0pt}\centering
\begin{mermaid}
sequenceDiagram
  autonumber
  actor U as 利用者
  participant B as ブラウザ
  participant A as 認証API
  participant S as 業務API
  participant D as DB
  U->>B: ログイン
  B->>+A: POST /token
  A->>D: ユーザー検証
  D-->>A: レコード
  A-->>-B: JWT
  B->>+S: GET /orders（Bearer）
  S->>A: トークン検証
  A-->>S: クレーム
  S->>D: SELECT
  D-->>S: 行集合
  S-->>-B: 200 JSON
  B-->>U: 一覧表示
\end{mermaid}
\end{minipage}
\caption{シーケンス図（番号・非同期矢印・複数参加者）}
\end{figure}

\begin{figure}[H]
\begin{minipage}[t]{0.42\textwidth}
\vspace{0pt}
\begin{lstlisting}[basicstyle=\footnotesize\ttfamily]
\begin{mermaid}
stateDiagram-v2
  [*] --> Draft: 新規作成
  Draft --> Review: 提出
  Review --> Draft: 差し戻し
  Review --> Approved: 承認
  Approved --> Published: 公開
  Published --> Archived: 終了
  Review --> Rejected: 却下
  Rejected --> [*]
  Archived --> [*]
\end{mermaid}
\end{lstlisting}
\end{minipage}%
\hfill
\begin{minipage}[t]{0.54\textwidth}
\vspace{0pt}\centering
\begin{mermaid}
stateDiagram-v2
  [*] --> Draft: 新規作成
  Draft --> Review: 提出
  Review --> Draft: 差し戻し
  Review --> Approved: 承認
  Approved --> Published: 公開
  Published --> Archived: 終了
  Review --> Rejected: 却下
  Rejected --> [*]
  Archived --> [*]
\end{mermaid}
\end{minipage}
\caption{状態遷移（\texttt{stateDiagram-v2}）}
\end{figure}

\section{更新履歴}

\begin{description}
\item[Version 1.0（2026-04-16）] \texttt{mermaid.sty} 安定版。
\item[Version 0.1（2026-04-15）] 初版（v1.0 に置き換え）。
\end{description}

\end{document}
