Open source CapCut alternative.
TypeScript
feat(site): Cut cloud backend — Prisma models, R2 storage, quota, render jobs, GC
David Le4ad0145fc3c2
diff --git a/site/.env.example b/site/.env.exampleindex 2ee12ef1..c0495dcb 100644--- a/site/.env.example+++ b/site/.env.example@@ -48,3 +48,14 @@ BROWSER_USE_API_KEY="replace-with-browser-use-api-key"# PostHog analytics (client-side project key; public by design, inlined at build).# Leave unset to disable tracking (e.g. local dev).NEXT_PUBLIC_POSTHOG_KEY="replace-with-posthog-project-key"++# Cloudflare R2 (Cut cloud-mode media storage)+R2_ACCOUNT_ID="replace-with-r2-account-id"+R2_ACCESS_KEY_ID="replace-with-r2-access-key-id"+R2_SECRET_ACCESS_KEY="replace-with-r2-secret-access-key"++# Cut render worker wake-on-demand. URL is the deployed Worker's /wake endpoint;+# the secret must match the Worker's CUT_WAKE_SECRET. Unset in local dev (run+# the worker by hand; it polls on its own).+CUT_RENDER_WAKE_URL="replace-with-worker-wake-url"+CUT_RENDER_WAKE_SECRET="replace-with-wake-secret"diff --git a/site/package-lock.json b/site/package-lock.jsonindex d9a7512a..52b14e76 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -12,6 +12,8 @@"dependencies": {"@ai-sdk/react": "^4.0.15","@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@aws-sdk/client-s3": "^3.1094.0",+ "@aws-sdk/s3-request-presigner": "^3.1094.0","@base-ui/react": "^1.6.0","@better-auth/api-key": "1.6.11","@better-auth/core": "1.6.11",@@ -52,6 +54,7 @@"zustand": "^5.0.5"},"devDependencies": {+ "@cloudflare/containers": "^0.3.7","@tailwindcss/postcss": "^4","@types/node": "^20","@types/pg": "^8.20.0",@@ -314,6 +317,331 @@}}},+ "node_modules/@aws-sdk/checksums": {+ "version": "3.1000.19",+ "resolved": "https://registry.npmjs.org/@aws-sdk/checksums/-/checksums-3.1000.19.tgz",+ "integrity": "sha512-Hc4N100RdkuWshKBnhPzmpdftfi9mCLz+OHFELHM1QIgMH4QRUUWyWgfiebta/YX2Bd62wTcm3EqAP8TeXv0gA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/client-s3": {+ "version": "3.1094.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/client-s3/-/client-s3-3.1094.0.tgz",+ "integrity": "sha512-Qkz3HXW9bBajTO1Pgvbxkj2THliDnYPFBaJwIF1mDmnPe1E7reV9V/QJxBz14slIvdcU0tiyB+z37Qns0EY9Zg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/checksums": "^3.1000.19",+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/credential-provider-node": "^3.972.71",+ "@aws-sdk/middleware-sdk-s3": "^3.972.65",+ "@aws-sdk/signature-v4-multi-region": "^3.996.41",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/fetch-http-handler": "^5.6.6",+ "@smithy/node-http-handler": "^4.9.6",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/core": {+ "version": "3.976.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.976.0.tgz",+ "integrity": "sha512-0cjRaEdlVoOrsNb9pP5q1Syyc8pXw5xSj2Np2ryReRTr9FppIIRVSdZK4lbnfmc2Hvgux/xBOUU6baB7z8//uA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "^3.974.2",+ "@aws-sdk/xml-builder": "^3.972.36",+ "@aws/lambda-invoke-store": "^0.3.0",+ "@smithy/core": "^3.29.4",+ "@smithy/signature-v4": "^5.6.5",+ "@smithy/types": "^4.16.1",+ "bowser": "^2.11.0",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-env": {+ "version": "3.972.60",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.60.tgz",+ "integrity": "sha512-BAkxdoe7tpDDqCghGpuOeHQRbm/2znVvOQm0AvpQbA2tbfMN46doN4zx65fv85ImP3KADwc2zQPmbrlI9MPfMg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-http": {+ "version": "3.972.62",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.62.tgz",+ "integrity": "sha512-g/0fGqKTb9xpKdd9AtpmV5Eo3DFKbnkpA2+w0peISSlu7NfAoWOuYBFxsu+yWBtxU89ka55ezoZBCbFaS8pjYQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/fetch-http-handler": "^5.6.6",+ "@smithy/node-http-handler": "^4.9.6",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-ini": {+ "version": "3.973.5",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.5.tgz",+ "integrity": "sha512-ylubazcRfq2TVus/qXucSXeC42Qdjp5HQxTu68K/BsdMiZlcSLD1zkpoCgApXZX1Y6YJhtGGs7ZHhO/GuIgBlw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/credential-provider-env": "^3.972.60",+ "@aws-sdk/credential-provider-http": "^3.972.62",+ "@aws-sdk/credential-provider-login": "^3.972.67",+ "@aws-sdk/credential-provider-process": "^3.972.60",+ "@aws-sdk/credential-provider-sso": "^3.973.4",+ "@aws-sdk/credential-provider-web-identity": "^3.972.66",+ "@aws-sdk/nested-clients": "^3.997.34",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/credential-provider-imds": "^4.4.9",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-login": {+ "version": "3.972.67",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.67.tgz",+ "integrity": "sha512-CCygIKJ9YbI3n84OClSaSppkgKKHVj2TGT33c6FRORZrYNZQ1POmD+ip0FLYokiJAK7sSdc3YVkOsBm90oxWMQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/nested-clients": "^3.997.34",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-node": {+ "version": "3.972.71",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.71.tgz",+ "integrity": "sha512-HIg7Q2osBzajQwL+1Vkyh2E7Gim3eTNb9RHIsOxDGjW0eZg4oEKtRs5sioCnc73ilhaOm4gX2lHVF8J7+nt2rg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/credential-provider-env": "^3.972.60",+ "@aws-sdk/credential-provider-http": "^3.972.62",+ "@aws-sdk/credential-provider-ini": "^3.973.5",+ "@aws-sdk/credential-provider-process": "^3.972.60",+ "@aws-sdk/credential-provider-sso": "^3.973.4",+ "@aws-sdk/credential-provider-web-identity": "^3.972.66",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/credential-provider-imds": "^4.4.9",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-process": {+ "version": "3.972.60",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.60.tgz",+ "integrity": "sha512-YIo3f99hM43QdYG8hDzwGemnR/pU95b0kramqSJUTleCqaB7+HwKf7YZFHqvOgTqZTPx/mRmNIqoDRr3U0Z3Tw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-sso": {+ "version": "3.973.4",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.4.tgz",+ "integrity": "sha512-BPdmL8sSBOCv4ngZ+3LHxyc3CNqDCEK37CHioCk7zGrTMY5sUtkH8q+o6qA80nn6w3/fyBPGNE7OIRlmoOxRQA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/nested-clients": "^3.997.34",+ "@aws-sdk/token-providers": "3.1092.0",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/credential-provider-web-identity": {+ "version": "3.972.66",+ "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.66.tgz",+ "integrity": "sha512-kSAziJboOmZmsR9/MTbiNjowl2BPes1bQuJpne4qAZ62ubi8fjfr/aupJSQje6udBoYxXTQbsL0e0kby2la3ng==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/nested-clients": "^3.997.34",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/middleware-sdk-s3": {+ "version": "3.972.65",+ "resolved": "https://registry.npmjs.org/@aws-sdk/middleware-sdk-s3/-/middleware-sdk-s3-3.972.65.tgz",+ "integrity": "sha512-udwNhRfDTfCB98mAHjjgsnKQlxygB4e0X+Obne/XjJpvVsF0YCQC8ZErd/8Z6IPoLQjtiKHzwqEDbZiLrJEnOg==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/signature-v4-multi-region": "^3.996.41",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/nested-clients": {+ "version": "3.997.34",+ "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.34.tgz",+ "integrity": "sha512-Y9REVrSwmLM+Qy6sZJ7ofMC2S3Hr3tPP/4CzL5U1olPP7OGoF+6+Px0E49cVQBtSxJtyeLJMf0UaBErfeSahAA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/signature-v4-multi-region": "^3.996.41",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/fetch-http-handler": "^5.6.6",+ "@smithy/node-http-handler": "^4.9.6",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/s3-request-presigner": {+ "version": "3.1094.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/s3-request-presigner/-/s3-request-presigner-3.1094.0.tgz",+ "integrity": "sha512-7kG3C37tPWEpz8TyHslFhi2TrQ10und7ijerO0V/Ljq2uxBWVi4SFcol8yp2gM09HYzMnkWCfOxAKJZ2OZvClw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/signature-v4-multi-region": "^3.996.41",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/signature-v4-multi-region": {+ "version": "3.996.41",+ "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.41.tgz",+ "integrity": "sha512-QMUytg+FQMGouc8gHS00KoYih3+N6cqmVI/pQGOIo7Nr7OpQaiXjSYOuL+vsPZ1tymY4LAQ8MYcHJmws5LRxng==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/types": "^3.974.2",+ "@smithy/signature-v4": "^5.6.5",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/token-providers": {+ "version": "3.1092.0",+ "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1092.0.tgz",+ "integrity": "sha512-hBYUAr6iBLNFcsiWTgtBb0stdSw39VOUq4Sp4A5caCNf66BAZplWN4FleKrVpJx5li2YgdnK2DqoFSMWC642FQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@aws-sdk/core": "^3.976.0",+ "@aws-sdk/nested-clients": "^3.997.34",+ "@aws-sdk/types": "^3.974.2",+ "@smithy/core": "^3.29.4",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/types": {+ "version": "3.974.2",+ "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.974.2.tgz",+ "integrity": "sha512-3W6IUtSxFbH6X7Wb7DzGCV5QiFQsd0g8bOfntpmDxQlzBoKWUMBu/JPQR0DwkE+Hpnxd6db1tXbOwdeHddG6cA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws-sdk/xml-builder": {+ "version": "3.972.36",+ "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.36.tgz",+ "integrity": "sha512-RdGmS1GLrtaTOLE1ElSluMldNrpk9Emq6uYs8SS8iHlu5xTAmM9rRkM91o48+rIRryBtyO9t+uLYCoMG6jVMVA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },+ "node_modules/@aws/lambda-invoke-store": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/@aws/lambda-invoke-store/-/lambda-invoke-store-0.3.0.tgz",+ "integrity": "sha512-sl4Bm6yiMNYrZKkqqDFWN0UfnWhlS8ivKxrYl+6t0gCLrqr8y3B2IqZZbFRkfaVVp7C/baApyh71P+LeE1A2sQ==",+ "license": "Apache-2.0",+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.0","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz",@@ -946,6 +1274,13 @@"resolved": "https://registry.npmjs.org/@better-fetch/fetch/-/fetch-1.1.21.tgz","integrity": "sha512-/ImESw0sskqlVR94jB+5+Pxjf+xBwDZF/N5+y2/q4EqD7IARUTSpPfIo8uf39SYpCxyOCtbyYpUrZ3F/k0zT4A=="},+ "node_modules/@cloudflare/containers": {+ "version": "0.3.7",+ "resolved": "https://registry.npmjs.org/@cloudflare/containers/-/containers-0.3.7.tgz",+ "integrity": "sha512-DM9dm3FnIBSyiSJ1FLavKwl/lk3oAmTaynCzZQ9pZR0ncRPquSxkxd8Nu2MFILxmDDsPkxKsSNEh9mHHMty4Fw==",+ "dev": true,+ "license": "MIT OR Apache-2.0"+ },"node_modules/@dotenvx/dotenvx": {"version": "1.66.0","resolved": "https://registry.npmjs.org/@dotenvx/dotenvx/-/dotenvx-1.66.0.tgz",@@ -3356,6 +3691,87 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/@smithy/core": {+ "version": "3.29.8",+ "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.29.8.tgz",+ "integrity": "sha512-rpCbCV+TimOBi3VLNBMmtTvgfOWcFIEAru3+TFlG87SL2F+te4jOnnNR+cf3uR4eJ5Qf4LnT80fqnBKgPRS6zA==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/credential-provider-imds": {+ "version": "4.4.13",+ "resolved": "https://registry.npmjs.org/@smithy/credential-provider-imds/-/credential-provider-imds-4.4.13.tgz",+ "integrity": "sha512-X+2HNZhWi5i3rJsCas0LPf6fTQUaKyJ40zd8aTO/bwpRfpU3biYaqLr7C1WMibL7PVKJalpi1PyybjGPNoHC8Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.29.8",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/fetch-http-handler": {+ "version": "5.6.10",+ "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.6.10.tgz",+ "integrity": "sha512-5/Yj9mS2JjTsB3B8ZX7euh77mrY9aXW23ag1yAmFykSRmA6vldqBrgqmSeQ50EjY+5SB8+aE4w14B6LKbBVEhQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.29.8",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/node-http-handler": {+ "version": "4.9.10",+ "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.9.10.tgz",+ "integrity": "sha512-ETQz9v/Z+nTQc6fRWTXxUpxJqwpmzB3Tn3WKAdHwWkeT+m+HE5czs6GNG8vW+4vyxXSls65RVcvOZwk7Q/PS/Q==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.29.8",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/signature-v4": {+ "version": "5.6.9",+ "resolved": "https://registry.npmjs.org/@smithy/signature-v4/-/signature-v4-5.6.9.tgz",+ "integrity": "sha512-g5rnEii/mkT0mjVJmlsaOfyNBtHNTecD9Lo4NP8D5HzMUEnZNpz7/FbvBCjNcV4vteHFAxOGiLUYNxPkDZZAPw==",+ "license": "Apache-2.0",+ "dependencies": {+ "@smithy/core": "^3.29.8",+ "@smithy/types": "^4.16.1",+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/@smithy/types": {+ "version": "4.16.1",+ "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.16.1.tgz",+ "integrity": "sha512-0JFs3V2y2M9tKW5na/qxe69Zv+uxLMO7QBbhxF/FHu/Gp2NFZAAL9tWl9PU02xxo07pb3G9FTyjNc6D5uZrJIg==",+ "license": "Apache-2.0",+ "dependencies": {+ "tslib": "^2.6.2"+ },+ "engines": {+ "node": ">=18.0.0"+ }+ },"node_modules/@stablelib/base64": {"version": "1.0.1","resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz",@@ -5259,6 +5675,12 @@"integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==","license": "ISC"},+ "node_modules/bowser": {+ "version": "2.14.1",+ "resolved": "https://registry.npmjs.org/bowser/-/bowser-2.14.1.tgz",+ "integrity": "sha512-tzPjzCxygAKWFOJP011oxFHs57HzIhOEracIgAePE4pqB3LikALKnSzUyU4MGs9/iCEUuHlAJTjTc5M+u7YEGg==",+ "license": "MIT"+ },"node_modules/brace-expansion": {"version": "1.1.14","resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz",diff --git a/site/package.json b/site/package.jsonindex a77c896a..99d4ee12 100644--- a/site/package.json+++ b/site/package.json@@ -16,6 +16,7 @@"prisma:prod": "dotenv -e .env -- prisma db push","engine:dev": "bun run src/cut/engine/main.ts","engine:build": "bash scripts/build-cut-engine.sh",+ "worker:build": "bun build --target=node --minify --external=pg-native src/cut/worker/main.ts --outfile dist/cut-worker/main.js","eval:cut-chat": "bun run scripts/eval-cut-chat.ts","test": "bun test src","test:genvideo": "bun run scripts/genvideo-selftest.ts",@@ -24,6 +25,8 @@"dependencies": {"@ai-sdk/react": "^4.0.15","@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@aws-sdk/client-s3": "^3.1094.0",+ "@aws-sdk/s3-request-presigner": "^3.1094.0","@base-ui/react": "^1.6.0","@better-auth/api-key": "1.6.11","@better-auth/core": "1.6.11",@@ -64,6 +67,7 @@"zustand": "^5.0.5"},"devDependencies": {+ "@cloudflare/containers": "^0.3.7","@tailwindcss/postcss": "^4","@types/node": "^20","@types/pg": "^8.20.0",diff --git a/site/prisma/Cut.prisma b/site/prisma/Cut.prismanew file mode 100644index 00000000..566be7ac--- /dev/null+++ b/site/prisma/Cut.prisma@@ -0,0 +1,101 @@+// Cut web mode: cloud-resident projects. Docs and metadata live here; media+// bytes live in R2 under keys recorded on CutMediaObject. Rows carry a plain+// userId (better-auth id) with no FK so the tables stay self-contained.++model CutProject {+ id String @id @default(cuid())+ userId String+ name String+ doc Json+ folderId String?+ // Optimistic concurrency for autosave: PUT sends the version it loaded and+ // conflicts 409 instead of clobbering a newer save from another device.+ version Int @default(1)+ previewKey String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, updatedAt])+}++model CutFolder {+ id String @id @default(cuid())+ userId String+ name String+ scope String @default("project") // project | library+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, scope])+}++// One R2 object. Quota and orphan GC read from here: `pending` rows were+// presigned but never completed and are collectible after a grace period.+model CutMediaObject {+ id String @id @default(cuid())+ userId String+ projectId String?+ r2Key String @unique+ fileName String+ mime String @default("")+ bytes BigInt @default(0)+ kind String @default("media") // media | export | preview | library | overlay+ uploadState String @default("pending") // pending | complete+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, kind])+ @@index([projectId, kind])+}++model CutLibraryAsset {+ id String @id @default(cuid())+ userId String+ mediaObjectId String+ folderId String?+ meta Json?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, createdAt])+}++model CutTemplate {+ id String @id @default(cuid())+ userId String+ name String+ doc Json+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, createdAt])+}++model CutStorageUsage {+ userId String @id+ bytes BigInt @default(0)+ updatedAt DateTime @updatedAt+}++// Work the render worker executes: exports, hover preview proxies, URL+// imports. The client polls through the hosted API; only the worker claims+// rows.+model CutRenderJob {+ id String @id @default(cuid())+ userId String+ projectId String?+ kind String // export | preview | import_url+ state String @default("queued") // queued | running | done | error | canceled+ progress Float @default(0)+ spec Json+ outputKey String?+ outName String?+ result Json?+ error String?+ claimedAt DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ @@index([userId, createdAt])+ @@index([state, createdAt])+}diff --git a/site/src/app/api/cut-cloud/[[...slug]]/route.ts b/site/src/app/api/cut-cloud/[[...slug]]/route.tsnew file mode 100644index 00000000..173a2260--- /dev/null+++ b/site/src/app/api/cut-cloud/[[...slug]]/route.ts@@ -0,0 +1,25 @@+import type { NextRequest } from "next/server";+import { withDonkeyAuth } from "@/lib/donkey-api-auth";+import { runGc } from "@/cut/server/cloud/gc";+import { cutCloudCatchAll } from "@/cut/server/cloud/routes";++// The hosted Cut backend: every /api/cut-cloud/* request authenticates via the+// session cookie (withDonkeyAuth) and dispatches through the cloud route table+// (src/cut/server/cloud/routes.ts). The client's cloud driver rewrites the+// engine's /api/cut/* paths to this prefix.+export const runtime = "nodejs";++const handle = withDonkeyAuth((request) => cutCloudCatchAll(request));++// The daily GC cron has no session; Vercel marks its requests with the+// x-vercel-cron header, which the platform strips from outside traffic.+// Everything else goes through auth (a superuser can also GET /gc directly).+export const GET = (request: NextRequest) =>+ new URL(request.url).pathname === "/api/cut-cloud/gc" &&+ request.headers.get("x-vercel-cron") === "1"+ ? runGc()+ : handle(request);+export const POST = handle;+export const PUT = handle;+export const DELETE = handle;+export const HEAD = handle;diff --git a/site/src/cut/server/cloud/gc.ts b/site/src/cut/server/cloud/gc.tsnew file mode 100644index 00000000..6113a685--- /dev/null+++ b/site/src/cut/server/cloud/gc.ts@@ -0,0 +1,49 @@+// Storage garbage collection: presigned-but-never-completed media objects and+// long-terminal render jobs. Runs from the Vercel daily cron (vercel.json) or+// a superuser hitting GET /api/cut-cloud/gc.+import { prisma } from "@/lib/prisma";+import { del } from "./r2";++const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;+const JOB_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;+const TERMINAL_STATES = ["done", "error", "canceled"];++export async function runGc(): Promise<Response> {+ const pending = await prisma.cutMediaObject.findMany({+ where: {+ uploadState: "pending",+ createdAt: { lt: new Date(Date.now() - PENDING_MAX_AGE_MS) },+ },+ select: { id: true, r2Key: true },+ });+ // Pending rows never counted toward usage, so no usage adjustment here.+ await del(pending.map((o) => o.r2Key));+ if (pending.length > 0) {+ await prisma.cutMediaObject.deleteMany({+ where: { id: { in: pending.map((o) => o.id) } },+ });+ }+ // Old terminal jobs go together with their overlay PNGs — the worker deletes+ // overlays when it settles a job, but a job canceled while still queued was+ // never claimed, so its overlays only die here.+ const oldJobs = await prisma.cutRenderJob.findMany({+ where: {+ state: { in: TERMINAL_STATES },+ createdAt: { lt: new Date(Date.now() - JOB_MAX_AGE_MS) },+ },+ select: { id: true, userId: true, spec: true },+ });+ const overlayKeys = oldJobs.flatMap((j) => {+ const overlays = (j.spec as { overlays?: { key?: unknown }[] } | null)?.overlays ?? [];+ const prefix = `cut/${j.userId}/overlays/`;+ return overlays+ .map((o) => o?.key)+ .filter((k): k is string => typeof k === "string" && k.startsWith(prefix));+ });+ await del(overlayKeys);+ const jobs =+ oldJobs.length > 0+ ? await prisma.cutRenderJob.deleteMany({ where: { id: { in: oldJobs.map((j) => j.id) } } })+ : { count: 0 };+ return Response.json({ pendingObjects: pending.length, renderJobs: jobs.count });+}diff --git a/site/src/cut/server/cloud/jobs.ts b/site/src/cut/server/cloud/jobs.tsnew file mode 100644index 00000000..ee08d8e7--- /dev/null+++ b/site/src/cut/server/cloud/jobs.ts@@ -0,0 +1,250 @@+// Render-job rows for the cloud worker (site/src/cut/worker). These routes only+// manage CutRenderJob rows — the worker claims and executes them. Response+// shapes byte-match the engine's export routes (http/export.ts + server/jobs.ts).+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import { renderJobCheck } from "./limits";+import { wakeRenderWorker } from "./wake";+import { getProject } from "./projects";+import { overlayKey, presignGet, presignPut } from "./r2";+import { caught, err, redirect } from "./util";++/** How long finished jobs stay in the export-jobs feed — the engine's registry+ * keeps a bounded terminal backlog; the cloud keeps a day. */+const FEED_WINDOW_MS = 24 * 60 * 60 * 1000;++type JobRow = {+ id: string;+ projectId: string | null;+ kind: string;+ state: string;+ progress: number;+ outputKey: string | null;+ outName: string | null;+ result: unknown;+ error: string | null;+ claimedAt: Date | null;+ createdAt: Date;+};++/** Engine job status ("queued" | "running" | "done" | "error") from a row's+ * state; a canceled row reads as the engine's canceled-export error. */+function engineStatus(row: JobRow): { status: string; error?: string } {+ if (row.state === "canceled") return { status: "error", error: row.error ?? "Export canceled." };+ return { status: row.state, error: row.error ?? undefined };+}++async function findJob(userId: string, id: string): Promise<JobRow | null> {+ return prisma.cutRenderJob.findFirst({ where: { id, userId } });+}++/** Engine-style export name: `base.mp4` with a " 2", " 3"… suffix when taken+ * by an existing export object or a job still in flight. The client derives the+ * base from the project name; the dedupe happens here, where the rows are. */+async function exportName(userId: string, projectId: string, baseName: string) {+ const base =+ baseName.replace(/\.mp4$/i, "").replace(/[/\\:*?"<>|]/g, "").trim().slice(0, 60) || "export";+ const [files, jobs] = await Promise.all([+ prisma.cutMediaObject.findMany({+ where: { userId, projectId, kind: "export" },+ select: { fileName: true },+ }),+ prisma.cutRenderJob.findMany({+ where: { userId, projectId, kind: "export" },+ select: { outName: true },+ }),+ ]);+ const taken = new Set<string>([+ ...files.map((f) => f.fileName),+ ...jobs.map((j) => j.outName).filter((n): n is string => !!n),+ ]);+ for (let n = 1; ; n++) {+ const candidate = n === 1 ? `${base}.mp4` : `${base} ${n}.mp4`;+ if (!taken.has(candidate)) return candidate;+ }+}++export const jobsCloud = {+ /** Presign overlay-PNG uploads for an export. Overlays are transient worker+ * inputs — no CutMediaObject bookkeeping, no quota. */+ async exportPresign(userId: string, req: Request) {+ try {+ const { files } = (await req.json()) as { files?: { name?: string; bytes?: number }[] };+ if (!Array.isArray(files) || files.length === 0) return err("files is required.", 400);+ const batchId = crypto.randomUUID().slice(0, 12);+ const out = await Promise.all(+ files.map(async (f) => {+ const name = String(f.name ?? "").replace(/[/\\]/g, "");+ if (!name) throw new Error("Every overlay needs a name.");+ const key = overlayKey(userId, batchId, name);+ return { name, key, url: await presignPut(key, "image/png") };+ })+ );+ return Response.json({ files: out });+ } catch (e) {+ return caught(e, "Could not presign the overlays.");+ }+ },++ /** Queue an export (or hover-preview) render. Same response as the engine's+ * exportApi.create: {id} or 400 {error}. */+ async exportCreate(userId: string, req: Request) {+ try {+ const body = (await req.json()) as {+ spec?: { target?: string; projectId?: string };+ overlays?: { name: string; key: string }[];+ projectId?: string;+ outName?: string;+ };+ if (!body.spec || typeof body.spec !== "object") return err("spec is required.", 400);+ const projectId = body.projectId ?? body.spec.projectId;+ if (!projectId) return err("projectId is required.", 400);+ const project = await getProject(userId, projectId);+ if (!project) return err("Project not found.", 400);+ // Overlay keys come from the client; only this user's own overlay+ // uploads are acceptable render inputs — anything else would let a+ // crafted key pull another account's R2 objects into the render.+ const overlayPrefix = `cut/${userId}/overlays/`;+ for (const o of body.overlays ?? []) {+ if (typeof o?.key !== "string" || !o.key.startsWith(overlayPrefix)) {+ return err("Invalid overlay key.", 400);+ }+ }+ const preview = body.spec.target === "preview";+ if (!preview) {+ const capped = await renderJobCheck(userId);+ if (capped) return capped;+ }+ const outName = preview+ ? "preview.mp4"+ : await exportName(userId, projectId, body.outName?.trim() || project.name);+ const row = await prisma.cutRenderJob.create({+ data: {+ userId,+ projectId,+ kind: preview ? "preview" : "export",+ spec: {+ spec: body.spec,+ overlays: body.overlays ?? [],+ } as unknown as Prisma.InputJsonValue,+ outName,+ },+ });+ wakeRenderWorker();+ return Response.json({ id: row.id });+ } catch (e) {+ return caught(e, "Export failed to start.");+ }+ },++ async exportStatus(userId: string, jobId: string) {+ const row = await findJob(userId, jobId);+ if (!row) return err("Unknown export.", 404);+ if (row.state === "queued") wakeRenderWorker();+ const { status, error } = engineStatus(row);+ return Response.json({+ status,+ progress: row.progress,+ error,+ outName: row.outName || undefined,+ });+ },++ async exportCancel(userId: string, jobId: string) {+ // The worker honors "canceled" mid-run; a queued row is simply never claimed.+ await prisma.cutRenderJob.updateMany({+ where: { id: jobId, userId, state: { in: ["queued", "running"] } },+ data: { state: "canceled" },+ });+ return Response.json({ ok: true });+ },++ async exportFile(userId: string, jobId: string) {+ try {+ const row = await findJob(userId, jobId);+ if (!row || row.state !== "done" || !row.outputKey) {+ return new Response("Export not ready.", { status: 404 });+ }+ return redirect(await presignGet(row.outputKey, row.outName ?? undefined));+ } catch (e) {+ return caught(e, "Export not ready.");+ }+ },++ /** The exports-dock feed: every export job for this account, start order —+ * same view the engine's listAllJobs builds (previews stay internal). */+ async exportFeed(userId: string) {+ const rows = await prisma.cutRenderJob.findMany({+ where: {+ userId,+ kind: "export",+ OR: [+ { state: { in: ["queued", "running"] } },+ { createdAt: { gte: new Date(Date.now() - FEED_WINDOW_MS) } },+ ],+ },+ orderBy: { createdAt: "asc" },+ });+ const projectIds = [...new Set(rows.map((r) => r.projectId).filter((p): p is string => !!p))];+ const projects = await prisma.cutProject.findMany({+ where: { userId, id: { in: projectIds } },+ select: { id: true, name: true },+ });+ const names = new Map(projects.map((p) => [p.id, p.name]));+ return Response.json(+ rows.map((r) => {+ const { status, error } = engineStatus(r);+ return {+ id: r.id,+ projectId: r.projectId ?? "",+ projectName: names.get(r.projectId ?? "") ?? "",+ status,+ progress: r.progress,+ outName: r.outName || undefined,+ error,+ createdAt: r.createdAt.getTime(),+ startedAt: r.claimedAt?.getTime(),+ };+ })+ );+ },++ /** Queue a URL import — async on the cloud (the worker downloads), unlike the+ * engine's synchronous route. */+ async importUrl(userId: string, projectId: string, req: Request) {+ try {+ const { url } = (await req.json()) as { url?: string };+ if (!url) return err("No URL provided.", 400);+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const capped = await renderJobCheck(userId);+ if (capped) return capped;+ const row = await prisma.cutRenderJob.create({+ data: {+ userId,+ projectId,+ kind: "import_url",+ spec: { url } as unknown as Prisma.InputJsonValue,+ },+ });+ wakeRenderWorker();+ return Response.json({ jobId: row.id });+ } catch (e) {+ return caught(e, "Could not import that URL.");+ }+ },++ /** Generic job poll for non-export kinds (import_url). */+ async status(userId: string, jobId: string) {+ const row = await findJob(userId, jobId);+ if (!row) return err("Unknown job.", 404);+ if (row.state === "queued") wakeRenderWorker();+ return Response.json({+ id: row.id,+ kind: row.kind,+ state: row.state,+ progress: row.progress,+ result: row.result ?? undefined,+ error: row.error ?? undefined,+ });+ },+};diff --git a/site/src/cut/server/cloud/library.ts b/site/src/cut/server/cloud/library.tsnew file mode 100644index 00000000..bcb5ea31--- /dev/null+++ b/site/src/cut/server/cloud/library.ts@@ -0,0 +1,583 @@+// Cloud twin of the engine's shared library (server/library.ts): asset metadata+// in CutLibraryAsset rows, template docs in CutTemplate rows, bytes in R2 under+// cut/<userId>/library/. Response shapes mirror the engine exactly.+import type {+ LibraryAsset,+ LibraryFolder,+ LibrarySource,+ LibraryTemplate,+ TemplateAudio,+ TemplateInput,+ TemplateLayer,+ TemplateMedia,+} from "../library";+import type { StoredAsset } from "@/cut/lib/types";+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import { getProject, takenMediaNames } from "./projects";+import { copy, del, head, libraryKey, presignGet, presignPut, projectMediaKey } from "./r2";+import { addUsage, quotaCheck } from "./usage";+import { caught, decodeFileParam, dedupeName, err, redirect, safeFileName, typeOf } from "./util";++/** Descriptive fields the engine derives with ffprobe; the cloud stores them on+ * the row, supplied by the client (which probed in the browser) or copied from+ * the source project doc. */+interface AssetMeta {+ name?: string;+ type?: "video" | "audio" | "image";+ duration?: number;+ width?: number;+ height?: number;+ source?: LibrarySource;+}++interface TemplateDoc {+ folderId?: string | null;+ duration: number;+ media: TemplateMedia[];+ layers: TemplateLayer[];+ audio: TemplateAudio[];+ texts: unknown[];+ cues: unknown[];+}++type MediaObjectRow = {+ id: string;+ r2Key: string;+ fileName: string;+ mime: string;+ bytes: bigint;+ uploadState: string;+};++async function takenLibraryNames(userId: string): Promise<Set<string>> {+ const rows = await prisma.cutMediaObject.findMany({+ where: { userId, kind: "library" },+ select: { fileName: true },+ });+ return new Set(rows.map((r) => r.fileName));+}++function assetView(+ row: { id: string; folderId: string | null; meta: unknown; createdAt: Date },+ obj: { fileName: string }+): LibraryAsset {+ const meta = (row.meta ?? {}) as AssetMeta;+ return {+ id: row.id,+ fileName: obj.fileName,+ name: meta.name ?? obj.fileName,+ type: meta.type ?? typeOf(obj.fileName) ?? "video",+ duration: meta.duration ?? 0,+ ...(meta.width ? { width: meta.width, height: meta.height } : {}),+ addedAt: row.createdAt.getTime(),+ folderId: row.folderId ?? null,+ ...(meta.source ? { source: meta.source } : {}),+ };+}++function templateView(row: { id: string; name: string; doc: unknown; createdAt: Date }): LibraryTemplate {+ const doc = row.doc as unknown as TemplateDoc;+ return {+ id: row.id,+ name: row.name,+ addedAt: row.createdAt.getTime(),+ folderId: doc.folderId ?? null,+ duration: doc.duration,+ media: doc.media ?? [],+ layers: doc.layers ?? [],+ audio: doc.audio ?? [],+ texts: doc.texts ?? [],+ cues: doc.cues ?? [],+ };+}++const asJson = (doc: TemplateDoc) => doc as unknown as Prisma.InputJsonValue;++async function findTemplate(userId: string, id: string) {+ return prisma.cutTemplate.findFirst({ where: { id, userId } });+}++/** A project media object row, complete, by fileName — the copy source for+ * save/saveTemplate/addToTemplate. */+async function projectMediaObject(userId: string, projectId: string, fileName: string) {+ return prisma.cutMediaObject.findFirst({+ where: { userId, projectId, kind: "media", fileName, uploadState: "complete" },+ });+}++async function libraryMediaObject(userId: string, fileName: string) {+ return prisma.cutMediaObject.findFirst({+ where: { userId, kind: "library", fileName },+ });+}++/** Copy one complete source object to a fresh library key, recording the row+ * and usage. Returns the library fileName. */+async function copyIntoLibrary(+ userId: string,+ src: MediaObjectRow,+ taken: Set<string>+): Promise<string> {+ const dest = dedupeName(safeFileName(src.fileName), taken);+ taken.add(dest);+ const key = libraryKey(userId, dest);+ await copy(src.r2Key, key);+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.create({+ data: {+ userId,+ r2Key: key,+ fileName: dest,+ mime: src.mime,+ bytes: src.bytes,+ kind: "library",+ uploadState: "complete",+ },+ });+ await addUsage(tx, userId, Number(src.bytes));+ });+ return dest;+}++/** Copy one library object into a project, recording the row and usage.+ * Returns the fileName inside the project. */+async function copyIntoProject(+ userId: string,+ projectId: string,+ libFileName: string,+ taken: Set<string>+): Promise<string> {+ const src = await libraryMediaObject(userId, libFileName);+ if (!src) throw new Error("Library asset not found.");+ const dest = dedupeName(safeFileName(libFileName), taken);+ taken.add(dest);+ const key = projectMediaKey(userId, projectId, dest);+ await copy(src.r2Key, key);+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.create({+ data: {+ userId,+ projectId,+ r2Key: key,+ fileName: dest,+ mime: src.mime,+ bytes: src.bytes,+ kind: "media",+ uploadState: "complete",+ },+ });+ await addUsage(tx, userId, Number(src.bytes));+ });+ return dest;+}++/** Delete one library media object (row + bytes + usage), best-effort on R2. */+async function deleteLibraryObject(userId: string, fileName: string) {+ const row = await libraryMediaObject(userId, fileName);+ if (!row) return;+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.delete({ where: { id: row.id } });+ if (row.uploadState === "complete") await addUsage(tx, userId, -Number(row.bytes));+ });+ await del([row.r2Key]);+}++export const libraryCloud = {+ async list(userId: string) {+ const [assetRows, folderRows, templateRows] = await Promise.all([+ prisma.cutLibraryAsset.findMany({ where: { userId }, orderBy: { createdAt: "desc" } }),+ prisma.cutFolder.findMany({ where: { userId, scope: "library" }, orderBy: { createdAt: "asc" } }),+ prisma.cutTemplate.findMany({ where: { userId }, orderBy: { createdAt: "desc" } }),+ ]);+ const objs = await prisma.cutMediaObject.findMany({+ where: { id: { in: assetRows.map((r) => r.mediaObjectId) } },+ select: { id: true, fileName: true },+ });+ const byId = new Map(objs.map((o) => [o.id, o]));+ const assets = assetRows+ .map((r) => {+ const obj = byId.get(r.mediaObjectId);+ return obj ? assetView(r, obj) : null;+ })+ .filter((a): a is LibraryAsset => a !== null);+ const folders: LibraryFolder[] = folderRows.map((f) => ({+ id: f.id,+ name: f.name,+ createdAt: f.createdAt.getTime(),+ }));+ const templates = templateRows.map(templateView);+ return Response.json({ assets, folders, templates });+ },++ /** Mint a presigned PUT for a direct-to-library upload. */+ async presign(userId: string, req: Request) {+ try {+ const body = (await req.json()) as { fileName?: string; mime?: string; bytes?: number };+ if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {+ return err("fileName and bytes are required.", 400);+ }+ if (!typeOf(body.fileName)) return err("Unsupported file type.", 400);+ const over = await quotaCheck(userId, body.bytes);+ if (over) return over;+ const fileName = dedupeName(safeFileName(body.fileName), await takenLibraryNames(userId));+ const key = libraryKey(userId, fileName);+ const url = await presignPut(key, body.mime ?? "application/octet-stream");+ await prisma.cutMediaObject.create({+ data: {+ userId,+ r2Key: key,+ fileName,+ mime: body.mime ?? "",+ bytes: BigInt(Math.round(body.bytes)),+ kind: "library",+ uploadState: "pending",+ },+ });+ return Response.json({ fileName, key, url });+ } catch (e) {+ return caught(e, "Could not presign the upload.");+ }+ },++ /** Finish a library upload: verify, mark complete, register the asset. */+ async complete(userId: string, req: Request) {+ try {+ const { key, meta } = (await req.json()) as { key?: string; meta?: AssetMeta };+ if (!key) return err("key is required.", 400);+ const obj = await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: key } });+ if (!obj) return err("Unknown upload.", 404);+ const info = obj.uploadState === "complete" ? null : await head(key);+ if (obj.uploadState !== "complete" && !info) return err("The upload never arrived.", 400);+ const row = await prisma.$transaction(async (tx) => {+ if (info) {+ await tx.cutMediaObject.update({+ where: { id: obj.id },+ data: {+ uploadState: "complete",+ bytes: BigInt(info.bytes),+ ...(info.mime ? { mime: info.mime } : {}),+ },+ });+ await addUsage(tx, userId, info.bytes);+ }+ return tx.cutLibraryAsset.create({+ data: {+ userId,+ mediaObjectId: obj.id,+ meta: {+ name: meta?.name ?? obj.fileName,+ type: meta?.type ?? typeOf(obj.fileName) ?? "video",+ duration: meta?.duration ?? 0,+ ...(meta?.width ? { width: meta.width, height: meta.height } : {}),+ ...(meta?.source ? { source: meta.source } : {}),+ } as unknown as Prisma.InputJsonValue,+ },+ });+ });+ return Response.json(assetView(row, obj));+ } catch (e) {+ return caught(e, "Could not complete the upload.");+ }+ },++ /** Copy a library asset into a project's media space. */+ async use(userId: string, req: Request) {+ try {+ const { assetId, projectId } = (await req.json()) as { assetId: string; projectId: string };+ const asset = await prisma.cutLibraryAsset.findFirst({ where: { id: assetId, userId } });+ if (!asset) throw new Error("Library asset not found.");+ const obj = await prisma.cutMediaObject.findUnique({ where: { id: asset.mediaObjectId } });+ if (!obj) throw new Error("Library asset not found.");+ if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ const fileName = await copyIntoProject(+ userId,+ projectId,+ obj.fileName,+ await takenMediaNames(userId, projectId)+ );+ return Response.json({ fileName });+ } catch (e) {+ return caught(e, "Could not add from library.");+ }+ },++ /** Copy a project media file into the shared library. */+ async save(userId: string, req: Request) {+ try {+ const { projectId, fileName, name } = (await req.json()) as {+ projectId: string;+ fileName: string;+ name?: string;+ };+ const src = await projectMediaObject(userId, projectId, fileName);+ if (!src) throw new Error("Media file not found in project.");+ const project = await getProject(userId, projectId);+ const docAsset = (project?.doc as { assets?: StoredAsset[] } | undefined)?.assets?.find(+ (a) => a.fileName === fileName+ );+ const dest = await copyIntoLibrary(userId, src, await takenLibraryNames(userId));+ const obj = await libraryMediaObject(userId, dest);+ if (!obj) throw new Error("Could not save to library.");+ const row = await prisma.cutLibraryAsset.create({+ data: {+ userId,+ mediaObjectId: obj.id,+ meta: {+ name: name || fileName,+ type: docAsset?.type ?? typeOf(dest) ?? "video",+ duration: docAsset?.duration ?? 0,+ ...(docAsset?.width ? { width: docAsset.width, height: docAsset.height } : {}),+ } as unknown as Prisma.InputJsonValue,+ },+ });+ return Response.json(assetView(row, obj));+ } catch (e) {+ return caught(e, "Could not save to library.");+ }+ },++ /** Move an item — asset or template — into a folder (or `null` to ungroup). */+ async move(userId: string, req: Request) {+ try {+ const { id, folderId } = (await req.json()) as { id: string; folderId: string | null };+ if (folderId) {+ const folder = await prisma.cutFolder.findFirst({+ where: { id: folderId, userId, scope: "library" },+ });+ if (!folder) throw new Error("Folder not found.");+ }+ const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });+ if (asset) {+ await prisma.cutLibraryAsset.update({ where: { id }, data: { folderId: folderId ?? null } });+ return Response.json({ ok: true });+ }+ const template = await findTemplate(userId, id);+ if (!template) throw new Error("Library item not found.");+ const doc = template.doc as unknown as TemplateDoc;+ await prisma.cutTemplate.update({+ where: { id },+ data: { doc: asJson({ ...doc, folderId: folderId ?? null }) },+ });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not move item.");+ }+ },++ async remove(userId: string, id: string) {+ try {+ const asset = await prisma.cutLibraryAsset.findFirst({ where: { id, userId } });+ if (!asset) throw new Error("Library asset not found.");+ const obj = await prisma.cutMediaObject.findUnique({ where: { id: asset.mediaObjectId } });+ await prisma.$transaction(async (tx) => {+ await tx.cutLibraryAsset.delete({ where: { id } });+ if (obj) {+ await tx.cutMediaObject.delete({ where: { id: obj.id } });+ if (obj.uploadState === "complete") await addUsage(tx, userId, -Number(obj.bytes));+ }+ });+ if (obj) await del([obj.r2Key]);+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete.");+ }+ },++ async serveMedia(userId: string, file: string) {+ try {+ return redirect(await presignGet(libraryKey(userId, decodeFileParam(file))));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },++ // --- Folders (scope "library") ---++ async createFolder(userId: string, req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const trimmed = (name ?? "").trim();+ if (!trimmed) throw new Error("Folder name required.");+ const row = await prisma.cutFolder.create({+ data: { userId, name: trimmed.slice(0, 80), scope: "library" },+ });+ return Response.json({ id: row.id, name: row.name, createdAt: row.createdAt.getTime() });+ } catch (e) {+ return caught(e, "Could not create folder.");+ }+ },++ async renameFolder(userId: string, id: string, req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const trimmed = (name ?? "").trim();+ if (!trimmed) throw new Error("Folder name required.");+ const row = await prisma.cutFolder.findFirst({ where: { id, userId, scope: "library" } });+ if (!row) throw new Error("Folder not found.");+ const updated = await prisma.cutFolder.update({+ where: { id },+ data: { name: trimmed.slice(0, 80) },+ });+ return Response.json({+ id: updated.id,+ name: updated.name,+ createdAt: updated.createdAt.getTime(),+ });+ } catch (e) {+ return caught(e, "Could not rename folder.");+ }+ },++ async deleteFolder(userId: string, id: string) {+ try {+ await prisma.$transaction(async (tx) => {+ await tx.cutFolder.deleteMany({ where: { id, userId, scope: "library" } });+ // Items in the folder fall back to ungrouped rather than vanishing.+ await tx.cutLibraryAsset.updateMany({+ where: { userId, folderId: id },+ data: { folderId: null },+ });+ const templates = await tx.cutTemplate.findMany({ where: { userId } });+ for (const t of templates) {+ const doc = t.doc as unknown as TemplateDoc;+ if (doc.folderId === id) {+ await tx.cutTemplate.update({+ where: { id: t.id },+ data: { doc: asJson({ ...doc, folderId: null }) },+ });+ }+ }+ });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete folder.");+ }+ },++ // --- Templates ---++ /** Save a timeline selection as a by-reference template: each source file is+ * copied into the library privately, then the edit is stored. */+ async saveTemplate(userId: string, req: Request) {+ try {+ const { projectId, ...input } = (await req.json()) as { projectId: string } & TemplateInput;+ if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ if (!input.media?.length && !input.texts?.length && !input.cues?.length) {+ throw new Error("Nothing to save.");+ }+ const taken = await takenLibraryNames(userId);+ const media: TemplateMedia[] = [];+ for (const m of input.media) {+ const src = await projectMediaObject(userId, projectId, m.fileName);+ if (!src) throw new Error("Media file not found in project.");+ const dest = await copyIntoLibrary(userId, src, taken);+ media.push({ fileName: dest, name: m.name, type: m.type, duration: m.duration, width: m.width, height: m.height });+ }+ const doc: TemplateDoc = {+ folderId: null,+ duration: input.duration,+ media,+ layers: input.layers ?? [],+ audio: input.audio ?? [],+ texts: input.texts ?? [],+ cues: input.cues ?? [],+ };+ const row = await prisma.cutTemplate.create({+ data: { userId, name: (input.name || "Template").trim().slice(0, 80), doc: asJson(doc) },+ });+ return Response.json(templateView(row));+ } catch (e) {+ return caught(e, "Could not save the template.");+ }+ },++ /** Materialize a template into a project: copy its media in and hand back the+ * project file names (in template media order) plus the stored edit. */+ async useTemplate(userId: string, id: string, req: Request) {+ try {+ const { projectId } = (await req.json()) as { projectId: string };+ if (!(await getProject(userId, projectId))) throw new Error("Project not found.");+ const row = await findTemplate(userId, id);+ if (!row) throw new Error("Template not found.");+ const template = templateView(row);+ const taken = await takenMediaNames(userId, projectId);+ const media: TemplateMedia[] = [];+ for (const m of template.media) {+ const dest = await copyIntoProject(userId, projectId, m.fileName, taken);+ media.push({ ...m, fileName: dest });+ }+ return Response.json({ template, media });+ } catch (e) {+ return caught(e, "Could not add the template.");+ }+ },++ /** Append one project media file to a template as a part at its end. */+ async addToTemplate(userId: string, id: string, req: Request) {+ try {+ const { projectId, ...input } = (await req.json()) as {+ projectId: string;+ media: TemplateMedia;+ layer?: Omit<TemplateLayer, "media" | "start">;+ audio?: Omit<TemplateAudio, "media" | "start">;+ extend: number;+ };+ const row = await findTemplate(userId, id);+ if (!row) throw new Error("Template not found.");+ const src = await projectMediaObject(userId, projectId, input.media.fileName);+ if (!src) throw new Error("Media file not found in project.");+ const dest = await copyIntoLibrary(userId, src, await takenLibraryNames(userId));+ const doc = (row.doc as unknown as TemplateDoc);+ const mi = (doc.media ?? []).length;+ const next: TemplateDoc = {+ ...doc,+ media: [...(doc.media ?? []), { ...input.media, fileName: dest }],+ audio: input.audio+ ? [...(doc.audio ?? []), { ...input.audio, media: mi, start: doc.duration }]+ : doc.audio ?? [],+ layers:+ !input.audio && input.layer+ ? [...(doc.layers ?? []), { ...input.layer, media: mi, start: doc.duration }]+ : doc.layers ?? [],+ duration: doc.duration + input.extend,+ };+ const updated = await prisma.cutTemplate.update({ where: { id }, data: { doc: asJson(next) } });+ return Response.json(templateView(updated));+ } catch (e) {+ return caught(e, "Could not add to the template.");+ }+ },++ async renameTemplate(userId: string, id: string, req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const trimmed = (name ?? "").trim();+ if (!trimmed) throw new Error("Template name required.");+ const row = await findTemplate(userId, id);+ if (!row) throw new Error("Template not found.");+ const updated = await prisma.cutTemplate.update({+ where: { id },+ data: { name: trimmed.slice(0, 80) },+ });+ return Response.json(templateView(updated));+ } catch (e) {+ return caught(e, "Could not rename the template.");+ }+ },++ async removeTemplate(userId: string, id: string) {+ try {+ const row = await findTemplate(userId, id);+ if (row) {+ await prisma.cutTemplate.delete({ where: { id } });+ // The media copies are private to this template, so removing them is safe.+ const doc = row.doc as unknown as TemplateDoc;+ for (const m of doc.media ?? []) await deleteLibraryObject(userId, m.fileName);+ }+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the template.");+ }+ },+};diff --git a/site/src/cut/server/cloud/limits.ts b/site/src/cut/server/cloud/limits.tsnew file mode 100644index 00000000..d7e10caa--- /dev/null+++ b/site/src/cut/server/cloud/limits.ts@@ -0,0 +1,41 @@+import { getActiveProSubscription } from "@/lib/billing/pro-subscription";+import { isDonkeySuperUser } from "@/lib/donkey-api-auth";+import { prisma } from "@/lib/prisma";++// Cut web mode's cost ceilings by account tier. Storage bounds R2; the daily+// render cap bounds worker CPU (exports + URL imports — hover previews are+// cheap and ride along uncounted). null = unlimited.+export type CutLimits = {+ storageBytes: number | null;+ renderJobsPerDay: number | null;+};++const FREE: CutLimits = { storageBytes: 250 * 1024 ** 2, renderJobsPerDay: 10 };+const PRO: CutLimits = { storageBytes: 50 * 1024 ** 3, renderJobsPerDay: 200 };+const UNLIMITED: CutLimits = { storageBytes: null, renderJobsPerDay: null };++export async function cutLimitsFor(userId: string): Promise<CutLimits> {+ if (await isDonkeySuperUser(userId)) return UNLIMITED;+ return (await getActiveProSubscription(userId)) ? PRO : FREE;+}++/** 429 when another counted render job would break the daily cap, else null. */+export async function renderJobCheck(userId: string): Promise<Response | null> {+ const limits = await cutLimitsFor(userId);+ if (limits.renderJobsPerDay === null) return null;+ const since = new Date(Date.now() - 24 * 60 * 60 * 1000);+ const used = await prisma.cutRenderJob.count({+ where: { userId, kind: { in: ["export", "import_url"] }, createdAt: { gte: since } },+ });+ if (used < limits.renderJobsPerDay) return null;+ // `error` is what the client's shared error paths render — keep it human.+ return Response.json(+ {+ error:+ "You've reached today's limit for exports and imports. It resets over the next 24 hours — or Pro raises it.",+ code: "daily_render_limit",+ limit: limits.renderJobsPerDay,+ },+ { status: 429 }+ );+}diff --git a/site/src/cut/server/cloud/media.ts b/site/src/cut/server/cloud/media.tsnew file mode 100644index 00000000..434ab878--- /dev/null+++ b/site/src/cut/server/cloud/media.ts@@ -0,0 +1,192 @@+// Media upload plumbing for cloud projects: browser bytes go straight to R2 via+// presigned PUTs; these routes mint the URLs and keep CutMediaObject + quota in+// step. Small images (AI generations, stock tiles) still ride through the+// server like the engine's importImage.+import { prisma } from "@/lib/prisma";+import { getProject, takenMediaNames } from "./projects";+import { head, presignGet, presignPut, projectMediaKey, putObject } from "./r2";+import { addUsage, quotaCheck } from "./usage";+import { caught, dedupeName, err, safeFileName } from "./util";++/** Direct-upload cap: anything larger goes through presign. */+const INLINE_UPLOAD_BYTES = 3.5 * 1024 * 1024;+const PRESIGN_GET_BATCH_MAX = 500;++/** Width/height from the image header (PNG, JPEG, GIF, WebP). The hosted+ * runtime has no ffprobe; unknown formats report 0×0. */+function imageDims(buf: Buffer): { width: number; height: number } {+ if (buf.length >= 24 && buf[0] === 0x89 && buf[1] === 0x50) {+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };+ }+ if (buf.length >= 10 && buf.toString("ascii", 0, 3) === "GIF") {+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8) };+ }+ if (buf.length > 4 && buf[0] === 0xff && buf[1] === 0xd8) {+ let i = 2;+ while (i + 9 < buf.length) {+ if (buf[i] !== 0xff) {+ i++;+ continue;+ }+ const marker = buf[i + 1];+ if (marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd9)) {+ i += 2;+ continue;+ }+ const isSof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;+ if (isSof) return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };+ i += 2 + buf.readUInt16BE(i + 2);+ }+ }+ if (buf.length >= 30 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") {+ const fmt = buf.toString("ascii", 12, 16);+ if (fmt === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };+ if (fmt === "VP8L") {+ const b = buf.readUInt32LE(21);+ return { width: (b & 0x3fff) + 1, height: ((b >> 14) & 0x3fff) + 1 };+ }+ if (fmt === "VP8X") return { width: 1 + buf.readUIntLE(24, 3), height: 1 + buf.readUIntLE(27, 3) };+ }+ return { width: 0, height: 0 };+}++export const mediaCloud = {+ /** Mint a presigned PUT for one project media upload. The fileName is deduped+ * and claimed by a pending CutMediaObject row before the URL goes out. */+ async presign(userId: string, projectId: string, req: Request) {+ try {+ const body = (await req.json()) as { fileName?: string; mime?: string; bytes?: number };+ if (!body.fileName || typeof body.bytes !== "number" || body.bytes <= 0) {+ return err("fileName and bytes are required.", 400);+ }+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const over = await quotaCheck(userId, body.bytes);+ if (over) return over;+ const fileName = dedupeName(+ safeFileName(body.fileName),+ await takenMediaNames(userId, projectId)+ );+ const key = projectMediaKey(userId, projectId, fileName);+ const url = await presignPut(key, body.mime ?? "application/octet-stream");+ await prisma.cutMediaObject.create({+ data: {+ userId,+ projectId,+ r2Key: key,+ fileName,+ mime: body.mime ?? "",+ bytes: BigInt(Math.round(body.bytes)),+ kind: "media",+ uploadState: "pending",+ },+ });+ return Response.json({ fileName, key, url });+ } catch (e) {+ return caught(e, "Could not presign the upload.");+ }+ },++ /** The browser finished its PUT: verify the object landed, mark the row+ * complete with the real size, and bump usage. */+ async complete(userId: string, req: Request) {+ try {+ const { key } = (await req.json()) as { key?: string };+ if (!key) return err("key is required.", 400);+ const row = await prisma.cutMediaObject.findFirst({ where: { userId, r2Key: key } });+ if (!row) return err("Unknown upload.", 404);+ if (row.uploadState === "complete") return Response.json({ fileName: row.fileName });+ const info = await head(key);+ if (!info) return err("The upload never arrived.", 400);+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.update({+ where: { id: row.id },+ data: {+ uploadState: "complete",+ bytes: BigInt(info.bytes),+ ...(info.mime ? { mime: info.mime } : {}),+ },+ });+ await addUsage(tx, userId, info.bytes);+ });+ return Response.json({ fileName: row.fileName });+ } catch (e) {+ return caught(e, "Could not complete the upload.");+ }+ },++ /** Batch signed GETs so a loaded project can hydrate every asset URL in one+ * round trip. Keys are deterministic from projectId + fileName. */+ async presignGetBatch(userId: string, req: Request) {+ try {+ const { items } = (await req.json()) as {+ items?: { projectId?: string; fileName?: string }[];+ };+ if (!Array.isArray(items)) return err("items is required.", 400);+ if (items.length > PRESIGN_GET_BATCH_MAX) return err("Too many items.", 400);+ const urls = await Promise.all(+ items+ .filter((i) => typeof i.projectId === "string" && typeof i.fileName === "string")+ .map(async (i) => ({+ projectId: i.projectId!,+ fileName: i.fileName!,+ url: await presignGet(projectMediaKey(userId, i.projectId!, safeFileName(i.fileName!))),+ }))+ );+ return Response.json({ urls });+ } catch (e) {+ return caught(e, "Could not sign the media URLs.");+ }+ },++ /** Mirror of the engine's importImage for small payloads: store the bytes,+ * return the MediaAsset shape. Larger callers use presign. */+ async importImage(userId: string, projectId: string, req: Request) {+ try {+ if (!(await getProject(userId, projectId))) return err("Project not found.", 404);+ const form = await req.formData();+ const file = form.get("file");+ if (!(file instanceof File)) return err("No image in upload.", 400);+ if (file.size > INLINE_UPLOAD_BYTES) return err("Image too large — use the presigned upload.", 413);+ const over = await quotaCheck(userId, file.size);+ if (over) return over;+ const nameField = form.get("name");+ const name = typeof nameField === "string" && nameField.trim() ? nameField.trim() : file.name;+ const origin = form.get("origin") === "generated" ? "generated" : undefined;+ const fileName = dedupeName(+ safeFileName(file.name),+ await takenMediaNames(userId, projectId)+ );+ const key = projectMediaKey(userId, projectId, fileName);+ const buf = Buffer.from(await file.arrayBuffer());+ await putObject(key, buf, file.type || "application/octet-stream");+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.create({+ data: {+ userId,+ projectId,+ r2Key: key,+ fileName,+ mime: file.type ?? "",+ bytes: BigInt(buf.length),+ kind: "media",+ uploadState: "complete",+ },+ });+ await addUsage(tx, userId, buf.length);+ });+ const dims = imageDims(buf);+ return Response.json({+ id: crypto.randomUUID().slice(0, 8),+ type: "image",+ name,+ fileName,+ duration: 0,+ width: dims.width,+ height: dims.height,+ ...(origin ? { origin } : {}),+ });+ } catch (e) {+ return caught(e, "Could not import the image.");+ }+ },+};diff --git a/site/src/cut/server/cloud/projects.ts b/site/src/cut/server/cloud/projects.tsnew file mode 100644index 00000000..2d07a25d--- /dev/null+++ b/site/src/cut/server/cloud/projects.ts@@ -0,0 +1,427 @@+// Cloud twin of the engine's project CRUD (server/projects.ts + http/projects.ts):+// docs and metadata in Postgres, media bytes in R2. Every query scopes by userId.+import type { ProjectDoc, ProjectFolder, ProjectSummary } from "@/cut/lib/types";+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import {+ copy,+ del,+ presignGet,+ projectExportKey,+ projectMediaKey,+} from "./r2";+import { addUsage } from "./usage";+import { caught, decodeFileParam, err, redirect } from "./util";++type ProjectRow = {+ id: string;+ userId: string;+ name: string;+ doc: unknown;+ folderId: string | null;+ version: number;+ previewKey: string | null;+ createdAt: Date;+ updatedAt: Date;+};++export async function getProject(userId: string, id: string): Promise<ProjectRow | null> {+ return prisma.cutProject.findFirst({ where: { id, userId } });+}++/** Every media fileName already claimed in the project — pending uploads hold+ * their name too, so a racing presign can't hand out the same one. */+export async function takenMediaNames(userId: string, projectId: string): Promise<Set<string>> {+ const rows = await prisma.cutMediaObject.findMany({+ where: { userId, projectId, kind: "media" },+ select: { fileName: true },+ });+ return new Set(rows.map((r) => r.fileName));+}++/** The row's grouping column is authoritative; the stored doc's folderId is+ * overlaid on read so the two can never disagree. */+function docOf(row: ProjectRow): ProjectDoc {+ const doc = row.doc as ProjectDoc;+ return { ...doc, folderId: row.folderId ?? null };+}++/** Mirror of the engine's summarize(): track 0 is the cut. sizeBytes comes from+ * the project's complete media objects instead of a directory walk. */+function summarize(row: ProjectRow, sizeBytes: number): ProjectSummary {+ const doc = docOf(row);+ const clips = Array.isArray(doc.clips) ? doc.clips : [];+ const assets = Array.isArray(doc.assets) ? doc.assets : [];+ const track0 = clips.filter((c) => (c.track ?? 0) === 0);+ const duration = track0.reduce((sum, c) => sum + Math.max(0, c.out - c.in), 0);+ const firstClip = track0[0];+ const firstClipAsset = firstClip ? assets.find((a) => a.id === firstClip.assetId) : undefined;+ const previewAsset =+ firstClipAsset ?? assets.find((a) => a.type === "video" || a.type === "image");+ const previewStart = firstClipAsset && firstClip ? firstClip.in : 0;+ return {+ id: row.id,+ name: doc.name,+ createdAt: row.createdAt.getTime(),+ updatedAt: row.updatedAt.getTime(),+ duration,+ clipCount: track0.length,+ assetCount: assets.length,+ previewFile: previewAsset?.fileName,+ previewIsImage: previewAsset?.type === "image",+ previewStart,+ hasPreview: row.previewKey != null,+ folderId: row.folderId ?? null,+ sizeBytes,+ };+}++async function projectSizes(userId: string, projectIds: string[]): Promise<Map<string, number>> {+ if (projectIds.length === 0) return new Map();+ const sums = await prisma.cutMediaObject.groupBy({+ by: ["projectId"],+ where: { userId, projectId: { in: projectIds }, uploadState: "complete" },+ _sum: { bytes: true },+ });+ return new Map(sums.map((s) => [s.projectId as string, Number(s._sum.bytes ?? 0)]));+}++const asJson = (doc: ProjectDoc) => doc as unknown as Prisma.InputJsonValue;++export const projectsCloud = {+ async list(userId: string) {+ const rows = await prisma.cutProject.findMany({+ where: { userId },+ orderBy: { updatedAt: "desc" },+ });+ const sizes = await projectSizes(userId, rows.map((r) => r.id));+ return Response.json(rows.map((r) => summarize(r, sizes.get(r.id) ?? 0)));+ },++ async create(userId: string, req: Request) {+ try {+ const { name, folderId } = (await req.json()) as { name?: string; folderId?: string | null };+ const folder = folderId+ ? await prisma.cutFolder.findFirst({ where: { id: folderId, userId, scope: "project" } })+ : null;+ const now = Date.now();+ const doc: ProjectDoc = {+ version: 1,+ name: (name ?? "Untitled").trim() || "Untitled",+ createdAt: now,+ updatedAt: now,+ assets: [],+ clips: [],+ audioClips: [],+ overlays: [],+ };+ const row = await prisma.cutProject.create({+ data: { userId, name: doc.name, doc: asJson(doc), folderId: folder?.id ?? null },+ });+ return Response.json(summarize(row, 0));+ } catch (e) {+ return caught(e, "Could not create project.");+ }+ },++ async get(userId: string, id: string) {+ const row = await getProject(userId, id);+ if (!row) return err("Project not found.", 404);+ return Response.json(docOf(row), {+ headers: { "x-cut-doc-version": String(row.version) },+ });+ },++ /** Optimistic-concurrency save: ?v= carries the version the client loaded;+ * a mismatch 409s with the current doc so the client can rebase. A PUT+ * without ?v= (first save) applies unconditionally. */+ async put(userId: string, id: string, req: Request) {+ try {+ const row = await getProject(userId, id);+ if (!row) return err("Project not found.", 404);+ const vParam = new URL(req.url).searchParams.get("v");+ const existing = docOf(row);+ const body = (await req.json()) as Partial<ProjectDoc>;+ const doc: ProjectDoc = {+ ...existing,+ name: typeof body.name === "string" && body.name.trim() ? body.name.trim() : existing.name,+ assets: Array.isArray(body.assets) ? body.assets : existing.assets,+ clips: Array.isArray(body.clips) ? body.clips : existing.clips,+ audioClips: Array.isArray(body.audioClips) ? body.audioClips : existing.audioClips,+ // Same legacy-shape handling as the engine: a merged client saving+ // `clips` clears the old separate overlay array.+ overlayClips: Array.isArray(body.overlayClips)+ ? body.overlayClips+ : Array.isArray(body.clips)+ ? []+ : existing.overlayClips,+ overlays: Array.isArray(body.overlays) ? body.overlays : existing.overlays,+ templates: Array.isArray(body.templates) ? body.templates : existing.templates,+ aspect: body.aspect === "9:16" || body.aspect === "16:9" ? body.aspect : existing.aspect,+ fadeIn: typeof body.fadeIn === "number" ? body.fadeIn : existing.fadeIn,+ fadeOut: typeof body.fadeOut === "number" ? body.fadeOut : existing.fadeOut,+ subtitles:+ body.subtitles && typeof body.subtitles === "object" ? body.subtitles : existing.subtitles,+ ui: body.ui && typeof body.ui === "object" ? { ...existing.ui, ...body.ui } : existing.ui,+ publish:+ body.publish && typeof body.publish === "object"+ ? { ...existing.publish, ...body.publish }+ : existing.publish,+ notes:+ body.notes && typeof body.notes === "object"+ ? { ...existing.notes, ...body.notes }+ : existing.notes,+ genvideo: body.genvideo !== undefined ? body.genvideo ?? undefined : existing.genvideo,+ };+ doc.updatedAt = Date.now();+ const data = { doc: asJson(doc), name: doc.name, version: { increment: 1 } };+ if (vParam === null) {+ // First save: apply unconditionally, report the authoritative version.+ const updated = await prisma.cutProject.update({ where: { id }, data });+ return Response.json({ ok: true, version: updated.version });+ }+ const v = Number(vParam);+ if (!Number.isInteger(v)) return err("Bad version.", 400);+ const updated = await prisma.cutProject.updateMany({+ where: { id, userId, version: v },+ data,+ });+ if (updated.count === 0) {+ const current = await getProject(userId, id);+ if (!current) return err("Project not found.", 404);+ return Response.json(+ { error: "conflict", doc: docOf(current), version: current.version },+ { status: 409 }+ );+ }+ return Response.json({ ok: true, version: v + 1 });+ } catch (e) {+ return caught(e, "Could not save project.");+ }+ },++ async remove(userId: string, id: string) {+ try {+ const row = await getProject(userId, id);+ if (!row) return err("Project not found.", 404);+ const objects = await prisma.cutMediaObject.findMany({+ where: { userId, projectId: id },+ });+ const freed = objects+ .filter((o) => o.uploadState === "complete")+ .reduce((sum, o) => sum + Number(o.bytes), 0);+ // Cancel the project's in-flight renders first: a job finishing after+ // the delete would re-register storage for a project nothing can see.+ await prisma.cutRenderJob.updateMany({+ where: { userId, projectId: id, state: { in: ["queued", "running"] } },+ data: { state: "canceled" },+ });+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.deleteMany({ where: { userId, projectId: id } });+ await tx.cutProject.delete({ where: { id } });+ await addUsage(tx, userId, -freed);+ });+ await del(objects.map((o) => o.r2Key));+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete project.");+ }+ },++ /** Duplicate a project: copy the doc and its media objects (not its exports)+ * into a fresh project. */+ async duplicate(userId: string, id: string) {+ try {+ const row = await getProject(userId, id);+ if (!row) return err("Project not found.", 404);+ const doc = docOf(row);+ const now = Date.now();+ const copyDoc: ProjectDoc = { ...doc, name: `${doc.name} copy`, createdAt: now, updatedAt: now };+ const media = await prisma.cutMediaObject.findMany({+ where: { userId, projectId: id, kind: "media", uploadState: "complete" },+ });+ const created = await prisma.cutProject.create({+ data: { userId, name: copyDoc.name, doc: asJson(copyDoc), folderId: row.folderId },+ });+ for (const m of media) {+ await copy(m.r2Key, projectMediaKey(userId, created.id, m.fileName));+ }+ const added = media.reduce((sum, m) => sum + Number(m.bytes), 0);+ await prisma.$transaction(async (tx) => {+ if (media.length > 0) {+ await tx.cutMediaObject.createMany({+ data: media.map((m) => ({+ userId,+ projectId: created.id,+ r2Key: projectMediaKey(userId, created.id, m.fileName),+ fileName: m.fileName,+ mime: m.mime,+ bytes: m.bytes,+ kind: "media",+ uploadState: "complete",+ })),+ });+ }+ await addUsage(tx, userId, added);+ });+ return Response.json(summarize(created, added));+ } catch (e) {+ return caught(e, "Could not duplicate project.");+ }+ },++ async move(userId: string, id: string, req: Request) {+ try {+ const { folderId } = (await req.json()) as { folderId: string | null };+ const row = await getProject(userId, id);+ if (!row) return err("Project not found.", 404);+ if (folderId) {+ const folder = await prisma.cutFolder.findFirst({+ where: { id: folderId, userId, scope: "project" },+ });+ if (!folder) return err("Folder not found.", 500);+ }+ await prisma.cutProject.update({ where: { id }, data: { folderId: folderId ?? null } });+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not move project.");+ }+ },++ async folders(userId: string) {+ const rows = await prisma.cutFolder.findMany({+ where: { userId, scope: "project" },+ orderBy: { createdAt: "asc" },+ });+ const folders: ProjectFolder[] = rows.map((f) => ({+ id: f.id,+ name: f.name,+ createdAt: f.createdAt.getTime(),+ }));+ return Response.json(folders);+ },++ async createFolder(userId: string, req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const trimmed = (name ?? "").trim();+ if (!trimmed) return err("Folder name required.", 500);+ const row = await prisma.cutFolder.create({+ data: { userId, name: trimmed.slice(0, 80), scope: "project" },+ });+ return Response.json({ id: row.id, name: row.name, createdAt: row.createdAt.getTime() });+ } catch (e) {+ return caught(e, "Could not create folder.");+ }+ },++ async renameFolder(userId: string, id: string, req: Request) {+ try {+ const { name } = (await req.json()) as { name?: string };+ const trimmed = (name ?? "").trim();+ if (!trimmed) return err("Folder name required.", 500);+ const row = await prisma.cutFolder.findFirst({ where: { id, userId, scope: "project" } });+ if (!row) return err("Folder not found.", 500);+ const updated = await prisma.cutFolder.update({+ where: { id },+ data: { name: trimmed.slice(0, 80) },+ });+ return Response.json({+ id: updated.id,+ name: updated.name,+ createdAt: updated.createdAt.getTime(),+ });+ } catch (e) {+ return caught(e, "Could not rename folder.");+ }+ },++ async deleteFolder(userId: string, id: string) {+ try {+ await prisma.$transaction([+ prisma.cutFolder.deleteMany({ where: { id, userId, scope: "project" } }),+ // Projects in the folder fall back to ungrouped rather than disappearing.+ prisma.cutProject.updateMany({ where: { userId, folderId: id }, data: { folderId: null } }),+ ]);+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete folder.");+ }+ },++ // --- Media / export / preview bytes: 302 to a signed R2 GET. ---++ async serveMedia(userId: string, id: string, file: string) {+ try {+ return redirect(await presignGet(projectMediaKey(userId, id, decodeFileParam(file))));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },++ async removeMedia(userId: string, id: string, file: string) {+ try {+ const fileName = decodeFileParam(file);+ const row = await prisma.cutMediaObject.findFirst({+ where: { userId, projectId: id, kind: "media", fileName },+ });+ if (row) {+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.delete({ where: { id: row.id } });+ if (row.uploadState === "complete") await addUsage(tx, userId, -Number(row.bytes));+ });+ await del([row.r2Key]);+ }+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the media file.");+ }+ },++ async listExports(userId: string, id: string) {+ const rows = await prisma.cutMediaObject.findMany({+ where: { userId, projectId: id, kind: "export", uploadState: "complete" },+ orderBy: { updatedAt: "desc" },+ });+ return Response.json(+ rows.map((r) => ({ file: r.fileName, size: Number(r.bytes), mtime: r.updatedAt.getTime() }))+ );+ },++ async serveExport(userId: string, id: string, file: string) {+ try {+ return redirect(await presignGet(projectExportKey(userId, id, decodeFileParam(file))));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },++ async removeExport(userId: string, id: string, file: string) {+ try {+ const fileName = decodeFileParam(file);+ const row = await prisma.cutMediaObject.findFirst({+ where: { userId, projectId: id, kind: "export", fileName },+ });+ if (row) {+ await prisma.$transaction(async (tx) => {+ await tx.cutMediaObject.delete({ where: { id: row.id } });+ if (row.uploadState === "complete") await addUsage(tx, userId, -Number(row.bytes));+ });+ await del([row.r2Key]);+ }+ return Response.json({ ok: true });+ } catch (e) {+ return caught(e, "Could not delete the export.");+ }+ },++ async servePreview(userId: string, id: string) {+ try {+ const row = await getProject(userId, id);+ if (!row?.previewKey) return new Response("Not found.", { status: 404 });+ return redirect(await presignGet(row.previewKey));+ } catch (e) {+ return caught(e, "Bad request.", 400);+ }+ },+};diff --git a/site/src/cut/server/cloud/r2.ts b/site/src/cut/server/cloud/r2.tsnew file mode 100644index 00000000..0d0d41e8--- /dev/null+++ b/site/src/cut/server/cloud/r2.ts@@ -0,0 +1,119 @@+// Cloudflare R2 access for Cut web mode. Media bytes live here; metadata rows+// (CutMediaObject) record the keys. Only credentials come from env — bucket+// name, key scheme, and expiries are code.+import {+ CopyObjectCommand,+ DeleteObjectsCommand,+ GetObjectCommand,+ HeadObjectCommand,+ PutObjectCommand,+ S3Client,+} from "@aws-sdk/client-s3";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";++const R2_BUCKET = "donkey-cut";++const PUT_EXPIRY_SECONDS = 60 * 60; // 1h — the client uploads right after presigning+const GET_EXPIRY_SECONDS = 24 * 60 * 60; // 24h — hydrated asset URLs live a session++export class R2NotConfiguredError extends Error {+ constructor() {+ super("cloud storage is not configured");+ }+}++let client: S3Client | null = null;++function r2(): S3Client {+ if (client) return client;+ const accountId = process.env.R2_ACCOUNT_ID;+ const accessKeyId = process.env.R2_ACCESS_KEY_ID;+ const secretAccessKey = process.env.R2_SECRET_ACCESS_KEY;+ if (!accountId || !accessKeyId || !secretAccessKey) throw new R2NotConfiguredError();+ client = new S3Client({+ region: "auto",+ endpoint: `https://${accountId}.r2.cloudflarestorage.com`,+ credentials: { accessKeyId, secretAccessKey },+ });+ return client;+}++// --- Key scheme: everything a user owns lives under cut/<userId>/. ---++export const projectMediaKey = (userId: string, projectId: string, fileName: string) =>+ `cut/${userId}/projects/${projectId}/media/${fileName}`;+export const projectExportKey = (userId: string, projectId: string, fileName: string) =>+ `cut/${userId}/projects/${projectId}/exports/${fileName}`;+export const projectPreviewKey = (userId: string, projectId: string) =>+ `cut/${userId}/projects/${projectId}/preview.mp4`;+export const libraryKey = (userId: string, fileName: string) =>+ `cut/${userId}/library/${fileName}`;+export const overlayKey = (userId: string, batchId: string, name: string) =>+ `cut/${userId}/overlays/${batchId}/${name}`;++export function presignPut(key: string, mime: string): Promise<string> {+ return getSignedUrl(+ r2(),+ new PutObjectCommand({ Bucket: R2_BUCKET, Key: key, ContentType: mime }),+ { expiresIn: PUT_EXPIRY_SECONDS }+ );+}++export function presignGet(key: string, downloadName?: string): Promise<string> {+ return getSignedUrl(+ r2(),+ new GetObjectCommand({+ Bucket: R2_BUCKET,+ Key: key,+ ...(downloadName+ ? { ResponseContentDisposition: `attachment; filename="${downloadName.replace(/"/g, "")}"` }+ : {}),+ }),+ { expiresIn: GET_EXPIRY_SECONDS }+ );+}++/** Object size/type, or null when the object does not exist. */+export async function head(key: string): Promise<{ bytes: number; mime: string } | null> {+ try {+ const res = await r2().send(new HeadObjectCommand({ Bucket: R2_BUCKET, Key: key }));+ return { bytes: Number(res.ContentLength ?? 0), mime: res.ContentType ?? "" };+ } catch (e) {+ if (e instanceof R2NotConfiguredError) throw e;+ return null;+ }+}++export async function copy(srcKey: string, dstKey: string): Promise<void> {+ await r2().send(+ new CopyObjectCommand({+ Bucket: R2_BUCKET,+ CopySource: `${R2_BUCKET}/${encodeURIComponent(srcKey).replace(/%2F/g, "/")}`,+ Key: dstKey,+ })+ );+}++export async function putObject(key: string, body: Buffer, mime: string): Promise<void> {+ await r2().send(+ new PutObjectCommand({ Bucket: R2_BUCKET, Key: key, Body: body, ContentType: mime })+ );+}++/** Best-effort bulk delete — object cleanup never fails a row delete. */+export async function del(keys: string[]): Promise<void> {+ if (keys.length === 0) return;+ try {+ const s3 = r2();+ for (let i = 0; i < keys.length; i += 1000) {+ await s3.send(+ new DeleteObjectsCommand({+ Bucket: R2_BUCKET,+ Delete: { Objects: keys.slice(i, i + 1000).map((Key) => ({ Key })), Quiet: true },+ })+ );+ }+ } catch {+ // Orphaned objects are collectible later by key prefix; the rows are gone.+ }+}diff --git a/site/src/cut/server/cloud/routes.ts b/site/src/cut/server/cloud/routes.tsnew file mode 100644index 00000000..b0633865--- /dev/null+++ b/site/src/cut/server/cloud/routes.ts@@ -0,0 +1,120 @@+// The hosted Cut API surface in one table, namespaced under /api/cut-cloud/*.+// The client's cloud driver rewrites /api/cut/X -> /api/cut-cloud/X, so paths+// mirror the engine table (http/routes.ts) with the cloud prefix, plus the+// cloud-only presign/job routes. Auth happens in the Next catch-all+// (withDonkeyAuth); every handler receives the session's userId and scopes+// every query by it.+import { type DonkeyAuthenticatedRequest, isDonkeySuperUser } from "@/lib/donkey-api-auth";+import { matchRouteTable, type RouteEntry } from "../http/match";+import { runGc } from "./gc";+import { jobsCloud } from "./jobs";+import { libraryCloud } from "./library";+import { mediaCloud } from "./media";+import { projectsCloud } from "./projects";+import { transcribeCloud } from "./transcribe";+import { usageApi } from "./usage";++type CloudHandler = (+ req: Request,+ userId: string,+ params: Record<string, string>+) => Response | Promise<Response>;++interface CloudRoute extends RouteEntry {+ handler: CloudHandler;+}++const CUT_CLOUD_ROUTES: CloudRoute[] = [+ { method: "GET", path: "/api/cut-cloud/projects", handler: (_r, u) => projectsCloud.list(u) },+ { method: "POST", path: "/api/cut-cloud/projects", handler: (r, u) => projectsCloud.create(u, r) },+ { method: "GET", path: "/api/cut-cloud/projects/folders", handler: (_r, u) => projectsCloud.folders(u) },+ { method: "POST", path: "/api/cut-cloud/projects/folders", handler: (r, u) => projectsCloud.createFolder(u, r) },+ { method: "PUT", path: "/api/cut-cloud/projects/folders/:id", handler: (r, u, p) => projectsCloud.renameFolder(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/projects/folders/:id", handler: (_r, u, p) => projectsCloud.deleteFolder(u, p.id) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/move", handler: (r, u, p) => projectsCloud.move(u, p.id, r) },+ { method: "GET", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.get(u, p.id) },+ { method: "PUT", path: "/api/cut-cloud/projects/:id", handler: (r, u, p) => projectsCloud.put(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/projects/:id", handler: (_r, u, p) => projectsCloud.remove(u, p.id) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/duplicate", handler: (_r, u, p) => projectsCloud.duplicate(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/exports", handler: (_r, u, p) => projectsCloud.listExports(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (_r, u, p) => projectsCloud.serveExport(u, p.id, p.file) },+ { method: "DELETE", path: "/api/cut-cloud/projects/:id/exports/:file", handler: (_r, u, p) => projectsCloud.removeExport(u, p.id, p.file) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.serveMedia(u, p.id, p.file) },+ { method: "DELETE", path: "/api/cut-cloud/projects/:id/media/:file", handler: (_r, u, p) => projectsCloud.removeMedia(u, p.id, p.file) },+ { method: "GET", path: "/api/cut-cloud/projects/:id/preview", handler: (_r, u, p) => projectsCloud.servePreview(u, p.id) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/image", handler: (r, u, p) => mediaCloud.importImage(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/media/presign", handler: (r, u, p) => mediaCloud.presign(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/media/complete", handler: (r, u) => mediaCloud.complete(u, r) },+ { method: "POST", path: "/api/cut-cloud/projects/:id/import-url", handler: (r, u, p) => jobsCloud.importUrl(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/media/presign-get", handler: (r, u) => mediaCloud.presignGetBatch(u, r) },++ { method: "GET", path: "/api/cut-cloud/library", handler: (_r, u) => libraryCloud.list(u) },+ { method: "POST", path: "/api/cut-cloud/library/presign", handler: (r, u) => libraryCloud.presign(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/complete", handler: (r, u) => libraryCloud.complete(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/use", handler: (r, u) => libraryCloud.use(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/save", handler: (r, u) => libraryCloud.save(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/move", handler: (r, u) => libraryCloud.move(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/templates", handler: (r, u) => libraryCloud.saveTemplate(u, r) },+ { method: "POST", path: "/api/cut-cloud/library/templates/:id/use", handler: (r, u, p) => libraryCloud.useTemplate(u, p.id, r) },+ { method: "POST", path: "/api/cut-cloud/library/templates/:id/add", handler: (r, u, p) => libraryCloud.addToTemplate(u, p.id, r) },+ { method: "PUT", path: "/api/cut-cloud/library/templates/:id", handler: (r, u, p) => libraryCloud.renameTemplate(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/library/templates/:id", handler: (_r, u, p) => libraryCloud.removeTemplate(u, p.id) },+ { method: "POST", path: "/api/cut-cloud/library/folders", handler: (r, u) => libraryCloud.createFolder(u, r) },+ { method: "PUT", path: "/api/cut-cloud/library/folders/:id", handler: (r, u, p) => libraryCloud.renameFolder(u, p.id, r) },+ { method: "DELETE", path: "/api/cut-cloud/library/folders/:id", handler: (_r, u, p) => libraryCloud.deleteFolder(u, p.id) },+ { method: "GET", path: "/api/cut-cloud/library/media/:file", handler: (_r, u, p) => libraryCloud.serveMedia(u, p.file) },+ { method: "DELETE", path: "/api/cut-cloud/library/:id", handler: (_r, u, p) => libraryCloud.remove(u, p.id) },++ { method: "GET", path: "/api/cut-cloud/export-jobs", handler: (_r, u) => jobsCloud.exportFeed(u) },+ { method: "POST", path: "/api/cut-cloud/export", handler: (r, u) => jobsCloud.exportCreate(u, r) },+ { method: "POST", path: "/api/cut-cloud/export/presign", handler: (r, u) => jobsCloud.exportPresign(u, r) },+ { method: "GET", path: "/api/cut-cloud/export/:jobId", handler: (_r, u, p) => jobsCloud.exportStatus(u, p.jobId) },+ { method: "DELETE", path: "/api/cut-cloud/export/:jobId", handler: (_r, u, p) => jobsCloud.exportCancel(u, p.jobId) },+ { method: "GET", path: "/api/cut-cloud/export/:jobId/file", handler: (_r, u, p) => jobsCloud.exportFile(u, p.jobId) },+ { method: "GET", path: "/api/cut-cloud/jobs/:jobId", handler: (_r, u, p) => jobsCloud.status(u, p.jobId) },++ { method: "POST", path: "/api/cut-cloud/transcribe", handler: (r, u) => transcribeCloud.transcribe(u, r) },+ { method: "GET", path: "/api/cut-cloud/usage", handler: (_r, u) => usageApi.get(u) },++ // GC also runs unauthenticated from the Vercel cron — see the catch-all+ // route, which checks the x-vercel-cron header before auth. Any other+ // non-superuser caller sees a plain 404.+ {+ method: "GET",+ path: "/api/cut-cloud/gc",+ handler: async (_r, u) =>+ (await isDonkeySuperUser(u)) ? runGc() : new Response("Not found.", { status: 404 }),+ },++ // The engine's models probe reports local CLI availability; hosted Cut has+ // only the Gemini path (chat runs from the page on the user's account).+ {+ method: "GET",+ path: "/api/cut-cloud/ai/models",+ handler: () =>+ Response.json({+ providers: {+ gemini: { available: true, note: "runs on your Donkey account", installed: true },+ },+ }),+ },+];++export async function cutCloudCatchAll(req: DonkeyAuthenticatedRequest): Promise<Response> {+ const { pathname } = new URL(req.url);+ const match = matchRouteTable(CUT_CLOUD_ROUTES, req.method, pathname);+ if (!match) return new Response("Not found.", { status: 404 });+ if ("methodNotAllowed" in match) {+ return new Response("Method not allowed.", {+ status: 405,+ headers: { Allow: match.methodNotAllowed.join(", ") },+ });+ }+ const res = await match.route.handler(req, req.donkey.userId, match.params);+ // A HEAD reply carries the GET headers but no body.+ if (match.head && res.body) {+ void res.body.cancel();+ return new Response(null, { status: res.status, headers: res.headers });+ }+ return res;+}diff --git a/site/src/cut/server/cloud/transcribe.ts b/site/src/cut/server/cloud/transcribe.tsnew file mode 100644index 00000000..d46576c1--- /dev/null+++ b/site/src/cut/server/cloud/transcribe.ts@@ -0,0 +1,187 @@+// Hosted transcription: one ~90s 16 kHz mono WAV chunk in, cue-level+// timestamps out. The client renders the timeline's audible mix, chunks it,+// and stitches the results (lib/cloudTranscribe.ts); this route only turns+// one chunk of speech into cues with Gemini, metered against the user's+// inference credits like every /api/inference route.+import {+ creditErrorResponse,+ recordFailedInferenceUsage,+ recordInferenceUsage,+ requireInferenceCredits,+} from "@/lib/credits/inference";+import {+ defaultGeminiClientFactory,+ geminiApiError,+ geminiCandidateParts,+ geminiCandidates,+ geminiClientConfig,+ stringValue,+} from "@/lib/inference/adapters/gemini-client";+import { geminiModelRoles } from "@/lib/inference/gemini-models";+import { toJsonValue } from "@/lib/inference/json";+import type { JsonValue } from "@/lib/inference/providers";+import { err } from "./util";++// The client sends ~2.9MB chunks (90s of 16-bit mono PCM); anything bigger is+// not ours and would blow past inline-audio comfort anyway.+const MAX_AUDIO_BYTES = 4 * 1024 * 1024;+const ROUTE = "/api/cut-cloud/transcribe/";+const PROVIDER = "gemini";+// The registry's chat flash: multimodal, takes inline audio, priced in+// provider-pricing.ts. No dedicated STT role exists, so speech-to-text rides+// the chat model.+const MODEL = geminiModelRoles.chat;++interface WireCue {+ start: number;+ end: number;+ text: string;+}++const transcribePrompt = (locale: string) =>+ [+ "Transcribe the speech in this audio verbatim, in the language actually spoken" ++ (locale ? ` (expected: ${locale})` : "") ++ ".",+ 'Return ONLY a JSON array of cues: [{"start": <seconds>, "end": <seconds>, "text": "<words>"}].',+ "Times are seconds from the start of this audio.",+ "Keep cues short — at most 7 words each — and in spoken order.",+ "Return [] when there is no speech.",+ ].join(" ");++/** The model's cue array, parsed defensively: code fences stripped, the+ * outermost [...] recovered from surrounding prose, entries validated and+ * clamped to the chunk. Null when no JSON array can be read at all. */+function parseCues(raw: string, maxEnd: number): WireCue[] | null {+ const cleaned = raw+ .trim()+ .replace(/^```(?:json)?\s*/i, "")+ .replace(/```\s*$/, "")+ .trim();+ let parsed: unknown;+ try {+ parsed = JSON.parse(cleaned);+ } catch {+ const s = cleaned.indexOf("[");+ const e = cleaned.lastIndexOf("]");+ if (s < 0 || e <= s) return null;+ try {+ parsed = JSON.parse(cleaned.slice(s, e + 1));+ } catch {+ return null;+ }+ }+ if (!Array.isArray(parsed)) return null;+ const cues: WireCue[] = [];+ for (const item of parsed) {+ if (!item || typeof item !== "object") continue;+ const { start, end, text } = item as Record<string, unknown>;+ if (typeof start !== "number" || typeof end !== "number" || typeof text !== "string") continue;+ if (!Number.isFinite(start) || !Number.isFinite(end)) continue;+ const s = Math.max(0, Math.min(start, maxEnd));+ const e = Math.max(0, Math.min(end, maxEnd));+ const t = text.trim();+ if (!t || e <= s) continue;+ cues.push({ start: s, end: e, text: t });+ }+ return cues.sort((a, b) => a.start - b.start);+}++export const transcribeCloud = {+ async transcribe(userId: string, req: Request): Promise<Response> {+ let audio: File | null = null;+ let locale = "";+ try {+ const form = await req.formData();+ const a = form.get("audio");+ audio = a instanceof File ? a : null;+ const l = form.get("locale");+ locale = typeof l === "string" ? l.trim() : "";+ } catch {+ return err("Send multipart form data with an audio file.", 400);+ }+ if (!audio || audio.size === 0) return err("Missing audio.", 400);+ if (audio.size > MAX_AUDIO_BYTES) return err("Audio chunk too large.", 413);++ const clientConfig = geminiClientConfig(process.env);+ if (!clientConfig.configured) {+ return err("Transcription is not configured on this deployment.", 500);+ }++ const credits = await requireInferenceCredits({+ enforceModelPrice: true,+ model: MODEL,+ provider: PROVIDER,+ route: ROUTE,+ userId,+ });+ if (!credits.ok) return credits.response;++ // Seconds of 16 kHz s16 mono after the 44-byte RIFF header — the clamp+ // ceiling for cue times the model may overshoot.+ const audioSeconds = Math.max(1, (audio.size - 44) / 32000);+ const wavBase64 = Buffer.from(await audio.arrayBuffer()).toString("base64");++ let raw: unknown;+ try {+ const client = defaultGeminiClientFactory(clientConfig.options);+ raw = await client.models.generateContent({+ model: MODEL,+ contents: [+ {+ role: "user",+ parts: [+ { inlineData: { mimeType: "audio/wav", data: wavBase64 } },+ { text: transcribePrompt(locale) },+ ],+ },+ ],+ // JSON mode without a schema — constrained decoding degrades output.+ config: { responseMimeType: "application/json", temperature: 0 },+ });+ } catch (error) {+ await recordFailedInferenceUsage({+ clientId: null,+ errorCode: "provider_error",+ model: MODEL,+ provider: PROVIDER,+ requestKind: "transcribe",+ route: ROUTE,+ userId,+ });+ const credit = creditErrorResponse(error);+ if (credit) return credit;+ const mapped = geminiApiError("Transcription failed.", error);+ return err(mapped.message, mapped.statusCode ?? 502);+ }++ // The call succeeded and spent tokens; record and charge before judging+ // the payload, exactly like the /api/inference routes.+ const usage = (raw as { usageMetadata?: unknown }).usageMetadata;+ try {+ await recordInferenceUsage({+ clientId: null,+ model: MODEL,+ provider: PROVIDER,+ requestKind: "transcribe",+ route: ROUTE,+ status: "succeeded",+ usage: toJsonValue(usage ?? null),+ userId,+ });+ } catch (error) {+ const credit = creditErrorResponse(error);+ if (credit) return credit;+ throw error;+ }++ const text = geminiCandidateParts(geminiCandidates(raw as JsonValue)[0])+ .map((p) => stringValue(p.text) ?? "")+ .join("");+ const cues = parseCues(text, audioSeconds);+ if (cues === null) {+ return err("The transcription model returned an unreadable response — try again.", 502);+ }+ return Response.json({ cues });+ },+};diff --git a/site/src/cut/server/cloud/usage.ts b/site/src/cut/server/cloud/usage.tsnew file mode 100644index 00000000..e03a2279--- /dev/null+++ b/site/src/cut/server/cloud/usage.ts@@ -0,0 +1,42 @@+import type { Prisma } from "@/generated/prisma/client";+import { prisma } from "@/lib/prisma";+import { cutLimitsFor } from "./limits";++export async function usageBytes(userId: string): Promise<number> {+ const row = await prisma.cutStorageUsage.findUnique({ where: { userId } });+ return row ? Number(row.bytes) : 0;+}++/** Adjust the user's stored-bytes counter inside the caller's transaction, so+ * it moves with the CutMediaObject rows it mirrors. Clamped at zero. */+export async function addUsage(tx: Prisma.TransactionClient, userId: string, delta: number) {+ const row = await tx.cutStorageUsage.findUnique({ where: { userId } });+ const next = Math.max(0, (row ? Number(row.bytes) : 0) + Math.round(delta));+ await tx.cutStorageUsage.upsert({+ where: { userId },+ create: { userId, bytes: BigInt(next) },+ update: { bytes: BigInt(next) },+ });+}++/** 413 when `incoming` more bytes would break the account's storage quota,+ * else null. Superusers are unquotaed. */+export async function quotaCheck(userId: string, incoming: number): Promise<Response | null> {+ const limits = await cutLimitsFor(userId);+ if (limits.storageBytes === null) return null;+ const bytes = await usageBytes(userId);+ if (bytes + incoming > limits.storageBytes) {+ return Response.json(+ { error: "storage_quota_exceeded", bytes, quotaBytes: limits.storageBytes },+ { status: 413 }+ );+ }+ return null;+}++export const usageApi = {+ async get(userId: string) {+ const [bytes, limits] = await Promise.all([usageBytes(userId), cutLimitsFor(userId)]);+ return Response.json({ bytes, quotaBytes: limits.storageBytes });+ },+};diff --git a/site/src/cut/server/cloud/util.ts b/site/src/cut/server/cloud/util.tsnew file mode 100644index 00000000..edaf9ebb--- /dev/null+++ b/site/src/cut/server/cloud/util.ts@@ -0,0 +1,53 @@+import path from "node:path";+import { R2NotConfiguredError } from "./r2";++export const err = (message: string, status: number) =>+ Response.json({ error: message }, { status });++export const caught = (e: unknown, fallback: string, status = 500) =>+ e instanceof R2NotConfiguredError+ ? err(e.message, 500)+ : err(e instanceof Error ? e.message : fallback, status);++export const redirect = (url: string) =>+ new Response(null, { status: 302, headers: { Location: url } });++/** Sanitize an upload name the way the engine's saveMedia does. */+export function safeFileName(original: string): string {+ const base = path+ .basename(original)+ .replace(/[^\w.\-() ]+/g, "_")+ .slice(-80);+ if (!base || base.startsWith(".")) throw new Error("Invalid file name.");+ return base;+}++/** A URL path segment decoded and checked: no separators, no dotfiles. */+export function decodeFileParam(raw: string): string {+ const name = decodeURIComponent(raw);+ if (!name || name.includes("/") || name.includes("\\") || name.startsWith(".")) {+ throw new Error("Invalid file name.");+ }+ return name;+}++/** First variant of `base` (stem, stem-1, stem-2, …) not in `taken` — the+ * engine's uniqueName against a known name set instead of the filesystem. */+export function dedupeName(base: string, taken: ReadonlySet<string>): string {+ const ext = path.extname(base);+ const stem = base.slice(0, base.length - ext.length) || "media";+ let name = base;+ for (let n = 1; taken.has(name); n++) name = `${stem}-${n}${ext}`;+ return name;+}++const VIDEO_RE = /\.(mp4|mov|m4v|webm|mkv)$/i;+const AUDIO_RE = /\.(mp3|m4a|aac|wav|ogg|flac)$/i;+const IMAGE_RE = /\.(png|jpe?g|webp|gif|avif|bmp)$/i;++export function typeOf(fileName: string): "video" | "audio" | "image" | null {+ if (VIDEO_RE.test(fileName)) return "video";+ if (AUDIO_RE.test(fileName)) return "audio";+ if (IMAGE_RE.test(fileName)) return "image";+ return null;+}diff --git a/site/src/cut/server/cloud/wake.ts b/site/src/cut/server/cloud/wake.tsnew file mode 100644index 00000000..0db68348--- /dev/null+++ b/site/src/cut/server/cloud/wake.ts@@ -0,0 +1,15 @@+// Wake the render worker's container. Fire-and-forget: a lost wake self-heals+// because the client keeps polling its queued job, and every such poll wakes+// again. The URL is per-deployment cross-service wiring (the Worker's+// workers.dev address), so it rides env beside the secret; with neither set+// (local dev), the dev worker is run by hand and polls on its own.+const wakeUrl = () => process.env.CUT_RENDER_WAKE_URL;++export function wakeRenderWorker(): void {+ const url = wakeUrl();+ if (!url) return;+ void fetch(url, {+ method: "POST",+ headers: { authorization: `Bearer ${process.env.CUT_RENDER_WAKE_SECRET ?? ""}` },+ }).catch(() => {});+}diff --git a/site/vercel.json b/site/vercel.jsonnew file mode 100644index 00000000..f4d85865--- /dev/null+++ b/site/vercel.json@@ -0,0 +1,3 @@+{+ "crons": [{ "path": "/api/cut-cloud/gc", "schedule": "0 4 * * *" }]+}