This commit is contained in:
Michael Zhang 2021-08-11 10:30:24 -05:00
commit f25282728f
Signed by: michael
GPG key ID: BDA47A31A3C8EE6B
25 changed files with 12469 additions and 0 deletions

6
.gitignore vendored Normal file
View file

@ -0,0 +1,6 @@
.DS_Store
/node_modules/
/src/node_modules/@sapper/
yarn-error.log
/__sapper__/
/test.db

2
.ignore Normal file
View file

@ -0,0 +1,2 @@
/package-lock.json
/rollup.config.js

157
README.md Normal file
View file

@ -0,0 +1,157 @@
# sapper-template
The default template for setting up a [Sapper](https://github.com/sveltejs/sapper) project. Can use either Rollup or webpack as bundler.
## Getting started
### Using `degit`
To create a new Sapper project based on Rollup locally, run
```bash
npx degit "sveltejs/sapper-template#rollup" my-app
```
For a webpack-based project, instead run
```bash
npx degit "sveltejs/sapper-template#webpack" my-app
```
[`degit`](https://github.com/Rich-Harris/degit) is a scaffolding tool that lets you create a directory from a branch in a repository.
Replace `my-app` with the path where you wish to create the project.
### Using GitHub templates
Alternatively, you can create the new project as a GitHub repository using GitHub's template feature.
Go to either [sapper-template-rollup](https://github.com/sveltejs/sapper-template-rollup) or [sapper-template-webpack](https://github.com/sveltejs/sapper-template-webpack) and click on "Use this template" to create a new project repository initialized by the template.
### Running the project
Once you have created the project, install dependencies and run the project in development mode:
```bash
cd my-app
npm install # or yarn
npm run dev
```
This will start the development server on [localhost:3000](http://localhost:3000). Open it and click around.
You now have a fully functional Sapper project! To get started developing, consult [sapper.svelte.dev](https://sapper.svelte.dev).
### Using TypeScript
By default, the template uses plain JavaScript. If you wish to use TypeScript instead, you need some changes to the project:
* Add `typescript` as well as typings as dependences in `package.json`
* Configure the bundler to use [`svelte-preprocess`](https://github.com/sveltejs/svelte-preprocess) and transpile the TypeScript code.
* Add a `tsconfig.json` file
* Update the project code to TypeScript
The template comes with a script that will perform these changes for you by running
```bash
node scripts/setupTypeScript.js
```
`@sapper` dependencies are resolved through `src/node_modules/@sapper`, which is created during the build. You therefore need to run or build the project once to avoid warnings about missing dependencies.
The script does not support webpack at the moment.
## Directory structure
Sapper expects to find two directories in the root of your project — `src` and `static`.
### src
The [src](src) directory contains the entry points for your app — `client.js`, `server.js` and (optionally) a `service-worker.js` — along with a `template.html` file and a `routes` directory.
#### src/routes
This is the heart of your Sapper app. There are two kinds of routes — *pages*, and *server routes*.
**Pages** are Svelte components written in `.svelte` files. When a user first visits the application, they will be served a server-rendered version of the route in question, plus some JavaScript that 'hydrates' the page and initialises a client-side router. From that point forward, navigating to other pages is handled entirely on the client for a fast, app-like feel. (Sapper will preload and cache the code for these subsequent pages, so that navigation is instantaneous.)
**Server routes** are modules written in `.js` files, that export functions corresponding to HTTP methods. Each function receives Express `request` and `response` objects as arguments, plus a `next` function. This is useful for creating a JSON API, for example.
There are three simple rules for naming the files that define your routes:
* A file called `src/routes/about.svelte` corresponds to the `/about` route. A file called `src/routes/blog/[slug].svelte` corresponds to the `/blog/:slug` route, in which case `params.slug` is available to the route
* The file `src/routes/index.svelte` (or `src/routes/index.js`) corresponds to the root of your app. `src/routes/about/index.svelte` is treated the same as `src/routes/about.svelte`.
* Files and directories with a leading underscore do *not* create routes. This allows you to colocate helper modules and components with the routes that depend on them — for example you could have a file called `src/routes/_helpers/datetime.js` and it would *not* create a `/_helpers/datetime` route.
#### src/node_modules/images
Images added to `src/node_modules/images` can be imported into your code using `import 'images/<filename>'`. They will be given a dynamically generated filename containing a hash, allowing for efficient caching and serving the images on a CDN.
See [`index.svelte`](src/routes/index.svelte) for an example.
#### src/node_modules/@sapper
This directory is managed by Sapper and generated when building. It contains all the code you import from `@sapper` modules.
### static
The [static](static) directory contains static assets that should be served publicly. Files in this directory will be available directly under the root URL, e.g. an `image.jpg` will be available as `/image.jpg`.
The default [service-worker.js](src/service-worker.js) will preload and cache these files, by retrieving a list of `files` from the generated manifest:
```js
import { files } from '@sapper/service-worker';
```
If you have static files you do not want to cache, you should exclude them from this list after importing it (and before passing it to `cache.addAll`).
Static files are served using [sirv](https://github.com/lukeed/sirv).
## Bundler configuration
Sapper uses Rollup or webpack to provide code-splitting and dynamic imports, as well as compiling your Svelte components. With webpack, it also provides hot module reloading. As long as you don't do anything daft, you can edit the configuration files to add whatever plugins you'd like.
## Production mode and deployment
To start a production version of your app, run `npm run build && npm start`. This will disable live reloading, and activate the appropriate bundler plugins.
You can deploy your application to any environment that supports Node 10 or above. As an example, to deploy to [Vercel Now](https://vercel.com) when using `sapper export`, run these commands:
```bash
npm install -g vercel
vercel
```
If your app can't be exported to a static site, you can use the [vercel-sapper](https://github.com/thgh/vercel-sapper) builder. You can find instructions on how to do so in its [README](https://github.com/thgh/vercel-sapper#basic-usage).
## Using external components
When using Svelte components installed from npm, such as [@sveltejs/svelte-virtual-list](https://github.com/sveltejs/svelte-virtual-list), Svelte needs the original component source (rather than any precompiled JavaScript that ships with the component). This allows the component to be rendered server-side, and also keeps your client-side app smaller.
Because of that, it's essential that the bundler doesn't treat the package as an *external dependency*. You can either modify the `external` option under `server` in [rollup.config.js](rollup.config.js) or the `externals` option in [webpack.config.js](webpack.config.js), or simply install the package to `devDependencies` rather than `dependencies`, which will cause it to get bundled (and therefore compiled) with your app:
```bash
npm install -D @sveltejs/svelte-virtual-list
```
## Troubleshooting
Using Windows and WSL2?
If your project lives outside the WSL root directory, [this limitation](https://github.com/microsoft/WSL/issues/4169) is known to cause live-reloading to fail. See [this issue](https://github.com/sveltejs/sapper/issues/1150) for details.
## Bugs and feedback
Sapper is in early development, and may have the odd rough edge here and there. Please be vocal over on the [Sapper issue tracker](https://github.com/sveltejs/sapper/issues).

11699
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

42
package.json Normal file
View file

@ -0,0 +1,42 @@
{
"name": "grubs",
"description": "grubs",
"version": "0.0.1",
"scripts": {
"dev": "sapper dev",
"build": "sapper build --legacy",
"export": "sapper export --legacy",
"start": "node __sapper__/build"
},
"dependencies": {
"compression": "^1.7.1",
"express": "^4.17.1",
"knex": "^0.21.21",
"sequelize": "^6.6.5",
"sirv": "^1.0.0",
"socket.io": "^4.1.3",
"sqlite3": "^5.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"@babel/core": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/plugin-transform-runtime": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/runtime": "^7.0.0",
"@rollup/plugin-babel": "^5.0.0",
"@rollup/plugin-commonjs": "^20.0.0",
"@rollup/plugin-node-resolve": "^8.0.0",
"@rollup/plugin-replace": "^2.4.0",
"@rollup/plugin-url": "^5.0.0",
"bufferutil": "^4.0.3",
"rollup": "^2.3.4",
"rollup-plugin-svelte": "^7.0.0",
"rollup-plugin-terser": "^7.0.0",
"sapper": "^0.28.0",
"socket.io-client": "^4.1.3",
"svelte": "^3.17.3",
"sveltestrap": "^5.6.0",
"utf-8-validate": "^5.0.5"
}
}

127
rollup.config.js Normal file
View file

@ -0,0 +1,127 @@
import path from 'path';
import resolve from '@rollup/plugin-node-resolve';
import replace from '@rollup/plugin-replace';
import commonjs from '@rollup/plugin-commonjs';
import url from '@rollup/plugin-url';
import svelte from 'rollup-plugin-svelte';
import babel from '@rollup/plugin-babel';
import { terser } from 'rollup-plugin-terser';
import config from 'sapper/config/rollup.js';
import pkg from './package.json';
const mode = process.env.NODE_ENV;
const dev = mode === 'development';
const legacy = !!process.env.SAPPER_LEGACY_BUILD;
const onwarn = (warning, onwarn) =>
(warning.code === 'MISSING_EXPORT' && /'preload'/.test(warning.message)) ||
(warning.code === 'CIRCULAR_DEPENDENCY' && /[/\\]@sapper[/\\]/.test(warning.message)) ||
onwarn(warning);
export default {
client: {
input: config.client.input(),
output: config.client.output(),
plugins: [
replace({
preventAssignment: true,
values:{
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
},
}),
svelte({
compilerOptions: {
dev,
hydratable: true
}
}),
url({
sourceDir: path.resolve(__dirname, 'src/node_modules/images'),
publicPath: '/client/'
}),
resolve({
browser: true,
dedupe: ['svelte']
}),
commonjs(),
legacy && babel({
extensions: ['.js', '.mjs', '.html', '.svelte'],
babelHelpers: 'runtime',
exclude: ['node_modules/@babel/**'],
presets: [
['@babel/preset-env', {
targets: '> 0.25%, not dead'
}]
],
plugins: [
'@babel/plugin-syntax-dynamic-import',
['@babel/plugin-transform-runtime', {
useESModules: true
}]
]
}),
!dev && terser({
module: true
})
],
preserveEntrySignatures: false,
onwarn,
},
server: {
input: config.server.input(),
output: config.server.output(),
plugins: [
replace({
preventAssignment: true,
values:{
'process.browser': false,
'process.env.NODE_ENV': JSON.stringify(mode)
},
}),
svelte({
compilerOptions: {
dev,
generate: 'ssr',
hydratable: true
},
emitCss: false
}),
url({
sourceDir: path.resolve(__dirname, 'src/node_modules/images'),
publicPath: '/client/',
emitFiles: false // already emitted by client build
}),
resolve({
dedupe: ['svelte']
}),
commonjs()
],
external: Object.keys(pkg.dependencies).concat(require('module').builtinModules),
preserveEntrySignatures: 'strict',
onwarn,
},
serviceworker: {
input: config.serviceworker.input(),
output: config.serviceworker.output(),
plugins: [
resolve(),
replace({
preventAssignment: true,
values:{
'process.browser': true,
'process.env.NODE_ENV': JSON.stringify(mode)
},
}),
commonjs(),
!dev && terser()
],
preserveEntrySignatures: false,
onwarn,
}
};

39
src/ambient.d.ts vendored Normal file
View file

@ -0,0 +1,39 @@
/**
* These declarations tell TypeScript that we allow import of images, e.g.
* ```
<script lang='ts'>
import successkid from 'images/successkid.jpg';
</script>
<img src="{successkid}">
```
*/
declare module "*.gif" {
const value: string;
export default value;
}
declare module "*.jpg" {
const value: string;
export default value;
}
declare module "*.jpeg" {
const value: string;
export default value;
}
declare module "*.png" {
const value: string;
export default value;
}
declare module "*.svg" {
const value: string;
export default value;
}
declare module "*.webp" {
const value: string;
export default value;
}

4
src/client.js Normal file
View file

@ -0,0 +1,4 @@
import * as sapper from '@sapper/app';
sapper.start({
target: document.querySelector('#sapper')
});

View file

@ -0,0 +1,67 @@
<script>
import { onMount } from "svelte";
import { Form, InputGroup, Input, Button, ListGroup, ListGroupItem } from "sveltestrap";
import { v4 as uuidv4 } from "uuid";
import { socket, clientText, clientShadow } from "../lib/stores";
import { emptyState, diffStates } from "../lib/state";
export let urlPath;
let text, shadow;
let connected = false;
$socket.on("connect", () => {
connected = true;
$socket.emit("fullSyncRequest", urlPath);
});
$socket.on("fullSync", newState => {
console.log("what the hell is this state", newState);
clientShadow.set(newState || emptyState());
});
clientText.subscribe(st => { text = st });
clientShadow.subscribe(st => { shadow = st });
let newGrubValue = "";
function newGrub() {
let s = newGrubValue.trim();
if (s == "") return false;
let key = `grub-${uuidv4()}`;
clientText.update(o => {
o.grubs[key] = s;
return o;
});
newGrubValue = "";
// compute the diff
console.log("text", text, "shadow", shadow);
let diff = diffStates(shadow, text);
console.log("diff", diff)
$socket.emit("diffs", diff);
return false;
}
</script>
<h3>Grubs</h3>
<form on:submit|preventDefault|stopPropagation = {newGrub}>
<InputGroup>
<Input
bind:value = {newGrubValue}
placeholder = "What do you need?" />
<Button>Hellosu</Button>
</InputGroup>
</form>
{connected}
<ListGroup>
{#each Array.from(text.grubs) as [key, grub]}
<ListGroupItem>
{grub}
</ListGroupItem>
{/each}
</ListGroup>

28
src/lib/models.js Normal file
View file

@ -0,0 +1,28 @@
import { Sequelize, DataTypes } from "sequelize";
const sequelize = new Sequelize("sqlite:test.db");
const Grub = sequelize.define("Grubs", {
id: {
type: DataTypes.STRING,
primaryKey: true,
},
tag: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
},
data: {
type: DataTypes.JSON,
allowNull: false,
},
}, {
// Other model options go here
tableName: "grubs",
indexes: [
{ fields: ["tag"] },
{ fields: ["id", "tag"] },
],
});
export { sequelize, Grub };

31
src/lib/server-sync.js Normal file
View file

@ -0,0 +1,31 @@
import { Sequelize, Op } from "sequelize";
import { sequelize, Grub } from "./models";
import { emptyState, patchState } from "./state";
export function socketHandler(socket) {
socket.on("fullSyncRequest", async msg => {
// get the latest message for this id
let result = await Grub.findOne({
where: { id: { [Op.eq]: msg } },
order: [ ["tag", "DESC" ] ],
});
socket.emit("fullSync", result);
});
socket.on("diffs", async msg => {
try {
console.log("patch", msg);
let lastGrub = await Grub.findOne({
where: { id: { [Op.eq]: msg } },
order: [ ["tag", "DESC" ] ],
});
console.log("last", lastGrub);
let newGrub = patchState(lastGrub, msg);
console.log("New", newGrub);
// await newGrub.save();
console.log(result);
} catch(err) {
console.log("holy Fuck error...", err);
}
});
}

55
src/lib/state.js Normal file
View file

@ -0,0 +1,55 @@
function emptyState() {
return { tag: 0, grubs: {}, recipes: {} };
}
function diffMaps(a, b) {
let deleted = Object.assign({}, a);
let updated = {};
for (let [key, value] of Object.entries(b)) {
// delete keys that are still in the second map
if (key in deleted) delete deleted[key];
if (!(key in a)) updated[key] = value;
else if (a[key] != b[key]) updated[key] = value;
}
return { deleted, updated };
}
function emptyDiff(diff) {
return diff.deleted.size == 0 && diff.updated.size == 0;
}
function diffStates(prev, next) {
let shadowTag = prev["tag"];
let tag = next["tag"];
let updated = {};
for (let key in prev) {
if (key === "tag") continue;
let diff = diffMaps(prev[key], next[key]);
if (!emptyDiff(diff)) updated[key] = diff;
}
updated["shadowTag"] = shadowTag;
updated["tag"] = tag;
return updated;
}
function patchMap(state, diff) {
let updated = Object.assign({}, state);
for (let key in diff.deleted) {
delete updated[key];
}
for (let [key, value] of Object.entries(diff.updated)) {
updated[key] = value;
}
return updated;
}
function patchState(state, diff) {
let updated = Object.assign({}, state);
for (let key in state) {
if (key === "tag") updated[key] = diff[key];
else if (key in diff) updated[key] = patchMap(state[key], diff[key]);
}
return updated;
}
export { emptyState, diffMaps, diffStates, emptyDiff, patchMap, patchState };

11
src/lib/stores.js Normal file
View file

@ -0,0 +1,11 @@
import io from "socket.io-client";
import { readable, writable } from 'svelte/store';
import { emptyState } from "./state";
export const socket = readable(io(), (set) => {
// do nothing lol
});
export const clientShadow = writable(emptyState());
export const clientText = writable(emptyState());

14
src/routes/[grubs].svelte Normal file
View file

@ -0,0 +1,14 @@
<script context="module">
export async function preload({ params }) {
return { grubs: params.grubs };
}
</script>
<script>
import { onMount } from "svelte";
import { socket } from "../lib/stores";
import GrubView from "../components/GrubView.svelte";
export let grubs;
</script>
<GrubView urlPath = {grubs} />

40
src/routes/_error.svelte Normal file
View file

@ -0,0 +1,40 @@
<script>
export let status;
export let error;
const dev = process.env.NODE_ENV === 'development';
</script>
<style>
h1, p {
margin: 0 auto;
}
h1 {
font-size: 2.8em;
font-weight: 700;
margin: 0 0 0.5em 0;
}
p {
margin: 1em auto;
}
@media (min-width: 480px) {
h1 {
font-size: 4em;
}
}
</style>
<svelte:head>
<title>{status}</title>
</svelte:head>
<h1>{status}</h1>
<p>{error.message}</p>
{#if dev && error.stack}
<pre>{error.stack}</pre>
{/if}

17
src/routes/_layout.svelte Normal file
View file

@ -0,0 +1,17 @@
<script>
</script>
<style>
main {
position: relative;
max-width: 56em;
background-color: white;
padding: 2em;
margin: 0 auto;
box-sizing: border-box;
}
</style>
<main>
<slot></slot>
</main>

5
src/routes/index.svelte Normal file
View file

@ -0,0 +1,5 @@
<script>
import GrubView from "../components/GrubView.svelte";
</script>
TODO: redirect to soemthing

31
src/server.js Normal file
View file

@ -0,0 +1,31 @@
import express from "express";
import { Server } from "socket.io";
import http from "http";
import sirv from "sirv";
import * as sapper from "@sapper/server";
import { socketHandler } from "./lib/server-sync";
import { sequelize } from "./lib/models";
const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";
const app = express();
const server = http.createServer(app);
const io = new Server(server);
app.use(sirv("static", { dev }));
app.use(sapper.middleware());
io.on("connection", socketHandler);
async function start() {
await sequelize.sync();
const port = PORT || 3000;
server.listen(port, () => {
console.log("listening on ", port);
});
}
start();

0
src/service-worker.js Normal file
View file

36
src/template.html Normal file
View file

@ -0,0 +1,36 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta name="theme-color" content="#333333">
%sapper.base%
<link rel="stylesheet" href="global.css">
<link rel="manifest" href="manifest.json" crossorigin="use-credentials">
<link rel="icon" type="image/png" href="favicon.png">
<link rel="apple-touch-icon" href="logo-192.png">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous">
<!-- Sapper creates a <script> tag containing `src/client.js`
and anything else it needs to hydrate the app and
initialise the router -->
%sapper.scripts%
<!-- Sapper generates a <style> tag containing critical CSS
for the current page. CSS for the rest of the app is
lazily loaded when it precaches secondary pages -->
%sapper.styles%
<!-- This contains the contents of the <svelte:head> component, if
the current page has one -->
%sapper.head%
</head>
<body>
<!-- The application will be rendered inside this element,
because `src/client.js` references it -->
<div id="sapper">%sapper.html%</div>
</body>
</html>

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

36
static/global.css Normal file
View file

@ -0,0 +1,36 @@
body {
margin: 0;
font-family: Roboto, -apple-system, BlinkMacSystemFont, Segoe UI, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
font-size: 14px;
line-height: 1.5;
color: #333;
}
h1, h2, h3, h4, h5, h6 {
margin: 0 0 0.5em 0;
font-weight: 400;
line-height: 1.2;
}
h1 {
font-size: 2em;
}
a {
color: inherit;
}
code {
font-family: menlo, inconsolata, monospace;
font-size: calc(1em - 2px);
color: #555;
background-color: #f0f0f0;
padding: 0.2em 0.4em;
border-radius: 2px;
}
@media (min-width: 400px) {
body {
font-size: 16px;
}
}

BIN
static/logo-192.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

BIN
static/logo-512.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

22
static/manifest.json Normal file
View file

@ -0,0 +1,22 @@
{
"background_color": "#ffffff",
"theme_color": "#333333",
"name": "TODO",
"short_name": "TODO",
"display": "minimal-ui",
"start_url": "/",
"icons": [
{
"src": "logo-192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "logo-512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any maskable"
}
]
}