BlueGit

projects-timfalken-com verhalenboek

feat: maak Verhalenboek installeerbaar als webapp

Voeg een manifest, service worker en boek-favicon toe zodat de site
onder /verhaaltjesboek/ als zelfstandige app op het beginscherm kan.

Co-authored-by: tim <tim@timfalken.com>

timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa

Authored 2026-10-05 · 6 weeks ago

Hash
944696d377ed680dd2709b958432384f1e08468d
Parent
1e30cc63
19 files changed +458 −7
.gitlab-ci.yml +3 −0
@@ -15,12 +15,15 @@ php_tests:
15 15 - php web/tests/storybook.php
16 16 - python3 web/tests/startup.py
17 17 - python3 web/tests/integration.py
18 - python3 web/tests/pwa.py
18 19
19 20 frontend_checks:
20 21 stage: test
21 22 image: node:22-bookworm-slim
22 23 script:
23 24 - node --check web/assets/app.js
25 - node --check web/assets/pwa.js
26 - node --check web/sw.js
24 27
25 28 # A real FTP fixture verifies that mirroring preserves production data and secrets.
26 29 deploy_tests:
@@ -15,12 +15,15 @@ php_tests:
15 - php web/tests/storybook.php
15 - php web/tests/storybook.php
16 - python3 web/tests/startup.py
16 - python3 web/tests/startup.py
17 - python3 web/tests/integration.py
17 - python3 web/tests/integration.py
18 - python3 web/tests/pwa.py
18
19
19frontend_checks:
20frontend_checks:
20 stage: test
21 stage: test
21 image: node:22-bookworm-slim
22 image: node:22-bookworm-slim
22 script:
23 script:
23 - node --check web/assets/app.js
24 - node --check web/assets/app.js
25 - node --check web/assets/pwa.js
26 - node --check web/sw.js
24
27
25# A real FTP fixture verifies that mirroring preserves production data and secrets.
28# A real FTP fixture verifies that mirroring preserves production data and secrets.
26deploy_tests:
29deploy_tests:
web/.htaccess +7 −0
@@ -23,8 +23,15 @@ DirectoryIndex index.php
23 23 </IfModule>
24 24
25 25 # Versioned asset URLs (?v=commit) may be cached for a long time.
26 # sw.js is the exception: a service worker is only updated when this URL is revalidated.
26 27 <IfModule mod_headers.c>
27 28 <FilesMatch "\.(css|js|png|svg|webp|woff2?)$">
28 29 Header set Cache-Control "public, max-age=31536000, immutable"
29 30 </FilesMatch>
31 <Files "sw.js">
32 Header set Cache-Control "no-cache"
33 </Files>
34 <Files "manifest.webmanifest">
35 Header set Cache-Control "no-cache"
36 </Files>
30 37 </IfModule>
@@ -23,8 +23,15 @@ DirectoryIndex index.php
23</IfModule>
23</IfModule>
24
24
25# Versioned asset URLs (?v=commit) may be cached for a long time.
25# Versioned asset URLs (?v=commit) may be cached for a long time.
26# sw.js is the exception: a service worker is only updated when this URL is revalidated.
26<IfModule mod_headers.c>
27<IfModule mod_headers.c>
27 <FilesMatch "\.(css|js|png|svg|webp|woff2?)$">
28 <FilesMatch "\.(css|js|png|svg|webp|woff2?)$">
28 Header set Cache-Control "public, max-age=31536000, immutable"
29 Header set Cache-Control "public, max-age=31536000, immutable"
29 </FilesMatch>
30 </FilesMatch>
31 <Files "sw.js">
32 Header set Cache-Control "no-cache"
33 </Files>
34 <Files "manifest.webmanifest">
35 Header set Cache-Control "no-cache"
36 </Files>
30</IfModule>
37</IfModule>
web/assets/apple-touch-icon.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/favicon-16.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/favicon-32.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/favicon.svg +24 −4
@@ -1,6 +1,26 @@
1 1 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Verhalenboek">
2 <rect width="64" height="64" rx="14" fill="#9a4032"/>
3 <path fill="#fffaf3" d="M16 14h24a8 8 0 0 1 8 8v26a8 8 0 0 0-8-6H16V14z"/>
4 <path fill="#f0e2d4" d="M16 42h24a8 8 0 0 1 8 8v0H22a6 6 0 0 1-6-6v-2z"/>
5 <path stroke="#9a4032" stroke-width="1.5" d="M24 24h14M24 30h14M24 36h9"/>
2 <defs>
3 <linearGradient id="cover" x1="10" y1="10" x2="54" y2="56" gradientUnits="userSpaceOnUse">
4 <stop offset="0%" stop-color="#6b97f2"/>
5 <stop offset="55%" stop-color="#3f63d4"/>
6 <stop offset="100%" stop-color="#2f4cb8"/>
7 </linearGradient>
8 <linearGradient id="pages" x1="0" y1="17" x2="0" y2="50" gradientUnits="userSpaceOnUse">
9 <stop offset="0%" stop-color="#fffaf0"/>
10 <stop offset="100%" stop-color="#f1e4cc"/>
11 </linearGradient>
12 <clipPath id="bookclip">
13 <path d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
14 </clipPath>
15 </defs>
16 <path fill="url(#cover)" d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
17 <path fill="url(#pages)" d="M16.2 17.4h30.6c1.7 0 3 1.35 3 3v26.8c0 1.65-1.35 3-3 3H16.2V17.4z"/>
18 <rect x="9" y="12" width="8" height="42" fill="#2a46a6" clip-path="url(#bookclip)"/>
19 <g fill="none" stroke="#b7a488" stroke-width="2.6" stroke-linecap="round">
20 <path d="M23.2 27.2h19.2"/>
21 <path d="M23.2 34.4h15.4"/>
22 <path d="M23.2 41.6h19.2"/>
23 </g>
24 <path fill="#f4a261" d="M40.2 6.2h8.6v18.8l-4.3-3.3-4.3 3.3V6.2z"/>
6 25 </svg>
26
@@ -1,6 +1,26 @@
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Verhalenboek">
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="Verhalenboek">
2 <rect width="64" height="64" rx="14" fill="#9a4032"/>
2 <defs>
3 <path fill="#fffaf3" d="M16 14h24a8 8 0 0 1 8 8v26a8 8 0 0 0-8-6H16V14z"/>
3 <linearGradient id="cover" x1="10" y1="10" x2="54" y2="56" gradientUnits="userSpaceOnUse">
4 <path fill="#f0e2d4" d="M16 42h24a8 8 0 0 1 8 8v0H22a6 6 0 0 1-6-6v-2z"/>
4 <stop offset="0%" stop-color="#6b97f2"/>
5 <path stroke="#9a4032" stroke-width="1.5" d="M24 24h14M24 30h14M24 36h9"/>
5 <stop offset="55%" stop-color="#3f63d4"/>
6 <stop offset="100%" stop-color="#2f4cb8"/>
7 </linearGradient>
8 <linearGradient id="pages" x1="0" y1="17" x2="0" y2="50" gradientUnits="userSpaceOnUse">
9 <stop offset="0%" stop-color="#fffaf0"/>
10 <stop offset="100%" stop-color="#f1e4cc"/>
11 </linearGradient>
12 <clipPath id="bookclip">
13 <path d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
14 </clipPath>
15 </defs>
16 <path fill="url(#cover)" d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
17 <path fill="url(#pages)" d="M16.2 17.4h30.6c1.7 0 3 1.35 3 3v26.8c0 1.65-1.35 3-3 3H16.2V17.4z"/>
18 <rect x="9" y="12" width="8" height="42" fill="#2a46a6" clip-path="url(#bookclip)"/>
19 <g fill="none" stroke="#b7a488" stroke-width="2.6" stroke-linecap="round">
20 <path d="M23.2 27.2h19.2"/>
21 <path d="M23.2 34.4h15.4"/>
22 <path d="M23.2 41.6h19.2"/>
23 </g>
24 <path fill="#f4a261" d="M40.2 6.2h8.6v18.8l-4.3-3.3-4.3 3.3V6.2z"/>
6</svg>
25</svg>
26
web/assets/icon-192.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/icon-512.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/icon-maskable-192.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/icon-maskable-512.png added Binary file +0 −0

