diff --git a/.github/workflows/demo.yaml b/.github/workflows/demo.yaml new file mode 100644 index 00000000..af1c9a81 --- /dev/null +++ b/.github/workflows/demo.yaml @@ -0,0 +1,90 @@ +name: Demo + +# The demo application, with PHP as WebAssembly, on GitHub Pages: see +# wasm-demo/castor.php. GitHub Pages must deploy from GitHub Actions, in the +# settings of the repository. + +on: + push: + branches: [ main ] + workflow_dispatch: ~ + +permissions: + contents: read + pages: write + id-token: write + +# One deployment at a time, the last push wins +concurrency: + group: pages + cancel-in-progress: true + +jobs: + deploy: + runs-on: ubuntu-latest + name: "Build and deploy the demo" + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + env: + COMPOSER_ROOT_VERSION: "dev-main" + defaults: + run: + working-directory: wasm-demo + steps: + - name: "Checkout" + uses: actions/checkout@v4 + + - name: "Setup PHP" + uses: shivammathur/setup-php@v2 + with: + php-version: "8.5" + tools: 'castor, composer:v2, flex' + coverage: none + + - name: "Setup node" + uses: actions/setup-node@v4 + with: + node-version: 24 + + - name: "Install PHP dependencies" + run: composer install --no-interaction --no-scripts + working-directory: . + + - name: "Install php-wasm-builder" + run: castor castor:composer install --no-interaction + + - name: "Configure GitHub Pages" + id: pages + uses: actions/configure-pages@v5 + + # The cache of the layers needs the docker-container driver of + # buildx, and the runtime token and URLs of GitHub Actions + - name: "Setup buildx" + uses: docker/setup-buildx-action@v3 + + - name: "Expose the GitHub Actions runtime" + uses: crazy-max/ghaction-github-runtime@v3 + + - name: "Build the demo" + run: > + castor demo:build + --base-path='${{ steps.pages.outputs.base_path }}/' + --set='*.cache-from=type=gha' + --set='*.cache-to=type=gha,mode=max,ignore-error=true' + + - name: "Check the pages of the admin panel" + run: castor demo:check + + # Only demo:check runs PHP in node + - name: "Remove the build for node" + run: rm public/build/php-node.* + + - name: "Upload the demo" + uses: actions/upload-pages-artifact@v3 + with: + path: wasm-demo/public + + - name: "Deploy to GitHub Pages" + id: deployment + uses: actions/deploy-pages@v4 diff --git a/config/routes.yaml b/config/routes.yaml index 9790f123..466f5cdb 100644 --- a/config/routes.yaml +++ b/config/routes.yaml @@ -1,8 +1,8 @@ index: path: / - controller: Symfony\Bundle\FrameworkBundle\Controller\TemplateController + controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController defaults: - template: base.html.twig + route: sylius_admin_ui_dashboard basic_create: path: /basic/create diff --git a/wasm-demo/.gitignore b/wasm-demo/.gitignore new file mode 100644 index 00000000..02ca1cbc --- /dev/null +++ b/wasm-demo/.gitignore @@ -0,0 +1,8 @@ +/.castor/vendor/ +/build/ +/public/build/ +/public/assets/ +/public/avatars/ +/public/bundles/ +/public/404.html +/.castor.stub.php diff --git a/wasm-demo/castor.composer.json b/wasm-demo/castor.composer.json new file mode 100644 index 00000000..2174784a --- /dev/null +++ b/wasm-demo/castor.composer.json @@ -0,0 +1,5 @@ +{ + "require": { + "lyrixx/php-wasm-builder": "^1.0" + } +} diff --git a/wasm-demo/castor.composer.lock b/wasm-demo/castor.composer.lock new file mode 100644 index 00000000..d28e6184 --- /dev/null +++ b/wasm-demo/castor.composer.lock @@ -0,0 +1,64 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "97a46a37ed63ca804f0891c1c941ee32", + "packages": [ + { + "name": "lyrixx/php-wasm-builder", + "version": "v1.0.0", + "source": { + "type": "git", + "url": "https://github.com/lyrixx/php-wasm-builder.git", + "reference": "59301bdddfd3d7387e8d7ae3b5e73ff633779a70" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/lyrixx/php-wasm-builder/zipball/59301bdddfd3d7387e8d7ae3b5e73ff633779a70", + "reference": "59301bdddfd3d7387e8d7ae3b5e73ff633779a70", + "shasum": "" + }, + "require": { + "php": ">=8.2" + }, + "type": "library", + "autoload": { + "files": [ + "src/functions-internal.php", + "src/functions.php" + ], + "psr-4": { + "PhpWasm\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Builds PHP as WebAssembly: a Dockerfile, and a castor function to build stacks (a PHP version, extensions, what to embed) with one command", + "keywords": [ + "castor", + "emscripten", + "php", + "wasm", + "webassembly" + ], + "support": { + "issues": "https://github.com/lyrixx/php-wasm-builder/issues", + "source": "https://github.com/lyrixx/php-wasm-builder/tree/v1.0.0" + }, + "time": "2026-11-24T11:17:01+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/wasm-demo/castor.php b/wasm-demo/castor.php new file mode 100644 index 00000000..e16e303c --- /dev/null +++ b/wasm-demo/castor.php @@ -0,0 +1,247 @@ +php(WASM_PHP_VERSION) + ->extensions('ctype', 'dom', 'fileinfo', 'filter', 'iconv', 'mbstring', 'pdo_sqlite', 'session', 'simplexml', 'tokenizer', 'xml', 'xmlreader', 'xmlwriter') + ->memory('256mb') + ->embed(EMBED, at: '/app') + ->warmup('bin/console', 'cache:warmup') + ->opcache(Opcache::Runtime) + ->targets(Target::Web, Target::Node) + ->outputDir(PUBLIC_DIR . '/build'); +} + +#[AsTask(name: 'embed', namespace: 'demo', description: 'Prepares the application to embed, in build/embed, and its public files, in public/')] +function embed( + #[AsOption(description: 'The admin UI: shadcn or bootstrap', autocomplete: ['shadcn', 'bootstrap'])] + string $ui = 'shadcn', + #[AsOption(description: 'The color themes of shadcn, "none" for the neutral one', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, autocomplete: ['blue', 'green', 'orange', 'rose', 'slate', 'stone', 'violet', 'zinc', 'none'])] + array $theme = ['rose'], +): void { + if (!in_array($ui, ['shadcn', 'bootstrap'], true)) { + throw new \InvalidArgumentException(\sprintf('The admin UI is "shadcn" or "bootstrap", not "%s".', $ui)); + } + + io()->section('The database, with the fixtures'); + $db = ROOT . '/var/demo.db'; + fs()->remove($db); + $dev = context() + ->withWorkingDirectory(ROOT) + ->withEnvironment(['APP_ENV' => 'dev', 'DATABASE_URL' => 'sqlite:///%kernel.project_dir%/var/demo.db']); + run(['php', 'bin/console', 'importmap:install'], context: $dev); + run(['php', 'bin/console', 'doctrine:schema:create', '-q'], context: $dev); + run(['php', 'bin/console', 'doctrine:fixtures:load', '-n', '-q'], context: $dev); + + io()->section('The application, without its dev dependencies'); + fs()->remove(EMBED); + fs()->mkdir(EMBED); + $mirror = static fn (string $path) => fs()->mirror(ROOT . "/{$path}", EMBED . "/{$path}"); + foreach (['app', 'assets', 'bin', 'config', 'templates', 'translations'] as $path) { + $mirror($path); + } + // Only Foundry needs them, a dev dependency + fs()->remove([EMBED . '/app/DataFixtures', EMBED . '/app/Factory', EMBED . '/app/Story']); + // symfony.lock: Flex does not run the recipes again + foreach (['importmap.php', 'symfony.lock'] as $path) { + fs()->copy(ROOT . "/{$path}", EMBED . "/{$path}"); + } + fs()->copy(ROOT . '/public/index.php', EMBED . '/public/index.php'); + foreach ((new Finder())->directories()->in(ROOT . '/src')->depth(0) as $package) { + foreach (['assets', 'config', 'public', 'src', 'templates', 'translations'] as $path) { + if (is_dir("{$package}/{$path}")) { + $mirror("src/{$package->getFilename()}/{$path}"); + } + } + } + fs()->mirror(__DIR__ . '/overlay', EMBED, options: ['override' => true]); + // DoctrineBundle 3 does not have them anymore, and the monorepo never runs + // in prod + $doctrine = EMBED . '/config/packages/doctrine.yaml'; + fs()->dumpFile($doctrine, preg_replace('/^\s+(auto_generate_proxy_classes|proxy_dir):.*\n/m', '', file_get_contents($doctrine))); + + $composer = json_decode(file_get_contents(ROOT . '/composer.json'), true, flags: \JSON_THROW_ON_ERROR); + foreach ($composer['require-dev'] as $package => $constraint) { + if (!in_array($package, DEV_ONLY_PACKAGES, true)) { + $composer['require'][$package] = $constraint; + } + } + unset($composer['require-dev'], $composer['autoload-dev'], $composer['scripts']); + $composer['autoload']['psr-4']['App\\'] = 'app/'; + $composer['config']['platform']['php'] = WASM_PHP_VERSION; + fs()->dumpFile(EMBED . '/composer.json', json_encode($composer, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES) . "\n"); + + $embed = context()->withWorkingDirectory(EMBED)->withEnvironment(['APP_ENV' => 'prod', 'APP_DEBUG' => '0']); + run(['composer', 'update', '--no-dev', '--no-scripts', '--no-interaction', '--classmap-authoritative'], context: $embed); + fs()->mirror(ROOT . '/assets/vendor', EMBED . '/assets/vendor'); + + io()->section(\sprintf('The %s admin UI', $ui)); + // The script of the monorepo: the bundle, its configuration, the template + // namespaces, and the Tailwind stylesheet of shadcn + run(['bin/switch-admin-ui', $ui], context: $embed); + if ('shadcn' === $ui) { + run(['bin/switch-admin-theme', ...$theme], context: $embed); + // What only works with shadcn, as the test credentials on the login + // page: before the Tailwind stylesheet is built, for its classes + fs()->mirror(__DIR__ . '/overlay-shadcn', EMBED, options: ['override' => true]); + } + + io()->section('The public files, that the server serves, not PHP'); + // Iconify is called for the icons that are not local: PHP has no network + // in the browser + run(['php', 'bin/console', 'ux:icons:lock', '-q'], context: $embed); + // ux:icons:lock only finds the ones of the templates: the menus and the + // grids name theirs in PHP and in the configuration + $icons = []; + foreach ((new Finder())->files()->in([EMBED . '/app', EMBED . '/config', EMBED . '/src', EMBED . '/templates'])->name(['*.php', '*.yaml', '*.twig']) as $file) { + // The usual sets, and any icon given to setIcon() or to an "icon" key + preg_match_all('/[\'"]((?:tabler|lucide|mdi):[a-z0-9-]+)[\'"]/', $file->getContents(), $matches); + array_push($icons, ...$matches[1]); + preg_match_all('/(?:setIcon\(\s*|[\'"]?icon[\'"]?\s*(?:=>|:)\s*)[\'"]([a-z0-9-]+:[a-z0-9-]+)[\'"]/', $file->getContents(), $matches); + array_push($icons, ...$matches[1]); + } + foreach (array_unique($icons) as $icon) { + if (!is_file(EMBED . '/assets/icons/' . str_replace(':', '/', $icon) . '.svg')) { + run(['php', 'bin/console', 'ux:icons:import', $icon, '-q'], context: $embed->withAllowFailure()); + } + } + run(['php', 'bin/console', 'assets:install', 'public', '--no-interaction', '-q'], context: $embed); + run(['php', 'bin/console', 'tailwind:build', '--minify', '-q'], context: $embed); + run(['php', 'bin/console', 'asset-map:compile', '-q'], context: $embed); + foreach (['assets', 'bundles'] as $path) { + fs()->remove(PUBLIC_DIR . "/{$path}"); + fs()->rename(EMBED . "/public/{$path}", PUBLIC_DIR . "/{$path}"); + } + fs()->remove(PUBLIC_DIR . '/avatars'); + fs()->mirror(ROOT . '/public/avatars', PUBLIC_DIR . '/avatars'); + // What PHP reads of the compiled assets, to render the importmap + fs()->mkdir(EMBED . '/public/assets'); + foreach ((new Finder())->files()->in(PUBLIC_DIR . '/assets')->depth(0)->name('*.json') as $file) { + fs()->copy($file->getPathname(), EMBED . '/public/assets/' . $file->getFilename()); + } + // Compiled in public/, and the cache is warmed up in PHP as WebAssembly, + // with the paths it has there + fs()->remove([EMBED . '/assets/vendor', EMBED . '/var']); + fs()->remove((new Finder())->directories()->in(EMBED . '/src')->depth(1)->name(['assets', 'public'])); + + // What is embedded is in the memory of PHP: only the English data of + // symfony/intl, 27 MB with every locale + fs()->remove((new Finder())->files()->in(EMBED . '/vendor/symfony/intl/Resources/data')->notName(['en.php', 'en_*.php', 'root.php', 'meta.php', '*.txt'])); + fs()->remove((new Finder())->directories()->in(EMBED . '/vendor')->depth('< 4')->name(['tests', 'Tests', 'doc', 'docs'])); + + io()->section('The database, and the name of the build'); + // Keep in sync with public/sw.js + fs()->copy($db, EMBED . '/data/demo.db'); + fs()->dumpFile(EMBED . '/data/build-id', bin2hex(random_bytes(8))); + + run(['du', '-sh', EMBED, EMBED . '/vendor']); +} + +#[AsTask(name: 'build', namespace: 'demo', description: 'Builds PHP as WebAssembly, with the application')] +function build_task( + #[AsOption(description: 'The admin UI: shadcn or bootstrap', autocomplete: ['shadcn', 'bootstrap'])] + string $ui = 'shadcn', + #[AsOption(description: 'The color themes of shadcn, "none" for the neutral one', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, autocomplete: ['blue', 'green', 'orange', 'rose', 'slate', 'stone', 'violet', 'zinc', 'none'])] + array $theme = ['rose'], + #[AsOption(description: 'Where the demo is in the URLs, "/Stack/" on the GitHub Pages of Sylius/Stack')] + string $basePath = '/', + #[AsOption(description: 'Given to "docker buildx bake --set", for a cache', mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY)] + array $set = [], + #[AsOption(description: 'Do not prepare the application again')] + bool $skipEmbed = false, +): void { + if (!preg_match('{^/([a-zA-Z0-9._-]+/)*$}', $basePath)) { + throw new \InvalidArgumentException(\sprintf('The base path starts and ends with a slash, as "/Stack/": "%s" does not.', $basePath)); + } + if (!$skipEmbed) { + embed($ui, $theme); + } + + // A cache made on the host has its paths, and its 64-bit integers: PHP as + // WebAssembly makes its own, with 32-bit ones + fs()->remove(EMBED . '/var'); + + // The web server serves the avatars, under the base path: vich_uploader_asset() + // does not add it. Keep in sync with config/packages/vich_uploader.yaml + $vich = EMBED . '/config/packages/vich_uploader.yaml'; + fs()->dumpFile($vich, preg_replace('{(uri_prefix:\s*)\S*(avatars/speakers)}', '${1}' . $basePath . '${2}', file_get_contents($vich))); + + io()->section('PHP as WebAssembly'); + build([stack()], $set); + + // php-web.mjs does not change when only the application does: the browser + // updates the service worker when a script that it imports changes, and + // fetches the .wasm again with another URL. Keep in sync with public/sw.js + fs()->dumpFile(PUBLIC_DIR . '/build/version.js', \sprintf("export default '%s';\n", file_get_contents(EMBED . '/data/build-id'))); + + // GitHub Pages answers a link to a page of the application, before the + // service worker is there, with 404.html: the start page, whose relative + // URLs are the ones of the root of the demo + fs()->dumpFile(PUBLIC_DIR . '/404.html', str_replace('
', \sprintf("\n
+ {{ 'app.demo.username'|trans({}, 'demo') }}: admin@example.com
+ {{ 'app.demo.password'|trans({}, 'demo') }}: admin
+
PHP, compiled to WebAssembly, runs Symfony, Doctrine and SQLite in a service worker: no server runs PHP.
+ +Starting PHP in the service worker…
+Log in with admin@example.com / admin.