Skip to content

Commit

Permalink
chore: add cloudflare and deno playgrounds
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 14, 2024
1 parent 452f64a commit 41a979b
Show file tree
Hide file tree
Showing 12 changed files with 813 additions and 30 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ dist
.eslintcache
*.log*
*.env*
.wrangler
16 changes: 7 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ We first need to initiate universal cross-hooks:
```js
import { createHandler } from "y-crossws";

const crosswsHandler = createHandler({});
const crosswsHandler = createHandler();
```

Depending on your server choice, use any of the [crossws supported adapters](https://crossws.unjs.io/adapters).
Expand All @@ -36,7 +36,7 @@ const server = createServer((req, res) => {
res.end("");
});

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

server.on("upgrade", ws.handleUpgrade);

Expand All @@ -52,7 +52,7 @@ server.listen(3000);
import { createHandler } from "y-crossws";
import crossws from "crossws/adapters/bun";

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

Bun.serve({
port: 3000,
Expand All @@ -75,7 +75,7 @@ Bun.serve({
import { createHandler } from "y-crossws";
import crossws from "crossws/adapters/deno";

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

Deno.serve({ port: 3000 }, (request, info) => {
if (request.headers.get("upgrade") === "websocket") {
Expand All @@ -96,7 +96,7 @@ Without durable object support:
import { createHandler } from "y-crossws";
import crossws from "crossws/adapters/cloudflare";

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

export default {
async fetch(request, env, context) {
Expand All @@ -115,7 +115,7 @@ import { createHandler } from "y-crossws";
import { DurableObject } from "cloudflare:workers";
import crossws from "crossws/adapters/cloudflare-durable";

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

export default {
async fetch(request, env, context) {
Expand Down Expand Up @@ -151,8 +151,6 @@ tag = "v1"
new_classes = ["$DurableObject"]
```



> [!NOTE]
> Read more in [crossws docs](https://crossws.unjs.io/adapters/cloudflare).
Expand All @@ -167,7 +165,7 @@ import { WebsocketProvider } from "y-crossws/provider";
const ydoc = new Y.Doc();
const wsUrl = `ws://${window.location.host}`;
const roomName = "default";
const provider = new WebsocketProvider(wsURL, roomName, ydoc, /* options */);
const provider = new WebsocketProvider(wsURL, roomName, ydoc /* options */);
```

### Provider options
Expand Down
11 changes: 9 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@
"lint": "eslint . && prettier -c src playground",
"lint:fix": "automd && eslint . --fix && prettier -w src playground",
"prepack": "pnpm build",
"play:bun": "bun run --watch ./playground/bun.ts",
"play:node": "node ./playground/node.mjs",
"play:bun": "PORT=3000 bun run --watch ./playground/bun.ts",
"play:cf-durable": "wrangler dev -c ./playground/wrangler.toml --env durable --port 3000",
"play:cf-worker": "wrangler dev -c ./playground/wrangler.toml --env worker --port 3000",
"play:deno": "PORT=3000 deno run --unstable-byonm -A ./playground/deno.ts",
"play:node": "PORT=3000 node ./playground/node.mjs",
"release": "pnpm test && changelogen --release && npm publish && git push --follow-tags",
"test": "pnpm lint && pnpm test:types",
"test:types": "tsc --noEmit --skipLibCheck"
Expand All @@ -50,6 +53,9 @@
"y-protocols": "^1.0.5"
},
"devDependencies": {
"@cloudflare/kv-asset-handler": "^0.3.4",
"@cloudflare/workers-types": "^4.20240806.0",
"@deno/types": "^0.0.1",
"@types/bun": "^1.1.6",
"@types/node": "^22.1.0",
"@types/ws": "^8.5.12",
Expand All @@ -62,6 +68,7 @@
"prettier": "^3.3.3",
"typescript": "^5.5.4",
"unbuild": "^3.0.0-rc.7",
"wrangler": "^3.71.0",
"ws": "^8.18.0",
"yjs": "^13.6.18"
},
Expand Down
4 changes: 2 additions & 2 deletions playground/bun.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import crossws from "crossws/adapters/bun";

Check failure on line 1 in playground/bun.ts

View workflow job for this annotation

GitHub Actions / ci

Cannot find module 'crossws/adapters/bun' or its corresponding type declarations.
import { createHandler } from "y-crossws";
import { createHandler } from "../src/index.ts";

const ws = crossws(createHandler());

const server = Bun.serve({
port: 3000,
port: process.env.PORT || 3000,
websocket: ws.websocket,
async fetch(request, server) {
// Websocket
Expand Down
44 changes: 44 additions & 0 deletions playground/cf-durable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { createHandler } from "../src/index.ts";
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
import { DurableObject } from "cloudflare:workers";
import crossws from "crossws/adapters/cloudflare-durable";

Check failure on line 4 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Cannot find module 'crossws/adapters/cloudflare-durable' or its corresponding type declarations.

// @ts-ignore
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
const assetManifest = JSON.parse(manifestJSON);

const ws = crossws(createHandler());

export default {
async fetch(request: Request, env: any, ctx: any) {
// Handle websocket
if (request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request as any, env, ctx);
}
// Handle static assets
try {
return await getAssetFromKV(
{ request, waitUntil: ctx.waitUntil.bind(ctx) },
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
},
);
} catch {
const pathname = new URL(request.url).pathname;
return new Response(`"${pathname}" not found`, { status: 404 });
}
},
};

export class $DurableObject extends DurableObject {
fetch(request) {

Check failure on line 35 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'request' implicitly has an 'any' type.
return ws.handleDurableUpgrade(this, request);
}
webSocketMessage(client, message) {

Check failure on line 38 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'client' implicitly has an 'any' type.

Check failure on line 38 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'message' implicitly has an 'any' type.
return ws.handleDurableMessage(this, client, message);
}
webSocketClose(client, code, reason, wasClean) {

Check failure on line 41 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'client' implicitly has an 'any' type.

Check failure on line 41 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'code' implicitly has an 'any' type.

Check failure on line 41 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'reason' implicitly has an 'any' type.

Check failure on line 41 in playground/cf-durable.ts

View workflow job for this annotation

GitHub Actions / ci

Parameter 'wasClean' implicitly has an 'any' type.
return ws.handleDurableClose(this, client, code, reason, wasClean);
}
}
31 changes: 31 additions & 0 deletions playground/cf-worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { createHandler } from "../src/index.ts";
import { getAssetFromKV } from "@cloudflare/kv-asset-handler";
import crossws from "crossws/adapters/cloudflare";

Check failure on line 3 in playground/cf-worker.ts

View workflow job for this annotation

GitHub Actions / ci

Cannot find module 'crossws/adapters/cloudflare' or its corresponding type declarations.

// @ts-ignore
import manifestJSON from "__STATIC_CONTENT_MANIFEST";
const assetManifest = JSON.parse(manifestJSON);

const ws = crossws(createHandler());

export default {
async fetch(request: Request, env: any, ctx: any) {
// Handle websocket
if (request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request as any, env, ctx);
}
// Handle static assets
try {
return await getAssetFromKV(
{ request, waitUntil: ctx.waitUntil.bind(ctx) },
{
ASSET_NAMESPACE: env.__STATIC_CONTENT,
ASSET_MANIFEST: assetManifest,
},
);
} catch {
const pathname = new URL(request.url).pathname;
return new Response(`"${pathname}" not found`, { status: 404 });
}
},
};
46 changes: 46 additions & 0 deletions playground/deno.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import crossws from "crossws/adapters/deno";
import { createHandler } from "../src/index.ts";

const ws = crossws(createHandler());

const mimes = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
};

Deno.serve(
{
port: Number.parseInt(Deno.env.get("PORT") || "3000"),
onListen: ({ port }) => {
console.log(`Server running at http://localhost:${port}`);
},
},
async (request, info) => {
// Websocket
if (request.headers.get("upgrade") === "websocket") {
return ws.handleUpgrade(request, info as any);
}
// Static
const url = new URL(request.url);
for (const path of [
`public${url.pathname}`,
`public${url.pathname}/index.html`,
]) {
const contents = await Deno.readTextFile(
new URL(path, import.meta.url),
).catch(() => undefined);
if (contents) {
const extname = path.match(/\.\w+$/)?.[0] as
| keyof typeof mimes
| undefined;
return new Response(contents, {
headers: {
"content-type": extname ? mimes[extname] : "text/plain",
},
});
}
}
return new Response("Not found", { status: 404 });
},
);
6 changes: 3 additions & 3 deletions playground/node.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ const server = createServer(async (req, res) => {
res.end("");
});

const ws = crossws(createHandler({}));
const ws = crossws(createHandler());

server.on("upgrade", ws.handleUpgrade);

server.listen(3000, () => {
console.log(`Server running at http://localhost:3000`);
server.listen(process.env.PORT || 3000, () => {
console.log(`Server running at http://localhost:${server.address().port}`);
});
2 changes: 1 addition & 1 deletion playground/public/tiptap/editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const defaultContent = `

const getInitialUser = () => {
return {
name: faker.name.fullName(),
name: faker.person.fullName(),
color: colors[Math.floor(Math.random() * colors.length)],
};
};
Expand Down
15 changes: 15 additions & 0 deletions playground/wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
compatibility_date = "2024-01-01"

site = { bucket = "./public" }

[env.worker]
main = "./cf-worker.ts"

[env.durable]
main = "./cf-durable.ts"
durable_objects.bindings = [
{ name = "$DurableObject", class_name = "$DurableObject" }
]
migrations = [
{ tag = "v1", new_classes = ["$DurableObject"] }
]
Loading

0 comments on commit 41a979b

Please sign in to comment.