Rust

Detector

Rust
Detects a project's packager, runtime, framework and rendering from its file names, languages and manifests.

In Appwrite#

Appwrite runs the Rust crate: the PHP extension serves the library and none of its PHP is left.

43 PHP classes served from Rust
Rust 1,801 lines (984 code)· PHP 0 lines (0 code)split
PartCodeCommentsBlankTotalFiles
Rust source9846411761,8016
PHP source00000

Comments include doc comments. Each side counts its src/; the PHP side is what the package still has in PHP.

Served from Rust (43)
Utopia\Detector\DetectionUtopia\Detector\Detection\FrameworkUtopia\Detector\Detection\Framework\AnalogUtopia\Detector\Detection\Framework\AngularUtopia\Detector\Detection\Framework\AstroUtopia\Detector\Detection\Framework\FlutterUtopia\Detector\Detection\Framework\JSUtopia\Detector\Detection\Framework\JasprUtopia\Detector\Detection\Framework\LynxUtopia\Detector\Detection\Framework\NextJsUtopia\Detector\Detection\Framework\NuxtUtopia\Detector\Detection\Framework\ReactUtopia\Detector\Detection\Framework\ReactNativeUtopia\Detector\Detection\Framework\RemixUtopia\Detector\Detection\Framework\SvelteUtopia\Detector\Detection\Framework\SvelteKitUtopia\Detector\Detection\Framework\TanStackStartUtopia\Detector\Detection\Framework\VueUtopia\Detector\Detection\PackagerUtopia\Detector\Detection\Packager\NPMUtopia\Detector\Detection\Packager\PNPMUtopia\Detector\Detection\Packager\YarnUtopia\Detector\Detection\RenderingUtopia\Detector\Detection\Rendering\SSRUtopia\Detector\Detection\Rendering\XStaticUtopia\Detector\Detection\RuntimeUtopia\Detector\Detection\Runtime\BunUtopia\Detector\Detection\Runtime\CPPUtopia\Detector\Detection\Runtime\DartUtopia\Detector\Detection\Runtime\DenoUtopia\Detector\Detection\Runtime\DotnetUtopia\Detector\Detection\Runtime\JavaUtopia\Detector\Detection\Runtime\NodeUtopia\Detector\Detection\Runtime\PHPUtopia\Detector\Detection\Runtime\PythonUtopia\Detector\Detection\Runtime\RubyUtopia\Detector\Detection\Runtime\SwiftUtopia\Detector\DetectorUtopia\Detector\Detector\FrameworkUtopia\Detector\Detector\PackagerUtopia\Detector\Detector\RenderingUtopia\Detector\Detector\RuntimeUtopia\Detector\Detector\Strategy

Install#

Shell
cargo add utopia-detector

Getting started#

Common tasks with Detector, each a complete program you can copy and run.

Before a project can be built, something has to work out what it is: which package manager it uses, which runtime runs it, which framework builds it, and whether the build is served by a server or as files. Each of these is a detector: add the options it may choose from and the inputs you have (file names, languages, a manifest), then call detect. This guide covers the common tasks.

Find the package manager

PackagerDetector returns the first option, in the order you added them, that has one of its files among the inputs. Put the more specific lockfiles first, since every npm-compatible project has a package.json.

Rust
use utopia_detector::{Npm, PackagerDetector, Pnpm, Yarn};

let mut detector = PackagerDetector::new();
detector.add_option(Pnpm).add_option(Yarn).add_option(Npm);
for file in ["package.json", "pnpm-lock.yaml", "src"] {
    detector.add_input(file);
}

assert_eq!(detector.detect().map(|p| p.name()), Some("pnpm"));
PHP
use Utopia\Detector\Detection\Packager\NPM;
use Utopia\Detector\Detection\Packager\PNPM;
use Utopia\Detector\Detection\Packager\Yarn;
use Utopia\Detector\Detector\Packager;

$detector = new Packager();
$detector->addOption(new PNPM())->addOption(new Yarn())->addOption(new NPM());
foreach (['package.json', 'pnpm-lock.yaml', 'src'] as $file) {
    $detector->addInput($file);
}