The contents of this binary file are not shown.

web/assets/mask-icon.svg added +4 −0
@@ -0,0 +1,4 @@
1 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2 <path fill="#000" d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
3 <path fill="#000" d="M40.2 6.2h8.6v18.8l-4.3-3.3-4.3 3.3V6.2z"/>
4 </svg>
@@ -0,0 +1,4 @@
1<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2 <path fill="#000" d="M9 15.2c0-2.8 2.3-5 5-5h36c2.8 0 5 2.2 5 5V49c0 2.8-2.2 5-5 5H14c-2.8 0-5-2.2-5-5V15.2z"/>
3 <path fill="#000" d="M40.2 6.2h8.6v18.8l-4.3-3.3-4.3 3.3V6.2z"/>
4</svg>
web/assets/pwa.js added +24 −0
@@ -0,0 +1,24 @@
1 'use strict';
2
3 function appScope() {
4 let path = window.location.pathname;
5 if (!path.endsWith('/')) {
6 if (/\.[a-z0-9]+$/i.test(path)) path = path.replace(/[^/]*$/, '');
7 else path += '/';
8 }
9 return new URL(path, window.location.origin);
10 }
11
12 function registerApp() {
13 if (!('serviceWorker' in navigator)) return;
14 const scope = appScope();
15 const swUrl = new URL('sw.js', scope);
16 const current = document.currentScript;
17 if (current && current.src) {
18 const version = new URL(current.src).searchParams.get('v');
19 if (version) swUrl.searchParams.set('v', version);
20 }
21 navigator.serviceWorker.register(swUrl.href, { scope: scope.href }).catch(function () {});
22 }
23
24 registerApp();
@@ -0,0 +1,24 @@
1'use strict';
2
3function appScope() {
4 let path = window.location.pathname;
5 if (!path.endsWith('/')) {
6 if (/\.[a-z0-9]+$/i.test(path)) path = path.replace(/[^/]*$/, '');
7 else path += '/';
8 }
9 return new URL(path, window.location.origin);
10}
11
12function registerApp() {
13 if (!('serviceWorker' in navigator)) return;
14 const scope = appScope();
15 const swUrl = new URL('sw.js', scope);
16 const current = document.currentScript;
17 if (current && current.src) {
18 const version = new URL(current.src).searchParams.get('v');
19 if (version) swUrl.searchParams.set('v', version);
20 }
21 navigator.serviceWorker.register(swUrl.href, { scope: scope.href }).catch(function () {});
22}
23
24registerApp();
web/docs.php +2 −1
@@ -8,8 +8,9 @@ $base = 'https://projects.timfalken.com/verhaaltjesboek';
8 8 <head>
9 9 <meta charset="utf-8">
10 10 <meta name="viewport" content="width=device-width, initial-scale=1">
11 <meta name="theme-color" content="#f4efe6">
11 12 <title>API · Verhalenboek</title>
12 <link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" type="image/svg+xml">
13 <?php pwaHead(); ?>
13 14 <link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
14 15 </head>
15 16 <body>
@@ -8,8 +8,9 @@ $base = 'https://projects.timfalken.com/verhaaltjesboek';
8<head>
8<head>
9<meta charset="utf-8">
9<meta charset="utf-8">
10<meta name="viewport" content="width=device-width, initial-scale=1">
10<meta name="viewport" content="width=device-width, initial-scale=1">
11<meta name="theme-color" content="#f4efe6">
11<title>API · Verhalenboek</title>
12<title>API · Verhalenboek</title>
12<link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" type="image/svg+xml">
13<?php pwaHead(); ?>
13<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
14<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
14</head>
15</head>
15<body>
16<body>
web/index.php +2 −1
@@ -17,8 +17,9 @@ $themeColor = $theme === 'dark' ? '#141210' : '#f4efe6';
17 17 <meta charset="utf-8">
18 18 <meta name="viewport" content="width=device-width, initial-scale=1">
19 19 <meta name="theme-color" content="<?= htmlspecialchars($themeColor, ENT_QUOTES) ?>">
20 <meta name="description" content="Elke dag drie verhalen.">
20 21 <title>Verhalenboek</title>
21 <link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" type="image/svg+xml">
22 <?php pwaHead(); ?>
22 23 <link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
23 24 <?php if ($logged): ?><script src="<?= htmlspecialchars(assetUrl('assets/app.js'), ENT_QUOTES) ?>" defer></script><?php endif ?>
24 25 </head>
@@ -17,8 +17,9 @@ $themeColor = $theme === 'dark' ? '#141210' : '#f4efe6';
17<meta charset="utf-8">
17<meta charset="utf-8">
18<meta name="viewport" content="width=device-width, initial-scale=1">
18<meta name="viewport" content="width=device-width, initial-scale=1">
19<meta name="theme-color" content="<?= htmlspecialchars($themeColor, ENT_QUOTES) ?>">
19<meta name="theme-color" content="<?= htmlspecialchars($themeColor, ENT_QUOTES) ?>">
20<meta name="description" content="Elke dag drie verhalen.">
20<title>Verhalenboek</title>
21<title>Verhalenboek</title>
21<link rel="icon" href="<?= htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES) ?>" type="image/svg+xml">
22<?php pwaHead(); ?>
22<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
23<link rel="stylesheet" href="<?= htmlspecialchars(assetUrl('assets/app.css'), ENT_QUOTES) ?>">
23<?php if ($logged): ?><script src="<?= htmlspecialchars(assetUrl('assets/app.js'), ENT_QUOTES) ?>" defer></script><?php endif ?>
24<?php if ($logged): ?><script src="<?= htmlspecialchars(assetUrl('assets/app.js'), ENT_QUOTES) ?>" defer></script><?php endif ?>
24</head>
25</head>
web/lib/bootstrap.php +22 −0
@@ -230,6 +230,28 @@ function assetUrl(string $path): string {
230 230 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
231 231 }
232 232
233 function pwaHead(): void {
234 $icon = htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES);
235 $png32 = htmlspecialchars(assetUrl('assets/favicon-32.png'), ENT_QUOTES);
236 $png16 = htmlspecialchars(assetUrl('assets/favicon-16.png'), ENT_QUOTES);
237 $mask = htmlspecialchars(assetUrl('assets/mask-icon.svg'), ENT_QUOTES);
238 $script = htmlspecialchars(assetUrl('assets/pwa.js'), ENT_QUOTES);
239 echo <<<HTML
240 <link rel="icon" href="{$icon}" type="image/svg+xml" sizes="any">
241 <link rel="icon" href="{$png32}" type="image/png" sizes="32x32">
242 <link rel="icon" href="{$png16}" type="image/png" sizes="16x16">
243 <link rel="apple-touch-icon" href="assets/apple-touch-icon.png" sizes="180x180">
244 <link rel="manifest" href="manifest.webmanifest">
245 <link rel="mask-icon" href="{$mask}" color="#3a5fc8">
246 <meta name="mobile-web-app-capable" content="yes">
247 <meta name="apple-mobile-web-app-capable" content="yes">
248 <meta name="apple-mobile-web-app-title" content="Verhalenboek">
249 <meta name="apple-mobile-web-app-status-bar-style" content="default">
250 <script src="{$script}" defer></script>
251
252 HTML;
253 }
254
233 255 function authRequest(string $path, ?array $form = null, ?string $token = null): array {
234 256 $ch=curl_init('https://auth.timfalken.com'.$path);
235 257 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
@@ -230,6 +230,28 @@ function assetUrl(string $path): string {
230 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
230 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
231}
231}
232
232
233function pwaHead(): void {
234 $icon = htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES);
235 $png32 = htmlspecialchars(assetUrl('assets/favicon-32.png'), ENT_QUOTES);
236 $png16 = htmlspecialchars(assetUrl('assets/favicon-16.png'), ENT_QUOTES);
237 $mask = htmlspecialchars(assetUrl('assets/mask-icon.svg'), ENT_QUOTES);
238 $script = htmlspecialchars(assetUrl('assets/pwa.js'), ENT_QUOTES);
239 echo <<<HTML
240<link rel="icon" href="{$icon}" type="image/svg+xml" sizes="any">
241<link rel="icon" href="{$png32}" type="image/png" sizes="32x32">
242<link rel="icon" href="{$png16}" type="image/png" sizes="16x16">
243<link rel="apple-touch-icon" href="assets/apple-touch-icon.png" sizes="180x180">
244<link rel="manifest" href="manifest.webmanifest">
245<link rel="mask-icon" href="{$mask}" color="#3a5fc8">
246<meta name="mobile-web-app-capable" content="yes">
247<meta name="apple-mobile-web-app-capable" content="yes">
248<meta name="apple-mobile-web-app-title" content="Verhalenboek">
249<meta name="apple-mobile-web-app-status-bar-style" content="default">
250<script src="{$script}" defer></script>
251
252HTML;
253}
254
233function authRequest(string $path, ?array $form = null, ?string $token = null): array {
255function authRequest(string $path, ?array $form = null, ?string $token = null): array {
234 $ch=curl_init('https://auth.timfalken.com'.$path);
256 $ch=curl_init('https://auth.timfalken.com'.$path);
235 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
257 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
web/manifest.webmanifest added +39 −0
@@ -0,0 +1,39 @@
1 {
2 "name": "Verhalenboek",
3 "short_name": "Verhalenboek",
4 "description": "Elke dag drie verhalen.",
5 "lang": "nl",
6 "dir": "ltr",
7 "id": "/verhaaltjesboek/",
8 "start_url": "/verhaaltjesboek/",
9 "scope": "/verhaaltjesboek/",
10 "display": "standalone",
11 "background_color": "#f4efe6",
12 "theme_color": "#f4efe6",
13 "icons": [
14 {
15 "src": "/verhaaltjesboek/assets/icon-192.png",
16 "sizes": "192x192",
17 "type": "image/png",
18 "purpose": "any"
19 },
20 {
21 "src": "/verhaaltjesboek/assets/icon-512.png",
22 "sizes": "512x512",
23 "type": "image/png",
24 "purpose": "any"
25 },
26 {
27 "src": "/verhaaltjesboek/assets/icon-maskable-192.png",
28 "sizes": "192x192",
29 "type": "image/png",
30 "purpose": "maskable"
31 },
32 {
33 "src": "/verhaaltjesboek/assets/icon-maskable-512.png",
34 "sizes": "512x512",
35 "type": "image/png",
36 "purpose": "maskable"
37 }
38 ]
39 }
@@ -0,0 +1,39 @@
1{
2 "name": "Verhalenboek",
3 "short_name": "Verhalenboek",
4 "description": "Elke dag drie verhalen.",
5 "lang": "nl",
6 "dir": "ltr",
7 "id": "/verhaaltjesboek/",
8 "start_url": "/verhaaltjesboek/",
9 "scope": "/verhaaltjesboek/",
10 "display": "standalone",
11 "background_color": "#f4efe6",
12 "theme_color": "#f4efe6",
13 "icons": [
14 {
15 "src": "/verhaaltjesboek/assets/icon-192.png",
16 "sizes": "192x192",
17 "type": "image/png",
18 "purpose": "any"
19 },
20 {
21 "src": "/verhaaltjesboek/assets/icon-512.png",
22 "sizes": "512x512",
23 "type": "image/png",
24 "purpose": "any"
25 },
26 {
27 "src": "/verhaaltjesboek/assets/icon-maskable-192.png",
28 "sizes": "192x192",
29 "type": "image/png",
30 "purpose": "maskable"
31 },
32 {
33 "src": "/verhaaltjesboek/assets/icon-maskable-512.png",
34 "sizes": "512x512",
35 "type": "image/png",
36 "purpose": "maskable"
37 }
38 ]
39}
web/router.php +9 −1
@@ -13,6 +13,14 @@ if (preg_match('~^/api\.php(?:/|$)~', $rel)) {
13 13 return true;
14 14 }
15 15 $full = __DIR__.$rel;
16 if ($rel !== '/' && is_file($full)) return false;
16 if ($rel !== '/' && is_file($full)) {
17 if (str_ends_with(strtolower($rel), '.webmanifest')) {
18 header('Content-Type: application/manifest+json; charset=utf-8');
19 header('Cache-Control: no-cache');
20 readfile($full);
21 return true;
22 }
23 return false;
24 }
17 25 require __DIR__.'/index.php';
18 26 return true;
@@ -13,6 +13,14 @@ if (preg_match('~^/api\.php(?:/|$)~', $rel)) {
13 return true;
13 return true;
14}
14}
15$full = __DIR__.$rel;
15$full = __DIR__.$rel;
16if ($rel !== '/' && is_file($full)) return false;
16if ($rel !== '/' && is_file($full)) {
17 if (str_ends_with(strtolower($rel), '.webmanifest')) {
18 header('Content-Type: application/manifest+json; charset=utf-8');
19 header('Cache-Control: no-cache');
20 readfile($full);
21 return true;
22 }
23 return false;
24}
17require __DIR__.'/index.php';
25require __DIR__.'/index.php';
18return true;
26return true;
web/sw.js added +120 −0
@@ -0,0 +1,120 @@
1 'use strict';
2
3 // Shell-cache voor offline lezen. API, inloggen en andere schrijfacties gaan altijd naar het netwerk.
4 const CACHE = 'verhalenboek-v1';
5 const PRECACHE = [
6 'assets/favicon.svg',
7 'assets/favicon-32.png',
8 'assets/favicon-16.png',
9 'assets/apple-touch-icon.png',
10 'assets/icon-192.png',
11 'assets/icon-512.png',
12 'assets/icon-maskable-192.png',
13 'assets/icon-maskable-512.png',
14 'assets/mask-icon.svg',
15 'assets/app.css',
16 'assets/app.js',
17 'assets/pwa.js',
18 ];
19
20 self.addEventListener('install', (event) => {
21 event.waitUntil(installShell());
22 });
23
24 self.addEventListener('activate', (event) => {
25 event.waitUntil(activateShell());
26 });
27
28 self.addEventListener('fetch', (event) => {
29 const request = event.request;
30 if (request.method !== 'GET') return;
31
32 let url;
33 try {
34 url = new URL(request.url);
35 } catch (error) {
36 return;
37 }
38 if (url.origin !== self.location.origin || bypass(url)) return;
39 if (url.pathname.endsWith('/sw.js')) return;
40
41 if (request.mode === 'navigate') {
42 event.respondWith(networkFirstNavigation(request));
43 return;
44 }
45 if (/\.(?:css|js|png|svg|webp|woff2?)$/i.test(url.pathname)) {
46 event.respondWith(networkFirstAsset(request));
47 }
48 });
49
50 async function installShell() {
51 const cache = await caches.open(CACHE);
52 const scope = self.registration.scope;
53 await cache.addAll(PRECACHE.map((path) => new URL(path, scope)));
54 try {
55 const shellUrl = new URL('./', scope);
56 const shell = await fetch(shellUrl, { cache: 'no-store' });
57 if (shell.ok && shell.type === 'basic' && !shell.redirected) await storeShell(cache, shellUrl, shell);
58 } catch (error) {
59 // Zonder HTML-shell blijft installeren mogelijk; de pagina vult de cache bij het eerste bezoek.
60 }
61 await self.skipWaiting();
62 }
63
64 async function activateShell() {
65 const keys = await caches.keys();
66 await Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)));
67 await self.clients.claim();
68 }
69
70 function bypass(url) {
71 return /\/(?:api|auth|callback)\.php(?:\/|$)/i.test(url.pathname);
72 }
73
74 async function networkFirstNavigation(request) {
75 const cache = await caches.open(CACHE);
76 try {
77 const response = await fetch(request);
78 if (response.ok && response.type === 'basic' && !response.redirected) {
79 try {
80 await storeShell(cache, request, response.clone());
81 } catch (error) {
82 // Een mislukte shell-cache mag het laden niet tegenhouden.
83 }
84 }
85 return response;
86 } catch (error) {
87 const cached = await cache.match(request, { ignoreSearch: true })
88 || await cache.match(new URL('./', self.registration.scope), { ignoreSearch: true });
89 if (cached) return cached;
90 return new Response('Verhalenboek is niet bereikbaar zonder internet.', {
91 status: 503,
92 headers: { 'Content-Type': 'text/plain; charset=utf-8' },
93 });
94 }
95 }
96
97 async function networkFirstAsset(request) {
98 const cache = await caches.open(CACHE);
99 try {
100 const response = await fetch(request);
101 if (response.ok && response.type === 'basic') await cache.put(request, response.clone());
102 return response;
103 } catch (error) {
104 const cached = await cache.match(request) || await cache.match(request, { ignoreSearch: true });
105 if (cached) return cached;
106 throw error;
107 }
108 }
109
110 async function storeShell(cache, request, response) {
111 const headers = new Headers(response.headers);
112 headers.delete('cache-control');
113 headers.delete('set-cookie');
114 const body = await response.blob();
115 await cache.put(request, new Response(body, {
116 status: response.status,
117 statusText: response.statusText,
118 headers,
119 }));
120 }
@@ -0,0 +1,120 @@
1'use strict';
2
3// Shell-cache voor offline lezen. API, inloggen en andere schrijfacties gaan altijd naar het netwerk.
4const CACHE = 'verhalenboek-v1';
5const PRECACHE = [
6 'assets/favicon.svg',
7 'assets/favicon-32.png',
8 'assets/favicon-16.png',
9 'assets/apple-touch-icon.png',
10 'assets/icon-192.png',
11 'assets/icon-512.png',
12 'assets/icon-maskable-192.png',
13 'assets/icon-maskable-512.png',
14 'assets/mask-icon.svg',
15 'assets/app.css',
16 'assets/app.js',
17 'assets/pwa.js',
18];
19
20self.addEventListener('install', (event) => {
21 event.waitUntil(installShell());
22});
23
24self.addEventListener('activate', (event) => {
25 event.waitUntil(activateShell());
26});
27
28self.addEventListener('fetch', (event) => {
29 const request = event.request;
30 if (request.method !== 'GET') return;
31
32 let url;
33 try {
34 url = new URL(request.url);
35 } catch (error) {
36 return;
37 }
38 if (url.origin !== self.location.origin || bypass(url)) return;
39 if (url.pathname.endsWith('/sw.js')) return;
40
41 if (request.mode === 'navigate') {
42 event.respondWith(networkFirstNavigation(request));
43 return;
44 }
45 if (/\.(?:css|js|png|svg|webp|woff2?)$/i.test(url.pathname)) {
46 event.respondWith(networkFirstAsset(request));
47 }
48});
49
50async function installShell() {
51 const cache = await caches.open(CACHE);
52 const scope = self.registration.scope;
53 await cache.addAll(PRECACHE.map((path) => new URL(path, scope)));
54 try {
55 const shellUrl = new URL('./', scope);
56 const shell = await fetch(shellUrl, { cache: 'no-store' });
57 if (shell.ok && shell.type === 'basic' && !shell.redirected) await storeShell(cache, shellUrl, shell);
58 } catch (error) {
59 // Zonder HTML-shell blijft installeren mogelijk; de pagina vult de cache bij het eerste bezoek.
60 }
61 await self.skipWaiting();
62}
63
64async function activateShell() {
65 const keys = await caches.keys();
66 await Promise.all(keys.filter((key) => key !== CACHE).map((key) => caches.delete(key)));
67 await self.clients.claim();
68}
69
70function bypass(url) {
71 return /\/(?:api|auth|callback)\.php(?:\/|$)/i.test(url.pathname);
72}
73
74async function networkFirstNavigation(request) {
75 const cache = await caches.open(CACHE);
76 try {
77 const response = await fetch(request);
78 if (response.ok && response.type === 'basic' && !response.redirected) {
79 try {
80 await storeShell(cache, request, response.clone());
81 } catch (error) {
82 // Een mislukte shell-cache mag het laden niet tegenhouden.
83 }
84 }
85 return response;
86 } catch (error) {
87 const cached = await cache.match(request, { ignoreSearch: true })
88 || await cache.match(new URL('./', self.registration.scope), { ignoreSearch: true });
89 if (cached) return cached;
90 return new Response('Verhalenboek is niet bereikbaar zonder internet.', {
91 status: 503,
92 headers: { 'Content-Type': 'text/plain; charset=utf-8' },
93 });
94 }
95}
96
97async function networkFirstAsset(request) {
98 const cache = await caches.open(CACHE);
99 try {
100 const response = await fetch(request);
101 if (response.ok && response.type === 'basic') await cache.put(request, response.clone());
102 return response;
103 } catch (error) {
104 const cached = await cache.match(request) || await cache.match(request, { ignoreSearch: true });
105 if (cached) return cached;
106 throw error;
107 }
108}
109
110async function storeShell(cache, request, response) {
111 const headers = new Headers(response.headers);
112 headers.delete('cache-control');
113 headers.delete('set-cookie');
114 const body = await response.blob();
115 await cache.put(request, new Response(body, {
116 status: response.status,
117 statusText: response.statusText,
118 headers,
119 }));
120}
web/tests/pwa.py added +202 −0
@@ -0,0 +1,202 @@
1 #!/usr/bin/env python3
2 """Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/."""
3 import json
4 import os
5 import socket
6 import struct
7 import subprocess
8 import tempfile
9 import time
10 import urllib.error
11 import urllib.request
12 from pathlib import Path
13
14 WEB = Path(__file__).resolve().parents[1]
15 ROOT = WEB.parent
16 PREFIX = '/verhaaltjesboek'
17 checks = 0
18
19 def check(value, label):
20 global checks
21 checks += 1
22 assert value, label
23
24 def png_size(path):
25 data = path.read_bytes()
26 check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG')
27 return struct.unpack('>II', data[16:24])
28
29 manifest = json.loads((WEB / 'manifest.webmanifest').read_text())
30 check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp')
31 check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave')
32 check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap')
33 check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap')
34 check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope')
35 check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina')
36 icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']}
37 for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]:
38 icon = icons.get((size, purpose))
39 check(icon is not None, f'Icoon {size} ({purpose})')
40 check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}')
41 file = WEB / icon['src'].removeprefix(PREFIX + '/')
42 check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}')
43
44 check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180')
45 check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32')
46 svg = (WEB / 'assets/favicon.svg').read_text()
47 check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer')
48 check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
49
50 worker = (WEB / 'sw.js').read_text()
51 check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
52 check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
53 check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
54 registrar = (WEB / 'assets/pwa.js').read_text()
55 check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
56
57 router = r'''<?php
58 declare(strict_types=1);
59 $root = getenv('VERHALENBOEK_WEBROOT');
60 $prefix = '/verhaaltjesboek';
61 $path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
62 if ($path === $prefix) {
63 header('Location: '.$prefix.'/');
64 return true;
65 }
66 if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) {
67 http_response_code(404);
68 header('Content-Type: text/plain; charset=utf-8');
69 echo 'Niet gevonden';
70 return true;
71 }
72 $rel = substr($path, strlen($prefix));
73 if (preg_match('#^/api\.php(?:/|$)#', $rel)) {
74 $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php';
75 require $root.'/api.php';
76 return true;
77 }
78 if ($rel === '/' || $rel === '') {
79 $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php';
80 require $root.'/index.php';
81 return true;
82 }
83 $file = $root.$rel;
84 if (str_ends_with(strtolower($rel), '.php') && is_file($file)) {
85 $_SERVER['SCRIPT_NAME'] = $prefix.$rel;
86 require $file;
87 return true;
88 }
89 if (is_file($file)) {
90 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
91 $type = match ($extension) {
92 'webmanifest' => 'application/manifest+json; charset=utf-8',
93 'js' => 'application/javascript; charset=utf-8',
94 'css' => 'text/css; charset=utf-8',
95 'svg' => 'image/svg+xml',
96 'png' => 'image/png',
97 default => 'application/octet-stream',
98 };
99 header('Content-Type: '.$type);
100 if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache');
101 readfile($file);
102 return true;
103 }
104 http_response_code(404);
105 header('Content-Type: text/plain; charset=utf-8');
106 echo 'Niet gevonden';
107 return true;
108 '''
109
110 def free_port():
111 with socket.socket() as sock:
112 sock.bind(('127.0.0.1', 0))
113 return sock.getsockname()[1]
114
115 def wait_for(url):
116 for _ in range(100):
117 try:
118 urllib.request.urlopen(url).close()
119 return
120 except urllib.error.URLError:
121 time.sleep(0.05)
122 raise RuntimeError('server startte niet: ' + url)
123
124 def fetch(url, method='GET', data=None, headers=None):
125 request = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
126 try:
127 response = urllib.request.urlopen(request)
128 except urllib.error.HTTPError as error:
129 response = error
130 with response:
131 body = response.read()
132 return response.status, {key.lower(): value for key, value in response.headers.items()}, body
133
134 with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp:
135 tmp_path = Path(tmp)
136 (tmp_path / 'data').mkdir()
137 router_path = tmp_path / 'router.php'
138 router_path.write_text(router)
139 port = free_port()
140 base = f'http://127.0.0.1:{port}{PREFIX}'
141 log = (tmp_path / 'server.log').open('w')
142 process = subprocess.Popen(
143 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)],
144 stdout=log, stderr=log, start_new_session=True,
145 env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)},
146 )
147 try:
148 wait_for(base + '/')
149 status, headers, body = fetch(base + '/manifest.webmanifest')
150 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type')
151 served = json.loads(body)
152 check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap')
153 status, headers, html = fetch(base + '/')
154 page = html.decode()
155 check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap')
156 check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief')
157 check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel')
158 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
159 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
160 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
161 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
162 status, headers, payload = fetch(base + '/assets/' + name)
163 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
164 status, headers, script = fetch(base + '/sw.js')
165 check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap')
166 status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'})
167 profile = json.loads(me)
168 check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken')
169 status, _, denied = fetch(
170 base + '/api.php/days',
171 method='POST',
172 data=b'{}',
173 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
174 )
175 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
176 status, doc_headers, docs = fetch(base + '/docs.php')
177 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
178 finally:
179 process.kill()
180 process.wait(timeout=5)
181 log.close()
182
183 root_port = free_port()
184 with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp:
185 env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')}
186 Path(tmp, 'data').mkdir()
187 log = Path(tmp, 'server.log').open('w')
188 process = subprocess.Popen(
189 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')],
190 stdout=log, stderr=log, start_new_session=True, env=env,
191 )
192 try:
193 wait_for(f'http://127.0.0.1:{root_port}/')
194 status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest')
195 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type')
196 check(b'"scope"' in body, 'Lokale router levert het manifest')
197 finally:
198 process.kill()
199 process.wait(timeout=5)
200 log.close()
201
202 print(f'PWA: {checks} controles geslaagd.')
@@ -0,0 +1,202 @@
1#!/usr/bin/env python3
2"""Manifest, pictogrammen en service worker, met de juiste scope onder /verhaaltjesboek/."""
3import json
4import os
5import socket
6import struct
7import subprocess
8import tempfile
9import time
10import urllib.error
11import urllib.request
12from pathlib import Path
13
14WEB = Path(__file__).resolve().parents[1]
15ROOT = WEB.parent
16PREFIX = '/verhaaltjesboek'
17checks = 0
18
19def check(value, label):
20 global checks
21 checks += 1
22 assert value, label
23
24def png_size(path):
25 data = path.read_bytes()
26 check(data.startswith(b'\x89PNG\r\n\x1a\n') and data[12:16] == b'IHDR', f'{path.name} is een PNG')
27 return struct.unpack('>II', data[16:24])
28
29manifest = json.loads((WEB / 'manifest.webmanifest').read_text())
30check(manifest['name'] == 'Verhalenboek' and manifest['short_name'] == 'Verhalenboek', 'Naam van de webapp')
31check(manifest['lang'] == 'nl' and manifest['display'] == 'standalone', 'Taal en standalone-weergave')
32check(manifest['start_url'] == PREFIX + '/' and manifest['scope'] == PREFIX + '/', 'start_url en scope blijven in de submap')
33check(manifest['id'] == PREFIX + '/', 'App-id blijft de submap')
34check(manifest['start_url'].startswith(manifest['scope']), 'start_url valt binnen scope')
35check(manifest['theme_color'] == '#f4efe6' and manifest['background_color'] == '#f4efe6', 'Kleuren volgen de pagina')
36icons = {(icon['sizes'], icon['purpose']): icon for icon in manifest['icons']}
37for size, purpose in [('192x192', 'any'), ('512x512', 'any'), ('192x192', 'maskable'), ('512x512', 'maskable')]:
38 icon = icons.get((size, purpose))
39 check(icon is not None, f'Icoon {size} ({purpose})')
40 check(icon['src'].startswith(PREFIX + '/assets/'), f'Icoonpad blijft in de submap: {icon["src"]}')
41 file = WEB / icon['src'].removeprefix(PREFIX + '/')
42 check(file.is_file() and png_size(file) == tuple(int(part) for part in size.split('x')), f'{file.name} is {size}')
43
44check(png_size(WEB / 'assets/apple-touch-icon.png') == (180, 180), 'apple-touch-icon is 180')
45check(png_size(WEB / 'assets/favicon-32.png') == (32, 32), 'favicon-32 is 32')
46svg = (WEB / 'assets/favicon.svg').read_text()
47check('f4a261' in svg.lower() and '3f63d4' in svg.lower(), 'Favicon blijft een blauw boek met oranje bladwijzer')
48check('<svg' in (WEB / 'assets/mask-icon.svg').read_text(), 'mask-icon is svg')
49
50worker = (WEB / 'sw.js').read_text()
51check("request.method !== 'GET'" in worker, 'Service worker laat schrijfacties met rust')
52check('api' in worker and 'auth' in worker and 'callback' in worker, 'Service worker slaat api en login over')
53check("pathname.endsWith('/sw.js')" in worker, 'Service worker cachet zichzelf niet')
54registrar = (WEB / 'assets/pwa.js').read_text()
55check("new URL('sw.js', scope)" in registrar and 'scope: scope.href' in registrar, 'Registratie gebruikt de map van de pagina')
56
57router = r'''<?php
58declare(strict_types=1);
59$root = getenv('VERHALENBOEK_WEBROOT');
60$prefix = '/verhaaltjesboek';
61$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
62if ($path === $prefix) {
63 header('Location: '.$prefix.'/');
64 return true;
65}
66if (!is_string($root) || $root === '' || !str_starts_with($path, $prefix.'/')) {
67 http_response_code(404);
68 header('Content-Type: text/plain; charset=utf-8');
69 echo 'Niet gevonden';
70 return true;
71}
72$rel = substr($path, strlen($prefix));
73if (preg_match('#^/api\.php(?:/|$)#', $rel)) {
74 $_SERVER['SCRIPT_NAME'] = $prefix.'/api.php';
75 require $root.'/api.php';
76 return true;
77}
78if ($rel === '/' || $rel === '') {
79 $_SERVER['SCRIPT_NAME'] = $prefix.'/index.php';
80 require $root.'/index.php';
81 return true;
82}
83$file = $root.$rel;
84if (str_ends_with(strtolower($rel), '.php') && is_file($file)) {
85 $_SERVER['SCRIPT_NAME'] = $prefix.$rel;
86 require $file;
87 return true;
88}
89if (is_file($file)) {
90 $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
91 $type = match ($extension) {
92 'webmanifest' => 'application/manifest+json; charset=utf-8',
93 'js' => 'application/javascript; charset=utf-8',
94 'css' => 'text/css; charset=utf-8',
95 'svg' => 'image/svg+xml',
96 'png' => 'image/png',
97 default => 'application/octet-stream',
98 };
99 header('Content-Type: '.$type);
100 if ($extension === 'webmanifest' || basename($file) === 'sw.js') header('Cache-Control: no-cache');
101 readfile($file);
102 return true;
103}
104http_response_code(404);
105header('Content-Type: text/plain; charset=utf-8');
106echo 'Niet gevonden';
107return true;
108'''
109
110def free_port():
111 with socket.socket() as sock:
112 sock.bind(('127.0.0.1', 0))
113 return sock.getsockname()[1]
114
115def wait_for(url):
116 for _ in range(100):
117 try:
118 urllib.request.urlopen(url).close()
119 return
120 except urllib.error.URLError:
121 time.sleep(0.05)
122 raise RuntimeError('server startte niet: ' + url)
123
124def fetch(url, method='GET', data=None, headers=None):
125 request = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
126 try:
127 response = urllib.request.urlopen(request)
128 except urllib.error.HTTPError as error:
129 response = error
130 with response:
131 body = response.read()
132 return response.status, {key.lower(): value for key, value in response.headers.items()}, body
133
134with tempfile.TemporaryDirectory(prefix='pwa-', dir=WEB / 'tests/artifacts') as tmp:
135 tmp_path = Path(tmp)
136 (tmp_path / 'data').mkdir()
137 router_path = tmp_path / 'router.php'
138 router_path.write_text(router)
139 port = free_port()
140 base = f'http://127.0.0.1:{port}{PREFIX}'
141 log = (tmp_path / 'server.log').open('w')
142 process = subprocess.Popen(
143 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{port}', '-t', str(tmp_path), str(router_path)],
144 stdout=log, stderr=log, start_new_session=True,
145 env={**os.environ, 'VERHALENBOEK_DATA_DIR': str(tmp_path / 'data'), 'VERHALENBOEK_WEBROOT': str(WEB)},
146 )
147 try:
148 wait_for(base + '/')
149 status, headers, body = fetch(base + '/manifest.webmanifest')
150 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Manifest heeft het juiste type')
151 served = json.loads(body)
152 check(served['start_url'] == PREFIX + '/' and served['scope'] == PREFIX + '/', 'Geserveerd manifest blijft in de submap')
153 status, headers, html = fetch(base + '/')
154 page = html.decode()
155 check(status == 200 and '<title>Verhalenboek</title>' in page, 'Startpagina onder de submap')
156 check('rel="manifest" href="manifest.webmanifest"' in page, 'Manifestlink is relatief')
157 check('href="/manifest' not in page and 'href="/assets/' not in page and 'src="/' not in page, 'Geen absolute paden vanaf de domeinwortel')
158 check('apple-mobile-web-app-capable' in page and 'apple-mobile-web-app-title' in page and 'Verhalenboek' in page, 'iOS-meta voor toevoegen aan beginscherm')
159 check('assets/apple-touch-icon.png' in page and 'assets/favicon.svg' in page and 'assets/pwa.js' in page, 'Favicon, aanraakicoon en registratie')
160 check('name="theme-color"' in page and '#f4efe6' in page, 'Thema-kleur')
161 for name in ['icon-192.png', 'icon-512.png', 'icon-maskable-512.png', 'apple-touch-icon.png', 'favicon.svg']:
162 status, headers, payload = fetch(base + '/assets/' + name)
163 check(status == 200 and len(payload) > 32, name + ' is bereikbaar')
164 status, headers, script = fetch(base + '/sw.js')
165 check(status == 200 and b"method !== 'GET'" in script and headers.get('content-type', '').startswith('application/javascript'), 'Service worker onder de submap')
166 status, _, me = fetch(base + '/api.php/me', headers={'Accept': 'application/json'})
167 profile = json.loads(me)
168 check(status == 200 and profile['user']['name'] == 'test_user_1', 'API GET onder de submap blijft werken')
169 status, _, denied = fetch(
170 base + '/api.php/days',
171 method='POST',
172 data=b'{}',
173 headers={'Accept': 'application/json', 'Content-Type': 'application/json'},
174 )
175 check(status == 403 and 'Ongeldige sessie' in json.loads(denied)['error'], 'API POST onder de submap blijft naar PHP gaan')
176 status, doc_headers, docs = fetch(base + '/docs.php')
177 check(status == 200 and 'rel="manifest" href="manifest.webmanifest"' in docs.decode(), 'Documentatie deelt het manifest')
178 finally:
179 process.kill()
180 process.wait(timeout=5)
181 log.close()
182
183root_port = free_port()
184with tempfile.TemporaryDirectory(prefix='pwa-root-', dir=WEB / 'tests/artifacts') as tmp:
185 env = {**os.environ, 'VERHALENBOEK_DATA_DIR': str(Path(tmp) / 'data')}
186 Path(tmp, 'data').mkdir()
187 log = Path(tmp, 'server.log').open('w')
188 process = subprocess.Popen(
189 ['php', '-d', 'opcache.enable=0', '-S', f'127.0.0.1:{root_port}', '-t', str(WEB), str(WEB / 'router.php')],
190 stdout=log, stderr=log, start_new_session=True, env=env,
191 )
192 try:
193 wait_for(f'http://127.0.0.1:{root_port}/')
194 status, headers, body = fetch(f'http://127.0.0.1:{root_port}/manifest.webmanifest')
195 check(status == 200 and headers.get('content-type', '').startswith('application/manifest+json'), 'Lokale router zet het manifest-type')
196 check(b'"scope"' in body, 'Lokale router levert het manifest')
197 finally:
198 process.kill()
199 process.wait(timeout=5)
200 log.close()
201
202print(f'PWA: {checks} controles geslaagd.')