Skip to content

Commit

Permalink
peat
Browse files Browse the repository at this point in the history
  • Loading branch information
dakujem committed Apr 16, 2022
0 parents commit c170dac
Show file tree
Hide file tree
Showing 12 changed files with 678 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.idea
vendor
composer.lock
21 changes: 21 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "dakujem/peat",
"license": "Unlicense",
"keywords": ["vite", "bridge"],
"authors": [
{
"name": "Andrej Rypák",
"email": "[email protected]"
}
],
"require": {
"php": "^7.4 || ^8",
"ext-json": "*",
"symfony/polyfill-php80": "^1"
},
"autoload": {
"psr-4": {
"Dakujem\\Peat\\": "src/"
}
}
}
24 changes: 24 additions & 0 deletions license.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
88 changes: 88 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Peat

PHP-vite bridge building tool, for any framework.

> 💿 `composer require dakujem/peat`

This tool helps integrate Vite-bundled JS apps into PHP-served web pages.

It provides a way to generate `<script>` and `<link>` tags to desired assets.


## Vite

Understanding of basics of how Vite works is essential for correct configuration.\
👉 [Vite](https://vitejs.dev)

For working integration, both `vite.config.js` and this bridge must be configured.


### Vite configuration

`build.manifest = true` - needed for integration.

`build.rollupOptions.input` must point to the `main.js` (or other JS entrypoint),
to override the default `index.html` entrypoint.

More info in the [Backend integration section](https://vitejs.dev/guide/backend-integration.html).

You may want to set `build.outDir` to point to a public dir's sub folder, so that you don't have to move the build files manually.


## Peat usage

Either `ViteBridge::makePassiveEntryLocator` friction reducer can be used, or custom entry locator setup can be composed.

To pregenerate cache for production, use `ViteBundleLocator::populateCache`.

To get asset URLs (or HTML tags), use the `ViteLocatorContract::entry` method.


## Example

> (JS sources are located in `/js/src` and the public dir is `/public`,
> `placeholder` may be replaced with any JS app/bundle name):
```js
// vite.config.js
import {defineConfig} from "vite";

export default defineConfig({
build: {
manifest: true,
outDir: '../public/placeholder', // output directly to the public dir
rollupOptions: {
// overwrite default .html entry
input: 'src/main.js',
}
}
});
```

```php
$vite = ViteBridge::makePassiveEntryLocator(
manifestFile: ROOT_DIR . '/public/placeholder/manifest.json',
cacheFile: TEMP_DIR . '/vite.php', // can be any writable file
assetPath: 'placeholder', // path from /public to the dir where the manifest is located
devServerUrl: $development ? 'http://localhost:3000' : null,
);

$html = (string) $vite->entry('src/main.js');
```

The result:
```html
<!-- PRODUCTION -->
<script type="module" src="/placeholder/assets/main.cf1f50e2.js"></script>
<script type="module" src="/placeholder/assets/vendor.5f8262d6.js"></script>
<link rel="stylesheet" href="/placeholder/assets/main.c9fc69a7.css" />

<!-- DEVELOPMENT -->
<script type="module" src="http://localhost:3000/@vite/client"></script>
<script type="module" src="http://localhost:3000/src/main.js"></script>
```

Note that you can also replace `placeholder` with an empty string ``,
then the manifest will be present directly in the public dir and the assets in the `/public/assets` dir,
which is the default.

42 changes: 42 additions & 0 deletions src/CollectiveLocator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

declare(strict_types=1);

namespace Dakujem\Peat;

use InvalidArgumentException;

/**
* Locator composed of multiple other locators attempting to return the entry in sequence.
*
* @author Andrej Rypak <[email protected]>
*/
final class CollectiveLocator implements ViteLocatorContract
{
private array $locators;

public function __construct(/*ViteLocatorContract|callable|null*/ ...$locators)
{
$this->locators = array_filter($locators);
foreach ($this->locators as $locator) {
if (!$locator instanceof ViteLocatorContract && !is_callable($locator)) {
throw new InvalidArgumentException(sprintf(
'Each locator must either implement %1$s or be callable with the same signature as %1$s::entry.',
ViteLocatorContract::class,
));
}
}
}

public function entry(string $name): ?ViteEntryAsset
{
$entryName = ltrim($name, '/');
foreach ($this->locators as $step) {
$asset = $step instanceof ViteLocatorContract ? $step->entry($entryName) : $step($entryName);
if ($asset !== null) {
return $asset;
}
}
return null;
}
}
33 changes: 33 additions & 0 deletions src/ConditionalLocator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Dakujem\Peat;

/**
* A conditional wrapper for a locator.
*
* @author Andrej Rypak <[email protected]>
*/
final class ConditionalLocator implements ViteLocatorContract
{
/** @var callable */
private $condition;
private ViteLocatorContract $serverLocator;

public function __construct(callable $condition, ViteLocatorContract $locator)
{
$this->condition = $condition;
$this->serverLocator = $locator;
}

public function __invoke(string $entryName): ?ViteEntryAsset
{
return $this->entry($entryName);
}

public function entry(string $name): ?ViteEntryAsset
{
return ($this->condition)($name) ? $this->serverLocator->entry($name) : null;
}
}
88 changes: 88 additions & 0 deletions src/ViteBridge.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

declare(strict_types=1);

namespace Dakujem\Peat;

use RuntimeException;

/**
* Static Vite entry locator factory.
*
* @author Andrej Rypak <[email protected]>
*/
final class ViteBridge
{
/**
* Returns a preconfigured asset entry locator.
* The locator reads the manifest file (or cache file) and serves asset objects.
*
* If the $devServerUrl is not `null`, links to Vite dev server are returned.
*
* The $assetPath can be used to force absolute paths or set the base path. Ignored by the dev server.
*
* @param string $manifestFile Path to the Vite-generated manifest json file.
* @param string $cacheFile This is where this locator stores (and reads from) its cache file. Must be writable.
* @param string $assetPath This will typically be relative path from the public dir to the dir with assets, or empty string ''.
* @param ?string $devServerUrl If passed, assets point to the Vite's dev server (development only).
* @param bool $strict Locators throw exceptions in strict mode, silently fail in lax mode.
* @return ViteLocatorContract
*/
public static function makePassiveEntryLocator(
string $manifestFile,
string $cacheFile,
string $assetPath = '',
?string $devServerUrl = null,
bool $strict = false
): ViteLocatorContract {
// If the dev server is on, all assets are served by the server.
if ($devServerUrl !== null) {
return new ViteServerLocator($devServerUrl);
}
// Otherwise, the assets are served from a bundle (build).
$bundleLocator = new ViteBuildLocator($manifestFile, $cacheFile, $assetPath, $strict);
if (!$strict) {
return $bundleLocator;
}
// In strict mode, the final step is to throw an exception.
return new CollectiveLocator(
$bundleLocator,
function (string $name) {
throw new RuntimeException('Not found: ' . $name);
},
);
}

/**
* @experimental
* @deprecated This function is experimental. Use at your own risk. May be removed without prior notice.
* @todo causes 1-2 second rendering hang.
* @internal I really do not want you to use this :-)
*/
public static function makeEntryLocatorWithServerDetector(
string $manifestFile,
string $cacheFile,
string $assetPath = '', // tightly bound to Vite's `build.outDir`, if it targets the public dir's subdirs.
?string $devServerUrl = null,
?callable $detector = null,
bool $strict = false
): ViteLocatorContract {
if ($devServerUrl === null) {
// No detection needed.
return self::makePassiveEntryLocator($manifestFile, $cacheFile, $assetPath, null, $strict);
}
// First, try the dev server,
// then the bundle,
// finally, when strict, kick the bucket.
return new CollectiveLocator(
new ConditionalLocator(
$detector ?? ViteServerDetector::usingCurl($devServerUrl),
new ViteServerLocator($devServerUrl)
),
new ViteBuildLocator($manifestFile, $cacheFile, $assetPath, $strict),
$strict ? function (string $name) {
throw new RuntimeException('Not found: ' . $name);
} : null,
);
}
}
Loading

0 comments on commit c170dac

Please sign in to comment.