echo $detector->detect()?->getName(), "\n"; // pnpm

Find the runtime

A RuntimeDetector matches by a Strategy: file names (FileMatch), their extensions (Extension) or language names (Languages). The packager you pass shapes the install command of runtimes that depend on it.

Rust
use utopia_detector::{Node, Php, Python, RuntimeDetector, Strategy};

let mut detector = RuntimeDetector::new(Strategy::Languages, "yarn");
detector.add_option(Node).add_option(Php).add_option(Python);
detector.add_input("TypeScript").add_input("Dockerfile");

let runtime = detector.detect().expect("a runtime");
assert_eq!(runtime.name(), "node");
assert_eq!(runtime.commands(), "yarn install");
assert_eq!(runtime.entrypoint(), "index.js");

assert_eq!(Strategy::new("languages")?, Strategy::Languages);
assert!(Strategy::new("magic").is_err());
PHP
use Utopia\Detector\Detection\Runtime\Node;
use Utopia\Detector\Detection\Runtime\PHP;
use Utopia\Detector\Detection\Runtime\Python;
use Utopia\Detector\Detector\Runtime;
use Utopia\Detector\Detector\Strategy;

$detector = new Runtime(new Strategy(Strategy::LANGUAGES), 'yarn');
$detector->addOption(new Node())->addOption(new PHP())->addOption(new Python());
$detector->addInput('TypeScript')->addInput('Dockerfile');

$runtime = $detector->detect();
echo $runtime->getName(), "\n";       // node
echo $runtime->getCommands(), "\n";   // yarn install
echo $runtime->getEntrypoint(), "\n"; // index.js

Find the framework from files and dependencies

A FrameworkDetector scores every framework: a point for each of its files among the file inputs, and a point for each of its packages in each manifest. Feed it the repository's file names and the content of package.json or pubspec.yaml.

Rust
use utopia_detector::{Astro, FrameworkDetector, NextJs, React, ReactNative};

