snapshot of https://github.com/tldraw/tldraw.git (main, 2026-09-23; blobs > 131072B omitted)
Some checks failed
Deploy analytics worker / Deploy analytics worker to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
i18n upload strings / Upload latest strings (push) Failing after 1s
Deploy bemo / Deploy bemo to ${{ (github.ref == 'refs/heads/bemo-production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
Deploy grafana resources / ${{ github.event_name == 'push' && 'Deploy grafana resources' || 'Validate grafana resources (dry run)' }} (push) Failing after 0s
End to end tests (dotcom) / Check for relevant changes (push) Failing after 0s
End to end tests (examples) / Check for relevant changes (push) Failing after 0s
End to end tests (mermaid readability) / Check for relevant changes (push) Failing after 1s
End to end tests (perf) / Check for relevant changes (push) Failing after 0s
Publish editor extensions / Publish editor extensions (push) Failing after 1s
Publish SDK packages / Remove the publish-packages label (push) Has been skipped
Checks / Tests & checks (push) Has been cancelled
Checks / Build all projects (push) Has been cancelled
Deploy templates / Deploy templates (push) Has been cancelled
End to end tests (dotcom) / End to end tests (dotcom) (push) Has been cancelled
End to end tests (mermaid readability) / End to end tests (mermaid readability) (push) Has been cancelled
End to end tests (perf) / End to end tests (perf) (push) Has been cancelled
Deploy .com / Deploy dotcom to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Has been cancelled
End to end tests (examples) / End to end tests (examples) (push) Has been cancelled
Publish SDK packages / Publish SDK packages (push) Has been cancelled
Publish SDK packages / Tell user released version (push) Has been cancelled
Publish SDK packages / Publishes code templates to separate repositories (push) Has been cancelled
Publish SDK packages / Deploys the template demos with the new SDK version (push) Has been cancelled
Some checks failed
Deploy analytics worker / Deploy analytics worker to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
i18n upload strings / Upload latest strings (push) Failing after 1s
Deploy bemo / Deploy bemo to ${{ (github.ref == 'refs/heads/bemo-production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
Deploy grafana resources / ${{ github.event_name == 'push' && 'Deploy grafana resources' || 'Validate grafana resources (dry run)' }} (push) Failing after 0s
End to end tests (dotcom) / Check for relevant changes (push) Failing after 0s
End to end tests (examples) / Check for relevant changes (push) Failing after 0s
End to end tests (mermaid readability) / Check for relevant changes (push) Failing after 1s
End to end tests (perf) / Check for relevant changes (push) Failing after 0s
Publish editor extensions / Publish editor extensions (push) Failing after 1s
Publish SDK packages / Remove the publish-packages label (push) Has been skipped
Checks / Tests & checks (push) Has been cancelled
Checks / Build all projects (push) Has been cancelled
Deploy templates / Deploy templates (push) Has been cancelled
End to end tests (dotcom) / End to end tests (dotcom) (push) Has been cancelled
End to end tests (mermaid readability) / End to end tests (mermaid readability) (push) Has been cancelled
End to end tests (perf) / End to end tests (perf) (push) Has been cancelled
Deploy .com / Deploy dotcom to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Has been cancelled
End to end tests (examples) / End to end tests (examples) (push) Has been cancelled
Publish SDK packages / Publish SDK packages (push) Has been cancelled
Publish SDK packages / Tell user released version (push) Has been cancelled
Publish SDK packages / Publishes code templates to separate repositories (push) Has been cancelled
Publish SDK packages / Deploys the template demos with the new SDK version (push) Has been cancelled
This commit is contained in:
27
apps/dotcom/image-resize-worker/README.md
Normal file
27
apps/dotcom/image-resize-worker/README.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# Images
|
||||
|
||||
Helpers for images on tldraw.com. Specifically, it's currently used to dynamically resize and optimize images on-the-fly via Cloudflare's image transform service.
|
||||
|
||||
## License
|
||||
|
||||
The code in this folder is Copyright (c) 2024-present tldraw Inc. The tldraw SDK is provided under the [tldraw license](https://github.com/tldraw/tldraw/blob/main/LICENSE.md).
|
||||
|
||||
## Trademarks
|
||||
|
||||
Copyright (c) 2024-present tldraw Inc. The tldraw name and logo are trademarks of tldraw. Please see our [trademark guidelines](https://github.com/tldraw/tldraw/blob/main/TRADEMARKS.md) for info on acceptable usage.
|
||||
|
||||
## Distributions
|
||||
|
||||
You can find tldraw on npm [here](https://www.npmjs.com/package/@tldraw/tldraw?activeTab=versions).
|
||||
|
||||
## Contribution
|
||||
|
||||
Found a bug? Please [submit an issue](https://github.com/tldraw/tldraw/issues/new).
|
||||
|
||||
## Community
|
||||
|
||||
Have questions, comments or feedback? [Join our discord](https://discord.tldraw.com/?utm_source=github&utm_medium=readme&utm_campaign=sociallink). For the latest news and release notes, visit [tldraw.dev](https://tldraw.dev).
|
||||
|
||||
## Contact
|
||||
|
||||
Find us on Twitter/X at [@tldraw](https://twitter.com/tldraw).
|
||||
31
apps/dotcom/image-resize-worker/package.json
Normal file
31
apps/dotcom/image-resize-worker/package.json
Normal file
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "images.tldraw.com",
|
||||
"description": "A Cloudflare Worker to resize and optimize images",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"author": {
|
||||
"name": "tldraw GB Ltd.",
|
||||
"email": "hello@tldraw.com"
|
||||
},
|
||||
"main": "src/index.ts",
|
||||
"scripts": {
|
||||
"dev": "yarn run -T tsx ../../../internal/scripts/workers/dev.ts --inspector-port 9339",
|
||||
"test-ci": "yarn run -T vitest run --passWithNoTests",
|
||||
"test": "yarn run -T vitest --passWithNoTests",
|
||||
"test-coverage": "yarn run -T vitest run --coverage --passWithNoTests",
|
||||
"lint": "yarn run -T tsx ../../../internal/scripts/lint.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tldraw/dotcom-shared": "workspace:*",
|
||||
"@tldraw/validate": "workspace:*",
|
||||
"@tldraw/worker-shared": "workspace:*",
|
||||
"itty-router": "^5.0.18",
|
||||
"react": "^19.2.1",
|
||||
"react-dom": "^19.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@cloudflare/workers-types": "^4.20260302.0",
|
||||
"lazyrepo": "0.0.0-alpha.27",
|
||||
"wrangler": "^4.75.0"
|
||||
}
|
||||
}
|
||||
145
apps/dotcom/image-resize-worker/src/worker.ts
Normal file
145
apps/dotcom/image-resize-worker/src/worker.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
import { APP_ASSET_UPLOAD_ENDPOINT } from '@tldraw/dotcom-shared'
|
||||
import { T } from '@tldraw/validate'
|
||||
import {
|
||||
createRouter,
|
||||
handleApiRequest,
|
||||
isAllowedOrigin,
|
||||
notFound,
|
||||
parseRequestQuery,
|
||||
type SentryEnvironment,
|
||||
} from '@tldraw/worker-shared'
|
||||
import { WorkerEntrypoint } from 'cloudflare:workers'
|
||||
|
||||
declare const fetch: typeof import('@cloudflare/workers-types').fetch
|
||||
declare const caches: {
|
||||
default: {
|
||||
match(request: unknown): Promise<Response | undefined>
|
||||
put(request: unknown, response: Response): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
// SENTRY_DSN, TLDRAW_ENV, WORKER_NAME and CF_VERSION_METADATA come from SentryEnvironment. The
|
||||
// version metadata binding below is half of what createSentry needs; the deploy script still passes
|
||||
// no SENTRY_DSN for this worker, so createSentry throws rather than reporting, and an unhandled
|
||||
// error here surfaces as a worker exception. Wiring up a DSN is a config change only.
|
||||
interface Environment extends SentryEnvironment {
|
||||
IS_LOCAL?: string
|
||||
MULTIPLAYER_SERVER?: string
|
||||
|
||||
SYNC_WORKER: Fetcher
|
||||
}
|
||||
|
||||
const queryValidator = T.object({
|
||||
w: T.string.optional(),
|
||||
q: T.string.optional(),
|
||||
})
|
||||
|
||||
function useServiceBinding(env: Environment, origin: string) {
|
||||
if (env.IS_LOCAL) return origin === 'localhost:3000'
|
||||
const multiplayerServer = env.MULTIPLAYER_SERVER
|
||||
if (!multiplayerServer) throw new Error('Missing MULTIPLAYER_SERVER env variable')
|
||||
return multiplayerServer.includes(origin)
|
||||
}
|
||||
|
||||
export default class Worker extends WorkerEntrypoint<Environment> {
|
||||
readonly router = createRouter<Environment>()
|
||||
.get('/:origin/:path+', async (request) => {
|
||||
const { origin, path } = request.params
|
||||
const query = parseRequestQuery(request, queryValidator)
|
||||
|
||||
if (!this.isValidOrigin(origin)) return notFound()
|
||||
|
||||
const accept = request.headers.get('Accept') ?? ''
|
||||
const format = accept.includes('image/avif')
|
||||
? ('avif' as const)
|
||||
: accept.includes('image/webp')
|
||||
? ('webp' as const)
|
||||
: null
|
||||
|
||||
const protocol = this.env.IS_LOCAL ? 'http' : 'https'
|
||||
const passthroughUrl = new URL(`${protocol}://${origin}/${path}`)
|
||||
const cacheKey = new URL(passthroughUrl)
|
||||
cacheKey.searchParams.set('format', format ?? 'original')
|
||||
for (const [key, value] of Object.entries(query)) {
|
||||
cacheKey.searchParams.set(key, value)
|
||||
}
|
||||
|
||||
const cachedResponse = await caches.default.match(cacheKey)
|
||||
if (cachedResponse) {
|
||||
// for some reason, cloudflare's cache doesn't seem to handle the etag properly:
|
||||
if (cachedResponse.status === 200) {
|
||||
const ifNoneMatch = request.headers.get('If-None-Match')
|
||||
const etag = cachedResponse.headers.get('etag')
|
||||
if (ifNoneMatch && etag) {
|
||||
const parsedEtag = parseEtag(etag)
|
||||
// An unparseable etag matches nothing; without this, two unparseable tags
|
||||
// compare equal as `null === null` and every request gets a 304.
|
||||
for (const tag of parsedEtag === null ? [] : ifNoneMatch.split(', ')) {
|
||||
if (parseEtag(tag) === parsedEtag) {
|
||||
return new Response(null, { status: 304 })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return cachedResponse
|
||||
}
|
||||
|
||||
const imageOptions: RequestInitCfPropertiesImage = {
|
||||
fit: 'scale-down',
|
||||
}
|
||||
if (format) imageOptions.format = format
|
||||
if (query.w) imageOptions.width = Number(query.w)
|
||||
if (query.q) imageOptions.quality = Number(query.q)
|
||||
|
||||
let actualResponse: Response
|
||||
if (useServiceBinding(this.env, origin)) {
|
||||
const route = `/${path}`
|
||||
if (!route.startsWith(APP_ASSET_UPLOAD_ENDPOINT)) {
|
||||
return notFound()
|
||||
}
|
||||
const req = new Request(passthroughUrl.href, { cf: { image: imageOptions } })
|
||||
actualResponse = await this.env.SYNC_WORKER.fetch(req)
|
||||
} else {
|
||||
const fetchedResponse = await fetch(passthroughUrl, {
|
||||
cf: { image: imageOptions },
|
||||
})
|
||||
// Normalize Cloudflare's response type to the DOM Response type used in this worker.
|
||||
actualResponse = new Response(fetchedResponse.body as unknown as BodyInit, {
|
||||
status: fetchedResponse.status,
|
||||
statusText: fetchedResponse.statusText,
|
||||
headers: fetchedResponse.headers as unknown as HeadersInit,
|
||||
})
|
||||
}
|
||||
if (!actualResponse.headers.get('content-type')?.startsWith('image/')) return notFound()
|
||||
if (actualResponse.status === 200) {
|
||||
this.ctx.waitUntil(caches.default.put(cacheKey, actualResponse.clone()))
|
||||
}
|
||||
|
||||
return actualResponse
|
||||
})
|
||||
.all('*', notFound)
|
||||
|
||||
override fetch(request: Request): Promise<Response> {
|
||||
return handleApiRequest({
|
||||
request,
|
||||
router: this.router,
|
||||
env: this.env,
|
||||
ctx: this.ctx,
|
||||
after: (response) => response,
|
||||
})
|
||||
}
|
||||
|
||||
isValidOrigin(origin: string) {
|
||||
if (this.env.IS_LOCAL) {
|
||||
return true
|
||||
}
|
||||
|
||||
return isAllowedOrigin(origin)
|
||||
}
|
||||
}
|
||||
|
||||
function parseEtag(etag: string) {
|
||||
const match = etag.match(/^(?:W\/)?"(.*)"$/)
|
||||
return match ? match[1] : null
|
||||
}
|
||||
11
apps/dotcom/image-resize-worker/tsconfig.json
Normal file
11
apps/dotcom/image-resize-worker/tsconfig.json
Normal file
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"extends": "../../../internal/config/tsconfig.base.json",
|
||||
"include": ["src"],
|
||||
"exclude": ["node_modules", "dist", ".tsbuild*"],
|
||||
"compilerOptions": { "noEmit": true, "emitDeclarationOnly": false },
|
||||
"references": [
|
||||
{ "path": "../../../packages/dotcom-shared" },
|
||||
{ "path": "../../../packages/validate" },
|
||||
{ "path": "../../../packages/worker-shared" }
|
||||
]
|
||||
}
|
||||
12
apps/dotcom/image-resize-worker/vitest.config.ts
Normal file
12
apps/dotcom/image-resize-worker/vitest.config.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
/// <reference types="vitest" />
|
||||
import { mergeConfig } from 'vitest/config'
|
||||
import baseConfig from '../../../internal/config/vitest/node-preset'
|
||||
|
||||
// image-resize-worker is a Node.js/Cloudflare Worker environment
|
||||
export default mergeConfig(baseConfig, {
|
||||
test: {
|
||||
// Use node environment instead of jsdom for worker apps
|
||||
environment: 'node',
|
||||
passWithNoTests: true,
|
||||
},
|
||||
})
|
||||
37
apps/dotcom/image-resize-worker/wrangler.toml
Normal file
37
apps/dotcom/image-resize-worker/wrangler.toml
Normal file
@@ -0,0 +1,37 @@
|
||||
main = "src/worker.ts"
|
||||
compatibility_date = "2024-06-20"
|
||||
|
||||
[dev]
|
||||
port = 8786
|
||||
|
||||
[env.dev]
|
||||
name = "image-optimizer"
|
||||
services = [{ binding = "SYNC_WORKER", service = "dev-tldraw-multiplayer" }]
|
||||
|
||||
[env.staging]
|
||||
name = "staging-image-optimizer"
|
||||
services = [{ binding = "SYNC_WORKER", service = "main-tldraw-multiplayer" }]
|
||||
route = { pattern = "staging-images.tldraw.xyz", custom_domain = true }
|
||||
|
||||
[env.production]
|
||||
name = "image-optimizer"
|
||||
services = [{ binding = "SYNC_WORKER", service = "tldraw-multiplayer" }]
|
||||
route = { pattern = "images.tldraw.xyz", custom_domain = true }
|
||||
|
||||
# createSentry needs this to tag releases. Named environments do not inherit the top-level
|
||||
# binding, so it has to be repeated for each one. env.preview is generated by
|
||||
# setWranglerPreviewConfig, which rewrites only the [env.preview] table and leaves this alone.
|
||||
[version_metadata]
|
||||
binding = "CF_VERSION_METADATA"
|
||||
|
||||
[env.dev.version_metadata]
|
||||
binding = "CF_VERSION_METADATA"
|
||||
|
||||
[env.preview.version_metadata]
|
||||
binding = "CF_VERSION_METADATA"
|
||||
|
||||
[env.staging.version_metadata]
|
||||
binding = "CF_VERSION_METADATA"
|
||||
|
||||
[env.production.version_metadata]
|
||||
binding = "CF_VERSION_METADATA"
|
||||
Reference in New Issue
Block a user