Skip to content

Commit

Permalink
Use React rather than a single, hacky JS script for running web app
Browse files Browse the repository at this point in the history
  • Loading branch information
jasoncabot committed Mar 8, 2024
1 parent 58bf0cb commit 93fd2e8
Show file tree
Hide file tree
Showing 28 changed files with 5,253 additions and 1,108 deletions.
7 changes: 6 additions & 1 deletion .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,18 @@ jobs:
- name: Install Web Dependencies
run: npm ci
working-directory: ./web
- name: Build Web
run: |
npm run build
npm run build:css
working-directory: ./web
- name: Publish Web
uses: cloudflare/pages-action@v1
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: 95ffb963e9a7dc68ae10699ffec445b2
projectName: fabled-story-book
directory: ./src
directory: ./dist
workingDirectory: ./web
wranglerVersion: '3'
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ bin
node_modules

web/src/example02
web/dist
.dev.vars
14 changes: 7 additions & 7 deletions cmd/wasm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (l *jsLoader) LoadSection(identifier jabl.SectionId, onLoaded func(code str
cb = js.FuncOf(func(this js.Value, args []js.Value) any {
result := args[0].String()
err := args[1]
if !err.IsNull() {
if !err.IsUndefined() {
onLoaded("", errors.New(err.String()))
} else {
onLoaded(result, nil)
Expand All @@ -58,13 +58,13 @@ func execSection(this js.Value, inputs []js.Value) any {
// The interpreter delegates back to the loader for getting the code to execute from an identifier
interpreter.Execute(section, state, func(section *jabl.Result, err error) {
if err != nil {
callback.Invoke(js.Null(), err.Error())
callback.Invoke(js.Undefined(), err.Error())
} else {
jsonValueOfRes, err := json.Marshal(section)
if err != nil {
callback.Invoke(js.Null(), err.Error())
callback.Invoke(js.Undefined(), err.Error())
} else {
callback.Invoke(string(jsonValueOfRes), js.Null())
callback.Invoke(string(jsonValueOfRes), js.Undefined())
}
}
})
Expand All @@ -79,9 +79,9 @@ func evalCode(this js.Value, inputs []js.Value) any {
interpreter.Evaluate(inputs[0].String(), state, func(section *jabl.Result, err error) {
jsonValueOfRes, err := json.Marshal(section)
if err != nil {
callback.Invoke(js.Null(), err.Error())
callback.Invoke(js.Undefined(), err.Error())
} else {
callback.Invoke(string(jsonValueOfRes), js.Null())
callback.Invoke(string(jsonValueOfRes), js.Undefined())
}
})
return nil
Expand All @@ -97,7 +97,7 @@ type localStorageMapper struct{}

func (s *localStorageMapper) Get(key string) (float64, error) {
value := js.Global().Get("bookStorage").Call("getItem", key)
if value.IsNull() {
if value.IsUndefined() {
return 0, nil
}
return strconv.ParseFloat(value.String(), 64)
Expand Down
24 changes: 0 additions & 24 deletions package-lock.json

This file was deleted.

5 changes: 0 additions & 5 deletions package.json

This file was deleted.

4 changes: 4 additions & 0 deletions web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
```
npm run watch:css
npm run watch:web
```
49 changes: 49 additions & 0 deletions web/build.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { build } from "esbuild";
import { readFileSync, writeFileSync } from "fs";

console.log("[esbuild] start " + new Date().toLocaleTimeString());

const scripts = build({
entryPoints: ["./src/index.tsx", "./src/**/*.wasm"],
bundle: true,
minify: true,
sourcemap: true,
outdir: "dist",
outbase: "src",
loader: {
".wasm": "file",
},
external: ["crypto", "fs", "util"],
});

const staticAssets = build({
entryPoints: ["./src/**/*.html", "./src/wasm-init.js", "./src/assets/**/*.png"],
minify: false,
sourcemap: true,
outdir: "dist",
outbase: "src",
loader: {
".png": "copy",
".html": "copy",
},
});

const functions = build({
entryPoints: ["./functions/**/*.ts"],
bundle: true,
metafile: true,
minify: false,
sourcemap: true,
outdir: "dist/functions",
external: ["crypto", "fs", "util", "@cloudflare/*"],
});

await Promise.all([scripts, staticAssets, functions]);

// Hack to force wrangler pages to rebuild
const packageJson = readFileSync("package.json", "utf8");
const pkg = JSON.parse(packageJson);
pkg.scripts["build:time"] = `echo "${new Date().toISOString()}"`;
writeFileSync("package.json", JSON.stringify(pkg, null, 2));

console.log("[esbuild] done " + new Date().toLocaleTimeString());
35 changes: 35 additions & 0 deletions web/functions/generate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Ai } from "@cloudflare/ai";

export async function onRequest(context) {
// read the bearer token from the request
const authHeader = context.request.headers.get("Authorization") ?? "";
const [_, token] = authHeader.split(" ");
if (token !== context.env.SECRET_KEY) {
return new Response("Unauthorized", { status: 401 });
}

if (context.env.AI === undefined) {
return new Response(
`{
print("AI not configured")
choice("Try again", { goto("generate") })
}`,
{ status: 200 },
);
}

const ai = new Ai(context.env.AI);
const input = {
prompt:
"In a realm shrouded in ancient lore and dark magic, a lone adventurer finds themselves ensnared within the labyrinthine depths of a mysterious dungeon. Each corridor and chamber is fraught with peril, housing puzzles of arcane origin and traps designed to thwart any attempts at escape. At the heart of the dungeon lies a promise of freedom, whispered by the enigmatic guardian who watches from the shadows. Yet, as the adventurer delves deeper, they realize that dark forces conspire to ensure that the secrets of the dungeon remain forever concealed. With their courage tested and their wits challenged, the adventurer must navigate the treacherous maze, unravel its mysteries, and confront the guardians that stand in the way of their ultimate escape. Craft a gripping hook that plunges the player into the thrilling journey of a solitary hero against the odds.",
};
const answer = (await ai.run("@cf/meta/llama-2-7b-chat-int8", input)).response;
const jabl = `{
${answer
.split("\n")
.map((line) => `print("${line.replace(/^"|"$/g, "")}")`)
.join("\n")}
choice("Continue", { goto("generate") })
}`;
return new Response(jabl);
}
Loading

0 comments on commit 93fd2e8

Please sign in to comment.