chore: added "refresh-prose" CLI command to build AST and ProseModel cache

This commit is contained in:
Ken Snyder
2022-01-27 22:56:57 -08:00
parent 39cf3f84e7
commit 1d50595692
83 changed files with 691 additions and 228 deletions

3
.gitignore vendored
View File

@@ -8,4 +8,5 @@
**/node_modules
**/.idea/
**/*.log
**/.do-devops.json
**/.do-devops.json
**/*.env

View File

@@ -9,8 +9,9 @@
"start:tauri-search": "pnpm -C ./packages/tauri-search run watch",
"start:docs": "pnpm -C ./packages/docs run watch",
"build:cli": "pnpm -C ./packages/tauri-search run build:cli",
"watch": "npx pnpm run -r watch",
"test": "npx pnpm run -r test",
"watch": "pnpm run watch --filter ./packages/* ",
"test": "pnpm run test --filter ./packages/*",
"refresh-prose": "pnpm -C ./packages/tauri-search run refresh-prose",
"up": "docker compose up -d",
"down": "docker compose down",
"into:scraper": "docker exec -it scraper bash",
@@ -23,7 +24,6 @@
"start:cli": "pnpm install",
"start:docker": "run-s up",
"ts-ast": "node ./bin/ts-ast.js",
"ts-ast-overview": "node ./bin/ts-ast-overview.js",
"vol:create": "run-s vol:create:*",
"vol:create:scraper": "docker volume create scraper",
"vol:create:search": "docker volume create search_db",

View File

@@ -0,0 +1,5 @@
{
"name": "Using fixtures to represent data",
"email": "hello@cypress.io",
"body": "Fixtures are a great way to mock data for responses to routes"
}

View File

@@ -0,0 +1,22 @@
/// <reference types="cypress" />
// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************
// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)
/**
* @type {Cypress.PluginConfig}
*/
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
}

View File

@@ -0,0 +1,25 @@
// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add('login', (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add('drag', { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add('dismiss', { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite('visit', (originalFn, url, options) => { ... })

View File

@@ -0,0 +1,20 @@
// ***********************************************************
// This example support/index.js is processed and
// loaded automatically before your test files.
//
// This is a great place to put global configuration and
// behavior that modifies Cypress.
//
// You can change the location of this file or turn off
// automatically serving support files with the
// 'supportFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/configuration
// ***********************************************************
// Import commands.js using ES2015 syntax:
import './commands'
// Alternatively you can use CommonJS syntax:
// require('./commands')

View File

