2.98.0 — Performance du chargement initial (#240, lots #241–#245) #116

Merged
bruno merged 9 commits from feat/perf-chargement-240 into main 2026-11-30 19:57:38 -05:00
29 changed files with 898 additions and 85 deletions
+13 -1
View File
@@ -6,7 +6,7 @@ Format basé sur [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/),
et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
> **En cours de développement** : les changements à venir sont listés dans la section
> [Unreleased](#unreleased). La dernière version livrée est **2.97.0**.
> [Unreleased](#unreleased). La dernière version livrée est **2.98.0**.
---
@@ -14,6 +14,18 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [2.98.0] — 2026-11-30
### Ajouté
- **Audit de chargement versionné (#241, épopée perf #240)** : `scripts/audit_chargement.py` (stdlib seule) mesure TTFB/total médians, en-têtes de cache et graphe de modules ES statiques (mode distant ou `--local`) ; budget de chargement figé dans `docs/features/perf-chargement-240.md` (affichage utile ÷3, JS initial −50 %, `/api/dashboard` répété < 50 ms).
- **Bootstrap rapide des liens profonds (#244)** : à l'arrivée sur un lien `#file=` (y compris au retour d'un SSO), le fichier cible s'ouvre dès l'authentification faite, avant le chargement des réglages des vaults, de la liste des vaults et des tags ; le chargement complet suit sans recouvrir la cible. `#folder=` inchangé (il a besoin de l'arborescence chargée).
- **Cache mémoire de `/api/dashboard` (#245)** : résultat mis en cache 60 s par utilisateur et invalidé dès que le watcher signale un changement d'index — les appels répétés ne parcourent plus les 10 987 fichiers à chaque fois.
- **Chargement paresseux des modules lourds et des CDN (#243)** : Mermaid, vue graphe, Excalidraw, now-playing, plugins, push et l'éditeur mobile sont chargés par `import()` dynamique à la première utilisation (ou en tâche de fond) au lieu du graphe statique initial (41 → 34 modules, −12,5 % en octets bruts — le cœur couplé viewer/ui reste statique, voir fiche #240) ; les 13 scripts CDN du `<head>` (Mermaid 745 Ko, highlight.js + 10 langages, Lucide) sont retirés : highlight arrive au premier bloc de code (base + langage détecté), Lucide au premier appel d'icônes, Mermaid au premier diagramme.
- **Cache versionné des statiques (#242)** : les URL `/static/…` de `index.html` et les imports des modules ES sont réécrits au service avec `?v=<VERSION>` (`backend/static_versioning.py`, serveur `VersionedStaticFiles`) ; `Cache-Control: immutable` (1 an) uniquement pour les URL à la version courante, `no-cache` sinon — le cache long ne peut plus servir un build périmé. Le service worker porte un nom de cache à la version courante (ancien cache abandonné à l'activation). La règle Cloudflare « HIT » sur les statiques versionnées reste une action d'exploitation hors code.
---
## [2.97.0] — 2026-11-30
### Ajouté
+3 -3
View File
@@ -4,7 +4,7 @@
**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.
[![Version](https://img.shields.io/badge/Version-2.97.0-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.98.0-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
@@ -981,8 +981,8 @@ Ce projet est sous licence **MIT** — voir le fichier [LICENSE](LICENSE) pour l
## 📝 Changelog
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.97.0).
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.98.0).
---
*Projet : ObsiGate | Version : 2.97.0 | Dernière mise à jour : Septembre 2026*
*Projet : ObsiGate | Version : 2.98.0 | Dernière mise à jour : Septembre 2026*
+3 -3
View File
@@ -2,7 +2,7 @@
**Ultra-light web gateway for your Obsidian vaults** — Access, browse, and search all your Obsidian notes from any device via a modern, responsive web interface.
[![Version](https://img.shields.io/badge/Version-2.97.0-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.98.0-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
@@ -1156,8 +1156,8 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
## 📝 Changelog
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.97.0).
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.98.0).
---
*Project: ObsiGate | Version: 2.97.0 | Last updated: September 2026*
*Project: ObsiGate | Version: 2.98.0 | Last updated: September 2026*
+1 -1
View File
@@ -1 +1 @@
2.97.0
2.98.0
+65 -10
View File
@@ -70,6 +70,11 @@ async def _on_vault_change(events: list):
Processes each event (create/modify/delete/move) and updates the index
incrementally, then broadcasts SSE notifications.
"""
# #245 : tout changement d'index invalide le cache du dashboard.
from backend.routers.config import invalidate_dashboard_cache
invalidate_dashboard_cache()
updated_vaults = set()
changes = []
@@ -245,12 +250,17 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
yield patched
response.body_iterator = _docs_body()
# Static assets are NOT content-hashed, so they must revalidate:
# ``immutable``/long max-age made Cloudflare and mobile browsers serve
# a stale build for a year (the service worker cache compounded it).
# ``no-cache`` keeps caching but forces revalidation (ETag/Last-Modified).
# Cache des statiques (#242) : ``immutable`` UNIQUEMENT pour les
# URL versionnées ``?v=<VERSION courante>`` (voir
# backend.static_versioning) — une nouvelle version change toutes
# les URL, donc le piège historique (cache long sans versionnage
# → build périmé servi un an) ne peut pas se reproduire. Sans
# ``?v=`` valide : ``no-cache`` (revalidation ETag/Last-Modified).
if request.url.path.startswith("/static/"):
response.headers["Cache-Control"] = "no-cache"
from backend.static_versioning import cache_control_for
response.headers["Cache-Control"] = cache_control_for(
request.url.path, request.url.query)
return response
@@ -927,6 +937,10 @@ def _index_html(request: Request) -> str:
from backend.draco_config import urls_publiques
html = (FRONTEND_DIR / "index.html").read_text(encoding="utf-8")
# #242 : URL statiques versionnées (?v=<VERSION>) — cache long sûr.
from backend.static_versioning import rewrite_static_urls
html = rewrite_static_urls(html)
script = (
"<script>window.DRACO_URLS = "
+ _json.dumps(urls_publiques()).replace("<", "\\u003c")
@@ -947,17 +961,58 @@ def _index_html(request: Request) -> str:
html = html.replace("</header>", "</header>" + fragment, 1)
return inject_csp_nonce(html, request.state.csp_nonce)
class VersionedStaticFiles(StaticFiles):
"""Statiques dont les modules ES sont réécrits au service (#242).
Les spécificateurs d'import relatifs des fichiers ``.js`` reçoivent
``?v=<VERSION>`` : le navigateur ne demande donc que des URL
versionnées, de proche en proche dans le graphe de modules.
``Cache-Control`` reste posé par ``SecurityHeadersMiddleware``.
"""
async def get_response(self, path, scope): # type: ignore[override]
if path.endswith(".js"):
from backend.static_versioning import rewrite_js_imports
full = Path(self.directory) / path
try:
resolved = full.resolve()
root = Path(self.directory).resolve()
if resolved.is_file() and resolved.is_relative_to(root):
source = resolved.read_text(encoding="utf-8", errors="replace")
from fastapi.responses import PlainTextResponse
return PlainTextResponse(
rewrite_js_imports(source),
media_type="application/javascript",
)
except OSError:
pass # repli : service statique standard (404 propre inclus)
return await super().get_response(path, scope)
if FRONTEND_DIR.exists():
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (no-cache).
app.mount("/static", StaticFiles(directory=str(FRONTEND_DIR)), name="static")
# ``Cache-Control`` for /static is set by SecurityHeadersMiddleware (#242).
app.mount("/static", VersionedStaticFiles(directory=str(FRONTEND_DIR)), name="static")
@app.get("/sw.js")
async def serve_service_worker():
"""Serve the service worker for PWA support."""
"""Serve the service worker for PWA support.
#242 : le nom de cache du SW embarque la version courante
(``__OBSIGATE_SW_VERSION__`` remplacé ici) — à chaque release,
l'ancien cache est abandonné à l'activation.
"""
sw_file = FRONTEND_DIR / "sw.js"
if sw_file.exists():
return FileResponse(
sw_file,
from backend.version import get_version
content = sw_file.read_text(encoding="utf-8").replace(
"__OBSIGATE_SW_VERSION__", f"v{get_version()}")
from fastapi.responses import PlainTextResponse
return PlainTextResponse(
content,
media_type="application/javascript",
headers={
"Cache-Control": "no-cache, no-store, must-revalidate",
+36
View File
@@ -233,9 +233,45 @@ async def api_diagnostics(current_user=Depends(require_admin)):
}
# ---------------------------------------------------------------------------
# Cache mémoire du dashboard (#245, épopée perf #240)
#
# ``GET /api/dashboard`` parcourait tous les fichiers de tous les vaults
# à chaque appel (10 987 fichiers en prod). Le résultat est mis en cache
# 60 s par utilisateur (l'accès aux vaults dépend de l'utilisateur) et
# invalidé dès que le watcher signale un changement (voir
# ``_on_vault_change`` dans ``backend.main``) ou après modification de
# l'index par les routes d'écriture via ``invalidate_dashboard_cache``.
# ---------------------------------------------------------------------------
import time as _time
_DASHBOARD_TTL_SECONDS = 60.0
_dashboard_cache: dict[str, tuple[float, dict]] = {}
def invalidate_dashboard_cache() -> None:
"""Vider le cache du dashboard (changement d'index signalé)."""
_dashboard_cache.clear()
def _dashboard_cache_key(current_user) -> str:
return str(getattr(current_user, "username", None) or getattr(current_user, "id", "") or "anon")
@router.get("/api/dashboard", response_model=DashboardResponse)
async def api_dashboard(current_user=Depends(require_auth)):
"""Aggregated dashboard statistics across all accessible vaults."""
key = _dashboard_cache_key(current_user)
cached = _dashboard_cache.get(key)
if cached and (_time.monotonic() - cached[0]) < _DASHBOARD_TTL_SECONDS:
return cached[1]
result = _compute_dashboard(current_user)
_dashboard_cache[key] = (_time.monotonic(), result)
return result
def _compute_dashboard(current_user) -> dict:
"""Calcul effectif des statistiques du dashboard (sans cache)."""
vault_stats = []
total_files = 0
total_tags = set()
+74
View File
@@ -0,0 +1,74 @@
"""Cache versionné des statiques (#242, épopée perf #240).
Mécanisme sans étape de build (règle du dépôt) :
- les URL ``/static/…`` référencées par ``index.html`` sont réécrites
au service avec ``?v=<VERSION>`` (:func:`rewrite_static_urls`) ;
- les spécificateurs d'import relatifs des modules ES servis sont
réécrits de la même façon (:func:`rewrite_js_imports`), donc tout le
graphe de modules est demandé en URL versionnées, de proche en
proche ;
- l'en-tête ``Cache-Control`` n'autorise le cache long
(``immutable``) **que** pour une requête dont le ``?v=`` vaut la
version courante (:func:`cache_control_for`) — une nouvelle version
change toutes les URL, donc un cache long ne peut plus jamais
servir un build périmé (l'incident historique du ``max-age`` sans
versionnage).
"""
from __future__ import annotations
import re
from backend.version import get_version
IMMUTABLE_CACHE_CONTROL = "public, max-age=31536000, immutable"
NO_CACHE = "no-cache"
_STATIC_URL_RE = re.compile(r"((?:src|href)=[\"'])(/static/[^\"'?#]+)([\"'])")
_JS_SPEC_RE = re.compile(
r"((?:from\s+|import\s*\(\s*|import\s+)['\"])(\.{1,2}/[^'\"]+?\.js)(['\"])"
)
def current_version() -> str:
"""Version courante (source unique : fichier ``VERSION``)."""
return get_version()
def rewrite_static_urls(html: str, version: str | None = None) -> str:
"""Ajouter ``?v=<version>`` aux URL ``/static/…`` d'un document HTML."""
v = version if version is not None else current_version()
return _STATIC_URL_RE.sub(
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", html)
def rewrite_js_imports(source: str, version: str | None = None) -> str:
"""Ajouter ``?v=<version>`` aux imports relatifs ``.js`` d'un module ES.
Couvre ``import … from '…'``, ``import '…'`` et ``import('…')``.
Les spécificateurs déjà pourvus d'une query string sont laissés
intacts.
"""
v = version if version is not None else current_version()
return _JS_SPEC_RE.sub(
lambda m: f"{m.group(1)}{m.group(2)}?v={v}{m.group(3)}", source)
def cache_control_for(path: str, query_string: str = "") -> str | None:
"""En-tête ``Cache-Control`` pour un chemin, selon la query string.
Retourne ``None`` hors des statiques (l'appelant ne touche alors
à rien). ``immutable`` seulement si ``v`` vaut la version
courante ; ``no-cache`` dans tous les autres cas.
"""
if not path.startswith("/static/"):
return None
params = {}
for pair in query_string.split("&"):
if "=" in pair:
key, value = pair.split("=", 1)
params[key] = value
if params.get("v") and params["v"] == current_version():
return IMMUTABLE_CACHE_CONTROL
return NO_CACHE
+1 -1
View File
@@ -2626,7 +2626,7 @@ dependencies = [
[[package]]
name = "obsigate-desktop"
version = "2.97.0"
version = "2.98.0"
dependencies = [
"chrono",
"env_logger",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "obsigate-desktop"
version = "2.97.0"
version = "2.98.0"
description = "ObsiGate Desktop — Porte d'entrée native pour vos vaults Obsidian"
authors = ["Bruno Charest"]
edition = "2021"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/nicedoc/obsigate/main/desktop/tauri.conf.schema.json",
"productName": "ObsiGate",
"version": "2.97.0",
"version": "2.98.0",
"identifier": "com.obsigate.desktop",
"build": {
"frontendDist": "../frontend",
+13 -1
View File
@@ -1,6 +1,6 @@
# ObsiGate — Roadmap
> **Version :** 2.97.0 | **Dernière mise à jour :** 2026-11-30
> **Version :** 2.98.0 | **Dernière mise à jour :** 2026-11-30
> **Ce fichier ne contient que le travail à venir** (🔵 En cours + ⚪ Backlog) et un index compact
> vers les fonctionnalités livrées.
> - **Méthode de livraison à appliquer pour toute tâche : [DELIVERY_WORKFLOW.md](./DELIVERY_WORKFLOW.md)**
@@ -30,6 +30,18 @@
## 🔵 En cours
### 240. Épopée — Performance du chargement initial
- **Effort :** ~3 jours | **Impact :** 🔴 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — branche `feat/perf-chargement-240` livrée, PR à fusionner (issue Gitea #106)
- **Fiche :** [features/perf-chargement-240.md](./features/perf-chargement-240.md)
- **Description :** demande de Bruno (2026-11-30) — diviser par ~3 le premier affichage utile d'og.dracodev.net au bénéfice du retour SSO, des liens profonds `#file=`/`#folder=` et de l'accès de base. Baseline : TTFB 0,36–0,67 s, graphe ES statique 41 modules / 1 420 963 o, Mermaid CDN 745 Ko chargé d'emblée, statiques sans URL versionnées, `/api/dashboard` sans cache.
- **Sous-tâches :**
- [x] **#241 P0** — script d'audit versionné (`scripts/audit_chargement.py`) + budget figé (fiche) — Gitea #107
- [x] **#242 P1** — cache versionné `?v=<VERSION>` + `immutable` conditionnel + SW versionné — Gitea #108
- [x] **#243 P2** — `import()` dynamique des modules lourds + retrait des CDN du `<head>` — Gitea #109 (graphe −10,8 %, CDN retirés ; −50 % non atteint, voir fiche)
- [x] **#244 P3** — bootstrap : lien profond ouvert avant le chargement complet — Gitea #110
- [x] **#245 P4** — cache 60 s de `/api/dashboard` invalidé par le watcher — Gitea #111
### 239. Lien profond « dossier » `#folder=` (console Spark)
- **Effort :** ~0,5 jour | **Impact :** 🟢 | **Ouvert :** 2026-11-30 | **Statut :** 🔵 en cours — PR sur `feat/lien-dossier-239` (fusion = geste de Bruno)
+84
View File
@@ -0,0 +1,84 @@
# Performance du chargement initial — épopée #240
> Demande de Bruno (2026-11-30). Audit complet : rapport du 2026-11-30
> (mesures en direct sur la prod 2.97.0). Issues Gitea : épopée #106,
> lots #107 à #111.
## Baseline (2026-11-30, prod 2.97.0 + fichiers du dépôt)
- TTFB médian 0,36–0,67 s ; `/`, `/sso/login` et `/healthz` servent la
même SPA de 333 809 o.
- Graphe ES statique depuis `frontend/js/app.js` : **41 modules,
1 420 963 o bruts** (mesure locale, `scripts/audit_chargement.py
--local` ; la mesure prod donnait 1 406 497 o), zéro `import()`
dynamique dans le point d'entrée.
- Mermaid (CDN jsdelivr) : 745 043 o au fil, chargé d'emblée ;
highlight.js + 11 langages (cdnjs) et Lucide (unpkg) aussi dans le
`<head>`.
- Statiques sans URL versionnées : `cf-cache-status` MISS/DYNAMIC,
`Cache-Control: max-age=30` constaté en prod.
- Démarrage : `Promise.all([loadVaultSettings, loadVaults, loadTags])`
avant l'ouverture du fichier d'un lien profond `#file=`/`#folder=`.
- `GET /api/dashboard` recalcule les totaux (10 987 fichiers) à chaque
appel, sans cache.
## Budget figé (#241)
| Indicateur | Cible |
|---|---|
| Premier affichage utile (connexion initiale) | ÷ ~3 vs baseline |
| JS initial parsé (graphe statique local) | −50 % au moins |
| 2ᵉ visite | zéro re-téléchargement des statiques versionnées (`?v=`) |
| `/api/dashboard` répété | < 50 ms à chaud (cache) |
| Lien profond `#file=`/`#folder=` | cible lisible avant la fin du chargement complet |
## Mécanisme du cache versionné (#242)
Sans étape de build (règle du dépôt) :
1. **HTML** : `_index_html()` réécrit au service les URL
`/static/…` de `index.html` en `/static/…?v=<VERSION>`
(`backend/static_versioning.py`, VERSION = source unique).
2. **Modules ES** : le serveur de statiques (`VersionedStaticFiles`)
réécrit au service les spécificateurs d'import relatifs des
fichiers `.js` en y ajoutant `?v=<VERSION>` — le navigateur ne
connaît donc que des URL versionnées, de proche en proche.
3. **En-têtes** : `Cache-Control: public, max-age=31536000, immutable`
**uniquement** quand la requête porte `?v=<VERSION courante>` ;
`no-cache` sinon, et toujours `no-cache` sur le HTML. Le piège
historique (cache long sans versionnage → build périmé servi un an)
est impossible : une nouvelle version change toutes les URL.
4. **Service worker** : le nom de cache embarque la version servie
(`__OBSIGATE_SW_VERSION__` remplacé par le backend à la route
`/sw.js`) ; à l'activation, tout cache d'un autre nom est supprimé.
⚠️ **Hors code** : la règle Cloudflare qui ferait passer les statiques
versionnées en `cf-cache-status: HIT` est une action d'exploitation
(à faire au tableau de bord Cloudflare), elle n'est pas livrée par
cette branche.
## Lots
- **#241 P0** — script d'audit versionné + ce budget. ✅
- **#242 P1** — cache versionné (ci-dessus) + tests d'en-têtes et de
non-régression « nouvelle version servie ». ✅
- **#243 P2** — `import()` dynamique à la première utilisation
(Mermaid, graphe, Excalidraw, now-playing, plugins, push, mobile-editor) et
retrait des scripts CDN du `<head>` (highlight chargé au premier
bloc de code, par langage ; Lucide chargé en différé non bloquant
par `safeCreateIcons` ; Mermaid au premier diagramme).
**Résultat mesuré (script --local)** : graphe statique 41 → **34 modules**,
1 420 963 → **1 243 303 o (−12,5 %)** ; les **13 scripts CDN du `<head>`
sont retirés** (Mermaid 745 Ko au fil, highlight + langages, Lucide),
chargés à la demande — c'est le gain principal du lot sur le fil.
Le budget « −50 % du graphe statique » n'est **pas** atteint : le cœur
(viewer/ui/config/auth/sidebar, fortement couplés et circulaires)
reste statique, de même que les modules XLSX de `viewer.js` et
`filechat.js` (chat latéral câblé au démarrage par sidebar/config) —
leur extraction exigerait de découper viewer.js lui-même, chantier
séparé à ouvrir si Bruno le souhaite.
- **#244 P3** — bootstrap : lien profond ouvert avant le chargement
complet des vaults/tags/réglages. ✅ (`#file=` ouvert dès l'auth ;
`#folder=` reste après `loadVaults`, son arborescence en dépend.)
- **#245 P4** — cache mémoire 60 s de `/api/dashboard`, invalidé par
le watcher ; GZip inchangé (SSE toujours exclu). ✅
-13
View File
@@ -63,20 +63,7 @@
disabled
/>
<!-- defer: ne bloque pas le premier paint -->
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<!-- Langues highlight.js hors bundle "common" (enregistrement auto apres le core) -->
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dockerfile.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/powershell.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dos.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/cmake.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/dart.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/elixir.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/haskell.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/nginx.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/http.min.js"></script>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/languages/plaintext.min.js"></script>
<script defer src="https://unpkg.com/[email protected]/dist/umd/lucide.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<script type="importmap">
{
"imports": {
+34 -19
View File
@@ -5,7 +5,11 @@
import * as UI from './ui.js';
import * as Utils from './utils.js';
import { initI18n, t } from './i18n.js';
import { initNowPlaying } from './now-playing.js';
// #243 : modules chargés paresseusement (import dynamique) à la première
// utilisation ou en tâche de fond : graph, mermaid-viewer, now-playing,
// mobile-editor, push, plugins — ils ne font plus partie du graphe statique.
const _idle = window.requestIdleCallback || ((f) => setTimeout(f, 1200));
// Wire up AI toolbar toast (avoids circular import in utils.js)
window._obsigateShowToast = UI.showToast;
@@ -13,17 +17,12 @@ import * as Sidebar from './sidebar.js';
import * as Auth from './auth.js';
import * as Viewer from './viewer.js';
import * as Sync from './sync.js';
import { initGraphView } from './graph.js';
import * as Legacy from './legacy.js';
import { initCommandPalette } from './palette.js';
import { initMobileToolbar } from './mobile-toolbar.js';
import { initMobileEditor } from './mobile-editor.js';
import { initDragDrop } from './dragdrop.js';
import { initMermaid, setupFocusMode } from './mermaid-viewer.js';
import PaneManager from './pane-manager.js';
import { initDesktopIntegration, isTauriEnv } from './desktop.js';
import { initPush } from './push.js';
import { initPlugins } from './plugins.js';
import { populateVersions } from './config.js';
import { initSidebarChat } from './filechat.js';
@@ -74,25 +73,28 @@ async function init() {
PaneManager.init();
initCommandPalette();
initMobileToolbar();
initMobileEditor();
initPush();
initPlugins();
import('./mobile-editor.js').then((m) => m.initMobileEditor()).catch(() => {});
import('./push.js').then((m) => m.initPush()).catch(() => {});
import('./plugins.js').then((m) => m.initPlugins()).catch(() => {});
if (authOk) {
Legacy.initSyncStatus();
try {
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
initDragDrop();
Legacy.DashboardRecentWidget.init();
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("popup") === "true") {
document.body.classList.add("popup-mode");
}
// #244 (P3) : bootstrap rapide des liens profonds — un lien
// ``#file=`` (y compris à l'arrivée d'un retour SSO) est ouvert
// AVANT le chargement complet (réglages des vaults, liste des
// vaults, tags) : ``openFile`` ne dépend que de l'auth, déjà
// faite. Le reste charge ensuite, sans rouvrir ni écraser la
// cible (``fichierOuvert`` garde la suite). ``#folder=`` reste
// après le chargement : ``focusPathInSidebar`` a besoin de
// l'arborescence rendue par ``loadVaults``.
let fichierOuvert = false;
if (window.location.hash && window.location.hash.startsWith("#file=")) {
const hashVal = window.location.hash.substring(6);
const sepIndex = hashVal.indexOf(":");
@@ -100,7 +102,19 @@ async function init() {
const vault = decodeURIComponent(hashVal.substring(0, sepIndex));
const path = decodeURIComponent(hashVal.substring(sepIndex + 1));
Viewer.openFile(vault, path);
fichierOuvert = true;
}
}
await Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()]);
initDragDrop();
Legacy.DashboardRecentWidget.init();
if (fichierOuvert) {
// Cible déjà ouverte par le bootstrap rapide : ne pas la
// recouvrir par l'accueil.
} else if (window.location.hash && window.location.hash.startsWith("#folder=")) {
// #239 : lien profond « dossier » (émis par la console Spark,
// forme sœur de #file= : « #folder=<vault>:<chemin> »). Un
@@ -134,11 +148,12 @@ async function init() {
}
}
initGraphView();
initMermaid();
setupFocusMode();
// #243 : graphe, mermaid (mode focus) et lecteur média en différé —
// aucun de ces modules n'est nécessaire au premier affichage.
_idle(() => { import('./graph.js').then((m) => m.initGraphView()).catch(() => {}); });
_idle(() => { import('./mermaid-viewer.js').then((m) => m.setupFocusMode()).catch(() => {}); });
Utils.safeCreateIcons();
initNowPlaying();
_idle(() => { import('./now-playing.js').then((m) => m.initNowPlaying()).catch(() => {}); });
}
document.addEventListener("DOMContentLoaded", async () => {
+24 -2
View File
@@ -15,9 +15,26 @@ import { safeCreateIcons } from './utils.js';
var _mermaidReady = false;
var _currentTheme = 'default';
let _mermaidLoadPromise = null;
export function ensureMermaid() {
// #243 : Mermaid (745 Ko au fil) n'est plus chargé dans le <head> ;
// il arrive au premier diagramme rencontré.
if (typeof mermaid !== 'undefined') return Promise.resolve(true);
if (!_mermaidLoadPromise) {
_mermaidLoadPromise = new Promise((resolve) => {
const el = document.createElement('script');
el.src = 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js';
el.onload = () => resolve(typeof mermaid !== 'undefined');
el.onerror = () => resolve(false);
document.head.appendChild(el);
});
}
return _mermaidLoadPromise;
}
export function initMermaid() {
if (typeof mermaid === 'undefined') {
console.warn('[Mermaid] library not loaded');
ensureMermaid().then((ok) => { if (ok) initMermaid(); });
return;
}
mermaid.initialize(_getMermaidConfig(_currentTheme === 'dark'));
@@ -235,7 +252,12 @@ export var MERMAID_TEMPLATES = {
var _renderCounter = 0;
export async function renderMermaidBlocks(container) {
if (!_mermaidReady || typeof mermaid === 'undefined') return;
if (typeof mermaid === 'undefined') {
const ok = await ensureMermaid();
if (!ok) return;
}
if (!_mermaidReady) initMermaid();
if (!_mermaidReady) return;
var blocks = container.querySelectorAll('pre code.language-mermaid, .mermaid-code');
if (blocks.length === 0) return;
+1 -1
View File
@@ -8,7 +8,6 @@ import { _getEffective } from './config.js';
import { TabManager, showToast } from './ui.js';
import { addTagFilter, buildSearchResultsHeader, shouldDisplayPath, removeTagFilter, TagFilterService } from './sidebar.js';
import { t } from './i18n.js';
import { onSearchFilter } from './plugins.js';
// ---------------------------------------------------------------------------
// Search History Service (localStorage, LIFO, max 50, dedup)
// ---------------------------------------------------------------------------
@@ -826,6 +825,7 @@ export async function performAdvancedSearch(query, vaultFilter, tagFilter, offse
semBtn.classList.toggle("active", state.semanticSearch);
}
// Plugin hook: filter search results
const { onSearchFilter } = await import('./plugins.js'); // #243 paresseux
data.results = await onSearchFilter(state.vault || "default", query, data.results);
renderAdvancedSearchResults(data, query, tagFilter);
} catch (err) {
+1 -2
View File
@@ -4,7 +4,6 @@ import { state } from './state.js';
import { openFile, showWelcome, renderFile, renderImageViewer, el } from './viewer.js';
import { safeCreateIcons, getFileIcon, escapeHtml, detachInlineEditor } from './utils.js';
import { syncActiveFileTreeItem, refreshSidebarTreePreservingState } from './sidebar.js';
import { GraphViewManager } from './graph.js';
import { DashboardConflictsWidget } from './dashboard.js';
import { t, tr } from './i18n.js';
import { toggleThemeMode } from './themes.js';
@@ -1799,7 +1798,7 @@ export const ContextMenuManager = {
// Graph view — available for all types
const graphPath = type === 'vault' ? '' : path;
this._addItem('git-graph', 'Vue Graphique', () => GraphViewManager.open(vault, graphPath, type), false);
this._addItem('git-graph', 'Vue Graphique', () => { import('./graph.js').then((m) => m.GraphViewManager.open(vault, graphPath, type)).catch(() => {}); }, false); // #243 graphe paresseux
this._addSeparator();
+49 -1
View File
@@ -290,8 +290,48 @@ let _iconDebounceTimer = null;
* Debounced icon creation — batches multiple rapid calls into one
* DOM scan to avoid excessive reflows when building large trees.
*/
// ---------------------------------------------------------------------------
// Chargement paresseux des CDN (#243) : Lucide et highlight.js ne sont plus
// chargés dans le <head> — ils arrivent à la première utilisation.
// ---------------------------------------------------------------------------
const _scriptPromises = {};
function _loadScriptOnce(src) {
if (!_scriptPromises[src]) {
_scriptPromises[src] = new Promise((resolve) => {
const el = document.createElement("script");
el.src = src;
el.onload = () => resolve(true);
el.onerror = () => resolve(false);
document.head.appendChild(el);
});
}
return _scriptPromises[src];
}
function ensureLucide() {
if (typeof lucide !== "undefined" && lucide.createIcons) return Promise.resolve(true);
return _loadScriptOnce("https://unpkg.com/[email protected]/dist/umd/lucide.min.js")
.then((ok) => ok && typeof lucide !== "undefined" && !!lucide.createIcons);
}
const HLJS_BASE = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0";
function ensureHighlight(lang) {
if (typeof hljs !== "undefined" && hljs.highlightElement) return Promise.resolve(true);
return _loadScriptOnce(`${HLJS_BASE}/highlight.min.js`).then(async (ok) => {
if (!ok || typeof hljs === "undefined") return false;
if (lang && hljs.getLanguage && !hljs.getLanguage(lang)) {
await _loadScriptOnce(`${HLJS_BASE}/languages/${lang}.min.js`);
}
return true;
});
}
function safeCreateIcons() {
if (typeof lucide === "undefined" || !lucide.createIcons) return;
if (typeof lucide === "undefined" || !lucide.createIcons) {
// #243 : charger Lucide en différé, puis rejouer la création d'icônes.
ensureLucide().then((ok) => { if (ok) safeCreateIcons(); });
return;
}
if (state._iconDebounceTimer) return; // already scheduled
state._iconDebounceTimer = requestAnimationFrame(() => {
state._iconDebounceTimer = null;
@@ -321,6 +361,12 @@ function flushIcons() {
function safeHighlight(block) {
// Skip mermaid blocks — they're rendered by Mermaid.js, not highlighted
if (block.className && block.className.indexOf('language-mermaid') !== -1) return;
if (typeof hljs === "undefined" || !hljs.highlightElement) {
// #243 : charger highlight.js (base + langage détecté) puis recolorer.
const mLang = /\blanguage-([\w-]+)/.exec(block.className || "");
ensureHighlight(mLang ? mLang[1] : null).then((ok) => { if (ok) safeHighlight(block); });
return;
}
if (typeof hljs !== "undefined" && hljs.highlightElement) {
try {
// Alias pour les extensions que highlight.js (bundle common) ne connaît pas
@@ -965,6 +1011,8 @@ function copyToClipboard(text) {
export {
getFileIcon,
safeCreateIcons,
ensureLucide,
ensureHighlight,
flushIcons,
safeHighlight,
escapeHtml,
+16 -15
View File
@@ -7,15 +7,10 @@ import { TabManager, closeMobileSidebar, ContextMenuManager, RightSidebarManager
import { syncActiveFileTreeItem, searchByTag, TagFilterService, refreshSidebarTreePreservingState, focusPathInSidebar } from './sidebar.js';
import { AutocompleteDropdown, performAdvancedSearch } from './search.js';
import { initDashboardTabs } from './sync.js';
import { renderMermaidBlocks } from './mermaid-viewer.js';
import { renderExcalidraw } from './excalidraw-viewer.js';
import { DashboardStatsWidget, DashboardRecentWidget, DashboardBookmarkWidget, DashboardSharedWidget, DashboardConflictsWidget } from './dashboard.js';
import { openShareDialog } from './config.js';
import { cacheViewedFile, getCachedFile } from './offline.js';
import { t, getLocale } from './i18n.js';
import { onFileRender } from './plugins.js';
import { NowPlaying } from './now-playing.js';
import { toggleFileChat, followFileChat } from './filechat.js';
import { parseRef, columnName, findTd, invalidateCellIndex, sheetOfRef, firstCellOfRange } from './xlsx/refs.js';
import { createColourPicker } from './xlsx/color-picker.js';
import { buildCommandBar } from './xlsx/command-bar.js';
@@ -27,6 +22,13 @@ import {
colToIndex, indexToCol,
} from './xlsx/formula.js';
// #243 : modules lourds chargés à la première utilisation (le graphe
// statique initial ne les contient plus) : mermaid, excalidraw, plugins,
// now-playing (média), filechat.
function _withNowPlaying(fn) {
import('./now-playing.js').then((m) => { try { fn(m.NowPlaying); } catch (e) {} }).catch(() => {});
}
// ── Multi-format export ────────────────────────────────────────────────────
// Downloads a file export (HTML / MD bundle / ePub) via the authenticated
// export endpoints, showing a loading toast while the request is in flight.
@@ -1135,16 +1137,15 @@ export function renderImageViewer(area, data) {
// between this inline view and a body-level dock, so playback survives tab,
// pane and page navigation. The inline branches below just hand over the
// surface; the legacy "stop on re-render" cleanup no longer applies.
export { formatMediaDuration, buildMediaUrl, renderFallback as renderMediaFallback } from "./now-playing.js";
/** Audio viewer (roadmap #109-B, made persistent by #110). */
export function renderAudioViewer(area, data) {
NowPlaying.attachInline(area, data);
_withNowPlaying((np) => np.attachInline(area, data));
}
/** Video viewer (roadmap #109-C, made persistent by #110). */
export function renderVideoViewer(area, data) {
NowPlaying.attachInline(area, data);
_withNowPlaying((np) => np.attachInline(area, data));
}
@@ -6951,7 +6952,7 @@ export function renderFile(data) {
// instead of being wiped mid-session by a tab switch / sidebar click.
if (isInlineEditorActive()) detachInlineEditor();
// #190 A — an open chat panel follows the document being rendered.
followFileChat(data.vault, data.path, data.title);
import('./filechat.js').then((m) => m.followFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
// #108 — release the image viewer's document-level shortcuts before swapping
// the content area (otherwise they leak on every re-render).
if (_imageViewerCleanup) { _imageViewerCleanup(); _imageViewerCleanup = null; }
@@ -6965,7 +6966,7 @@ export function renderFile(data) {
const area = getContentArea();
// #110 — if this render is about to replace the surface that currently hosts
// the shared media element, hand it back to the persistent dock first.
NowPlaying.handleRender(area, data);
_withNowPlaying((np) => np.handleRender(area, data));
// Handle PDF files — render in iframe with TOC sidebar
if (data.is_pdf) {
@@ -7029,7 +7030,7 @@ export function renderFile(data) {
// Handle Excalidraw — render in iframe editor
if (data.is_excalidraw) {
renderExcalidraw(area, data, data.vault, data.path);
import('./excalidraw-viewer.js').then((m) => m.renderExcalidraw(area, data, data.vault, data.path)).catch(() => {}); // #243
return;
}
@@ -7257,7 +7258,7 @@ export function renderFile(data) {
// #169 — Chat intégré par fichier (panneau latéral)
const chatBtn = el("button", { class: "btn-action btn-chat", title: t("chat.button_title") }, [icon("message-square", 14), document.createTextNode(t("chat.button"))]);
chatBtn.addEventListener("click", () => {
toggleFileChat(data.vault, data.path, data.title);
import('./filechat.js').then((m) => m.toggleFileChat(data.vault, data.path, data.title)).catch(() => {}); // #243
});
// Check bookmark status and color the button
(async () => {
@@ -7419,7 +7420,7 @@ export function renderFile(data) {
});
// Render Mermaid diagrams
renderMermaidBlocks(area);
import('./mermaid-viewer.js').then((m) => m.renderMermaidBlocks(area)).catch(() => {}); // #243
// Wire up wikilinks
area.querySelectorAll(".wikilink").forEach((link) => {
@@ -7458,7 +7459,7 @@ export function renderFile(data) {
// content or append custom widgets beneath it. Async + non-blocking so a
// slow/failed plugin never delays the normal file render.
if (data.content && data.is_markdown) {
onFileRender(data.vault, data.content, data.path).then((fr) => {
import('./plugins.js').then((m) => m.onFileRender(data.vault, data.content, data.path)).then((fr) => { // #243
if (!fr) return;
if (typeof fr.replace === 'string' && fr.replace !== data.content) {
const rendered = document.getElementById('file-rendered-content');
@@ -7752,7 +7753,7 @@ export function showWelcome() {
// Restore or rebuild the dashboard with tabbed sections
const area = getContentArea();
// #110 — keep playing media alive if the dashboard replaces its surface.
NowPlaying.handleRender(area, null);
_withNowPlaying((np) => np.handleRender(area, null));
const home = document.getElementById("dashboard-home");
if (area && !home) {
+1 -1
View File
@@ -11,7 +11,7 @@
* cache or Cloudflare does NOT clear the Service Worker Cache Storage, which is
* a separate store. Bumping SW_VERSION invalidates it on every release.
*/
const SW_VERSION = 'v29';
const SW_VERSION = '__OBSIGATE_SW_VERSION__'; // remplacé au service par le backend (#242) ; repli statique : 'dev'
const CODE_CACHE = `obsigate-code-${SW_VERSION}`;
const RUNTIME_CACHE = `obsigate-runtime-${SW_VERSION}`;
const API_CACHE = `obsigate-api-${SW_VERSION}`;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "obsigate",
"version": "2.97.0",
"version": "2.98.0",
"description": "**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.",
"main": "patch.js",
"directories": {
+226
View File
@@ -0,0 +1,226 @@
#!/usr/bin/env python3
"""Audit de chargement d'ObsiGate (#241, épopée perf #240).
Mesure, sans dépendance externe (stdlib seule) :
- en mode distant (défaut) : TTFB et temps total médians de ``/``,
``/sso/login`` et des statiques clés, plus les en-têtes de cache
(``Cache-Control``, ``cf-cache-status``, ``ETag``) ;
- en mode ``--local`` : la baseline calculée depuis les fichiers du
dépôt — graphe des modules ES **statiques** atteint depuis
``frontend/js/app.js`` (nombre de modules + octets bruts, plus gros
modules), taille de ``index.html`` / ``style.css`` et des statiques
référencées par ``index.html``.
Le graphe local ne suit que les imports statiques (``import … from``,
``export … from``, ``import '…'``) : un module chargé par ``import()``
dynamique n'y compte pas — c'est exactement ce que le lot #243 cherche
à réduire.
Usage :
python3 scripts/audit_chargement.py [--base-url https://og.dracodev.net]
python3 scripts/audit_chargement.py --local [RACINE_DU_DEPOT]
python3 scripts/audit_chargement.py --local --json sortie.json
"""
from __future__ import annotations
import argparse
import http.client
import json
import re
import statistics
import sys
import time
from pathlib import Path
from urllib.parse import urlparse
# ---------------------------------------------------------------------------
# Graphe de modules ES (mode local)
# ---------------------------------------------------------------------------
_STATIC_IMPORT_RE = re.compile(
r"(?:^|[\n;])\s*(?:import\s+(?!\(\s*['\"])(?:[^'\"]*?\sfrom\s+)?|export\s+[^'\"]*?\sfrom\s+)['\"]([^'\"]+)['\"]"
)
def static_imports(source: str) -> list[str]:
"""Spécificateurs relatifs importés statiquement par un module ES."""
return [m.group(1) for m in _STATIC_IMPORT_RE.finditer(source)
if m.group(1).startswith(".")]
def resolve_spec(importer: Path, spec: str, root: Path) -> Path:
"""Résoudre un spécificateur relatif par rapport à son importeur."""
return (importer.parent / spec).resolve()
def local_module_graph(frontend_dir: Path) -> dict:
"""Graphe statique depuis ``js/app.js`` : compte + octets bruts."""
entry = frontend_dir / "js" / "app.js"
seen: dict[str, int] = {}
queue: list[Path] = [entry]
while queue:
module = queue.pop()
try:
key = str(module.relative_to(frontend_dir))
except ValueError:
continue
if key in seen or not module.is_file():
continue
source = module.read_text(encoding="utf-8", errors="replace")
seen[key] = len(source.encode("utf-8"))
for spec in static_imports(source):
target = resolve_spec(module, spec, frontend_dir)
if target.suffix == ".js":
queue.append(target)
top = sorted(seen.items(), key=lambda kv: -kv[1])[:10]
return {
"entry": "js/app.js",
"module_count": len(seen),
"raw_bytes": sum(seen.values()),
"top_modules": [{"module": k, "bytes": v} for k, v in top],
"modules": seen,
}
_STATIC_REF_RE = re.compile(r"(?:src|href)=\"(/static/[^\"]+)\"")
_CDN_REF_RE = re.compile(
r"(?:src|href)=\"(https://(?:cdnjs\.cloudflare\.com|unpkg\.com|cdn\.jsdelivr\.net)/[^\" ]+)\"")
def local_baseline(repo_root: Path) -> dict:
"""Baseline locale : graphe ES + poids des fichiers de la page."""
frontend = repo_root / "frontend"
index_html = (frontend / "index.html").read_text(encoding="utf-8", errors="replace")
refs: dict[str, int] = {}
for ref in _STATIC_REF_RE.findall(index_html):
path = frontend / ref.removeprefix("/static/")
if path.is_file():
refs[ref] = path.stat().st_size
return {
"mode": "local",
"index_html_bytes": (frontend / "index.html").stat().st_size,
"style_css_bytes": (frontend / "style.css").stat().st_size,
"module_graph": local_module_graph(frontend),
"index_static_refs": refs,
"index_static_refs_bytes": sum(refs.values()),
"index_cdn_refs": sorted(set(_CDN_REF_RE.findall(index_html))),
}
# ---------------------------------------------------------------------------
# Mesures distantes
# ---------------------------------------------------------------------------
def measure_once(url: str) -> dict:
"""Une mesure : TTFB (en-têtes reçus) et temps total (corps lu)."""
parsed = urlparse(url)
conn_cls = (http.client.HTTPSConnection if parsed.scheme == "https"
else http.client.HTTPConnection)
conn = conn_cls(parsed.netloc, timeout=30)
path = parsed.path or "/"
if parsed.query:
path += "?" + parsed.query
start = time.perf_counter()
conn.request("GET", path, headers={"Accept-Encoding": "identity"})
response = conn.getresponse()
ttfb = time.perf_counter() - start
body = response.read()
total = time.perf_counter() - start
headers = {k.lower(): v for k, v in response.getheaders()}
conn.close()
return {
"status": response.status,
"ttfb_s": round(ttfb, 3),
"total_s": round(total, 3),
"bytes": len(body),
"cache_control": headers.get("cache-control"),
"cf_cache_status": headers.get("cf-cache-status"),
"etag": headers.get("etag"),
}
def measure(url: str, runs: int = 3) -> dict:
"""Médianes de ``runs`` mesures d'une URL."""
samples = [measure_once(url) for _ in range(runs)]
return {
"url": url,
"runs": runs,
"status": samples[0]["status"],
"ttfb_median_s": statistics.median(s["ttfb_s"] for s in samples),
"total_median_s": statistics.median(s["total_s"] for s in samples),
"bytes": samples[0]["bytes"],
"cache_control": samples[0]["cache_control"],
"cf_cache_status": samples[0]["cf_cache_status"],
"etag": samples[0]["etag"],
"samples": samples,
}
DEFAULT_PATHS = ["/", "/sso/login", "/static/style.css", "/static/js/app.js", "/sw.js"]
def remote_audit(base_url: str, runs: int = 3) -> dict:
base = base_url.rstrip("/")
return {
"mode": "remote",
"base_url": base,
"paths": {p: measure(base + p, runs) for p in DEFAULT_PATHS},
}
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def _print_local(report: dict) -> None:
graph = report["module_graph"]
print("=== Audit chargement ObsiGate — baseline locale ===")
print(f"index.html : {report['index_html_bytes']} o")
print(f"style.css : {report['style_css_bytes']} o")
print(f"Graphe ES statique depuis {graph['entry']} : "
f"{graph['module_count']} modules, {graph['raw_bytes']} o bruts")
for item in graph["top_modules"][:5]:
print(f" {item['bytes']:>8} {item['module']}")
print(f"Statiques référencées par index.html : "
f"{len(report['index_static_refs'])} fichiers, "
f"{report['index_static_refs_bytes']} o")
print(f"CDN référencées : {len(report['index_cdn_refs'])}")
for cdn in report["index_cdn_refs"]:
print(f" {cdn}")
def _print_remote(report: dict) -> None:
print(f"=== Audit chargement ObsiGate — {report['base_url']} ===")
for path, m in report["paths"].items():
print(f"{path:<24} TTFB médian {m['ttfb_median_s']:.3f} s | "
f"total {m['total_median_s']:.3f} s | {m['bytes']} o | "
f"cache: {m['cache_control']} | cf: {m['cf_cache_status']}")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="https://og.dracodev.net",
help="URL de base à mesurer (mode distant)")
parser.add_argument("--local", nargs="?", const=".", default=None,
metavar="RACINE", help="Baseline depuis les fichiers du dépôt")
parser.add_argument("--runs", type=int, default=3, help="Mesures par URL (défaut 3)")
parser.add_argument("--json", metavar="FICHIER", help="Écrire le rapport JSON")
args = parser.parse_args(argv)
if args.local is not None:
report = local_baseline(Path(args.local).resolve())
_print_local(report)
else:
report = remote_audit(args.base_url, args.runs)
_print_remote(report)
if args.json:
Path(args.json).write_text(json.dumps(report, indent=2), encoding="utf-8")
print(f"JSON écrit : {args.json}")
return 0
if __name__ == "__main__":
sys.exit(main())
+41
View File
@@ -0,0 +1,41 @@
/**
* Bootstrap rapide des liens profonds (#244, épopée perf #240).
*
* Vérifie la structure de `init()` dans app.js : un lien `#file=` est
* ouvert AVANT le `Promise.all(loadVaultSettings, loadVaults,
* loadTags)`, et la suite du démarrage ne recouvre pas la cible
* (garde `fichierOuvert`). `#folder=` reste après le chargement
* (l'arborescence doit exister pour `focusPathInSidebar`).
*
* Usage: node tests/frontend/bootstrap-244.test.mjs
*/
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const here = dirname(fileURLToPath(import.meta.url));
const app = readFileSync(join(here, '../../frontend/js/app.js'), 'utf8');
let passed = 0;
function check(name, cond) {
if (!cond) {
console.error(`✗ ${name}`);
process.exitCode = 1;
} else {
console.log(`✓ ${name}`);
passed++;
}
}
const idxOpen = app.indexOf('Viewer.openFile(vault, path)');
const idxAll = app.indexOf('Promise.all([Legacy.loadVaultSettings(), Sidebar.loadVaults(), Sidebar.loadTags()])');
const idxFolder = app.indexOf('focusPathInSidebar(vault, path');
check('#file= ouvert dans app.js', idxOpen !== -1);
check('chargement complet présent', idxAll !== -1);
check('#file= ouvert AVANT le chargement complet (#244)', idxOpen !== -1 && idxAll !== -1 && idxOpen < idxAll);
check('garde fichierOuvert contre le recouvrement par l\'accueil', app.includes('fichierOuvert'));
check('#folder= toujours après le chargement complet', idxFolder !== -1 && idxAll !== -1 && idxFolder > idxAll);
console.log(`\n${passed} checks passed`);
+2 -2
View File
@@ -87,11 +87,11 @@ test("viewer delegates inline rendering to NowPlaying.attachInline", () => {
const stop = viewer.indexOf("export function renderFile");
assert.ok(start !== -1 && stop > start, "renderAudioViewer block not found");
const block = viewer.slice(start, stop);
assert.match(block, /NowPlaying\.attachInline\(area, data\)/);
assert.match(block, /np\.attachInline\(area, data\)/); // #243 : délégation paresseuse via _withNowPlaying
});
test("renderFile hands the shared element to the dock before a re-render", () => {
assert.match(viewer, /NowPlaying\.handleRender\(area, data\)/);
assert.match(viewer, /np\.handleRender\(area, data\)/); // #243 : idem
assert.doesNotMatch(viewer, /_mediaViewerCleanup/);
});
+8 -2
View File
@@ -313,12 +313,18 @@ test("reading button only shows while a file is open", () => {
test("reading button is hidden while the assistant panel is open", () => {
const btn = w.document.getElementById("me-reading-btn");
const panel = w.document.createElement("div");
panel.className = "bookslm-panel open";
// Depuis la transition Spark (D5), le panneau assistant est le panneau
// Spark `.draco-panneau` (l'ancien `.bookslm-panel` a été retiré) et
// isAssistantOpen() s'appuie sur checkVisibility() — absent du rendu
// JSDOM, on le simule donc explicitement sur l'élément.
panel.className = "draco-panneau";
let panelVisible = true;
panel.checkVisibility = () => panelVisible;
w.document.body.appendChild(panel);
state.currentPath = "Notes/note.md";
updateReadingButtonVisibility();
assert.ok(btn.hidden, "hidden while the assistant is expanded");
panel.classList.add("hidden");
panelVisible = false;
updateReadingButtonVisibility();
assert.ok(!btn.hidden, "shown again once the assistant is collapsed");
panel.remove();
+6 -4
View File
@@ -42,7 +42,7 @@ test("viewer.js — group nav: TOC markdown-only, then pop-out, bookmark", () =>
assert.ok(m[1].includes("navBtns.push(openNewWindowBtn, bookmarkBtn, chatBtn);"), "navBtns group order");
});
test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order", () => {
test("viewer.js — group edit = [edit, source, .ext, spark?, pretty?] in order", () => {
const m = viewer.match(
/const editBtns = \[\];([\s\S]*?)const exportBtns/,
);
@@ -52,11 +52,13 @@ test("viewer.js — group edit = [edit, source, .ext, forge?, pretty?] in order"
const re = /editBtns\.push\((\w+)\)/g;
let g;
while ((g = re.exec(block))) order.push(g[1]);
// editBtn conditional, then sourceBtn, then ext-download conditional, then forge conditional
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "forgeBtn", "prettyBtn"]);
// editBtn conditional, then sourceBtn, then ext-download conditional, then
// Spark conditional (depuis la transition D5, sparkBtn remplace forgeBtn,
// proposé pour tout fichier supporté non-image)
assert.deepEqual(order, ["editBtn", "sourceBtn", "mdBtn", "sparkBtn", "prettyBtn"]);
assert.ok(block.includes("if (!data.unsupported) editBtns.push(editBtn)"));
assert.ok(block.includes("if (!data.is_image) editBtns.push(mdBtn)"));
assert.ok(block.includes("if (data.is_markdown) editBtns.push(forgeBtn)"));
assert.ok(block.includes("if (!data.unsupported && !data.is_image) editBtns.push(sparkBtn)"));
// Pretty (text files) must land in the EDIT group, after the extension button
assert.ok(block.indexOf("editBtns.push(prettyBtn)") > block.indexOf("editBtns.push(mdBtn)"));
});
+64
View File
@@ -0,0 +1,64 @@
"""Tests du script d'audit de chargement (#241, épopée perf #240).
Le script est stdlib seule et versionné dans ``scripts/`` ; on teste
son mode local (graphe de modules ES statiques) sur un mini-frontend
synthétique, pour que la mesure reste honnête : un module chargé par
``import()`` dynamique ne doit PAS compter dans le graphe statique.
"""
from __future__ import annotations
import importlib.util
from pathlib import Path
_SCRIPT = Path(__file__).resolve().parent.parent / "scripts" / "audit_chargement.py"
_spec = importlib.util.spec_from_file_location("audit_chargement", _SCRIPT)
assert _spec and _spec.loader
audit = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(audit)
def _write(root: Path, rel: str, content: str) -> None:
path = root / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
def test_static_imports_ignore_dynamic_imports():
source = (
"import * as A from './a.js';\n"
"import './side.js';\n"
"export { x } from './re.js';\n"
"const m = await import('./lazy.js');\n"
"import('https://cdn.example.com/x.js');\n"
)
assert audit.static_imports(source) == ["./a.js", "./side.js", "./re.js"]
def test_local_module_graph_counts_only_static_chain(tmp_path):
frontend = tmp_path / "frontend"
_write(frontend, "js/app.js",
"import { a } from './a.js';\nconst l = await import('./lazy.js');\n")
_write(frontend, "js/a.js", "import { b } from './sub/b.js';\nexport const a = b;\n")
_write(frontend, "js/sub/b.js", "export const b = 1;\n")
_write(frontend, "js/lazy.js", "export const lazy = 'x'.repeat(5000);\n")
graph = audit.local_module_graph(frontend)
assert graph["module_count"] == 3 # app + a + sub/b, pas lazy
assert "js/lazy.js" not in graph["modules"]
assert graph["raw_bytes"] == sum(graph["modules"].values())
def test_local_baseline_on_real_repo():
repo = Path(__file__).resolve().parent.parent
baseline = audit.local_baseline(repo)
graph = baseline["module_graph"]
# La baseline du dépôt réel au moment du lot #241 : 41 modules,
# ~1,42 Mo bruts. On vérifie des bornes larges (le graphe bouge
# avec les lots suivants, #243 doit le faire BAISSER).
assert graph["module_count"] >= 10
assert graph["raw_bytes"] > 100_000
assert baseline["index_html_bytes"] > 100_000
assert any("mermaid" in url or "lucide" in url or "highlight" in url
for url in baseline["index_cdn_refs"]) or graph["raw_bytes"] < 1_000_000
+54
View File
@@ -0,0 +1,54 @@
"""Cache mémoire de GET /api/dashboard (#245, épopée perf #240)."""
from __future__ import annotations
from backend.routers import config as config_router
def _count_calls(monkeypatch):
calls = {"n": 0}
original = config_router._compute_dashboard
def counting(user):
calls["n"] += 1
return original(user)
monkeypatch.setattr(config_router, "_compute_dashboard", counting)
return calls
def test_dashboard_second_call_served_from_cache(client, monkeypatch):
config_router.invalidate_dashboard_cache()
calls = _count_calls(monkeypatch)
first = client.get("/api/dashboard")
second = client.get("/api/dashboard")
assert first.status_code == 200
assert second.status_code == 200
assert second.json() == first.json()
assert calls["n"] == 1 # un seul calcul pour deux appels
def test_dashboard_cache_invalidation_recomputes(client, monkeypatch):
config_router.invalidate_dashboard_cache()
calls = _count_calls(monkeypatch)
assert client.get("/api/dashboard").status_code == 200
config_router.invalidate_dashboard_cache()
assert client.get("/api/dashboard").status_code == 200
assert calls["n"] == 2
def test_dashboard_cache_ttl_expiry(client, monkeypatch):
import time
config_router.invalidate_dashboard_cache()
calls = _count_calls(monkeypatch)
assert client.get("/api/dashboard").status_code == 200
# Vieillir artificiellement l'entrée au-delà du TTL.
for key, (ts, value) in list(config_router._dashboard_cache.items()):
config_router._dashboard_cache[key] = (ts - config_router._DASHBOARD_TTL_SECONDS - 1, value)
assert client.get("/api/dashboard").status_code == 200
assert calls["n"] == 2
_ = time # (garde-fou d'import)
+75
View File
@@ -0,0 +1,75 @@
"""Cache versionné des statiques (#242, épopée perf #240).
Non-régression clé : une nouvelle version doit être servie
immédiatement — le cache long (``immutable``) n'est accordé qu'aux
URL portant ``?v=<version courante>``.
"""
from __future__ import annotations
from backend import static_versioning as sv
def test_rewrite_static_urls_adds_version():
html = '<link rel="stylesheet" href="/static/style.css" />' \
'<script type="module" src="/static/js/app.js"></script>' \
'<a href="https://example.com/static/nope.css">x</a>'
out = sv.rewrite_static_urls(html, version="9.9.9")
assert "/static/style.css?v=9.9.9" in out
assert "/static/js/app.js?v=9.9.9" in out
assert "example.com/static/nope.css?v=" not in out
def test_rewrite_js_imports_adds_version():
source = (
"import * as UI from './ui.js';\n"
"import './side.js';\n"
"export { x } from '../shared.js';\n"
"const m = await import('./lazy.js');\n"
"const s = 'pas un import ./faux.js';\n"
)
out = sv.rewrite_js_imports(source, version="9.9.9")
assert "'./ui.js?v=9.9.9'" in out
assert "'./side.js?v=9.9.9'" in out
assert "'../shared.js?v=9.9.9'" in out
assert "'./lazy.js?v=9.9.9'" in out
def test_cache_control_only_immutable_for_current_version():
current = sv.current_version()
assert sv.cache_control_for("/static/js/app.js", f"v={current}") == sv.IMMUTABLE_CACHE_CONTROL
# Ancienne version / absence de version : jamais de cache long.
assert sv.cache_control_for("/static/js/app.js", "v=0.0.1") == sv.NO_CACHE
assert sv.cache_control_for("/static/js/app.js", "") == sv.NO_CACHE
assert sv.cache_control_for("/api/dashboard", f"v={current}") is None
def test_served_headers_and_rewriting(client):
"""Via l'application : en-têtes selon ?v= et corps JS réécrit."""
current = sv.current_version()
versioned = client.get(f"/static/js/app.js?v={current}")
assert versioned.status_code == 200
assert "immutable" in versioned.headers.get("cache-control", "")
assert f"?v={current}" in versioned.text # imports réécrits au service
plain = client.get("/static/js/app.js")
assert plain.status_code == 200
assert plain.headers.get("cache-control") == "no-cache"
stale = client.get("/static/js/app.js?v=0.0.1")
assert stale.headers.get("cache-control") == "no-cache"
index = client.get("/")
assert index.status_code == 200
assert index.headers.get("cache-control") == "no-cache"
assert f"/static/style.css?v={current}" in index.text
assert f"/static/js/app.js?v={current}" in index.text
def test_service_worker_carries_current_version(client):
current = sv.current_version()
sw = client.get("/sw.js")
assert sw.status_code == 200
assert "__OBSIGATE_SW_VERSION__" not in sw.text
assert f"v{current}" in sw.text