let mut detector = FrameworkDetector::new("npm");
detector.add_option(Astro).add_option(NextJs).add_option(React).add_option(ReactNative);
detector.add_file("package.json");
detector.add_manifest(r#"{"dependencies": {"react": "^18.2.0", "react-native": "^0.74.0"}}"#);

let framework = detector.detect().expect("a framework");
assert_eq!(framework.name(), "react-native");
assert_eq!(framework.install_command(), "npm install");
assert_eq!(framework.build_command(), "npm run build");
PHP
use Utopia\Detector\Detection\Framework\Astro;
use Utopia\Detector\Detection\Framework\NextJs;
use Utopia\Detector\Detection\Framework\React;
use Utopia\Detector\Detection\Framework\ReactNative;
use Utopia\Detector\Detector\Framework;

$detector = new Framework('npm');
$detector->addOption(new Astro())->addOption(new NextJs())->addOption(new React())->addOption(new ReactNative());
$detector->addInput('package.json', Framework::INPUT_FILE);
$detector->addInput('{"dependencies": {"react": "^18.2.0", "react-native": "^0.74.0"}}', Framework::INPUT_PACKAGES);

$framework = $detector->detect();
echo $framework->getName(), "\n";           // react-native
echo $framework->getInstallCommand(), "\n"; // npm install
echo $framework->getBuildCommand(), "\n";   // npm run build

Read how a framework is configured to render

Some frameworks say in their configuration whether they render on a server. config_files lists the files to read, in priority order, and adapter reads one.

Rust
use utopia_detector::{Adapter, Astro, Framework, Jaspr};

let astro = Astro;
assert_eq!(astro.config_files()[0], "astro.config.mjs");
assert_eq!(astro.adapter(b"export default defineConfig({ output: 'server' })"), Some(Adapter::Ssr));
assert_eq!(astro.adapter(b"// output: 'server'\nexport default defineConfig({})"), Some(Adapter::Static));

assert_eq!(Jaspr.adapter(b"jaspr:\n  mode: static\n"), Some(Adapter::Static));
assert_eq!(Jaspr.adapter(b"name: my_site\n"), None);
PHP
use Utopia\Detector\Detection\Framework\Astro;
use Utopia\Detector\Detection\Framework\Jaspr;

$astro = new Astro();
echo $astro->getConfigFiles()[0], "\n"; // astro.config.mjs
echo $astro->getAdapter("export default defineConfig({ output: 'server' })"), "\n"; // ssr
echo $astro->getAdapter("// output: 'server'\nexport default defineConfig({})"), "\n"; // static

echo (new Jaspr())->getAdapter("jaspr:\n  mode: static\n"), "\n"; // static
var_dump((new Jaspr())->getAdapter("name: my_site\n")); // string(0) ""

Tell server-rendered builds from static ones

A RenderingDetector looks at a framework's build output. It returns the first option with one of that framework's server files; otherwise the build is static, with its only HTML file as the fallback page when there is exactly one.

Rust
use utopia_detector::{RenderingDetector, Ssr, Static};

let mut detector = RenderingDetector::new("nuxt");
detector.add_option(Ssr::new()).add_option(Static::new());
detector.add_input("nuxt.config.js").add_input("server/index.mjs");
assert_eq!(detector.detect().name(), "ssr");

let mut detector = RenderingDetector::new("nuxt");
detector.add_option(Ssr::new()).add_option(Static::new());
detector.add_input("index.html").add_input("_nuxt/entry.js");
let rendering = detector.detect();
assert_eq!((rendering.name(), rendering.fallback_file()), ("static", Some("index.html")));
PHP
use Utopia\Detector\Detection\Rendering\SSR;
use Utopia\Detector\Detection\Rendering\XStatic;
use Utopia\Detector\Detector\Rendering;

$detector = new Rendering('nuxt');
$detector->addOption(new SSR())->addOption(new XStatic());
$detector->addInput('nuxt.config.js')->addInput('server/index.mjs');
echo $detector->detect()->getName(), "\n"; // ssr

$detector = new Rendering('nuxt');
$detector->addOption(new SSR())->addOption(new XStatic());
$detector->addInput('index.html')->addInput('_nuxt/entry.js');
$rendering = $detector->detect();
echo $rendering->getName(), ' ', $rendering->getFallbackFile(), "\n"; // static index.html

Reference#

Detection of what a project is from what it contains: its package manager, its language runtime, its web framework, and whether a build is served by a server or as static files.

Each question has a detector fed with inputs (file names, language names or manifest contents) and options to choose from:

  • PackagerDetector with Packagers (Npm, Pnpm, Yarn);
  • RuntimeDetector with Runtimes (Node, Php, Python and eight more), matching by a Strategy;
  • FrameworkDetector with Frameworks (NextJs, Nuxt, SvelteKit, Astro, Flutter and ten more), scored on files and dependencies;
  • RenderingDetector with Renderings (Ssr, Static).

Options are traits, so a project can add its own. Runtime and framework detections come back as Detected, which carries the detector's packager into the install and build commands.

PHP: ports utopia-php/detector.

PHPRust
Utopia\Detector\Detector (abstract), Detection (abstract)one detector type per question; no common base
Detector::addOption(), addInput(), detect()add_option, add_input (add_file / add_manifest on FrameworkDetector), detect on each detector
Detector\Packager, Detection\PackagerPackagerDetector, Packager
Detection\Packager\NPM, PNPM, YarnNpm, Pnpm, Yarn
Detector\Runtime, Detection\RuntimeRuntimeDetector, Runtime
Detector\Strategy (FILEMATCH, EXTENSION, LANGUAGES)Strategy
Detection\Runtime\Bun, CPP, Dart, Deno, Dotnet, Java, Node, PHP, Python, Ruby, SwiftBun, Cpp, Dart, Deno, Dotnet, Java, Node, Php, Python, Ruby, Swift
Detector\Framework, Detection\FrameworkFrameworkDetector, Framework
Framework::INPUT_FILE, INPUT_PACKAGESInput
Framework::dependencies()dependencies
Detection\Framework\JS (abstract)the JavaScript frameworks' shared install and build commands
Detection\Framework\Analog, Angular, Astro, Flutter, Jaspr, Lynx, NextJs, Nuxt, React, ReactNative, Remix, Svelte, SvelteKit, TanStackStart, VueAnalog, Angular, Astro, Flutter, Jaspr, Lynx, NextJs, Nuxt, React, ReactNative, Remix, Svelte, SvelteKit, TanStackStart, Vue
getAdapter() ('ssr', 'static', '')Framework::adapter (Adapter, None)
setPackager() on a runtime or frameworkthe packager argument of Runtime::commands, Framework::install_command, Framework::build_command; Detected passes the detector's
Detector\Rendering, Detection\RenderingRenderingDetector, Rendering (Rendered from detect)
Detection\Rendering\SSR, XStaticSsr, Static
\InvalidArgumentException, \ExceptionError::InvalidArgument, Error::Exception

PHP passes file names as byte strings; here they are Strings, so a name that is not UTF-8 has to be converted before it is added.

Rust
use utopia_detector::{FrameworkDetector, NextJs, Nuxt, SvelteKit};

let mut detector = FrameworkDetector::new("pnpm");
detector.add_option(NextJs).add_option(Nuxt).add_option(SvelteKit);
for file in ["src", "package.json", "svelte.config.js"] {
    detector.add_file(file);
}

let framework = detector.detect().expect("a framework");
assert_eq!(framework.name(), "sveltekit");
assert_eq!(framework.build_command(), "pnpm run build");
PHP
use Utopia\Detector\Detection\Framework\NextJs;
use Utopia\Detector\Detection\Framework\Nuxt;
use Utopia\Detector\Detection\Framework\SvelteKit;
use Utopia\Detector\Detector\Framework;

$detector = new Framework('pnpm');
$detector->addOption(new NextJs())->addOption(new Nuxt())->addOption(new SvelteKit());
foreach (['src', 'package.json', 'svelte.config.js'] as $file) {
    $detector->addInput($file, Framework::INPUT_FILE);
}

$framework = $detector->detect();
echo $framework->getName(), "\n";         // sveltekit
echo $framework->getBuildCommand(), "\n"; // pnpm run build

API#

What utopia_detector exports at its root.

Structs

AnalogAnalog, the Angular meta-framework.AngularAngular.AstroAstro. It renders components of other frameworks, so their files and packages count for it too; a tie between Astro and another framework goes to the other one.BunBun.CppC++.DartDart.DenoDeno.DetectedA runtime or framework a detector chose, with the detector's packager: its commands are the ones for that packager. Everything else is the option itself, through `Deref`.Dotnet.NET.FlutterFlutter (web).FrameworkDetectorFinds a project's framework by scoring every option: one point per framework file among the file inputs, and one per framework package declared in each manifest input. The highest score wins; a tie goes to the framework with the fewest [parents](Framework::parents), except that Astro yields to the runner-up.JasprJaspr, the Dart web framework. It is detected from the same pubspec files as Flutter and wins once a `jaspr` package appears, whatever order the options were added in.JavaJava.LynxLynx.NextJsNext.js.NodeNode.js: the only runtime whose install command follows the packager.Npmnpm: `package.json` or `package-lock.json`.NuxtNuxt.PackagerDetectorFinds the packager of a project from its file names: the first option, in the order they were added, with one of its files among the inputs.PhpPHP.Pnpmpnpm: `pnpm-lock.yaml`.PythonPython.ReactReact.ReactNativeReact Native.RemixRemix: always server-side.RenderingDetectorTells how a framework's build is served from the build's file names: the first option, in the order they were added, with one of its files for the framework among the inputs; otherwise static output, falling back to the only HTML file when there is exactly one.RubyRuby.RuntimeDetectorFinds the runtime of a project: the first option, in the order they were added, that matches an input the way the `Strategy` says.ScoreOne option as a framework detector scores it.SsrServer-side rendering: the build has a server entry for the framework.StaticStatic output: plain files, with an optional fallback page.SvelteSvelte.SvelteKitSvelteKit: static when the configuration (or `package.json`) uses `@sveltejs/adapter-static`, server-side otherwise.SwiftSwift.TanStackStartTanStack Start: server-side with a Nitro plugin or without prerendering, static when it prerenders.VueVue.YarnYarn: `yarn.lock`.