@@ -8,10 +8,12 @@
"lint": "eslint \"**/*.{vue,ts,js}\"",
"preview": "vite preview",
"preview-https": "serve dist",
"test": "vitest",
"test": "vitest run",
"test:e2e": "cypress open",
"test:unit": "vitest",
"typecheck": "vue-tsc --noEmit"
"test:dev": "vitest dev",
"typecheck": "vue-tsc --noEmit",
"watch": "pnpm run dev"
},
"dependencies": {
"@vueuse/core": "^7.5.4",
@@ -53,6 +55,7 @@
"eslint": "^8.7.0",
"eslint-plugin-cypress": "^2.12.1",
"https-localhost": "^4.7.0",
"jsdom": "^19.0.0",
"markdown-it-collapsible": "^1.0.0",
"markdown-it-link-attributes": "^4.0.0",
"markdown-it-prism": "^2.2.2",

View File

@@ -165,7 +165,7 @@ export default defineConfig({
include: ["test/**/*.test.ts"],
environment: "jsdom",
api: {
port: 5555,
port: 4444,
host: "0.0.0.0",
},

View File

@@ -9,9 +9,11 @@
"clean": "rimraf dist/* bin/*",
"lint": "eslint src --ext ts,js,tsx,jsx --fix --no-error-on-unmatched-pattern",
"prune": "docker system prune",
"sitemap": "node bin/sitemap.js",
"refresh-prose": "node bin/refresh-prose.js",
"restart": "docker compose restart",
"build:cli": "tsup src/cli/*.ts --format=esm,cjs --clean --sourcemap -d bin",
"test": "vitest --ui",
"test": "vitest run",
"ts-ast": "node ./bin/ts-ast.js",
"ts-ast-overview": "node ./bin/ts-ast-overview.js",
"watch": "run-p watch:*",
@@ -20,6 +22,7 @@
},
"dependencies": {
"cheerio": "^1.0.0-rc.10",
"dotenv": "^14.3.2",
"gray-matter": "^4.0.3",
"inferred-types": "^0.18.4",
"native-dash": "^1.21.5",

View File

View File

@@ -10,6 +10,9 @@ export function isHeading(something: string): something is "h1" | "h2" | "h3" {
return ["h1", "h2", "h3"].includes(something);
}
/**
* Checks that frontmatter content is in the right form
*/
function validateFrontmatter(f: string, matter: Record<string, any>) {
const typedMatter = { ...matter } as ITauriFrontmatter;
if (matter?.title && typeof matter.title !== "string") {
@@ -35,10 +38,44 @@ function validateFrontmatter(f: string, matter: Record<string, any>) {
return typedMatter;
}
function isLocalFiles(input: MarkdownInput): input is { files: string[] } {
return "files" in input;
}
// function isContentWithFile(input: ParseMarkdown):
export type MarkdownInput = { files: string[] } | { content: string; file: string };
function parseContent(f: string, content: string) {
// const hash = h32(content);
// TODO: turn hashing back on once figure out why Vite is throwing a compiler error
const hash = 42;
const { data: frontmatter, content: text } = matter(content);
const { h1, h2, h3, hasCodeBlock, programmingLanguages, otherSymbols } = simpleParse(
f,
content
);
const { filename, filepath } = splitFile(f);
return {
filename,
filepath,
hash,
frontmatter: validateFrontmatter(f, frontmatter),
text,
h1,
h2,
h3,
hasCodeBlock,
programmingLanguages,
otherSymbols,
} as MarkdownAst;
}
/**
* Takes in a list of files and parses them in three ways:
* Takes in either list of files (in filesystem) or the content of a markdown along with it's filename
* and parses it in three ways:
*
* 1. uses the `greymatter` library to extract
* 1. uses the `graymatter` library to extract
* - all frontmatter data
* - the MD content with the frontmatter extracted
* 2. uses the `simple-markdown` parser to detect:
@@ -48,39 +85,25 @@ function validateFrontmatter(f: string, matter: Record<string, any>) {
* 3. finally it will also add the `filepath` and `filename` along with a content `hash`
* which can be used detect whether content has changed
*/
export async function parseMarkdown(files: string[]) {
// const { h32 } = await xxhash();
const tokens: MarkdownAst[] = [];
for (const f of files) {
try {
const { filename, filepath } = splitFile(f);
const content = await readFile(f, { encoding: "utf-8" });
// const hash = h32(content);
// TODO: turn hashing back on once figure out why Vite is throwing a compiler error
const hash = 42;
const { data: frontmatter, content: text } = matter(content);
const { h1, h2, h3, hasCodeBlock, programmingLanguages, otherSymbols } =
simpleParse(f, content);
tokens.push({
filename,
filepath,
hash,
frontmatter: validateFrontmatter(f, frontmatter),
text,
h1,
h2,
h3,
hasCodeBlock,
programmingLanguages,
otherSymbols,
});
} catch (err) {
(err as Error).message = `Problem parsing file ${f}: ${(err as Error).message}`;
throw err;
export async function parseMarkdown<T extends MarkdownInput>(input: T) {
let ast: MarkdownAst | MarkdownAst[];
if (isLocalFiles(input)) {
const tokens: MarkdownAst[] = [];
for (const f of input.files) {
try {
const content = await readFile(f, { encoding: "utf-8" });
tokens.push(parseContent(f, content));
} catch (err) {
(err as Error).message = `Problem parsing file ${f}: ${(err as Error).message}`;
throw err;
}
}
ast = tokens;
} else {
ast = parseContent(input.file, input.content);
}
return tokens;
return ast as T extends { files: string[] } ? MarkdownAst[] : MarkdownAst;
}
function splitFile(f: string) {
@@ -138,6 +161,12 @@ function simpleParse(f: string, content: string) {
programmingLanguages.add(node.lang);
break;
case "paragraph":
if (Array.isArray(node.content)) {
extract(node.content);
}
break;
default:
otherSymbols.add(node.type);
}

View File

@@ -0,0 +1,9 @@
import { readFile } from "fs/promises";
import { config } from "dotenv";
(async () => {
config();
const repo = process.env.REPO || "tauri";
const branch = process.env.BRANCH || "dev";
const currentSitemap = await readFile(`src/generated/sitemap-${repo}-${branch}`);
})();

View File

@@ -0,0 +1,129 @@
/* eslint-disable no-console */
import axios from "axios";
import { existsSync, mkdirSync } from "fs";
import { readFile, rm, writeFile } from "fs/promises";
import { join } from "node:path";
import path from "path";
import { parseMarkdown } from "~/ast/parseMarkdown";
import { ProseMapper } from "~/mappers";
import { IProseModel } from "~/models/ProseModel";
import { getEnv } from "~/utils/getEnv";
import { flattenSitemap, sitemapDictionary } from "../utils/convertSitemap";
import { buildDocsSitemap, IDocsSitemap } from "../utils/github/buildDocsSitemap";
export interface IRefreshProseOptions {
force?: boolean;
}
function jsonFileFromMarkdown(file: string, repo: string, branch: string) {
return join(`src/generated/ast/prose/${repo}_${branch}/`, file.replace(".md", ".json"));
}
/** writes file to local path, ensuring directory exists */
async function write(file: string, data: string) {
const dir = path.dirname(file);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
await writeFile(file, data, "utf-8");
}
function documentsCacheFile(file: string, repo: string, branch: string) {
const dir = `src/generated/ast/prose/${repo}_${branch}`;
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
return join(dir, file);
}
async function cacheMarkdownAst(file: string, url: string, repo: string, branch: string) {
const jsonFile = jsonFileFromMarkdown(file, repo, branch);
const content = (await axios.get(url)).data;
const ast = await parseMarkdown({ file, content });
await write(jsonFile, JSON.stringify(ast));
console.log(`- wrote markdown AST file: ${jsonFile}`);
return ast;
}
export async function refreshProse(
repo: string,
branch: string,
options: IRefreshProseOptions = {}
) {
const sitemapFile = `src/generated/sitemap-${repo}-${branch}.json`;
const existingSitemap = existsSync(sitemapFile);
if (existingSitemap) {
console.log(`- existing sitemap found [${sitemapFile}]`);
console.log(`- will use to detect changes in prose`);
} else {
console.log(
`- no existing sitemap for ${repo}@${branch}; all markdown content will be pulled down`
);
}
const currentSitemap = existingSitemap
? sitemapDictionary(JSON.parse(await readFile(sitemapFile, "utf-8")) as IDocsSitemap)
: {};
const newSitemap = await buildDocsSitemap({ repo, ref: branch });
const flatmap = flattenSitemap(newSitemap);
const documents: IProseModel[] = [];
const unchanged: string[] = [];
const changed: string[] = [];
for (const file of flatmap) {
const cache = currentSitemap[file.filepath];
if (cache && cache.sha === file.sha) {
unchanged.push(file.filepath);
if (
options.force ||
!existsSync(jsonFileFromMarkdown(file.filepath, repo, branch))
) {
documents.push(
ProseMapper(
await cacheMarkdownAst(file.filepath, file.download_url, repo, branch)
)
);
}
} else {
changed.push(file.filepath);
console.log(`- change in "${file.filepath}" detected`);
documents.push(
ProseMapper(
await cacheMarkdownAst(file.filepath, file.download_url, repo, branch)
)
);
}
}
console.log(
`- finished writing markdown AST files [ ${changed.length} changed, ${unchanged.length} unchanged]`
);
await write(
documentsCacheFile("documents.json", repo, branch),
JSON.stringify(documents)
);
console.log(
`- wrote Meilisearch documents to "${documentsCacheFile(
"documents.json",
repo,
branch
)}"`
);
if (currentSitemap) {
// look for files which have been removed, since last time
const current = flattenSitemap(JSON.parse(await readFile(sitemapFile, "utf-8")));
const lookup = sitemapDictionary(newSitemap);
const removed = current.filter((c) => !lookup[c.filepath]).map((i) => i.filepath);
if (removed.length > 0) {
console.log(
`- detected ${removed.length} files which no longer exist: ${removed.join(", ")}`
);
for (const file of removed) {
await rm(jsonFileFromMarkdown(file, repo, branch));
}
}
}
}
(async () => {
const { repo, branch, force } = getEnv();
await refreshProse(repo, branch, { force });
})();

View File

@@ -0,0 +1,15 @@
import { writeFile } from "fs/promises";
import { buildDocsSitemap } from "~/utils/github/buildDocsSitemap";
import { config } from "dotenv";
(async () => {
config();
const repo = process.env.REPO || "tauri";
const ref = process.env.BRANCH || "dev";
const sitemap = await buildDocsSitemap({ ref, repo });
await writeFile(
`src/generated/sitemap-${repo}-${ref}.json`,
JSON.stringify(sitemap),
"utf-8"
);
})();

View File

@@ -0,0 +1,6 @@
# AST Folder
A place where _generated_ content will be placed. This includes:
- **AST info**: this acts as a sort of "cache" of what was used to build the current index
- **Sitemap**: a JSON file indicating the sitemap of Markdown documents ... this is done on a per repo, per branch manner where files are `sitemap-[repo]-[branch]`

View File

@@ -0,0 +1 @@
{"filename":"cli.md","filepath":"docs/api","hash":42,"frontmatter":{"id":"cli","title":"CLI"},"text":"\nimport Command from '@theme/Command'\nimport Alert from '@theme/Alert'\n\n\nThe tauri.js cli is composed in TypeScript and published as JavaScript. \n\n## `info`\n\n<Command name=\"info\" />\n\n```\n Description\n Returns the known state of tauri dependencies and configuration\n```\n\nIt shows a concise list of information about the environment, Rust, Node.js and their versions as well as some relevant configurations.\n\n<Alert title=\"Note\" icon=\"info-alt\">\nThis command is pretty helpful when you need to have a quick overview of your application. When requesting some help, it can be useful that you share this report with us.\n</Alert>\n\n## `init`\n\n<Command name=\"init\" />\n\n```\n Description\n Inits the Tauri template. If Tauri cannot find the src-tauri/tauri.conf.json\n it will create one.\n Usage\n $ tauri init\n Options\n --help, -h Displays this message\n --force, -f Force init to overwrite [conf|template|all]\n --log, -l Logging [boolean]\n --directory, -d Set target directory for init\n --tauriPath, -t Path of the Tauri project to use (relative to the cwd)\n```\n\n## `dev`\n\n<Command name=\"dev\" />\n\n```\n Description\n Tauri dev.\n Usage\n $ tauri dev\n Options\n --help, -h Displays this message\n```\n\nThis command will open the WebView in development mode. It makes use of the `build.devPath` property from your `src-tauri/tauri.conf.json` file.\n\nIf you have entered a command to the `build.beforeDevCommand` property, this one will be executed before the `dev` command.\n\n<a href=\"/docs/api/config#build\">See more about the configuration.</a><br/><br/>\n\n<Alert title=\"Troubleshooting\" type=\"warning\" icon=\"alert\">\n\nIf you're not using `build.beforeDevCommand`, make sure your `build.devPath` is correct and, if using a development server, that it's started before using this command.\n</Alert>\n\n## `deps`\n\n<Command name=\"deps update\" />\n\n```sh\n Description\n Tauri dependency management script\n Usage\n $ tauri deps [install|update]\n```\n\n\n## `build`\n\n<Command name=\"build\" />\n\n```\n Description\n Tauri build.\n Usage\n $ tauri build\n Options\n --help, -h Displays this message\n --debug, -d Build a tauri app with debugging\n```\n\nThis command will bundle your application, either in production mode or debug mode if you used the `--debug` flag. It makes use of the `build.distDir` property from your `src-tauri/tauri.conf.json` file.\n\nIf you have entered a command to the `build.beforeBuildCommand` property, this one will be executed before the `build` command.\n\n<a href=\"/docs/api/config#build\">See more about the configuration.</a>\n\n## `icon`\n\n<Command name=\"icon\" />\n\n```\n Description\n Create all the icons you need for your Tauri app.\n\n Usage\n $ tauri icon\n\n Options\n --help, -h Displays this message\n --log, -l Logging [boolean]\n --icon, -i Source icon (png, 1240x1240 with transparency)\n --target, -t Target folder (default: 'src-tauri/icons')\n --compression, -c Compression type [pngquant|optipng|zopfli]\n```\n\nThis command will generate a set of icons, based on the source icon you've entered.\n\n## `version`\n\n<Command name=\"--version\" />\n\n```\n Description\n Returns the current version of tauri\n```\n\nThis command will show the current version of Tauri.\n\n## CLI usage\n\nSee more about the usage through this [complete guide](/docs/usage/development/integration).\n\n","h1":[],"h2":[{"content":"info","type":"inlineCode"},{"content":"init","type":"inlineCode"},{"content":"dev","type":"inlineCode"},{"content":"deps","type":"inlineCode"},{"content":"build","type":"inlineCode"},{"content":"icon","type":"inlineCode"},{"content":"version","type":"inlineCode"},{"content":"CLI usage","type":"text"}],"h3":[],"hasCodeBlock":true,"programmingLanguages":[null,"sh"],"otherSymbols":["text","inlineCode","link"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"intro.md","filepath":"docs/getting-started","hash":42,"frontmatter":{"title":"Introduction"},"text":"\nimport OSList from '@theme/OSList'\n\nWelcome to Tauri!\n\nTauri is a polyglot and generic system that is very composable and allows engineers to make a wide variety of applications. It is used for building applications for Desktop Computers using a combination of [Rust](https://www.rust-lang.org/) tools and HTML rendered in a Webview. Apps built with Tauri can ship with any number of pieces of an optional JS API / Rust API so that webviews can control the system via message passing.\n\nAnything that can be displayed on a website, can be displayed in a Tauri webview app!\n\nDevelopers are free to build the web front-end displayed in a Webview through Tauri with any web frameworks of their choice!\n**Developers can even extend the default API** with their own functionality and bridge the Webview and Rust-based backend easily!\n\nThe Architecture is more fully described in [Architecture](https://github.com/tauri-apps/tauri/blob/dev/ARCHITECTURE.md).\n\nThis guide will help you create your first Tauri app. It should only take about 10 minutes, although it could take longer if you have a slower internet connection.\n\nIf you find an error or something unclear, or would like to propose an improvement, you have several options:\n\n1. Open an issue on our [Github Repo](https://github.com/tauri-apps/tauri-docs)\n2. Visit our [Discord server](https://discord.gg/tauri) and raise your concern\n3. Request to join the education working group on Discord to gain access to its discussion channel\n\n## Steps\n\n1. Install and configure system prerequisites\n2. Create a web app with your frontend framework of choice\n3. Use the Tauri CLI to setup Tauri in your app\n4. Write native Rust code to add functionality or improve performance (totally optional)\n5. Use `tauri dev` to develop your app with features like hot module reloading and webview devtools\n6. Use `tauri build` to package your app into a tiny installer\n\n### Setting up Your Environment\n\nBefore creating an app, you'll have to install and configure some developer tools. This guide assumes that you know what the command line is, how to install packages on your operating system, and generally know your way around the development side of computing.\n\nFollow the platform-specific guides to get started:\n\n<OSList content={{\n linux: { title: 'Linux Setup', link: '/docs/getting-started/setup-linux'},\n macos: { title: 'macOS Setup', link: '/docs/getting-started/setup-macos'},\n windows: { title: 'Windows Setup', link: '/docs/getting-started/setup-windows'}\n}} />\n\nAfter that, you'll be ready to [add Tauri to your project!](/docs/usage/development/integration)\n","h1":[],"h2":[{"content":"Steps","type":"text"}],"h3":[{"content":"Setting up Your Environment","type":"text"}],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","link","strong","list"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"setup-macos.md","filepath":"docs/getting-started","hash":42,"frontmatter":{"title":"Setup for macOS"},"text":"\nimport Alert from '@theme/Alert'\nimport { Intro } from '@theme/SetupDocs'\nimport Icon from '@theme/Icon'\n\n<Intro />\n\n## 1. System Dependencies&nbsp;<Icon title=\"alert\" color=\"danger\"/>\n\n\nYou will need to have <a href=\"https://brew.sh/\" target=\"_blank\">Homebrew</a> installed to run the following command.\n\n```sh\n$ brew install gcc\n```\n\nYou will also need to make sure `xcode` is installed.\n\n```sh\n$ xcode-select --install\n```\n\n## 2. Node.js Runtime and Package Manager&nbsp;<Icon title=\"control-skip-forward\" color=\"warning\"/>\n\n### Node.js (npm included)\n\nWe recommend using nvm to manage your Node.js runtime. It allows you to easily switch versions and update Node.js.\n\n```sh\n$ curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh | bash\n```\n\n<Alert title=\"Note\">\nWe have audited this bash script, and it does what it says it is supposed to do. Nevertheless, before blindly curl-bashing a script, it is always wise to look at it first. Here is the file as a mere <a href=\"https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.2/install.sh\" target=\"_blank\">download link</a>.\n</Alert>\n\nOnce nvm is installed, close and reopen your terminal, then install the latest version of Node.js and npm:\n\n```sh\n$ nvm install node --latest-npm\n$ nvm use node\n```\n\nIf you have any problems with nvm, please consult their <a href=\"https://github.com/nvm-sh/nvm\">project readme</a>.\n\n### Optional Node.js Package Manager\n\nYou may want to use an alternative to npm:\n\n- <a href=\"https://yarnpkg.com/getting-started\" target=\"_blank\">Yarn</a>, is preferred by Tauri's team\n- <a href=\"https://pnpm.js.org/en/installation\" target=\"_blank\">pnpm</a>\n\n## 3. Rustc and Cargo Package Manager&nbsp;<Icon title=\"control-skip-forward\" color=\"warning\"/>\n\nThe following command will install <a href=\"https://rustup.rs/\" target=\"_blank\">rustup</a>, the official installer for <a href=\"https://www.rust-lang.org/\" target=\"_blank\">Rust</a>.\n\n```\n$ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh\n```\n\n<Alert title=\"Note\">\nWe have audited this bash script, and it does what it says it is supposed to do. Nevertheless, before blindly curl-bashing a script, it is always wise to look at it first. Here is the file as a mere <a href=\"https://sh.rustup.rs\" target=\"_blank\">download link</a>.\n</Alert>\n\nTo make sure that Rust has been installed successfully, run the following command:\n\n```sh\n$ rustc --version\nlatest update on 2019-12-19, rust version 1.40.0\n```\n\nYou may need to restart your terminal if the command does not work.\n\n## Continue\n\nNow that you have set up the macOS-specific dependencies for Tauri, learn how to [add Tauri to your project](/docs/usage/development/integration).\n","h1":[],"h2":[{"content":"1","type":"text"},{"content":"2","type":"text"},{"content":"3","type":"text"},{"content":"Continue","type":"text"}],"h3":[{"content":"Node","type":"text"},{"content":"Optional Node","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["sh",null],"otherSymbols":["text","link","inlineCode","list"]}

View File

@@ -0,0 +1 @@
{"filename":"setup-windows.md","filepath":"docs/getting-started","hash":42,"frontmatter":{"title":"Setup for Windows"},"text":"\nimport Alert from '@theme/Alert'\nimport Icon from '@theme/Icon'\nimport { Intro } from '@theme/SetupDocs'\n\n<Alert title=\"Note\">\n\nFor those using the Windows Subsystem for Linux (WSL) please refer to our [Linux specific instructions](/docs/getting-started/setup-linux) instead.\n</Alert>\n\n<Intro />\n\n## 1. System Dependencies&nbsp;<Icon title=\"alert\" color=\"danger\"/>\n\nYou'll need to install Microsoft Visual Studio C++ build tools. <a href=\"https://visualstudio.microsoft.com/visual-cpp-build-tools/\" target=\"_blank\">Download the installer here</a>, and then run it. When it asks you what packages you would like to install, select C++ Build Tools.\n\n<Alert title=\"Note\">\nThis is a big download (over 1GB) and takes the most time, so go grab a coffee.\n</Alert>\n\n<Alert type=\"warning\">\nYou may need to uninstall the 2017 version of the build tools if you have them. There are reports of Tauri not working with both the 2017 and 2019 versions installed.\n</Alert>\n\n## 2. Node.js Runtime and Package Manager&nbsp;<Icon title=\"control-skip-forward\" color=\"warning\"/>\n\n### Node.js (npm included)\n\nWe recommend using <a href=\"https://github.com/coreybutler/nvm-windows#installation--upgrades\" target=\"_blank\">nvm-windows</a> to manage your Node.js runtime. It allows you to easily switch versions and update Node.js.\n\nThen run the following from an Administrative PowerShell and press Y when prompted:\n\n```powershell\n# BE SURE YOU ARE IN AN ADMINISTRATIVE PowerShell!\nnvm install latest\nnvm use {{latest}} # Replace with your latest downloaded version\n```\n\nThis will install the most recent version of Node.js with npm.\n\n### Optional Node.js Package Manager\n\nYou may want to use an alternative to npm:\n\n- <a href=\"https://yarnpkg.com/getting-started\" target=\"_blank\">Yarn</a>, is preferred by Tauri's team\n- <a href=\"https://pnpm.js.org/en/installation\" target=\"_blank\">pnpm</a>\n\n## 3. Rustc and Cargo Package Manager&nbsp;<Icon title=\"control-skip-forward\" color=\"warning\"/>\n\nNow you will need to install <a href=\"https://www.rust-lang.org/\" target=\"_blank\">Rust</a>. The easiest way to do this is to use <a href=\"https://rustup.rs/\" target=\"_blank\">rustup</a>, the official installer.\n\n- <a href=\"https://win.rustup.rs/x86_64\" target=\"_blank\">64-bit download link</a>\n- <a href=\"https://win.rustup.rs/i686\" target=\"_blank\">32-bit download link</a>\n\nDownload and install the proper variant for your computer's architecture.\n\n## 4. Install WebView2\n\n<Alert title=\"Note\">\nWebView2 is pre-installed in Windows 11. \n</Alert>\n\nFinally, you will need to install WebView2. The best way to do this is to download and run the Evergreen Bootstrapper from [this page](https://developer.microsoft.com/en-us/microsoft-edge/webview2/#download-section).\n\n## Continue\n\nNow that you have set up the Windows-specific dependencies for Tauri, learn how to [add Tauri to your project](/docs/usage/development/integration).\n","h1":[],"h2":[{"content":"1","type":"text"},{"content":"2","type":"text"},{"content":"3","type":"text"},{"content":"4","type":"text"},{"content":"Continue","type":"text"}],"h3":[{"content":"Node","type":"text"},{"content":"Optional Node","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["powershell"],"otherSymbols":["text","link","list"]}

View File

@@ -0,0 +1 @@
{"filename":"cross-platform.md","filepath":"docs/usage/ci-cd","hash":42,"frontmatter":{"title":"Cross-Platform Compilation"},"text":"\nHow to use GH Action for Building: a glance at Tauri Action.","h1":[],"h2":[],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text"]}

View File

@@ -0,0 +1 @@
{"filename":"signing-macos.md","filepath":"docs/usage/ci-cd","hash":42,"frontmatter":{"title":"Signing for macOS"},"text":"\nSigning for macOS","h1":[],"h2":[],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"contributor-guide.md","filepath":"docs/usage","hash":42,"frontmatter":{"title":"Contributor Guide"},"text":"\ntodo: make this friendlier and more complete\n\nTauri is a polyglot system that uses:\n\n- git\n- Node.js\n- Rust\n- GitHub actions\n\nIt can be developed on macOS, Linux and Windows.\n\n## Contribution Flow\n\n1. File an Issue\n2. Fork the Repository\n3. Make Your Changes\n4. Make a PR\n\n### A Note About Contributions to the Rust Libraries\n\nWhen contributing to the Rust libraries `tauri`, `tauri-api`, and `tauri-updater`; you will want to setup an environment for RLS (the Rust Language Server). In the Tauri root directory, there is a `.scripts` folder that contains a set of scripts to automate adding a couple temporary environment variables to your shell/terminal. These environment variables point to directories in the test fixture which will prevent RLS from crashing on compile-time. This is a necessary step for setting up a development environment for Tauri's Rust libraries.\n\n##### _Example Instructions_\n\n1. Navigate to the Tauri Root directory.\n2. Execute a script based on your Operating System from this folder: `.scripts/init_env.bat` for Windows Cmd, `.scripts/init_env.ps1` for Windows Powershell, `. .scripts/init_env.sh` for Linux/macOS bash (note the first `.` in this command).\n3. Open your text editor/IDE from this shell/terminal.\n\n## Hands On Example\n\nLet's make a new example. That's a great way to learn. We are going to assume you are on a nixy type of environment like Linux or macOS and have all of your development dependencies like rust and node already sorted out.\n\n```sh\ngit clone git@github.com:tauri-apps/tauri.git\ncd tauri/cli/tauri.js\nyarn\nmkdir ../../examples/vanillajs && cd \"$_\"\n```\n\n```json\n \"tauri:source\": \"node ../../../cli/tauri.js/bin/tauri\",\n```\n\n```ini\n [dependencies.tauri]\n path = \"../../../../core/tauri\"\n features = [ \"all-api\" ]\n```\n","h1":[],"h2":[{"content":"Contribution Flow","type":"text"},{"content":"Hands On Example","type":"text"}],"h3":[{"content":"A Note About Contributions to the Rust Libraries","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["sh","json","ini"],"otherSymbols":["text","list","inlineCode","h5"]}

View File

@@ -0,0 +1 @@
{"filename":"debugging.md","filepath":"docs/usage/development","hash":42,"frontmatter":{"title":"App Debugging","sidebar_label":"App Debugging (3/4)"},"text":"\nimport Alert from '@theme/Alert'\nimport Command from '@theme/Command'\n\nWith all the moving pieces in Tauri, you may run into a problem that requires debugging. There are a handful of locations where error details are printed, and Tauri includes some tools to make the debugging process easier.\n\n## Rust Console\n\nWhen you run a Tauri app in development mode you will have a Rust console available. This is in the terminal where you ran e.g. `tauri dev`. You can use the following code to print something to that console from within a Rust file:\n\n```rust\nprintln!(\"Message from Rust: {}\", msg);\n```\n\nSometimes you may have an error in your Rust code, and the Rust compiler can give you lots of information. If, for example, `tauri dev` crashes, you can rerun it like this on Linux and macOS:\n\n```sh\nRUST_DEBUG=1 tauri dev\n```\n\nor like this on MS Windows:\n\n```sh\nset RUST_DEBUG=1\ntauri dev\n```\n\nThis will give you a granular stack trace. Generally speaking, the Rust compiler will help you by\ngiving you detailed information about the issue, such as:\n\n```\nerror[E0425]: cannot find value `sun` in this scope\n --> src/main.rs:11:5\n |\n11 | sun += i.to_string().parse::<u64>().unwrap();\n | ^^^ help: a local variable with a similar name exists: `sum`\n\nerror: aborting due to previous error\n\nFor more information about this error, try `rustc --explain E0425`.\n```\n\n## WebView JS Console\n\nRight click in the WebView, and choose `Inspect Element`. This will open up a web-inspector similar to the Chrome or Firefox dev tools you are used to.\n\n## Create a Debug Build\n\nThere are cases where you might need to inspect the JS console in the final bundle, so Tauri provides a simple command to create a debugging bundle:\n\n<Command name=\"build --debug\" />\n\nLike the normal build and dev processes, the first time you run this it will take more time than subsequent runs. The final bundled app will be placed in `src-tauri/target/debug/bundle`. That app will ship with the development console enabled.\n\n## Run Your App From the Terminal\n\nYou can also run a built app from the terminal, which will also give you the Rust compiler notes (in case of errors) or your `println` messages. Just find the file `src-tauri/target/(release|debug)/[app name]` and either double click it (but be warned, the terminal will close on errors) or just run it in directly in your console.\n","h1":[],"h2":[{"content":"Rust Console","type":"text"},{"content":"WebView JS Console","type":"text"},{"content":"Create a Debug Build","type":"text"},{"content":"Run Your App From the Terminal","type":"text"}],"h3":[],"hasCodeBlock":true,"programmingLanguages":["rust","sh",null],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"development.md","filepath":"docs/usage/development","hash":42,"frontmatter":{"title":"App Development","sidebar_label":"App Development (2/4)"},"text":"\nimport Alert from '@theme/Alert'\nimport Command from '@theme/Command'\n\n### 1. Start Your Devserver\n\nNow that you have everything setup, you should start your application development server provided by your UI framework or bundler (assuming you're using one, of course).\n\n<Alert title=\"Note\">\nEvery framework has its own development tooling. It is outside of the scope of this document to treat them all or keep them up to date.\n</Alert>\n\n### 2. Start Tauri Development Window\n\n<Command name=\"dev\" />\n\nThe first time you run this command, it will take several minutes for the Rust package manager to download and build all the required packages. Since they are cached, subsequent builds will be much faster, as only your code will need rebuilding.\n\nOnce Rust has finished building, the webview will open and it should display your web app. You can make changes to your web app, and if your tooling enables it, the webview should update automatically just like a browser. When you make changes to your Rust files, they will be rebuilt automatically and your app will restart.\n\n<Alert title=\"A note about Cargo.toml and Source Control\" icon=\"info-alt\">\n In your project repository, you SHOULD commit the \"src-tauri/Cargo.toml\" to git because you want it to be deterministic. You SHOULD NOT commit the \"src-tauri/target\" folder or any of its contents.\n</Alert>\n","h1":[],"h2":[],"h3":[{"content":"1","type":"text"},{"content":"2","type":"text"}],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text"]}

View File

@@ -0,0 +1 @@
{"filename":"integration.md","filepath":"docs/usage/development","hash":42,"frontmatter":{"title":"Tauri Integration","sidebar_label":"Tauri Integration (1/4)"},"text":"\nimport Alert from '@theme/Alert'\nimport Command from '@theme/Command'\nimport Link from '@docusaurus/Link'\n\n<Alert title=\"Please note\" type=\"warning\" icon=\"alert\">\n You must have completed all the steps required for setting up the development environment on your machine. If you haven't done this yet, please see the <a href=\"/docs/getting-started/intro#setting-up-your-environment\"> setup page for your operating system</a>.\n</Alert>\n\n### 1. Install Tauri CLI Package as a Dev Dependency:\n\n```bash\ncd project-folder\n\n# Not required if you already have a package.json:\n# yarn init\n# OR\n# npm init\n\nyarn add -D @tauri-apps/cli\n# OR\nnpm install -D @tauri-apps/cli\n```\n\n<Alert title=\"Note\">\n You can install Tauri as both a local and a global dependency, but we recommend installing it locally.\n</Alert>\n\nIf you decide to use Tauri as a local package with npm (not yarn), you will have to define a custom script to your package.json:\n\n```js title=package.json\n{\n // This content is just a sample\n \"scripts\": {\n \"tauri\": \"tauri\"\n }\n}\n```\n\n### 1. Install Tauri API Package as a Dependency (optional):\n\nThe `@tauri-apps/api` package is recommended for projects using ES modules or modern build tools such as Webpack or Vite. It is the most secure way to access the Tauri APIs.\n\n```bash\nyarn add @tauri-apps/api\n# OR\nnpm install @tauri-apps/api\n```\n\n### 2. Initialize Tauri in Your App\n\n<Command name=\"init\" />\n\nThis command will place a new folder in your current working directory, `src-tauri`.\n\n```sh\n└── src-tauri\n ├── .gitignore\n ├── Cargo.toml\n ├── rustfmt.toml\n ├── tauri.conf.json\n ├── icons\n │ ├── 128x128.png\n │ ├── 128x128@2x.png\n │ ├── 32x32.png\n │ ├── Square107x107Logo.png\n │ ├── Square142x142Logo.png\n │ ├── Square150x150Logo.png\n │ ├── Square284x284Logo.png\n │ ├── Square30x30Logo.png\n │ ├── Square310x310Logo.png\n │ ├── Square44x44Logo.png\n │ ├── Square71x71Logo.png\n │ ├── Square89x89Logo.png\n │ ├── StoreLogo.png\n │ ├── icon.icns\n │ ├── icon.ico\n │ └── icon.png\n └── src\n ├── build.rs\n ├── cmd.rs\n └── main.rs\n```\n\n### 3. Check `tauri info` to Make Sure Everything Is Set up Properly:\n\n<Command name=\"info\" />\n\nWhich should return something like:\n\n```\nOperating System - Darwin(16.7.0) - darwin/x64\n\nNode.js environment\n Node.js - 12.16.3\n @tauri-apps/cli - 1.0.0-beta.2\n @tauri-apps/api - 1.0.0-beta.1\n\nGlobal packages\n npm - 6.14.4\n yarn - 1.22.4\n\nRust environment\n rustc - 1.52.1\n cargo - 1.52.0\n\nApp directory structure\n/node_modules\n/src-tauri\n/src\n/public\n\nApp\n tauri.rs - 1.0.0-beta.1\n build-type - bundle\n CSP - default-src blob: data: filesystem: ws: wss: http: https: tauri: 'unsafe-eval' 'unsafe-inline' 'self' img-src: 'self'\n distDir - ../public\n devPath - ../public\n framework - Svelte\n bundler - Rollup\n```\n\nThis information can be very helpful when triaging problems.\n\n### Patterns\n\nWe've also defined prebuilt configurations called \"Patterns\". They may help you to customize Tauri to fit your needs.\n[See more about patterns](/docs/usage/patterns/about-patterns).\n\n## Vue CLI Plugin Tauri\n\nIf you are using Vue CLI, it is recommended to use the official [CLI plugin](https://github.com/tauri-apps/vue-cli-plugin-tauri).\n","h1":[],"h2":[{"content":"Vue CLI Plugin Tauri","type":"text"}],"h3":[{"content":"1","type":"text"},{"content":"1","type":"text"},{"content":"2","type":"text"},{"content":"3","type":"text"},{"content":"Patterns","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["bash","sh",null],"otherSymbols":["text","inlineCode","link"]}

View File

@@ -0,0 +1 @@
{"filename":"publishing.md","filepath":"docs/usage/development","hash":42,"frontmatter":{"title":"App Publishing","sidebar_label":"App Publishing (4/4)"},"text":"\nimport Alert from '@theme/Alert'\nimport Command from '@theme/Command'\n\n### 1. Build Your Web App\n\nNow that you are ready to package your project, you will need to run your framework's or bundler's build command (assuming you're using one, of course).\n\n<Alert title=\"Note\">\nEvery framework has its own publishing tooling. It is outside of the scope of this document to treat them all or keep them up to date.\n</Alert>\n\n### 2. Bundle your application with Tauri\n\n<Command name=\"build\" />\n\nThis command will embed your web assets into a single binary with your Rust code. The binary itself will be located in `src-tauri/target/release/[app name]`, and installers will be located in `src-tauri/target/release/bundle/`.\n\nLike the `tauri dev` command, the first time you run this, it will take some time to collect the Rust crates and build everything - but on subsequent runs it will only need to rebuild your code, which is much quicker.\n","h1":[],"h2":[],"h3":[{"content":"1","type":"text"},{"content":"2","type":"text"}],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"updating.md","filepath":"docs/usage/development","hash":42,"frontmatter":{"title":"Updating"},"text":"import Alert from '@theme/Alert'\n\n<Alert title=\"Please note\" type=\"warning\" icon=\"alert\">\n Especially during the alpha and beta phases, you are expected to keep all Tauri dependencies and toolchains up to date. There is no support for any versions other than latest.\n</Alert>\n\n## Automatic updates\n\nThe Tauri JS CLI has a command to install and update all needed dependencies, just run `tauri deps install` or `tauri deps update`.\n\n## Manual updates\n\n### Update NPM Packages\n\nIf you are using the `tauri` package:\n```bash\n$ yarn upgrade @tauri-apps/cli @tauri-apps/api --latest\n$ npm install @tauri-apps/cli@latest @tauri-apps/api@latest\n```\nYou can also detect what the latest version of Tauri is on the command line, using:\n- `npm outdated @tauri-apps/cli`\n- `yarn outdated @tauri-apps/cli`\n\nAlternatively, if you are using the `vue-cli-plugin-tauri` approach:\n```bash\n$ yarn upgrade vue-cli-plugin-tauri --latest\n$ npm install vue-cli-plugin-tauri@latest\n```\n\n### Update Cargo Packages\nGo to `src-tauri/Cargo.toml` and change `tauri` to\n`tauri = { version = \"%version%\" }` where `%version%` is the version number shown above. (You can just use the `MAJOR.MINOR`) version, like `0.9`.\n\nThen do the following:\n```bash\n$ cd src-tauri\n$ cargo update -p tauri\n```\nYou can also run `cargo outdated -r tauri` to get direct information about the core library's latest version.\n","h1":[],"h2":[{"content":"Automatic updates","type":"text"},{"content":"Manual updates","type":"text"}],"h3":[{"content":"Update NPM Packages","type":"text"}],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"debian.md","filepath":"docs/usage/guides/bundler","hash":42,"frontmatter":{"title":"Debian packages"},"text":"\nimport Alert from '@theme/Alert'\n\nTauri allows your app to be packaged as a `.deb` (Debian package) file.\n\n# Bootstrapper\n\nInstead of launching the app directly, you can configure the bundled app to run a script that tries to expose the environment variables to the app; without that you'll have trouble using system programs because the `PATH` environment variable isn't correct. Enable it with the <a href=\"/docs/api/config#tauri.bundle.deb.useBootstrapper\">`useBootstrapper`</a> config.\n\n# Custom files\n\nTo include custom files to the debian package, you can configure a mapping on `tauri.conf.json > tauri > bundle > deb > files` as follows:\n\n```json\n{\n \"tauri\": {\n \"bundle\": {\n \"deb\": {\n \"files\": {\n \"/usr/lib/README.md\": \"../README.md\", // copies the README.md file to /usr/lib/README.md\n \"usr/lib/assets\": \"../public/\" // copies the entire public directory to /usr/lib/assets\n }\n }\n }\n }\n}\n```\n\n<Alert title=\"Note\" icon=\"info-alt\">\nEach `files` object key is the path on the debian package, and the value is a path to a file or directory relative to the `tauri.conf.json` file.\n</Alert>\n","h1":[{"content":"Bootstrapper","type":"text"},{"content":"Custom files","type":"text"}],"h2":[],"h3":[],"hasCodeBlock":true,"programmingLanguages":["json"],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"introduction.md","filepath":"docs/usage/guides/bundler","hash":42,"frontmatter":{"title":"Introduction"},"text":"\nThe Tauri Bundler is a Rust harness for compiling your binary, packaging assets, and preparing a final bundle.\n\nIt will detect your operating system and build a bundle accordingly. It currently supports:\n\n- Linux: .deb, .appimage\n- macOS: .app, .dmg\n- Windows: .exe, .msi","h1":[],"h2":[],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","list"]}

View File

@@ -0,0 +1 @@
{"filename":"sidecar.md","filepath":"docs/usage/guides/bundler","hash":42,"frontmatter":{"title":"Sidecar (Embedding External Binaries)","sidebar_label":"Sidecar"},"text":"\nimport Alert from '@theme/Alert'\n\nYou may need to embed depending binaries in order to make your application work or to prevent users having to install additional dependencies (e.g. Node.js, Python, etc).\n\nTo bundle the binaries of your choice, you can add the `externalBin` property to the `tauri > bundle` object in your `tauri.conf.json`.\n\nSee more about tauri.conf.json configuration <a href=\"/docs/api/config#tauri.bundle\">here</a>.\n\n`externalBin` expects a list of strings targeting binaries either with absolute or relative paths.\n\nHere is a sample to illustrate the configuration, this is not a complete `tauri.conf.json` file:\n\n```json\n{\n \"tauri\": {\n \"bundle\": {\n \"externalBin\": [\"/absolute/path/to/app\", \"relative/path/to/binary\", \"bin/python\"]\n }\n }\n}\n```\n\nA binary with the same name and a `-$TARGET_TRIPLE` suffix must exist on the specified path. For instance, `\"externalBin\": [\"bin/python\"]` requires a `src-tauri/bin/python-x86_64-unknown-linux-gnu` executable on Linux. You can find the current platform's target triple running the following command:\n\n```bash\nRUSTC_BOOTSTRAP=1 rustc -Z unstable-options --print target-spec-json\n```\n\nHere's a Node.js script to append the target triple to a binary:\n\n```javascript\nconst execa = require('execa')\nconst fs = require('fs')\n\nlet extension = ''\nif (process.platform === 'win32') {\n extension = '.exe'\n}\n\nasync function main() {\n const rustInfo = (await execa('rustc', ['-vV'])).stdout\n const targetTriple = /host: (\\S+)/g.exec(rustInfo)[1]\n if (!targetTriple) {\n console.error('Failed to determine platform target triple')\n }\n fs.renameSync(\n `src-tauri/binaries/app${extension}`,\n `src-tauri/binaries/app-${targetTriple}${extension}`\n )\n}\n\nmain().catch((e) => {\n throw e\n})\n\n```\n\n## Running the sidecar binary on JavaScript\n\nOn the JavaScript code, import the `Command` class on the `shell` module and use the `sidecar` static method:\n\n```javascript\nimport { Command } from '@tauri-apps/api/shell'\n// alternatively, use `window.__TAURI__.shell.Command`\n// `my-sidecar` is the value specified on `tauri.conf.json > tauri > bundle > externalBin`\nconst command = Command.sidecar('my-sidecar')\nconst output = await command.execute()\n```\n\n## Running the sidecar binary on Rust\n\nOn the Rust code, import the `Command` struct from the `tauri::api::process` module:\n\n```rust\nlet (mut rx, mut child) = Command::new_sidecar(\"my-sidecar\")\n .expect(\"failed to create `my-sidecar` binary command\")\n .spawn()\n .expect(\"Failed to spawn sidecar\");\n\ntauri::async_runtime::spawn(async move {\n // read events such as stdout\n while let Some(event) = rx.recv().await {\n if let CommandEvent::Stdout(line) = event {\n window\n .emit(\"message\", Some(format!(\"'{}'\", line)))\n .expect(\"failed to emit event\");\n // write to stdin\n child.write(\"message from Rust\\n\".as_bytes()).unwrap();\n }\n }\n});\n```\n\n## Using Node.js on a sidecar\n\nThe Tauri [sidecar example](https://github.com/tauri-apps/tauri/tree/dev/examples/sidecar) demonstrates how to use the sidecar API to run a Node.js application on Tauri.\nIt compiles the Node.js code using [pkg](https://github.com/vercel/pkg) and uses the scripts above to run it.\n","h1":[],"h2":[{"content":"Running the sidecar binary on JavaScript","type":"text"},{"content":"Running the sidecar binary on Rust","type":"text"},{"content":"Using Node","type":"text"}],"h3":[],"hasCodeBlock":true,"programmingLanguages":["json","bash","javascript","rust"],"otherSymbols":["text","inlineCode","link"]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"plugin.md","filepath":"docs/usage/guides","hash":42,"frontmatter":{"title":"Write Tauri Plugins"},"text":"\nimport Alert from '@theme/Alert'\n\n<Alert title=\"Note\" icon=\"info-alt\">\nTauri will soon offer Plugin starter kits so the process of writing a Plugin crate will be simplified.\n\nFor now it's recommended to follow the [official Tauri plugins](#official-tauri-plugins).\n</Alert>\n\nPlugins allow you to hook into the Tauri application lifecycle and introduce new commands.\n\n## Writing a Plugin\n\nTo write a plugin you just need to implement the `tauri::plugin::Plugin` trait:\n\n```rust\nuse tauri::{plugin::{Plugin, Result as PluginResult}, Runtime, PageLoadPayload, Window, Invoke, AppHandle};\n\nstruct MyAwesomePlugin<R: Runtime> {\n invoke_handler: Box<dyn Fn(Invoke<R>) + Send + Sync>,\n // plugin state, configuration fields\n}\n\n// the plugin custom command handlers if you choose to extend the API.\n#[tauri::command]\n// this will be accessible with `invoke('plugin:awesome|initialize')`.\n// where `awesome` is the plugin name.\nfn initialize() {}\n\n#[tauri::command]\n// this will be accessible with `invoke('plugin:awesome|do_something')`.\nfn do_something() {}\n\nimpl<R: Runtime> MyAwesomePlugin<R> {\n // you can add configuration fields here,\n // see https://doc.rust-lang.org/1.0.0/style/ownership/builders.html\n pub fn new() -> Self {\n Self {\n invoke_handler: Box::new(tauri::generate_handler![initialize, do_something]),\n }\n }\n}\n\nimpl<R: Runtime> Plugin<R> for MyAwesomePlugin<R> {\n /// The plugin name. Must be defined and used on the `invoke` calls.\n fn name(&self) -> &'static str {\n \"awesome\"\n }\n\n /// The JS script to evaluate on initialization.\n /// Useful when your plugin is accessible through `window`\n /// or needs to perform a JS task on app initialization\n /// e.g. \"window.awesomePlugin = { ... the plugin interface }\"\n fn initialization_script(&self) -> Option<String> {\n None\n }\n\n /// initialize plugin with the config provided on `tauri.conf.json > plugins > $yourPluginName` or the default value.\n fn initialize(&mut self, app: &AppHandle<R>, config: serde_json::Value) -> PluginResult<()> {\n Ok(())\n }\n\n /// Callback invoked when the Window is created.\n fn created(&mut self, window: Window<R>) {}\n\n /// Callback invoked when the webview performs a navigation.\n fn on_page_load(&mut self, window: Window<R>, payload: PageLoadPayload) {}\n\n /// Extend the invoke handler.\n fn extend_api(&mut self, message: Invoke<R>) {\n (self.invoke_handler)(message)\n }\n}\n```\n\nNote that each function on the `Plugin` trait is optional, except the `name` function.\n\n## Using a plugin\n\nTo use a plugin, just pass an instance of the `MyAwesomePlugin` struct to the App's `plugin` method:\n\n```rust\nfn main() {\n let awesome_plugin = MyAwesomePlugin::new();\n tauri::Builder::default()\n .plugin(awesome_plugin)\n .run(tauri::generate_context!())\n .expect(\"failed to run app\");\n}\n```\n\n## Official Tauri Plugins\n\n- [Stronghold (WIP)](https://github.com/tauri-apps/tauri-plugin-stronghold)\n- [Authenticator (WIP)](https://github.com/tauri-apps/tauri-plugin-authenticator)\n- [Logging (WIP)](https://github.com/tauri-apps/tauri-plugin-log)\n- [SQL (WIP)](https://github.com/tauri-apps/tauri-plugin-sql)\n","h1":[],"h2":[{"content":"Writing a Plugin","type":"text"},{"content":"Using a plugin","type":"text"},{"content":"Official Tauri Plugins","type":"text"}],"h3":[],"hasCodeBlock":true,"programmingLanguages":["rust"],"otherSymbols":["text","link","inlineCode","list"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"multiwindow.md","filepath":"docs/usage/guides/utils","hash":42,"frontmatter":{"title":"Multiwindow"},"text":"\nManage multiple windows on a single application.\n","h1":[],"h2":[],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text"]}

View File

@@ -0,0 +1 @@
{"filename":"icons.md","filepath":"docs/usage/guides/visual","hash":42,"frontmatter":{"title":"Icons"},"text":"\nimport Command from '@theme/Command'\nimport Alert from '@theme/Alert'\n\nTauri ships with a default iconset based on its logo. This is probably NOT what you want when you ship your application. To remedy this common situation, Tauri provides the `icon` command that will take an input file and create all the icons needed for the various platforms:\n\n<Command name=\"icon\"/>\n\n```sh\nOptions\n --help, -h Displays this message\n --log, l Logging [boolean]\n --icon, i Source icon (png, 1240x1240 with transparency)\n --target, t Target folder (default: 'src-tauri/icons')\n --compression, c Compression type [pngquant|optipng|zopfli]\n```\n\nThese will be placed in your `src-tauri/icons` folder where they will automatically be included in your built app.\n\nIf you need to source your icons from some other location, you can edit this part of the `src-tauri/tauri.conf.json` file:\n\n```json\n{\n \"tauri\": {\n \"bundle\": {\n \"icon\": [\n \"icons/32x32.png\",\n \"icons/128x128.png\",\n \"icons/128x128@2x.png\",\n \"icons/icon.icns\",\n \"icons/icon.ico\"\n ]\n }\n }\n}\n```\n\n<Alert type=\"info\" icon=\"info-alt\" title=\"Note on filetypes\">\n\n - icon.icns = macOS\n - icon.ico = MS Windows\n - \\*.png = Linux\n\n</Alert>\n","h1":[],"h2":[],"h3":[],"hasCodeBlock":true,"programmingLanguages":["sh","json"],"otherSymbols":["text","inlineCode","list"]}

View File

@@ -0,0 +1 @@
{"filename":"menu.md","filepath":"docs/usage/guides/visual","hash":42,"frontmatter":{"title":"Window Menu"},"text":"\nNative application menus can be attached to a window.\n\n### Creating a menu\n\nTo create a native window menu, import the `Menu`, `Submenu`, `MenuItem` and `CustomMenuItem` types.\nThe `MenuItem` enum contains a collection of platform-specific items (currently not implemented on Windows).\nThe `CustomMenuItem` allows you to create your own menu items and add special functionality to them.\n\n```rust\nuse tauri::{CustomMenuItem, Menu, MenuItem, Submenu};\n```\n\nCreate a `Menu` instance:\n\n```rust\n// here `\"quit\".to_string()` defines the menu item id, and the second parameter is the menu item label.\nlet quit = CustomMenuItem::new(\"quit\".to_string(), \"Quit\");\nlet close = CustomMenuItem::new(\"close\".to_string(), \"Close\");\nlet submenu = Submenu::new(\"File\", Menu::new().add_item(quit).add_item(close));\nlet menu = Menu::new()\n .add_native_item(MenuItem::Copy)\n .add_item(CustomMenuItem::new(\"hide\", \"Hide\"))\n .add_submenu(submenu);\n```\n\n### Adding the menu to all windows\n\nThe defined menu can be set to all windows using the `menu` API on the `tauri::Builder` struct:\n\n```rust\nuse tauri::{CustomMenuItem, Menu, MenuItem, Submenu};\n\nfn main() {\n let menu = Menu::new(); // configure the menu\n tauri::Builder::default()\n .menu(menu)\n .run(tauri::generate_context!())\n .expect(\"error while running tauri application\");\n}\n```\n\n### Adding the menu to a specific window\n\nYou can create a window and set the menu to be used. This allows defining a specific menu set for each application window.\n\n```rust\nuse tauri::{CustomMenuItem, Menu, MenuItem, Submenu};\nuse tauri::WindowBuilder;\n\nfn main() {\n let menu = Menu::new(); // configure the menu\n tauri::Builder::default()\n .create_window(\n \"main-window\".to_string(),\n tauri::WindowUrl::App(\"index.html\".into()),\n move |window_builder, webview_attributes| {\n (window_builder.menu(menu), webview_attributes)\n },\n )\n .run(tauri::generate_context!())\n .expect(\"error while running tauri application\");\n}\n```\n\n### Listening to events on custom menu items\n\nEach `CustomMenuItem` triggers an event when clicked. Use the `on_menu_event` API to handle them, either on the global `tauri::Builder` or on an specific window.\n\n#### Listening to events on global menus\n\n```rust\nuse tauri::{CustomMenuItem, Menu, MenuItem};\n\nfn main() {\n let menu = vec![]; // insert the menu array here\n tauri::Builder::default()\n .menu(menu)\n .on_menu_event(|event| {\n match event.menu_item_id() {\n \"quit\" => {\n std::process::exit(0);\n }\n \"close\" => {\n event.window().close().unwrap();\n }\n _ => {}\n }\n })\n .run(tauri::generate_context!())\n .expect(\"error while running tauri application\");\n}\n```\n\n#### Listening to events on window menus\n\n```rust\nuse tauri::{CustomMenuItem, Menu, MenuItem};\nuse tauri::{Manager, WindowBuilder};\n\nfn main() {\n let menu = vec![]; // insert the menu array here\n tauri::Builder::default()\n .create_window(\n \"main-window\".to_string(),\n tauri::WindowUrl::App(\"index.html\".into()),\n move |window_builder, webview_attributes| {\n (window_builder.menu(menu), webview_attributes)\n },\n )\n .setup(|app| {\n let window = app.get_window(\"main-window\").unwrap();\n let window_ = window.clone();\n window.on_menu_event(move |event| {\n match event.menu_item_id().as_str() {\n \"quit\" => {\n std::process::exit(0);\n }\n \"close\" => {\n window_.close().unwrap();\n }\n _ => {}\n }\n });\n Ok(())\n })\n .run(tauri::generate_context!())\n .expect(\"error while running tauri application\");\n}\n```\n\n### Updating menu items\n\nThe `Window` struct has a `menu_handle` method, which allows updating menu items:\n\n```rust\nfn main() {\n tauri::Builder::default()\n .setup(|app| {\n let main_window = app.get_window(\"main\").unwrap();\n let menu_handle = main_window.menu_handle();\n std::thread::spawn(move || {\n // you can also `set_selected`, `set_enabled` and `set_native_image` (macOS only).\n menu_handle.get_item(\"item_id\").set_title(\"New title\");\n })\n Ok(())\n })\n}\n```\n","h1":[],"h2":[],"h3":[{"content":"Creating a menu","type":"text"},{"content":"Adding the menu to all windows","type":"text"},{"content":"Adding the menu to a specific window","type":"text"},{"content":"Listening to events on custom menu items","type":"text"},{"content":"Updating menu items","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["rust"],"otherSymbols":["text","inlineCode","h4"]}

View File

@@ -0,0 +1 @@
{"filename":"splashscreen.md","filepath":"docs/usage/guides/visual","hash":42,"frontmatter":{"title":"Splashscreen"},"text":"\nimport Link from '@docusaurus/Link'\n\nIf your webpage could take some time to load, or if you need to run an initialization procedure in Rust before displaying your main window, a splashscreen could improve the loading experience for the user.\n\n### Setup\n\nFirst, create a `splashscreen.html` in your `distDir` that contains the HTML code for a splashscreen. Then, update your `tauri.conf.json` like so:\n\n```diff\n\"windows\": [\n {\n \"title\": \"Tauri App\",\n \"width\": 800,\n \"height\": 600,\n \"resizable\": true,\n \"fullscreen\": false,\n+ \"visible\": false // Hide the main window by default\n },\n // Add the splashscreen window\n+ {\n+ \"width\": 400,\n+ \"height\": 200,\n+ \"decorations\": false,\n+ \"url\": \"splashscreen.html\",\n+ \"label\": \"splashscreen\"\n+ }\n]\n```\n\nNow, your main window will be hidden and the splashscreen window will show when your app is launched. Next, you'll need a way to close the splashscreen and show the main window when your app is ready. How you do this depends on what you are waiting for before closing the splashscreen.\n\n### Waiting for Webpage\n\nIf you are waiting for your web code, you'll want to create a `close_splashscreen` [command](../command.md).\n\n```rust title=src-tauri/main.rs\nuse tauri::Manager;\n// Create the command:\n#[tauri::command]\nfn close_splashscreen(window: tauri::Window) {\n // Close splashscreen\n if let Some(splashscreen) = window.get_window(\"splashscreen\") {\n splashscreen.close().unwrap();\n }\n // Show main window\n window.get_window(\"main\").unwrap().show().unwrap();\n}\n\n// Register the command:\nfn main() {\n tauri::Builder::default()\n // Add this line\n .invoke_handler(tauri::generate_handler![close_splashscreen])\n .run(tauri::generate_context!())\n .expect(\"failed to run app\");\n}\n\n```\n\nThen, you can call it from your JS:\n\n```js\n// With the Tauri API npm package:\nimport { invoke } from '@tauri-apps/api/tauri'\n// With the Tauri global script:\nconst invoke = window.__TAURI__.invoke\n\ndocument.addEventListener('DOMContentLoaded', () => {\n // This will wait for the window to load, but you could\n // run this function on whatever trigger you want\n invoke('close_splashscreen')\n})\n```\n\n### Waiting for Rust\n\nIf you are waiting for Rust code to run, put it in the `setup` function handler so you have access to the `App` instance:\n\n```rust title=src-tauri/main.rs\nuse tauri::Manager;\nfn main() {\n tauri::Builder::default()\n .setup(|app| {\n let splashscreen_window = app.get_window(\"splashscreen\").unwrap();\n let main_window = app.get_window(\"main\").unwrap();\n // we perform the initialization code on a new task so the app doesn't freeze\n tauri::async_runtime::spawn(async move {\n // initialize your app here instead of sleeping :)\n println!(\"Initializing...\");\n std::thread::sleep(std::time::Duration::from_secs(2));\n println!(\"Done initializing.\");\n\n // After it's done, close the splashscreen and display the main window\n splashscreen_window.close().unwrap();\n main_window.show().unwrap();\n });\n Ok(())\n })\n .run(tauri::generate_context!())\n .expect(\"failed to run app\");\n}\n```\n","h1":[],"h2":[],"h3":[{"content":"Setup","type":"text"},{"content":"Waiting for Webpage","type":"text"},{"content":"Waiting for Rust","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["diff",null],"otherSymbols":["text","inlineCode","link"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"window-customization.md","filepath":"docs/usage/guides/visual","hash":42,"frontmatter":{"title":"Window Customization"},"text":"\nTauri provides lots of options for customizing the look and feel of your app's window. You can create custom titlebars, have transparent windows, enforce size constraints, and more.\n\n## Configuration\n\nThere are three ways to change the window configuration:\n\n- [Through tauri.conf.json](https://tauri.studio/en/docs/api/config/#tauri.windows)\n- [Through the JS API](https://tauri.studio/en/docs/api/js/classes/window.windowmanager)\n- [Through the Window in Rust](https://tauri.studio/en/docs/api/rust/tauri/window/struct.window)\n\n## Creating a Custom Titlebar\n\nA common use of these window features is creating a custom titlebar. This short tutorial will guide you through that process.\n\n### CSS\n\nYou'll need to add some CSS for the titlebar to keep it at the top of the screen and style the buttons:\n\n```css\n.titlebar {\n height: 30px;\n background: #329ea3;\n user-select: none;\n display: flex;\n justify-content: flex-end;\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n}\n.titlebar-button {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n width: 30px;\n height: 30px;\n}\n.titlebar-button:hover {\n background: #5bbec3;\n}\n```\n\n### HTML\n\nNow, you'll need to add the HTML for the titlebar. Put this at the top of your `<body>` tag:\n\n```html\n<div data-tauri-drag-region class=\"titlebar\">\n <div class=\"titlebar-button\" id=\"titlebar-minimize\">\n <img\n src=\"https://api.iconify.design/mdi:window-minimize.svg\"\n alt=\"minimize\"\n />\n </div>\n <div class=\"titlebar-button\" id=\"titlebar-maximize\">\n <img\n src=\"https://api.iconify.design/mdi:window-maximize.svg\"\n alt=\"maximize\"\n />\n </div>\n <div class=\"titlebar-button\" id=\"titlebar-close\">\n <img src=\"https://api.iconify.design/mdi:close.svg\" alt=\"close\" />\n </div>\n</div>\n```\n\nNote that you may need to move the rest of your content down so that the titlebar doesn't cover it.\n\n### JS\n\nFinally, you'll need to make the buttons work:\n\n\n```js\nimport { appWindow } from '@tauri-apps/api/window'\ndocument\n .getElementById('titlebar-minimize')\n .addEventListener('click', () => appWindow.minimize())\ndocument\n .getElementById('titlebar-maximize')\n .addEventListener('click', () => appWindow.toggleMaximize())\ndocument\n .getElementById('titlebar-close')\n .addEventListener('click', () => appWindow.close())\n```\n","h1":[],"h2":[{"content":"Configuration","type":"text"},{"content":"Creating a Custom Titlebar","type":"text"}],"h3":[{"content":"CSS","type":"text"},{"content":"HTML","type":"text"},{"content":"JS","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["css","html","js"],"otherSymbols":["text","list","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"ci.md","filepath":"docs/usage/guides/webdriver","hash":42,"frontmatter":{"title":"Continuous Integration"},"text":"\nUtilizing Linux and some programs to create a fake display, it is possible to run [WebDriver] tests with\n[`tauri-driver`] on your CI. The following example will use the [WebdriverIO] example we [previously built together] and\nGitHub Actions.\n\nThis means the following assumptions:\n\n1. The Tauri application is in the repository root and the binary builds when running `cargo build --release`.\n2. The [WebDriverIO] test runner is in the `webdriver/webdriverio` directory and runs when `yarn test` is used in that\n directory.\n\nThe following is a commented GitHub Actions workflow file at `.github/workflows/webdriver.yml`\n\n```yaml\n# run this action when the repository is pushed to\non: [ push ]\n\n# the name of our workflow\nname: WebDriver\n\njobs:\n # a single job named test\n test:\n # the display name the test job\n name: WebDriverIO Test Runner\n\n # we want to run on the latest linux environment\n runs-on: ubuntu-latest\n\n # the steps our job runs **in order**\n steps:\n # checkout the code on the workflow runner\n - uses: actions/checkout@v2\n\n # install system dependencies that Tauri needs to compile on Linux.\n # note the extra dependencies for `tauri-driver` to run which are `webkit2gtk-driver` and `xvfb`\n - name: Tauri dependencies\n run: >-\n sudo apt-get update &&\n sudo apt-get install -y\n libgtk-3-dev\n libgtksourceview-3.0-dev\n webkit2gtk-4.0\n libappindicator3-dev\n webkit2gtk-driver\n xvfb\n\n # install the latest Rust stable\n - name: Rust stable\n uses: actions-rs/toolchain@v1\n with:\n toolchain: stable\n\n # we run our rust tests before the webdriver tests to avoid testing a broken application\n - name: Cargo test\n uses: actions-rs/cargo@v1\n with:\n command: test\n\n # build a release build of our application to be used during our WebdriverIO tests\n - name: Cargo build\n uses: actions-rs/cargo@v1\n with:\n command: build\n args: --release\n\n # install the latest stable node version at the time of writing\n - name: Node v16\n uses: actions/setup-node@v1\n with:\n node-version: 16.x\n\n # install our Node.js dependencies with Yarn\n - name: Yarn install\n run: yarn install\n working-directory: webdriver/webdriverio\n\n # install the latest version of `tauri-driver`.\n # note: the tauri-driver version is independent of any other Tauri versions\n - name: Install tauri-driver\n uses: actions-rs/cargo@v1\n with:\n command: install\n args: tauri-driver\n\n # run the WebdriverIO test suite.\n # we run it through `xvfb-run` (the dependency we installed earlier) to have a fake\n # display server which allows our application to run headless without any changes to the code\n - name: WebdriverIO\n run: xvfb-run yarn test\n working-directory: webdriver/webdriverio\n```\n\n[WebDriver]: https://www.w3.org/TR/webdriver/\n[`tauri-driver`]: https://crates.io/crates/tauri-driver\n[WebdriverIO]: https://webdriver.io/\n[previously built together]: example/webdriverio\n","h1":[],"h2":[],"h3":[],"hasCodeBlock":true,"programmingLanguages":["yaml"],"otherSymbols":["text","inlineCode","list","def"]}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
{"filename":"introduction.md","filepath":"docs/usage/guides/webdriver","hash":42,"frontmatter":{"title":"Introduction"},"text":"import Alert from '@theme/Alert'\n\n<Alert title=\"Currently in pre-alpha\" type=\"info\" icon=\"info-alt\">\n\nWebdriver support for Tauri is still in pre-alpha. Tooling that is dedicated to it such as [tauri-driver] is still in\nactive development and may change as necessary over time. Additionally, only Windows and Linux are currently supported.\n</Alert>\n\n[WebDriver] is a standardized interface to interact with web documents that is primarily intended for automated testing.\nTauri supports the [WebDriver] interface by leveraging the native platform's [WebDriver] server underneath a\ncross-platform wrapper [`tauri-driver`].\n\n## System Dependencies\n\nInstall the latest [`tauri-driver`] or update an existing installation by running:\n\n```sh\ncargo install tauri-driver\n```\n\nBecause we currently utilize the platform's native [WebDriver] server, there are some requirements for running\n[`tauri-driver`] on supported platforms. Platform support is currently limited to Linux and Windows.\n\n### Linux\n\nWe use `WebKitWebDriver` on linux platforms. Check if this binary exists already (command `which WebKitWebDriver`) as\nsome distributions bundle it with the regular webkit package. Other platforms may have a separate package for them such\nas `webkit2gtk-driver` on Debian based distributions.\n\n### Windows\n\nMake sure to grab the version of [Microsoft Edge Driver] that matches your Windows' Edge version that the application is\nbeing built and tested on. On up-to-date Window installs, this should almost always be the latest stable version. If the\ntwo versions do not match, you may experience your WebDriver testing suite hanging while trying to connect.\n\nThe download contains a binary called `msedgedriver.exe`. [`tauri-driver`] looks for that binary in the `$PATH` so make\nsure it's either available on the path or use the `--native-driver` option on [`tauri-driver`]. On Windows CI machines,\nyou may want to download this automatically as part of the CI setup process to ensure the Edge and Edge Driver versions\nstay in sync. A guide on how to do this may be added at a later date.\n\n## Example Application\n\nThe [next section](example/setup) of the guide will show step-by-step how to create a minimal example application that\nis tested with WebDriver.\n\nIf you prefer to just see the result of the guide and look over a finished minimal codebase that utilizes it then you\ncan look at https://github.com/chippers/hello_tauri. That example also comes with a CI script to test with GitHub\nactions, but you may still be interested in the [WebDriver CI](ci) guide as it explains the concept a bit more.\n\n[WebDriver]: https://www.w3.org/TR/webdriver/\n[`tauri-driver`]: https://crates.io/crates/tauri-driver\n[tauri-driver]: https://crates.io/crates/tauri-driver\n[Microsoft Edge Driver]: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/\n","h1":[],"h2":[{"content":"System Dependencies","type":"text"},{"content":"Example Application","type":"text"}],"h3":[{"content":"Linux","type":"text"},{"content":"Windows","type":"text"}],"hasCodeBlock":true,"programmingLanguages":["sh"],"otherSymbols":["text","inlineCode","link","def"]}

View File

@@ -0,0 +1 @@
{"filename":"intro.md","filepath":"docs/usage","hash":42,"frontmatter":{"title":"Introduction"},"text":"\nThis part of the documentation is dedicated to learning how to use Tauri.\n\nTauri provides a [CLI](/docs/api/cli), a Rust API, and a [JavaScript API](/docs/api/js/index) that you can use in your project. Because raw docs can be quite scary to newcomers (especially people who have never played with Rust before), we've created this \"learn by example\" section.\n\nHere you will find guides and techniques to add to your own project in order to fulfill your goals.\n\n## A Step Further\n\n- [Understanding Tauri Patterns](/docs/usage/patterns/about-patterns)\n- [Add Tauri to my existing project](/docs/usage/development/integration)\n- [Tauri Development Cycle](/docs/usage/development/development)\n\n## Guides\n\n- [How to embed custom binaries](/docs/usage/guides/bundler/sidecar)\n- [How to customize app icons](/docs/usage/guides/visual/icons)\n","h1":[],"h2":[{"content":"A Step Further","type":"text"},{"content":"Guides","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","link","list"]}

View File

@@ -0,0 +1 @@
{"filename":"about-patterns.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"id":"about-patterns","title":"A word on patterns","sidebar_label":"A word on patterns"},"text":"\nTauri patterns are descriptions of use-cases that are entirely configurable within the `src-tauri/tauri.conf.json` file. These are not the limits of what Tauri can do, and there are probably more out there. If you discover one, why not get in touch and help us update this collection!\n\nIf you haven't read about the general design of Tauri, then it would make the most sense for you to visit the [\"Getting started\"](/docs/getting-started/intro) and become familiar with the basic architecture and terminology used in these patterns. \n","h1":[],"h2":[],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode","link"]}

View File

@@ -0,0 +1 @@
{"filename":"bridge.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Bridge"},"text":"\nimport Rater from '@theme/Rater'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"3\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"4\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"4\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Bridge.png')} alt=\"Bridge\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Highly configurable</li>\n <li>No Rust skills required</li>\n </ul>\n Cons:\n <ul>\n <li>Some WebAPIs unavailable</li>\n <li>Challenge to implement</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe Bridge recipe is a secure pattern where messages are passed between brokers via an implicit bridge using the API. It isolates functionality to scope and passes messages instead of functionality.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph TD\n H==>F\n subgraph WEBVIEW\n F-.-E\n end\n D-->E\n E-->D\n B-->D\n D-->B\n subgraph RUST\n A==>H\n A-->B\n B-.-C\n B-.-G\n end\n A[Binary]\n B{Rust Broker}\n C[Subprocess 2]\n G[Subprocess 1]\n D(( API BRIDGE ))\n E{JS Broker}\n F[Window]\n H{Bootstrap}\n style D fill:#ccc,stroke:#333,stroke-width:4px,color:white\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px`} />\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": { // all API values are default false\n \"all\": false, // use this flag to enable all API features\n \"shell\": {\n \"execute\": false, // enable application execution\n \"open\": false, // open link/path in the default app\n },\n \"fs\": {\n \"listFiles\": false, // list files in a directory\n \"readBinaryFile\": false, // read binary file from local filesystem\n \"readTextFile\": false, // read text file from local filesystem\n \"setTitle\": false, // set the window title\n \"writeFile\": false // write file to local filesystem\n }\n }\n}\n\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"cloudbridge.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Cloudbridge"},"text":"\nimport Rater from '@theme/Rater'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"1\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"3\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"2\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Cloudbridge.png')} alt=\"Cloudbridge\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>All available features</li>\n <li>No Rust skills required</li>\n </ul>\n Cons:\n <ul>\n <li>Largest bundle size</li>\n <li>Hard to separate concerns</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe Cloudbridge recipe combines the flexibility of a localhost and the security of the bridge. With so many features, it can be easy to get lost.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph TD\n H==>F2\n H==>D2\n D2-->F2\n F2-->D2\n B-->D\n D-->B\n E2-->D\n D-->E2\n subgraph WEBVIEW\n F2\n E2\n end\n subgraph SERVER\n D2\n E-->D2\n end\n subgraph RUST\n A==>H\n A-->B\n B-.-C\n end\n A[Binary]\n B{Rust Broker}\n C[Subprocess]\n D(( API BRIDGE ))\n E{JS Broker}\n D2(( localhost ))\n E[bundled resources]\n E2{JS Broker}\n F2[Window]\n H{Bootstrap}\n style D fill:#ccc,stroke:#333,stroke-width:4px,color:white\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px\n style SERVER fill:#49A24A,stroke:#2B6063,stroke-width:4px\n `} />\n\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": {\n \"all\": true // enable entire API\n }\n}\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"cloudish.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Cloudish"},"text":"\nimport Rater from '@theme/Rater'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"3\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"3\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"2\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Cloudish.png')} alt=\"Cloudish\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Similar to a SPA web-app</li>\n <li>No Rust skills required</li>\n </ul>\n Cons:\n <ul>\n <li>No access to Rust API</li>\n <li>Uses a localhost server</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe Cloudish recipe is a pattern for maximum flexibility and app performance. It uses a localhost server, which means that your app will technically be available to other processes, like browsers and potentially other devices on the network. All of your assets are baked into the binary, but served as if they were distinct files.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph TD\n H==>F\n H==>D\n D-->F\n F-->D\n subgraph RUST\n A==>H\n end\n subgraph WEBVIEW\n F\n end\n subgraph SERVER\n D\n E-->D\n end\n A[Binary]\n D(( localhost ))\n E[bundled resources]\n F[Window]\n H{Bootstrap}\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px\n style SERVER fill:#49A24A,stroke:#2B6063,stroke-width:4px`} />\n\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": {\n \"all\": false // disable entire API\n }\n}\n\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"glui.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"GLUI"},"text":"\nimport Alert from '@theme/Alert'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<Alert type=\"warning\" icon=\"info-alt\" title=\"Please note\">\nThis pattern is not available for now.\n</Alert>\n\nimport Rater from '@theme/Rater'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"0\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"0\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"0\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/GLUI.png')} alt=\"GLUI\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Framebuffer FTW</li>\n <li>Window events rigged</li>\n </ul>\n Cons:\n <ul>\n <li>Broken on your machine</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe GLUI is a research pattern that we will use internally to test approaches using a GLUTIN window. Were not sure yet if it will make the final cut as a bona fide alternative to WebView, although early tests with transparent and multiwindow are exciting.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph TD\n A==>H\n H==>G\n A-->D\n D-->G\n subgraph GLUTIN\n G\n end\n subgraph RUST\n A\n end\n A[Binary]\n D(Framebuffer)\n G[GL Window]\n H{Bootstrap}\n style GLUTIN stroke:${colors.blue.dark},stroke-width:4px\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px`} />\n\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": { // all API endpoints are default false\n \"all\": false, // disable the api\n },\n \"window\": { // not yet normative\n \"glutin\": true,\n \"webview\": false\n }\n}\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"hermit.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Hermit"},"text":"\nimport Rater from '@theme/Rater'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"0\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Hermit.png')} alt=\"Hermit\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Quick to make</li>\n <li>Smallest size</li>\n </ul>\n Cons:\n <ul>\n <li>No remote resources</li>\n <li>No access to API</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe Hermit recipe is a pattern for ultimate application isolation where all logic is self-contained in the Window and the binary exists merely to bootstrap the Window. There is no communication back to Rust from the Window, there is no localhost server, and the Window has no access to any remote resources. The Hermit is great for interactive Kiosk Mode and standalone HTML based games.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph LR\n A==>H\n H==>F\n subgraph WEBVIEW\n F\n end\n subgraph RUST\n A\n end\n A[fa:fa-cog Binary ]\n F[fa:fa-window-maximize Window]\n H{Bootstrap}\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px`} />\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n\n```json\n\"tauri\": {\n \"allowlist\": {\n \"all\": false, // disable and tree-shake all api functions\n }\n}\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":true,"programmingLanguages":["json"],"otherSymbols":["text","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"lockdown.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Lockdown"},"text":"\nimport Rater from '@theme/Rater'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"2\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"4\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"5\" color=\"#fff04d\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Lockdown.png')} alt=\"Lockdown\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Highest security rating</li>\n <li>Elegant and powerful</li>\n </ul>\n Cons:\n <ul>\n <li>Rust skills required</li>\n <li>No remote resources</li>\n </ul>\n </div>\n</div>\n\n\n## Description\n\nThe Lockdown recipe is a minimal usage of the [Bridge pattern](/docs/usage/patterns/bridge), which only allows interaction between Rust and the Window via expiring JS Promise Closures that are injected into the Window by Rust and nulled as part of the callback.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph TD\n H==>F\n G-.->B\n B-->G\n subgraph WEBVIEW\n G-->F\n end\n subgraph RUST\n A-->B\n A==>H\n end\n A[Binary]\n B[API:Event]\n F[Window]\n G((Promise Closure))\n H{Bootstrap}\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px`} />\n\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": {} // all API endpoints are default false\n}\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","link","inlineCode"]}

View File

@@ -0,0 +1 @@
{"filename":"multiwin.md","filepath":"docs/usage/patterns","hash":42,"frontmatter":{"title":"Multiwin"},"text":"\nimport Alert from '@theme/Alert'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\n\nimport Rater from '@theme/Rater'\n\n<div className=\"row\">\n <div className=\"col col--4\">\n <table>\n <tr>\n <td>Ease of Use</td>\n <td><Rater value=\"4\"/></td>\n </tr>\n <tr>\n <td>Extensibility</td>\n <td><Rater value=\"4\"/></td>\n </tr>\n <tr>\n <td>Performance</td>\n <td><Rater value=\"3\"/></td>\n </tr>\n <tr>\n <td>Security</td>\n <td><Rater value=\"5\"/></td>\n </tr>\n </table>\n </div>\n <div className=\"col col--4 pattern-logo\">\n <img src={useBaseUrl('img/patterns/Multiwin.png')} alt=\"Multiwin\" />\n </div>\n <div className=\"col col--4\">\n Pros:\n <ul>\n <li>Windows can be spawned or destroyed at runtime</li>\n <li>Separation of concerns</li>\n </ul>\n Cons:\n <ul>\n <li>Somewhat complex</li>\n </ul>\n </div>\n</div>\n\n## Description\n\nThe Multiwin recipe will allow you to have multiple windows.\n\n## Diagram\n\nimport Mermaid, { colors } from '@theme/Mermaid'\n\n<Mermaid chart={`graph LR\n A==>H\n H==>F\n H==>G\n subgraph WEBVIEW\n F\n end\n subgraph WINIT\n G\n end\n subgraph RUST\n A\n end\n A[Binary]\n F[Window]\n G[Window]\n H{Bootstrap}\n style WINIT stroke:${colors.blue.dark},stroke-width:4px\n style RUST fill:${colors.orange.light},stroke:${colors.orange.dark},stroke-width:4px\n style WEBVIEW fill:${colors.blue.light},stroke:${colors.blue.dark},stroke-width:4px`} />\n\n\n## Configuration\n\nHere's what you need to add to your tauri.conf.json file:\n```json\n\"tauri\": {\n \"allowlist\": {}, // all API endpoints are default false\n \"windows\": [{\n \"title\": \"Window1\",\n \"label\": \"main\",\n }, {\n \"title\": \"Splash\",\n \"label\": \"splashscreen\"\n }]\n}\n\n```\n","h1":[],"h2":[{"content":"Description","type":"text"},{"content":"Diagram","type":"text"},{"content":"Configuration","type":"text"}],"h3":[],"hasCodeBlock":false,"programmingLanguages":[],"otherSymbols":["text","inlineCode"]}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,37 @@
import { omit } from "native-dash";
import { join } from "path";
import { IDocsSitemap } from "./github/buildDocsSitemap";
export interface IFlatSitemap {
/** the full "relative path" (aka, dir and filename combined) */
filepath: string;
sha: string;
size: number;
download_url: string;
}
export type ISitemapDictionary = Record<string, Omit<IFlatSitemap, "filepath">>;
/**
* Flattens the hierarchical structure of a sitemap into an easily iterable array
*/
export function flattenSitemap(sm: IDocsSitemap): IFlatSitemap[] {
let flat: IFlatSitemap[] = [];
for (const f of sm.files) {
const filepath = join(sm.dir, f.name);
flat.push({ filepath, sha: f.sha, size: f.size, download_url: f.download_url });
}
if (sm.children && sm.children.length > 0) {
for (const child of sm.children) {
flat = flat.concat(...flattenSitemap(child));
}
}
return flat;
}
export function sitemapDictionary(sm: IDocsSitemap) {
return flattenSitemap(sm).reduce((acc, i) => {
return { ...acc, [i.filepath]: { ...omit(i, "filepath") } };
}, {} as ISitemapDictionary);
}

View File

@@ -10,7 +10,7 @@ export type IGetContentOptions = IGetContentFallback | {};
* **getContent**
*
* Utility which allows for setting a fallback location and then exposing a
* consumer facing fuction which allows a user to choose from a file or network
* consumer facing function which allows a user to choose from a file or network
* based location for content.
*
* Note: the first caller who sets up this higher-order function gets to choose

View File

@@ -0,0 +1,12 @@
import { config } from "dotenv";
export function getEnv() {
config();
return {
repo: process.env.REPO || "tauri",
branch: process.env.BRANCH || "dev",
github_token: process.env.GITHUB_TOKEN || undefined,
github_user: process.env.GITHUB_USER || undefined,
force: process.env.FORCE ? Boolean(process.env.FORCE) : false,
};
}

View File

@@ -0,0 +1,103 @@
import { Endpoints } from "@octokit/types";
import axios from "axios";
import { join } from "node:path";
import { GITHUB_API_BASE } from "~/constants";
import { getEnv } from "../getEnv";
export type GithubContentsReq =
Endpoints["GET /repos/{owner}/{repo}/contents/{path}"]["parameters"];
export type GithubContentsResp =
Endpoints["GET /repos/{owner}/{repo}/contents/{path}"]["response"];
const DEFAULT: GithubContentsReq = {
owner: "tauri-apps",
path: "docs",
repo: "tauri",
ref: "dev",
};
export interface IDocsSitemapFile {
name: string;
size: number;
sha: string;
download_url: string;
}
export interface IDocsSitemap {
dir: string;
files: IDocsSitemapFile[];
children: IDocsSitemap[];
}
async function getDirectory(o: GithubContentsReq) {
const { github_token, github_user } = getEnv();
const url = `${GITHUB_API_BASE}/repos/${o.owner}/${o.repo}/contents/${o.path}?ref=${o.ref}`;
try {
const res = await axios.get(url, {
httpAgent: "Tauri Search",
...(github_token && github_user
? { auth: { username: github_user, password: github_token } }
: {}),
});
if (res.status < 299) {
return res;
} else {
throw new Error(
`The attempt to call Github's "contents" API failed [${res.status}, ${url}]: ${res.statusText}`
);
}
} catch (err) {
throw new Error(
`The attempt to call Github's "contents" API failed [${url}]: ${
(err as Error).message
}`
);
}
}
function reduceClutter(
dir: string,
resp: GithubContentsResp["data"]
): [files: IDocsSitemap["files"], children: string[]] {
if (!Array.isArray(resp)) {
resp = [resp];
}
const files: IDocsSitemap["files"] = resp
.filter((i) => i.type === "file" && i.name.endsWith(".md"))
.map((f) => ({
name: f.name,
size: f.size,
sha: f.sha,
download_url: f.download_url as string,
}));
const children = resp.filter((i) => i.type === "dir").map((d) => d.name);
return [files, children];
}
/**
* Uses Github API to build a sitemap of markdown files for a given repo
*/
export async function buildDocsSitemap(options: Partial<GithubContentsReq> = DEFAULT) {
const o = { ...DEFAULT, ...options };
const [files, children] = reduceClutter(o.path, (await getDirectory(o)).data);
const sitemap: IDocsSitemap = {
dir: o.path,
files,
children: [],
};
if (children.length > 0) {
const waitFor: Promise<IDocsSitemap>[] = [];
for (const child of children) {
const p = join(o.path, `/${child}`);
const mo = { ...o, path: p };
waitFor.push(buildDocsSitemap(mo));
}
const resolved = await Promise.all(waitFor);
sitemap.children = resolved;
}
return sitemap;
}

View File

@@ -0,0 +1,24 @@
import { Endpoints } from "@octokit/types";
import axios from "axios";
import { GITHUB_API_BASE } from "~/constants";
export type GithubCommitsReq = Endpoints["GET /repos/{owner}/{repo}/commits"]["request"];
export type GithubCommitsResp =
Endpoints["GET /repos/{owner}/{repo}/commits"]["response"];
export type IGithubCommitsOptions = {
page?: number;
per_page?: number;
sha?: string;
path?: string;
since?: string;
until?: string;
};
export async function getCommits(
ownerRepo: `${string}/${string}`,
qp: IGithubCommitsOptions
): Promise<GithubCommitsResp> {
const url = `${GITHUB_API_BASE}/repos/${ownerRepo}/commits`;
const params: IGithubCommitsOptions = { page: 1, per_page: 3, ...qp };
return axios.get(url, { params });
}

View File

@@ -1,3 +0,0 @@
# Parsers
These just clean up the AST to the minimal props needed

View File

@@ -1,20 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstClass, TypescriptBlock } from "~/types";
export function parseClass(mod: string, fn: TypescriptBlock): TsAstClass {
return {
kind: TypescriptKind.Class,
name: fn.name,
module: mod,
comment: fn.comment,
type: fn.type,
properties:
fn.signatures?.map((s) => ({
name: s.name,
kind: s.kindString,
comment: s.comment,
type: s.type,
})) || [],
fileName: fn.sources?.shift()?.fileName as string,
};
}

View File

@@ -1,20 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstEnumeration, TypescriptBlock } from "~/types";
export function parseEnumeration(mod: string, fn: TypescriptBlock): TsAstEnumeration {
return {
kind: TypescriptKind.Enumeration,
name: fn.name,
module: mod,
comment: fn.comment,
type: fn.type,
properties:
fn.signatures?.map((s) => ({
name: s.name,
kind: s.kindString,
comment: s.comment,
type: s.type,
})) || [],
fileName: fn.sources?.shift()?.fileName as string,
};
}

View File

@@ -1,20 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstFunction, TypescriptBlock } from "~/types";
export function parseFunction(mod: string, fn: TypescriptBlock): TsAstFunction {
return {
kind: TypescriptKind.Function,
name: fn.name,
module: mod,
comment: fn.comment,
type: fn.type,
signature:
fn.signatures?.map((s) => ({
name: s.name,
kind: s.kindString,
comment: s.comment,
type: s.type,
})) || [],
fileName: fn.sources?.shift()?.fileName as string,
};
}

View File

@@ -1,20 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstInterface, TypescriptBlock } from "~/types";
export function parseInterface(mod: string, i: TypescriptBlock): TsAstInterface {
return {
kind: TypescriptKind.Interface,
name: i.name,
module: mod,
comment: i.comment,
type: i.type,
fileName: i.sources?.shift()?.fileName as string,
properties:
i.children?.map((c) => ({
name: c.name,
kind: c.kindString,
comment: c.comment,
type: c.type,
})) || [],
};
}

View File

@@ -1,35 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TypescriptSymbol, TypescriptBlock } from "~/types";
export function parseModule(mod: TypescriptBlock) {
const modDefn: TypescriptSymbol = {
kind: TypescriptKind.Namespace,
name: mod.name,
module: mod.name,
type: mod.type,
fileName: mod.sources?.shift()?.fileName,
comment: mod.comment,
children: [],
};
const symbols: TypescriptSymbol[] = [modDefn];
for (const i of mod.children || []) {
symbols.push({
kind: i.kindString,
name: i.name,
module: mod.name,
comment: i.comment,
type: i.type,
fileName: i.sources?.shift()?.fileName || "",
signatures: i.signatures?.map((s) => ({
name: s.name,
kind: s.kindString,
comment: s.comment,
type: s.type,
})),
children: i.children,
});
}
return symbols;
}

View File

@@ -1,15 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstReference, TypescriptBlock } from "~/types";
export function parseReference(mod: string, i: TypescriptBlock): TsAstReference {
return {
kind: TypescriptKind.Reference,
name: i.name,
module: mod,
comment: i.comment,
type: i.type,
target: i.target,
fileName: i.sources?.shift()?.fileName as string,
children: i?.children || [],
};
}

View File

@@ -1,14 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstTypeAlias, TypescriptBlock } from "~/types";
export function parseTypeAlias(mod: string, ta: TypescriptBlock): TsAstTypeAlias {
return {
kind: TypescriptKind.TypeAlias,
name: ta.name,
module: mod,
comment: ta.comment,
type: ta.type,
fileName: ta.sources?.shift()?.fileName as string,
};
}

View File

@@ -1,14 +0,0 @@
import { TypescriptKind } from "~/enums";
import { TsAstVariable, TypescriptBlock } from "~/types";
export function parseVariable(mod: string, v: TypescriptBlock): TsAstVariable {
return {
kind: TypescriptKind.Variable,
name: v.name,
module: mod,
comment: v.comment,
type: v.type,
defaultValue: v.defaultValue,
fileName: v.sources?.shift()?.fileName as string,
};
}

View File

@@ -0,0 +1,82 @@
import { describe, expect, it } from "vitest";
import smd from "simple-markdown";
// TODO: come back and see if we can monkey patch in improved rules or possibly look for a different parser
/**
* the default rules from simple-markdown aren't picking up all languages in code blocks.
*/
describe.skip("markdown tools", () => {
it("json code block detected when presented in normal fashion", () => {
const content = `
# Example
This is an example
\`\`\`json
{
"foo": "bar"
}
\`\`\`
`;
const parser = smd.defaultBlockParse;
const tree = parser(content);
const codeBlocks = tree.filter((i) => i.lang === "json");
console.log(JSON.stringify(tree, null, 2));
expect(codeBlocks.length).toBe(1);
});
it("json code block detected when it immediately following a heading tag ", () => {
const content = `
# Example
\`\`\`json
{
"foo": "bar"
}
\`\`\`
`;
const parser = smd.defaultBlockParse;
const tree = parser(content);
const codeBlocks = tree.filter((i) => i.lang === "json");
console.log(JSON.stringify(tree, null, 2));
expect(codeBlocks.length).toBe(1);
});
it("json code block detected when there is syntax to right of language", () => {
const content = `
# Example
\`\`\`json title=src-tauri/tauri.conf.json:tauri.cli
{
"foo": "bar"
}
\`\`\`
`;
const parser = smd.defaultBlockParse;
const tree = parser(content);
const inlineCode = tree.filter((i) => i.type === "text");
console.log(JSON.stringify(tree, null, 2));
expect(inlineCode.length).toBe(1);
});
it("json code block detected when there is syntax to right of language", () => {
const content = `
Add this in tauri.conf.json
\`\`\`json
"updater": {
"active": true,
"endpoints": [
"https://releases.myapp.com/{{target}}/{{current_version}}"
],
"dialog": true,
"pubkey": ""
}
\`\`\`
`;
const parser = smd.defaultBlockParse;
const tree = parser(content);
const inlineCode = tree.filter((i) => i.type === "text");
console.log(JSON.stringify(tree, null, 2));
expect(inlineCode.length).toBe(1);
});
});

View File

@@ -9,7 +9,7 @@ describe("markdownParser()", () => {
"guides/cli.md", //
].map((i) => `test/fixtures/prose/${i}`);
const fileMeta = await parseMarkdown(files);
const fileMeta = await parseMarkdown({ files });
const expectations: Record<
string,
{
@@ -65,7 +65,7 @@ describe("markdownParser()", () => {
"Rust",
"Javascript",
],
programmingLanguages: ["json", "js", "rust"],
programmingLanguages: ["json", "js", "rust", "none", "bash"],
frontmatter: {},
},
"intro.md": {
@@ -86,16 +86,22 @@ describe("markdownParser()", () => {
expect(f.h2.every((i) => h3.includes(i.content)));
}
});
it(`Prog Lang:: ${f.filepath}/${f.filename}`, async () => {
it(`Prog Lang: ${f.filepath}/${f.filename}`, async () => {
// expect(
// f.programmingLanguages.length,
// `We expect programming languages to include: ${expectations[f.filename][
// "programmingLanguages"
// ].join(", ")} but instead got: ${f.programmingLanguages.join(", ")}`
// ).toBe(expectations[f.filename]["programmingLanguages"].length);
const expectedLangs = expectations[f.filename]["programmingLanguages"];
expect(
f.programmingLanguages.length,
`We expect programming languages to include: ${expectations[f.filename][
f.programmingLanguages.every((i) => expectedLangs.includes(i)),
`found: ${f.programmingLanguages.join(
", "
)} but but expected every member of [${expectations[f.filename][
"programmingLanguages"
].join(", ")} but instead got: ${f.programmingLanguages.join(", ")}`
).toBe(expectations[f.filename]["programmingLanguages"].length);
for (const plang of expectations[f.filename]["programmingLanguages"]) {
expect(f.programmingLanguages.every((i) => plang.includes(i))).toBeTruthy();
}
].join(", ")}]`
).toBeTruthy();
});
it(`Frontmatter:: ${f.filepath}/${f.filename}`, async () => {
for (const key of Object.keys(expectations[f.filename]["frontmatter"] || {})) {
@@ -103,9 +109,5 @@ describe("markdownParser()", () => {
}
});
}
it("json", async () => {
const meta = (await parseMarkdown(["test/fixtures/guides/updater.md"]))[0];
console.log(meta.otherSymbols);
});
});
});

View File

@@ -66,7 +66,7 @@ Users can run your app as `$ ./app tauri.txt dest.txt` and the arg matches map w
A named argument is a (key, value) pair where the key identifies the value. With the following configuration:
```json title=src-tauri/tauri.conf.json:tauri.cli
```json
{
"args": [
{

View File

@@ -154,6 +154,7 @@ PENDING is emitted when the download is started and DONE when the install is com
ERROR is emitted when there is an error with the updater. We suggest to listen to this event even if the dialog is enabled.
### Rust
```rust
window.listen("tauri://update-status".to_string(), move |msg| {
println!("New status: {:?}", msg);

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,38 @@
import { readFile } from "fs/promises";
import { beforeAll, describe, expect, it } from "vitest";
import { flattenSitemap, sitemapDictionary } from "~/utils/convertSitemap";
import { IDocsSitemap } from "~/utils/github/buildDocsSitemap";
let sitemap: IDocsSitemap;
describe("flattenSitemap()", () => {
beforeAll(async () => {
sitemap = JSON.parse(
await readFile("test/fixtures/sitemap-tauri-dev.json", "utf-8")
) as IDocsSitemap;
});
it("flattening works as expected", async () => {
const flat = flattenSitemap(sitemap);
expect(Array.isArray(flat)).toBeTruthy();
for (const file of flat) {
expect(file).toHaveProperty("filepath");
expect(file).toHaveProperty("sha");
expect(file).toHaveProperty("size");
expect(file).toHaveProperty("download_url");
}
});
it("convert to dictionary", () => {
const arr = flattenSitemap(sitemap);
const dict = sitemapDictionary(sitemap);
expect(typeof dict).toBe("object");
expect(Object.keys(dict).length).toEqual(arr.length);
for (const key of arr.map((i) => i.filepath)) {
const file = dict[key];
expect(file).toHaveProperty("sha");
expect(file).toHaveProperty("size");
expect(file).toHaveProperty("download_url");
}
});
});

30
pnpm-lock.yaml generated
View File

@@ -35,6 +35,7 @@ importers:
eslint-plugin-cypress: ^2.12.1
floating-vue: ^2.0.0-beta.3
https-localhost: ^4.7.0
jsdom: ^19.0.0
markdown-it-collapsible: ^1.0.0
markdown-it-link-attributes: ^4.0.0
markdown-it-prism: ^2.2.2
@@ -101,6 +102,7 @@ importers:
eslint: 8.7.0
eslint-plugin-cypress: 2.12.1_eslint@8.7.0
https-localhost: 4.7.0
jsdom: 19.0.0
markdown-it-collapsible: 1.0.0
markdown-it-link-attributes: 4.0.0
markdown-it-prism: 2.2.2
@@ -117,7 +119,7 @@ importers:
vite-plugin-windicss: 1.6.3_vite@2.7.13
vite-ssg: 0.17.7_1ede6668370ad42aad1df87e2fa73e29
vitepress: 0.21.6
vitest: 0.1.27
vitest: 0.1.27_jsdom@19.0.0
vue-tsc: 0.31.1_typescript@4.5.5
packages/tauri-search:
@@ -134,6 +136,7 @@ importers:
axios: ^0.25.0
changeset: ^0.2.6
cheerio: ^1.0.0-rc.10
dotenv: ^14.3.2
eslint: ^8.7.0
eslint-config-prettier: ^8.3.0
eslint-plugin-cypress: ^2.12.1
@@ -162,6 +165,7 @@ importers:
xxhash-wasm: ^1.0.1
dependencies:
cheerio: 1.0.0-rc.10
dotenv: 14.3.2
gray-matter: 4.0.3
inferred-types: 0.18.4
native-dash: 1.21.5
@@ -1784,8 +1788,8 @@ packages:
vue-i18n:
optional: true
dependencies:
'@intlify/message-compiler': 9.2.0-beta.29
'@intlify/shared': 9.2.0-beta.29
'@intlify/message-compiler': 9.2.0-beta.30
'@intlify/shared': 9.2.0-beta.30
jsonc-eslint-parser: 1.4.1
source-map: 0.6.1
vue-i18n: 9.1.9_vue@3.2.29
@@ -1820,11 +1824,11 @@ packages:
source-map: 0.6.1
dev: false
/@intlify/message-compiler/9.2.0-beta.29:
resolution: {integrity: sha512-FvMDwe57VvupujvNYUY90J8wv26wKu6j7I93dLwBOo/PTg7nQqFrmYQAF23UfDAdXO4FTdgHfFyb5ecYrN+n3g==}
/@intlify/message-compiler/9.2.0-beta.30:
resolution: {integrity: sha512-2kj/0nLIFrgiO86f9VifcUUcV8LdzXt4YYPIujx/LkTEQOuSFUo/bNiMaG1hyfiU/8mfq6tsaWKjoOZjeao1eQ==}
engines: {node: '>= 12'}
dependencies:
'@intlify/shared': 9.2.0-beta.29
'@intlify/shared': 9.2.0-beta.30
source-map: 0.6.1
dev: true
@@ -1847,8 +1851,8 @@ packages:
engines: {node: '>= 10'}
dev: false
/@intlify/shared/9.2.0-beta.29:
resolution: {integrity: sha512-blMW14WBr3fiCEk/XO4IbSxM8WMAhQOzEgWzP1aqbkeXbIMiHeyFI0ZexwyTKsvDZz0wEWlhupQi+9udrJsozA==}
/@intlify/shared/9.2.0-beta.30:
resolution: {integrity: sha512-E1WHRTIlUEse3d/6t1pAagSXRxmeVeNIhx5kT80dfpYxw8lOnCWV9wLve2bq9Fkv+3TD2I5j+CdN7jvSl3LdsA==}
engines: {node: '>= 12'}
dev: true
@@ -1866,7 +1870,7 @@ packages:
optional: true
dependencies:
'@intlify/bundle-utils': 2.2.0_vue-i18n@9.1.9
'@intlify/shared': 9.2.0-beta.29
'@intlify/shared': 9.2.0-beta.30
'@rollup/pluginutils': 4.1.2
debug: 4.3.3
fast-glob: 3.2.11
@@ -3741,6 +3745,11 @@ packages:
domelementtype: 2.2.0
domhandler: 4.3.0
/dotenv/14.3.2:
resolution: {integrity: sha512-vwEppIphpFdvaMCaHfCEv9IgwcxMljMw2TnAQBB4VWPvzXQLTb82jwmdOKzlEVUL3gNFT4l4TPKO+Bn+sqcrVQ==}
engines: {node: '>=12'}
dev: false
/ecc-jsbn/0.1.2:
resolution: {integrity: sha1-OoOpBOVDUyh4dMVkt1SThoSamMk=}
dependencies:
@@ -8267,7 +8276,7 @@ packages:
- stylus
dev: true
/vitest/0.1.27:
/vitest/0.1.27_jsdom@19.0.0:
resolution: {integrity: sha512-w95Izu+jzust3Ov0KdvN9xZPQm8dG5P1hNOB+uKQ+HFexFcdUW/oa0C0/NR2m2wVpsr23psRPzrBPNlBKgm0qA==}
engines: {node: '>=14.14.0'}
hasBin: true
@@ -8289,6 +8298,7 @@ packages:
'@types/chai': 4.3.0
'@types/chai-subset': 1.3.3
chai: 4.3.4
jsdom: 19.0.0
local-pkg: 0.4.1
tinypool: 0.1.1
tinyspy: 0.2.8