diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e82ae6f4d5..96662e736d8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1666,3 +1666,43 @@ jobs: # - name: Print rows in the user table # if: always() # run: spacetime sql quickstart-chat "SELECT * FROM user" + + typescript-submodules: + needs: [merge_queue_noop, upload-build-artifacts-linux] + if: ${{ needs.merge_queue_noop.outputs.skip != 'true' }} + name: TypeScript - Submodules + runs-on: spacetimedb-new-runner-2 + env: + ARTIFACT_SUFFIX: linux + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + + - uses: ./.github/actions/setup-pnpm + with: + run_install: true + + - name: Build TypeScript SDK + run: pnpm --dir crates/bindings-typescript run build + + - *set-cargo-target-dir + - *download-build-artifacts + - *extract-build-artifacts + + - name: Use the workspace SpacetimeDB toolchain + run: | + ln -sf spacetimedb-cli "$CARGO_TARGET_DIR/release/spacetime" + echo "$CARGO_TARGET_DIR/release" >> "$GITHUB_PATH" + + - name: Check submodules + run: | + pnpm -r -F "./spacetime-*-ts/**" run typecheck + pnpm -r -F "./spacetime-*-ts/**" run test + + - name: Build submodule packages and examples + run: pnpm -r -F "./spacetime-*-ts/**" run build diff --git a/.gitignore b/.gitignore index 1f3b49ecd2d..4e591eb8d48 100644 --- a/.gitignore +++ b/.gitignore @@ -205,6 +205,14 @@ __pycache__/ ## JetBrains .idea/ +# TypeScript submodule development outputs +spacetime-*-ts/example/.stdb-server-token +spacetime-*-ts/example/public/app.js +spacetime-*-ts/example/public/app.js.map +spacetime-*-ts/example/public/app.css +spacetime-*-ts/example/public/app.css.map +spacetime-*-ts/ts-codegen/ + /protobuf cs-src/ crates/bench/spacetime.svg diff --git a/.prettierignore b/.prettierignore index 41800b56b39..63e9880376a 100644 --- a/.prettierignore +++ b/.prettierignore @@ -4,3 +4,8 @@ dist target .github coverage +**/public/app.js +**/public/app.js.map +**/public/app.css +**/public/app.css.map +**/src/module_bindings/** diff --git a/eslint.config.js b/eslint.config.js index ffe5c709e54..302384c32a2 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -20,6 +20,9 @@ export default tseslint.config( '**/dist/**', '**/build/**', '**/coverage/**', + '**/public/app.js', + '**/src/module_bindings/**', + '**/ts-codegen/**', '**/templates/angular-ts/.angular/**', ], }, @@ -62,6 +65,7 @@ export default tseslint.config( './tsconfig.json', './crates/bindings-typescript/tsconfig.json', './crates/bindings-typescript/test-app/tsconfig.json', + './spacetime-submodule-shared-ts/tsconfig.json', './templates/react-ts/tsconfig.json', './templates/chat-react-ts/tsconfig.json', './templates/money-exchange-react-ts/tsconfig.json', @@ -118,6 +122,19 @@ export default tseslint.config( ], }, }, + { + files: ['spacetime-*-ts/**/example/public/ui.js'], + languageOptions: { + sourceType: 'script', + globals: globals.browser, + }, + }, + { + files: ['spacetime-*-ts/**/*.{ts,tsx}'], + rules: { + '@typescript-eslint/no-explicit-any': 'error', + }, + }, { files: ['templates/angular-ts/src/**/*.ts'], rules: { diff --git a/package.json b/package.json index a97c459e51c..eee6d27f423 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ }, "type": "module", "scripts": { - "run-all": "pnpm -r -F ./crates/bindings-typescript -F ./crates/bindings-typescript/examples/quickstart-chat -F ./crates/bindings-typescript/test-app -F ./docs -F \"./templates/**\" run", + "run-all": "pnpm -r -F ./crates/bindings-typescript -F ./crates/bindings-typescript/test-app -F ./docs -F \"./templates/**\" -F \"./spacetime-*-ts/**\" run", "format": "pnpm run-all format && prettier eslint.config.js --write", "lint": "pnpm run-all lint && prettier eslint.config.js --check", "build": "pnpm run-all build", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5ed3e919ac8..2ad8187bffa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -49,7 +49,7 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.6.3) vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) codex-plugin/scripts: devDependencies: @@ -134,7 +134,7 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.9.3) '@vitest/coverage-v8': specifier: ^3.2.4 - version: 3.2.4(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 3.2.4(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) brotli-size-cli: specifier: ^1.0.0 version: 1.0.0 @@ -158,7 +158,7 @@ importers: version: 10.9.2(@types/node@22.18.0)(typescript@5.9.3) tsup: specifier: ^8.1.0 - version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.2) + version: 8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(typescript@5.9.3)(yaml@2.8.2) typescript: specifier: ^5.9.3 version: 5.9.3 @@ -167,10 +167,10 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.9.3) vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vitest: specifier: ^3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) crates/bindings-typescript/case-conversion-test-client: dependencies: @@ -205,13 +205,13 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^4.3.1 - version: 4.7.0(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 4.7.0(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) typescript: specifier: ^5.2.2 version: 5.9.2 vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) docs: dependencies: @@ -340,6 +340,258 @@ importers: specifier: workspace:^ version: link:../../crates/bindings-typescript + spacetime-cron-ts: + dependencies: + cron-parser: + specifier: 5.5.0 + version: 5.5.0 + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/example: + dependencies: + '@spacetimedb/submodule-shared': + specifier: workspace:* + version: link:../../spacetime-submodule-shared-ts + dotenv: + specifier: ^16.4.7 + version: 16.6.1 + express: + specifier: ^4.21.2 + version: 4.21.2 + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/express': + specifier: ^4.17.21 + version: 4.17.23 + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + esbuild: + specifier: ^0.28.0 + version: 0.28.2 + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/example/spacetimedb: + dependencies: + '@spacetimedb/cron': + specifier: workspace:* + version: link:../.. + spacetimedb: + specifier: workspace:* + version: link:../../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-cron-ts/spacetimedb: + dependencies: + '@spacetimedb/cron': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-crypto-ts: + dependencies: + '@noble/hashes': + specifier: ^2.2.0 + version: 2.3.0 + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/example: + dependencies: + '@spacetimedb/submodule-shared': + specifier: workspace:* + version: link:../../spacetime-submodule-shared-ts + dotenv: + specifier: ^16.4.7 + version: 16.6.1 + express: + specifier: ^4.21.2 + version: 4.21.2 + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/express': + specifier: ^4.17.21 + version: 4.17.23 + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + esbuild: + specifier: ^0.28.0 + version: 0.28.2 + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/example/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:../.. + spacetimedb: + specifier: workspace:* + version: link:../../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-rate-limit-ts/spacetimedb: + dependencies: + '@spacetimedb/rate-limit': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-retry-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + prettier: + specifier: ^3.3.3 + version: 3.6.2 + spacetimedb: + specifier: workspace:* + version: link:../crates/bindings-typescript + tsx: + specifier: ^4.21.0 + version: 4.23.12 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-retry-ts/spacetimedb: + dependencies: + '@spacetimedb/retry': + specifier: workspace:* + version: link:.. + spacetimedb: + specifier: workspace:* + version: link:../../crates/bindings-typescript + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + typescript: + specifier: ^5.9.3 + version: 5.9.3 + + spacetime-submodule-shared-ts: + devDependencies: + '@types/node': + specifier: ^22.10.2 + version: 22.18.0 + eslint: + specifier: ^9.17.0 + version: 9.33.0(jiti@2.6.1) + jsdom: + specifier: ^26.1.0 + version: 26.1.0 + prettier: + specifier: ^3.3.3 + version: 3.6.2 + typescript: + specifier: ~5.6.2 + version: 5.6.3 + vitest: + specifier: ^3.2.4 + version: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + templates/angular-ts: dependencies: '@angular/common': @@ -366,10 +618,10 @@ importers: devDependencies: '@angular/build': specifier: ^21.2.12 - version: 21.2.13(@angular/compiler-cli@21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3))(@angular/compiler@21.2.15)(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(@angular/platform-browser@21.2.15(@angular/common@21.2.15(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2)))(@types/node@24.3.0)(chokidar@5.0.0)(jiti@2.6.1)(postcss@8.5.6)(terser@5.43.1)(tslib@2.8.1)(tsx@4.21.0)(typescript@5.9.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(yaml@2.8.2) + version: 21.2.13(@angular/compiler-cli@21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3))(@angular/compiler@21.2.15)(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(@angular/platform-browser@21.2.15(@angular/common@21.2.15(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2)))(@types/node@25.9.5)(chokidar@5.0.0)(jiti@2.6.1)(postcss@8.5.6)(terser@5.43.1)(tslib@2.8.1)(tsx@4.23.12)(typescript@5.9.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(yaml@2.8.2) '@angular/cli': specifier: ^21.2.12 - version: 21.2.13(@types/node@24.3.0)(chokidar@5.0.0) + version: 21.2.13(@types/node@25.9.5)(chokidar@5.0.0) '@angular/compiler-cli': specifier: ^21.2.12 version: 21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3) @@ -404,7 +656,7 @@ importers: version: 5.6.3 vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/bun-ts: dependencies: @@ -414,7 +666,7 @@ importers: devDependencies: '@types/bun': specifier: latest - version: 1.3.14 + version: 1.4.1 bun: specifier: ^1.3.2 version: 1.3.9 @@ -454,7 +706,7 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -481,10 +733,10 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.6.3) vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vitest: specifier: 3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@24.3.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.5)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/chat-react-ts/spacetimedb: dependencies: @@ -519,7 +771,7 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -543,7 +795,7 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.6.3) vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/keynote-2: dependencies: @@ -641,13 +893,13 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/money-exchange-react-ts: dependencies: @@ -681,7 +933,7 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) eslint: specifier: ^9.17.0 version: 9.33.0(jiti@2.6.1) @@ -708,16 +960,16 @@ importers: version: 8.40.0(eslint@9.33.0(jiti@2.6.1))(typescript@5.6.3) vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vitest: specifier: 3.2.4 - version: 3.2.4(@types/debug@4.1.12)(@types/node@24.3.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 3.2.4(@types/debug@4.1.12)(@types/node@25.9.5)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/nuxt-ts: dependencies: nuxt: specifier: ~3.16.0 - version: 3.16.2(@parcel/watcher@2.5.6)(@types/node@24.3.0)(better-sqlite3@12.6.2)(cac@6.7.14)(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)))(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13)(eslint@9.33.0(jiti@2.6.1))(ioredis@5.9.2)(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(typescript@5.6.3)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3))(yaml@2.8.2) + version: 3.16.2(@parcel/watcher@2.5.6)(@types/node@25.9.5)(better-sqlite3@12.6.2)(cac@6.7.14)(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)))(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13)(eslint@9.33.0(jiti@2.6.1))(ioredis@5.9.2)(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(typescript@5.6.3)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3))(yaml@2.8.2) spacetimedb: specifier: workspace:* version: link:../../crates/bindings-typescript @@ -749,13 +1001,13 @@ importers: version: 18.3.7(@types/react@18.3.23) '@vitejs/plugin-react': specifier: ^5.0.2 - version: 5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/remix-ts: dependencies: @@ -783,7 +1035,7 @@ importers: devDependencies: '@remix-run/dev': specifier: ^2.16.0 - version: 2.17.4(@remix-run/react@2.17.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@5.6.3))(@remix-run/serve@2.17.4(typescript@5.6.3))(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3))(tsx@4.21.0)(typescript@5.6.3)(vite@5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1))(yaml@2.8.2) + version: 2.17.4(@remix-run/react@2.17.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@5.6.3))(@remix-run/serve@2.17.4(typescript@5.6.3))(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3))(tsx@4.23.12)(typescript@5.6.3)(vite@5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1))(yaml@2.8.2) '@types/react': specifier: ^18.3.18 version: 18.3.23 @@ -795,7 +1047,7 @@ importers: version: 5.6.3 vite: specifier: ^5.4.0 - version: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) + version: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) templates/solid-ts: dependencies: @@ -811,10 +1063,10 @@ importers: version: 5.6.3 vite: specifier: ^7.1.5 - version: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vite-plugin-solid: specifier: ^2.11.8 - version: 2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) templates/svelte-ts: dependencies: @@ -824,7 +1076,7 @@ importers: devDependencies: '@sveltejs/vite-plugin-svelte': specifier: ^5.1.1 - version: 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) svelte: specifier: ^5.0.0 version: 5.46.4 @@ -836,7 +1088,7 @@ importers: version: 5.6.3 vite: specifier: ^6.4.1 - version: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) templates/tanstack-ts: dependencies: @@ -857,7 +1109,7 @@ importers: version: 1.162.8(@tanstack/query-core@5.90.19)(@tanstack/react-query@5.90.19(react@19.2.4))(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(@tanstack/router-core@1.162.6)(react-dom@19.2.4(react@19.2.4))(react@19.2.4) '@tanstack/react-start': specifier: ^1.162.0 - version: 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0) + version: 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0) react: specifier: ^19.0.0 version: 19.2.4 @@ -879,16 +1131,16 @@ importers: version: 19.2.3(@types/react@19.1.13) '@vitejs/plugin-react': specifier: ^4.3.0 - version: 4.7.0(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 4.7.0(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) typescript: specifier: ^5.7.2 version: 5.9.3 vite: specifier: ^7.1.5 - version: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(typescript@5.9.3)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + version: 5.1.4(typescript@5.9.3)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) templates/vue-ts: dependencies: @@ -901,13 +1153,13 @@ importers: devDependencies: '@vitejs/plugin-vue': specifier: ^5.2.4 - version: 5.2.4(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + version: 5.2.4(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) typescript: specifier: ~5.6.2 version: 5.6.3 vite: specifier: ^6.4.1 - version: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + version: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vue-tsc: specifier: ^2.2.0 version: 2.2.12(typescript@5.6.3) @@ -2559,14 +2811,14 @@ packages: cpu: [ppc64] os: [aix] - '@esbuild/aix-ppc64@0.27.2': - resolution: {integrity: sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==} + '@esbuild/aix-ppc64@0.27.3': + resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] - '@esbuild/aix-ppc64@0.27.3': - resolution: {integrity: sha512-9fJMTNFTWZMh5qwrBItuziu834eOCUcEqymSH7pY+zoMVEZg3gcPuBNxH1EvfVYe9h0x/Ptw8KBzv7qxb7l8dg==} + '@esbuild/aix-ppc64@0.28.2': + resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==} engines: {node: '>=18'} cpu: [ppc64] os: [aix] @@ -2601,14 +2853,14 @@ packages: cpu: [arm64] os: [android] - '@esbuild/android-arm64@0.27.2': - resolution: {integrity: sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==} + '@esbuild/android-arm64@0.27.3': + resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==} engines: {node: '>=18'} cpu: [arm64] os: [android] - '@esbuild/android-arm64@0.27.3': - resolution: {integrity: sha512-YdghPYUmj/FX2SYKJ0OZxf+iaKgMsKHVPF1MAq/P8WirnSpCStzKJFjOjzsW0QQ7oIAiccHdcqjbHmJxRb/dmg==} + '@esbuild/android-arm64@0.28.2': + resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==} engines: {node: '>=18'} cpu: [arm64] os: [android] @@ -2643,14 +2895,14 @@ packages: cpu: [arm] os: [android] - '@esbuild/android-arm@0.27.2': - resolution: {integrity: sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==} + '@esbuild/android-arm@0.27.3': + resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==} engines: {node: '>=18'} cpu: [arm] os: [android] - '@esbuild/android-arm@0.27.3': - resolution: {integrity: sha512-i5D1hPY7GIQmXlXhs2w8AWHhenb00+GxjxRncS2ZM7YNVGNfaMxgzSGuO8o8SJzRc/oZwU2bcScvVERk03QhzA==} + '@esbuild/android-arm@0.28.2': + resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==} engines: {node: '>=18'} cpu: [arm] os: [android] @@ -2685,14 +2937,14 @@ packages: cpu: [x64] os: [android] - '@esbuild/android-x64@0.27.2': - resolution: {integrity: sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==} + '@esbuild/android-x64@0.27.3': + resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==} engines: {node: '>=18'} cpu: [x64] os: [android] - '@esbuild/android-x64@0.27.3': - resolution: {integrity: sha512-IN/0BNTkHtk8lkOM8JWAYFg4ORxBkZQf9zXiEOfERX/CzxW3Vg1ewAhU7QSWQpVIzTW+b8Xy+lGzdYXV6UZObQ==} + '@esbuild/android-x64@0.28.2': + resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==} engines: {node: '>=18'} cpu: [x64] os: [android] @@ -2727,14 +2979,14 @@ packages: cpu: [arm64] os: [darwin] - '@esbuild/darwin-arm64@0.27.2': - resolution: {integrity: sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==} + '@esbuild/darwin-arm64@0.27.3': + resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] - '@esbuild/darwin-arm64@0.27.3': - resolution: {integrity: sha512-Re491k7ByTVRy0t3EKWajdLIr0gz2kKKfzafkth4Q8A5n1xTHrkqZgLLjFEHVD+AXdUGgQMq+Godfq45mGpCKg==} + '@esbuild/darwin-arm64@0.28.2': + resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==} engines: {node: '>=18'} cpu: [arm64] os: [darwin] @@ -2769,14 +3021,14 @@ packages: cpu: [x64] os: [darwin] - '@esbuild/darwin-x64@0.27.2': - resolution: {integrity: sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==} + '@esbuild/darwin-x64@0.27.3': + resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==} engines: {node: '>=18'} cpu: [x64] os: [darwin] - '@esbuild/darwin-x64@0.27.3': - resolution: {integrity: sha512-vHk/hA7/1AckjGzRqi6wbo+jaShzRowYip6rt6q7VYEDX4LEy1pZfDpdxCBnGtl+A5zq8iXDcyuxwtv3hNtHFg==} + '@esbuild/darwin-x64@0.28.2': + resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==} engines: {node: '>=18'} cpu: [x64] os: [darwin] @@ -2811,14 +3063,14 @@ packages: cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-arm64@0.27.2': - resolution: {integrity: sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==} + '@esbuild/freebsd-arm64@0.27.3': + resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] - '@esbuild/freebsd-arm64@0.27.3': - resolution: {integrity: sha512-ipTYM2fjt3kQAYOvo6vcxJx3nBYAzPjgTCk7QEgZG8AUO3ydUhvelmhrbOheMnGOlaSFUoHXB6un+A7q4ygY9w==} + '@esbuild/freebsd-arm64@0.28.2': + resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==} engines: {node: '>=18'} cpu: [arm64] os: [freebsd] @@ -2853,14 +3105,14 @@ packages: cpu: [x64] os: [freebsd] - '@esbuild/freebsd-x64@0.27.2': - resolution: {integrity: sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==} + '@esbuild/freebsd-x64@0.27.3': + resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] - '@esbuild/freebsd-x64@0.27.3': - resolution: {integrity: sha512-dDk0X87T7mI6U3K9VjWtHOXqwAMJBNN2r7bejDsc+j03SEjtD9HrOl8gVFByeM0aJksoUuUVU9TBaZa2rgj0oA==} + '@esbuild/freebsd-x64@0.28.2': + resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==} engines: {node: '>=18'} cpu: [x64] os: [freebsd] @@ -2895,14 +3147,14 @@ packages: cpu: [arm64] os: [linux] - '@esbuild/linux-arm64@0.27.2': - resolution: {integrity: sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==} + '@esbuild/linux-arm64@0.27.3': + resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==} engines: {node: '>=18'} cpu: [arm64] os: [linux] - '@esbuild/linux-arm64@0.27.3': - resolution: {integrity: sha512-sZOuFz/xWnZ4KH3YfFrKCf1WyPZHakVzTiqji3WDc0BCl2kBwiJLCXpzLzUBLgmp4veFZdvN5ChW4Eq/8Fc2Fg==} + '@esbuild/linux-arm64@0.28.2': + resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==} engines: {node: '>=18'} cpu: [arm64] os: [linux] @@ -2937,14 +3189,14 @@ packages: cpu: [arm] os: [linux] - '@esbuild/linux-arm@0.27.2': - resolution: {integrity: sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==} + '@esbuild/linux-arm@0.27.3': + resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==} engines: {node: '>=18'} cpu: [arm] os: [linux] - '@esbuild/linux-arm@0.27.3': - resolution: {integrity: sha512-s6nPv2QkSupJwLYyfS+gwdirm0ukyTFNl3KTgZEAiJDd+iHZcbTPPcWCcRYH+WlNbwChgH2QkE9NSlNrMT8Gfw==} + '@esbuild/linux-arm@0.28.2': + resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==} engines: {node: '>=18'} cpu: [arm] os: [linux] @@ -2979,14 +3231,14 @@ packages: cpu: [ia32] os: [linux] - '@esbuild/linux-ia32@0.27.2': - resolution: {integrity: sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==} + '@esbuild/linux-ia32@0.27.3': + resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==} engines: {node: '>=18'} cpu: [ia32] os: [linux] - '@esbuild/linux-ia32@0.27.3': - resolution: {integrity: sha512-yGlQYjdxtLdh0a3jHjuwOrxQjOZYD/C9PfdbgJJF3TIZWnm/tMd/RcNiLngiu4iwcBAOezdnSLAwQDPqTmtTYg==} + '@esbuild/linux-ia32@0.28.2': + resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==} engines: {node: '>=18'} cpu: [ia32] os: [linux] @@ -3021,14 +3273,14 @@ packages: cpu: [loong64] os: [linux] - '@esbuild/linux-loong64@0.27.2': - resolution: {integrity: sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==} + '@esbuild/linux-loong64@0.27.3': + resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==} engines: {node: '>=18'} cpu: [loong64] os: [linux] - '@esbuild/linux-loong64@0.27.3': - resolution: {integrity: sha512-WO60Sn8ly3gtzhyjATDgieJNet/KqsDlX5nRC5Y3oTFcS1l0KWba+SEa9Ja1GfDqSF1z6hif/SkpQJbL63cgOA==} + '@esbuild/linux-loong64@0.28.2': + resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==} engines: {node: '>=18'} cpu: [loong64] os: [linux] @@ -3063,14 +3315,14 @@ packages: cpu: [mips64el] os: [linux] - '@esbuild/linux-mips64el@0.27.2': - resolution: {integrity: sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==} + '@esbuild/linux-mips64el@0.27.3': + resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] - '@esbuild/linux-mips64el@0.27.3': - resolution: {integrity: sha512-APsymYA6sGcZ4pD6k+UxbDjOFSvPWyZhjaiPyl/f79xKxwTnrn5QUnXR5prvetuaSMsb4jgeHewIDCIWljrSxw==} + '@esbuild/linux-mips64el@0.28.2': + resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==} engines: {node: '>=18'} cpu: [mips64el] os: [linux] @@ -3105,14 +3357,14 @@ packages: cpu: [ppc64] os: [linux] - '@esbuild/linux-ppc64@0.27.2': - resolution: {integrity: sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==} + '@esbuild/linux-ppc64@0.27.3': + resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] - '@esbuild/linux-ppc64@0.27.3': - resolution: {integrity: sha512-eizBnTeBefojtDb9nSh4vvVQ3V9Qf9Df01PfawPcRzJH4gFSgrObw+LveUyDoKU3kxi5+9RJTCWlj4FjYXVPEA==} + '@esbuild/linux-ppc64@0.28.2': + resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==} engines: {node: '>=18'} cpu: [ppc64] os: [linux] @@ -3147,14 +3399,14 @@ packages: cpu: [riscv64] os: [linux] - '@esbuild/linux-riscv64@0.27.2': - resolution: {integrity: sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==} + '@esbuild/linux-riscv64@0.27.3': + resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] - '@esbuild/linux-riscv64@0.27.3': - resolution: {integrity: sha512-3Emwh0r5wmfm3ssTWRQSyVhbOHvqegUDRd0WhmXKX2mkHJe1SFCMJhagUleMq+Uci34wLSipf8Lagt4LlpRFWQ==} + '@esbuild/linux-riscv64@0.28.2': + resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==} engines: {node: '>=18'} cpu: [riscv64] os: [linux] @@ -3189,14 +3441,14 @@ packages: cpu: [s390x] os: [linux] - '@esbuild/linux-s390x@0.27.2': - resolution: {integrity: sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==} + '@esbuild/linux-s390x@0.27.3': + resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==} engines: {node: '>=18'} cpu: [s390x] os: [linux] - '@esbuild/linux-s390x@0.27.3': - resolution: {integrity: sha512-pBHUx9LzXWBc7MFIEEL0yD/ZVtNgLytvx60gES28GcWMqil8ElCYR4kvbV2BDqsHOvVDRrOxGySBM9Fcv744hw==} + '@esbuild/linux-s390x@0.28.2': + resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==} engines: {node: '>=18'} cpu: [s390x] os: [linux] @@ -3231,14 +3483,14 @@ packages: cpu: [x64] os: [linux] - '@esbuild/linux-x64@0.27.2': - resolution: {integrity: sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==} + '@esbuild/linux-x64@0.27.3': + resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==} engines: {node: '>=18'} cpu: [x64] os: [linux] - '@esbuild/linux-x64@0.27.3': - resolution: {integrity: sha512-Czi8yzXUWIQYAtL/2y6vogER8pvcsOsk5cpwL4Gk5nJqH5UZiVByIY8Eorm5R13gq+DQKYg0+JyQoytLQas4dA==} + '@esbuild/linux-x64@0.28.2': + resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==} engines: {node: '>=18'} cpu: [x64] os: [linux] @@ -3261,14 +3513,14 @@ packages: cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-arm64@0.27.2': - resolution: {integrity: sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==} + '@esbuild/netbsd-arm64@0.27.3': + resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] - '@esbuild/netbsd-arm64@0.27.3': - resolution: {integrity: sha512-sDpk0RgmTCR/5HguIZa9n9u+HVKf40fbEUt+iTzSnCaGvY9kFP0YKBWZtJaraonFnqef5SlJ8/TiPAxzyS+UoA==} + '@esbuild/netbsd-arm64@0.28.2': + resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==} engines: {node: '>=18'} cpu: [arm64] os: [netbsd] @@ -3303,14 +3555,14 @@ packages: cpu: [x64] os: [netbsd] - '@esbuild/netbsd-x64@0.27.2': - resolution: {integrity: sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==} + '@esbuild/netbsd-x64@0.27.3': + resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] - '@esbuild/netbsd-x64@0.27.3': - resolution: {integrity: sha512-P14lFKJl/DdaE00LItAukUdZO5iqNH7+PjoBm+fLQjtxfcfFE20Xf5CrLsmZdq5LFFZzb5JMZ9grUwvtVYzjiA==} + '@esbuild/netbsd-x64@0.28.2': + resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==} engines: {node: '>=18'} cpu: [x64] os: [netbsd] @@ -3333,14 +3585,14 @@ packages: cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-arm64@0.27.2': - resolution: {integrity: sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==} + '@esbuild/openbsd-arm64@0.27.3': + resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] - '@esbuild/openbsd-arm64@0.27.3': - resolution: {integrity: sha512-AIcMP77AvirGbRl/UZFTq5hjXK+2wC7qFRGoHSDrZ5v5b8DK/GYpXW3CPRL53NkvDqb9D+alBiC/dV0Fb7eJcw==} + '@esbuild/openbsd-arm64@0.28.2': + resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==} engines: {node: '>=18'} cpu: [arm64] os: [openbsd] @@ -3375,14 +3627,14 @@ packages: cpu: [x64] os: [openbsd] - '@esbuild/openbsd-x64@0.27.2': - resolution: {integrity: sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==} + '@esbuild/openbsd-x64@0.27.3': + resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] - '@esbuild/openbsd-x64@0.27.3': - resolution: {integrity: sha512-DnW2sRrBzA+YnE70LKqnM3P+z8vehfJWHXECbwBmH/CU51z6FiqTQTHFenPlHmo3a8UgpLyH3PT+87OViOh1AQ==} + '@esbuild/openbsd-x64@0.28.2': + resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==} engines: {node: '>=18'} cpu: [x64] os: [openbsd] @@ -3399,14 +3651,14 @@ packages: cpu: [arm64] os: [openharmony] - '@esbuild/openharmony-arm64@0.27.2': - resolution: {integrity: sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==} + '@esbuild/openharmony-arm64@0.27.3': + resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] - '@esbuild/openharmony-arm64@0.27.3': - resolution: {integrity: sha512-NinAEgr/etERPTsZJ7aEZQvvg/A6IsZG/LgZy+81wON2huV7SrK3e63dU0XhyZP4RKGyTm7aOgmQk0bGp0fy2g==} + '@esbuild/openharmony-arm64@0.28.2': + resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==} engines: {node: '>=18'} cpu: [arm64] os: [openharmony] @@ -3441,14 +3693,14 @@ packages: cpu: [x64] os: [sunos] - '@esbuild/sunos-x64@0.27.2': - resolution: {integrity: sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==} + '@esbuild/sunos-x64@0.27.3': + resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==} engines: {node: '>=18'} cpu: [x64] os: [sunos] - '@esbuild/sunos-x64@0.27.3': - resolution: {integrity: sha512-PanZ+nEz+eWoBJ8/f8HKxTTD172SKwdXebZ0ndd953gt1HRBbhMsaNqjTyYLGLPdoWHy4zLU7bDVJztF5f3BHA==} + '@esbuild/sunos-x64@0.28.2': + resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==} engines: {node: '>=18'} cpu: [x64] os: [sunos] @@ -3483,14 +3735,14 @@ packages: cpu: [arm64] os: [win32] - '@esbuild/win32-arm64@0.27.2': - resolution: {integrity: sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==} + '@esbuild/win32-arm64@0.27.3': + resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==} engines: {node: '>=18'} cpu: [arm64] os: [win32] - '@esbuild/win32-arm64@0.27.3': - resolution: {integrity: sha512-B2t59lWWYrbRDw/tjiWOuzSsFh1Y/E95ofKz7rIVYSQkUYBjfSgf6oeYPNWHToFRr2zx52JKApIcAS/D5TUBnA==} + '@esbuild/win32-arm64@0.28.2': + resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==} engines: {node: '>=18'} cpu: [arm64] os: [win32] @@ -3525,14 +3777,14 @@ packages: cpu: [ia32] os: [win32] - '@esbuild/win32-ia32@0.27.2': - resolution: {integrity: sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==} + '@esbuild/win32-ia32@0.27.3': + resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==} engines: {node: '>=18'} cpu: [ia32] os: [win32] - '@esbuild/win32-ia32@0.27.3': - resolution: {integrity: sha512-QLKSFeXNS8+tHW7tZpMtjlNb7HKau0QDpwm49u0vUp9y1WOF+PEzkU84y9GqYaAVW8aH8f3GcBck26jh54cX4Q==} + '@esbuild/win32-ia32@0.28.2': + resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==} engines: {node: '>=18'} cpu: [ia32] os: [win32] @@ -3567,14 +3819,14 @@ packages: cpu: [x64] os: [win32] - '@esbuild/win32-x64@0.27.2': - resolution: {integrity: sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==} + '@esbuild/win32-x64@0.27.3': + resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==} engines: {node: '>=18'} cpu: [x64] os: [win32] - '@esbuild/win32-x64@0.27.3': - resolution: {integrity: sha512-4uJGhsxuptu3OcpVAzli+/gWusVGwZZHTlS63hh++ehExkVT8SgiEf7/uC/PclrPPkLhZqGgCTjd0VWLo6xMqA==} + '@esbuild/win32-x64@0.28.2': + resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==} engines: {node: '>=18'} cpu: [x64] os: [win32] @@ -4144,49 +4396,42 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] - libc: [glibc] '@napi-rs/nice-linux-arm64-musl@1.1.1': resolution: {integrity: sha512-+2Rzdb3nTIYZ0YJF43qf2twhqOCkiSrHx2Pg6DJaCPYhhaxbLcdlV8hCRMHghQ+EtZQWGNcS2xF4KxBhSGeutg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] - libc: [musl] '@napi-rs/nice-linux-ppc64-gnu@1.1.1': resolution: {integrity: sha512-4FS8oc0GeHpwvv4tKciKkw3Y4jKsL7FRhaOeiPei0X9T4Jd619wHNe4xCLmN2EMgZoeGg+Q7GY7BsvwKpL22Tg==} engines: {node: '>= 10'} cpu: [ppc64] os: [linux] - libc: [glibc] '@napi-rs/nice-linux-riscv64-gnu@1.1.1': resolution: {integrity: sha512-HU0nw9uD4FO/oGCCk409tCi5IzIZpH2agE6nN4fqpwVlCn5BOq0MS1dXGjXaG17JaAvrlpV5ZeyZwSon10XOXw==} engines: {node: '>= 10'} cpu: [riscv64] os: [linux] - libc: [glibc] '@napi-rs/nice-linux-s390x-gnu@1.1.1': resolution: {integrity: sha512-2YqKJWWl24EwrX0DzCQgPLKQBxYDdBxOHot1KWEq7aY2uYeX+Uvtv4I8xFVVygJDgf6/92h9N3Y43WPx8+PAgQ==} engines: {node: '>= 10'} cpu: [s390x] os: [linux] - libc: [glibc] '@napi-rs/nice-linux-x64-gnu@1.1.1': resolution: {integrity: sha512-/gaNz3R92t+dcrfCw/96pDopcmec7oCcAQ3l/M+Zxr82KT4DljD37CpgrnXV+pJC263JkW572pdbP3hP+KjcIg==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [glibc] '@napi-rs/nice-linux-x64-musl@1.1.1': resolution: {integrity: sha512-xScCGnyj/oppsNPMnevsBe3pvNaoK7FGvMjT35riz9YdhB2WtTG47ZlbxtOLpjeO9SqqQ2J2igCmz6IJOD5JYw==} engines: {node: '>= 10'} cpu: [x64] os: [linux] - libc: [musl] '@napi-rs/nice-openharmony-arm64@1.1.1': resolution: {integrity: sha512-6uJPRVwVCLDeoOaNyeiW0gp2kFIM4r7PL2MczdZQHkFi9gVlgm+Vn+V6nTWRcu856mJ2WjYJiumEajfSm7arPQ==} @@ -4222,6 +4467,10 @@ packages: '@napi-rs/wasm-runtime@1.1.1': resolution: {integrity: sha512-p64ah1M1ld8xjWv3qbvFwHiFVWrq1yFvV4f7w+mzaqiR4IlSgkqhcRdHwsGgomwzBH51sRY4NEowLxnaBjcW/A==} + '@noble/hashes@2.3.0': + resolution: {integrity: sha512-oN+QwyX7VSHotibwubG3kpzbwKrfnyR6OOO+3Nk/53ADL7FmgHHz4TgrbaYKvvOw09u6QTx0oiH1cNCIOuN0CQ==} + engines: {node: '>= 20.19.0'} + '@node-rs/jieba-android-arm-eabi@1.10.4': resolution: {integrity: sha512-MhyvW5N3Fwcp385d0rxbCWH42kqDBatQTyP8XbnYbju2+0BO/eTeCCLYj7Agws4pwxn2LtdldXRSKavT7WdzNA==} engines: {node: '>= 10'} @@ -4660,42 +4909,36 @@ packages: engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm-musl@2.5.6': resolution: {integrity: sha512-Ve3gUCG57nuUUSyjBq/MAM0CzArtuIOxsBdQ+ftz6ho8n7s1i9E1Nmk/xmP323r2YL0SONs1EuwqBp2u1k5fxg==} engines: {node: '>= 10.0.0'} cpu: [arm] os: [linux] - libc: [musl] '@parcel/watcher-linux-arm64-glibc@2.5.6': resolution: {integrity: sha512-f2g/DT3NhGPdBmMWYoxixqYr3v/UXcmLOYy16Bx0TM20Tchduwr4EaCbmxh1321TABqPGDpS8D/ggOTaljijOA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-arm64-musl@2.5.6': resolution: {integrity: sha512-qb6naMDGlbCwdhLj6hgoVKJl2odL34z2sqkC7Z6kzir8b5W65WYDpLB6R06KabvZdgoHI/zxke4b3zR0wAbDTA==} engines: {node: '>= 10.0.0'} cpu: [arm64] os: [linux] - libc: [musl] '@parcel/watcher-linux-x64-glibc@2.5.6': resolution: {integrity: sha512-kbT5wvNQlx7NaGjzPFu8nVIW1rWqV780O7ZtkjuWaPUgpv2NMFpjYERVi0UYj1msZNyCzGlaCWEtzc+exjMGbQ==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [glibc] '@parcel/watcher-linux-x64-musl@2.5.6': resolution: {integrity: sha512-1JRFeC+h7RdXwldHzTsmdtYR/Ku8SylLgTU/reMuqdVD7CtLwf0VR1FqeprZ0eHQkO0vqsbvFLXUmYm/uNKJBg==} engines: {node: '>= 10.0.0'} cpu: [x64] os: [linux] - libc: [musl] '@parcel/watcher-wasm@2.5.6': resolution: {integrity: sha512-byAiBZ1t3tXQvc8dMD/eoyE7lTXYorhn+6uVW5AC+JGI1KtJC/LvDche5cfUE+qiefH+Ybq0bUCJU0aB1cSHUA==} @@ -5704,145 +5947,121 @@ packages: resolution: {integrity: sha512-9VlPY/BN3AgbukfVHAB8zNFWB/lKEuvzRo1NKev0Po8sYFKx0i+AQlCYftgEjcL43F2h9Ui1ZSdVBc4En/sP2w==} cpu: [arm] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm-gnueabihf@4.56.0': resolution: {integrity: sha512-E8jKK87uOvLrrLN28jnAAAChNq5LeCd2mGgZF+fGF5D507WlG/Noct3lP/QzQ6MrqJ5BCKNwI9ipADB6jyiq2A==} cpu: [arm] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.50.2': resolution: {integrity: sha512-+GdKWOvsifaYNlIVf07QYan1J5F141+vGm5/Y8b9uCZnG/nxoGqgCmR24mv0koIWWuqvFYnbURRqw1lv7IBINw==} cpu: [arm] os: [linux] - libc: [musl] '@rollup/rollup-linux-arm-musleabihf@4.56.0': resolution: {integrity: sha512-jQosa5FMYF5Z6prEpTCCmzCXz6eKr/tCBssSmQGEeozA9tkRUty/5Vx06ibaOP9RCrW1Pvb8yp3gvZhHwTDsJw==} cpu: [arm] os: [linux] - libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.50.2': resolution: {integrity: sha512-df0Eou14ojtUdLQdPFnymEQteENwSJAdLf5KCDrmZNsy1c3YaCNaJvYsEUHnrg+/DLBH612/R0xd3dD03uz2dg==} cpu: [arm64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm64-gnu@4.56.0': resolution: {integrity: sha512-uQVoKkrC1KGEV6udrdVahASIsaF8h7iLG0U0W+Xn14ucFwi6uS539PsAr24IEF9/FoDtzMeeJXJIBo5RkbNWvQ==} cpu: [arm64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.50.2': resolution: {integrity: sha512-iPeouV0UIDtz8j1YFR4OJ/zf7evjauqv7jQ/EFs0ClIyL+by++hiaDAfFipjOgyz6y6xbDvJuiU4HwpVMpRFDQ==} cpu: [arm64] os: [linux] - libc: [musl] '@rollup/rollup-linux-arm64-musl@4.56.0': resolution: {integrity: sha512-vLZ1yJKLxhQLFKTs42RwTwa6zkGln+bnXc8ueFGMYmBTLfNu58sl5/eXyxRa2RarTkJbXl8TKPgfS6V5ijNqEA==} cpu: [arm64] os: [linux] - libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.50.2': resolution: {integrity: sha512-OL6KaNvBopLlj5fTa5D5bau4W82f+1TyTZRr2BdnfsrnQnmdxh4okMxR2DcDkJuh4KeoQZVuvHvzuD/lyLn2Kw==} cpu: [loong64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-loong64-gnu@4.56.0': resolution: {integrity: sha512-FWfHOCub564kSE3xJQLLIC/hbKqHSVxy8vY75/YHHzWvbJL7aYJkdgwD/xGfUlL5UV2SB7otapLrcCj2xnF1dg==} cpu: [loong64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.56.0': resolution: {integrity: sha512-z1EkujxIh7nbrKL1lmIpqFTc/sr0u8Uk0zK/qIEFldbt6EDKWFk/pxFq3gYj4Bjn3aa9eEhYRlL3H8ZbPT1xvA==} cpu: [loong64] os: [linux] - libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.50.2': resolution: {integrity: sha512-I21VJl1w6z/K5OTRl6aS9DDsqezEZ/yKpbqlvfHbW0CEF5IL8ATBMuUx6/mp683rKTK8thjs/0BaNrZLXetLag==} cpu: [ppc64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-ppc64-gnu@4.56.0': resolution: {integrity: sha512-iNFTluqgdoQC7AIE8Q34R3AuPrJGJirj5wMUErxj22deOcY7XwZRaqYmB6ZKFHoVGqRcRd0mqO+845jAibKCkw==} cpu: [ppc64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.56.0': resolution: {integrity: sha512-MtMeFVlD2LIKjp2sE2xM2slq3Zxf9zwVuw0jemsxvh1QOpHSsSzfNOTH9uYW9i1MXFxUSMmLpeVeUzoNOKBaWg==} cpu: [ppc64] os: [linux] - libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.50.2': resolution: {integrity: sha512-Hq6aQJT/qFFHrYMjS20nV+9SKrXL2lvFBENZoKfoTH2kKDOJqff5OSJr4x72ZaG/uUn+XmBnGhfr4lwMRrmqCQ==} cpu: [riscv64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-riscv64-gnu@4.56.0': resolution: {integrity: sha512-in+v6wiHdzzVhYKXIk5U74dEZHdKN9KH0Q4ANHOTvyXPG41bajYRsy7a8TPKbYPl34hU7PP7hMVHRvv/5aCSew==} cpu: [riscv64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.50.2': resolution: {integrity: sha512-82rBSEXRv5qtKyr0xZ/YMF531oj2AIpLZkeNYxmKNN6I2sVE9PGegN99tYDLK2fYHJITL1P2Lgb4ZXnv0PjQvw==} cpu: [riscv64] os: [linux] - libc: [musl] '@rollup/rollup-linux-riscv64-musl@4.56.0': resolution: {integrity: sha512-yni2raKHB8m9NQpI9fPVwN754mn6dHQSbDTwxdr9SE0ks38DTjLMMBjrwvB5+mXrX+C0npX0CVeCUcvvvD8CNQ==} cpu: [riscv64] os: [linux] - libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.50.2': resolution: {integrity: sha512-4Q3S3Hy7pC6uaRo9gtXUTJ+EKo9AKs3BXKc2jYypEcMQ49gDPFU2P1ariX9SEtBzE5egIX6fSUmbmGazwBVF9w==} cpu: [s390x] os: [linux] - libc: [glibc] '@rollup/rollup-linux-s390x-gnu@4.56.0': resolution: {integrity: sha512-zhLLJx9nQPu7wezbxt2ut+CI4YlXi68ndEve16tPc/iwoylWS9B3FxpLS2PkmfYgDQtosah07Mj9E0khc3Y+vQ==} cpu: [s390x] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.50.2': resolution: {integrity: sha512-9Jie/At6qk70dNIcopcL4p+1UirusEtznpNtcq/u/C5cC4HBX7qSGsYIcG6bdxj15EYWhHiu02YvmdPzylIZlA==} cpu: [x64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.56.0': resolution: {integrity: sha512-MVC6UDp16ZSH7x4rtuJPAEoE1RwS8N4oK9DLHy3FTEdFoUTCFVzMfJl/BVJ330C+hx8FfprA5Wqx4FhZXkj2Kw==} cpu: [x64] os: [linux] - libc: [glibc] '@rollup/rollup-linux-x64-musl@4.50.2': resolution: {integrity: sha512-HPNJwxPL3EmhzeAnsWQCM3DcoqOz3/IC6de9rWfGR8ZCuEHETi9km66bH/wG3YH0V3nyzyFEGUZeL5PKyy4xvw==} cpu: [x64] os: [linux] - libc: [musl] '@rollup/rollup-linux-x64-musl@4.56.0': resolution: {integrity: sha512-ZhGH1eA4Qv0lxaV00azCIS1ChedK0V32952Md3FtnxSqZTBTd6tgil4nZT5cU8B+SIw3PFYkvyR4FKo2oyZIHA==} cpu: [x64] os: [linux] - libc: [musl] '@rollup/rollup-openbsd-x64@4.56.0': resolution: {integrity: sha512-O16XcmyDeFI9879pEcmtWvD/2nyxR9mF7Gs44lf1vGGx8Vg2DRNx11aVXBEqOQhWb92WN4z7fW/q4+2NYzCbBA==} @@ -6384,12 +6603,12 @@ packages: '@types/bonjour@3.5.13': resolution: {integrity: sha512-z9fJ5Im06zvUL548KvYNecEVlA7cVDkGUi6kZusb04mpyEFKCIZJvloCcmpmLaIahDpOQGHaHmG6imtPMmPXGQ==} - '@types/bun@1.3.14': - resolution: {integrity: sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==} - '@types/bun@1.3.9': resolution: {integrity: sha512-KQ571yULOdWJiMH+RIWIOZ7B2RXQGpL1YQrBtLIV3FqDcCu6FsbFUBwhdKUlCKUpS3PJDsHlJ1QKlpxoVR+xtw==} + '@types/bun@1.4.1': + resolution: {integrity: sha512-0AVGiTXGajf1rgKom3N+c5L7CBxuoyyv1i44M0nX4UDK0G/fnRAMiri93nHuVPIb429KKtAgj7HatVmmOjeQLA==} + '@types/chai@5.2.2': resolution: {integrity: sha512-8kB30R7Hwqf40JPiKhVzodJs2Qc1ZJ5zuT3uzw5Hq/dhNCl3G3l83jfpdI1e20BP348+fV7VIL/+FxaXkqBmWg==} @@ -6513,8 +6732,8 @@ packages: '@types/node@22.18.0': resolution: {integrity: sha512-m5ObIqwsUp6BZzyiy4RdZpzWGub9bqLJMvZDD0QMXhxjqMHMENlj+SqF5QxoUwaQNFe+8kz8XM8ZQhqkQPTgMQ==} - '@types/node@24.3.0': - resolution: {integrity: sha512-aPTXCrfwnDLj4VvXrm+UUCQjNEvJgNA8s5F1cvwQU+3KNltTOkBm1j30uNLyqqPNe7gE3KFzImYoZEfLhp4Yow==} + '@types/node@25.9.5': + resolution: {integrity: sha512-OScDchr2fwuUmWdf4kZ9h7PcJiYDVInhJizG/biAq3cAvqwYktuy/TYGGdZNMtNTFUP7rnb0NU4TUdm82kt4Rg==} '@types/object-inspect@1.13.0': resolution: {integrity: sha512-lwGTVESDDV+XsQ1pH4UifpJ1f7OtXzQ6QBOX2Afq2bM/T3oOt8hF6exJMjjIjtEWeAN2YAo25J7HxWh97CCz9w==} @@ -7760,12 +7979,12 @@ packages: buffer@6.0.3: resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==} - bun-types@1.3.14: - resolution: {integrity: sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ==} - bun-types@1.3.9: resolution: {integrity: sha512-+UBWWOakIP4Tswh0Bt0QD0alpTY8cb5hvgiYeWCMet9YukHbzuruIEeXC2D7nMJPB12kbh8C7XJykSexEqGKJg==} + bun-types@1.4.1: + resolution: {integrity: sha512-loKuVrAFZKfEv+JvWkHRS9GW5IqLuLRjVXN9p+vZvBN86O5hf/pBZQ5hSoyipsrMmWObZBDvWnlmKvjKTM0PdA==} + bun@1.3.9: resolution: {integrity: sha512-v5hkh1us7sMNjfimWE70flYbD5I1/qWQaqmJ45q2qk5H/7muQVa478LSVRSFyGTBUBog2LsPQnfIRdjyWJRY+A==} cpu: [arm64, x64] @@ -8252,6 +8471,10 @@ packages: create-require@1.1.1: resolution: {integrity: sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==} + cron-parser@5.5.0: + resolution: {integrity: sha512-oML4lKUXxizYswqmxuOCpgFS8BNUJpIu6k/2HVHyaL8Ynnf3wdf9tkns0yRdJLSIjkJ+b0DXHMZEHGpMwjnPww==} + engines: {node: '>=18'} + croner@9.1.0: resolution: {integrity: sha512-p9nwwR4qyT5W996vBZhdvBCnMhicY5ytZkR4D1Xj0wuTDEiMnjwR57Q3RXYY/s0EpX6Ay3vgIcfaR+ewGHsi+g==} engines: {node: '>=18.0'} @@ -8926,13 +9149,13 @@ packages: engines: {node: '>=18'} hasBin: true - esbuild@0.27.2: - resolution: {integrity: sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==} + esbuild@0.27.3: + resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==} engines: {node: '>=18'} hasBin: true - esbuild@0.27.3: - resolution: {integrity: sha512-8VwMnyGCONIs6cWue2IdpHxHnAjzxnw2Zr7MkVxB2vjmQ2ivqGFb4LEG3SMnv0Gb2F/G/2yA8zUaiL1gywDCCg==} + esbuild@0.28.2: + resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==} engines: {node: '>=18'} hasBin: true @@ -8999,6 +9222,7 @@ packages: eslint@9.33.0: resolution: {integrity: sha512-TS9bTNIryDzStCpJN93aC5VRSW3uTx9sClUn4B87pwiCaJh220otoI0X8mJKr+VcPtniMdN8GKjlwgWGUv5ZKA==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} + deprecated: This version is no longer supported. Please see https://eslint.org/version-support for other options. hasBin: true peerDependencies: jiti: '*' @@ -10584,6 +10808,10 @@ packages: lunr@2.3.9: resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + luxon@3.7.2: + resolution: {integrity: sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==} + engines: {node: '>=12'} + lz-string@1.5.0: resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} hasBin: true @@ -13918,6 +14146,7 @@ packages: tsconfck@2.1.2: resolution: {integrity: sha512-ghqN1b0puy3MhhviwO2kGF8SeMDNhEbnKxjK7h6+fvY9JAxqvXi8y5NAHSQv687OVboS2uZIByzGd45/YxrRHg==} engines: {node: ^14.13.1 || ^16 || >=18} + deprecated: unmaintained hasBin: true peerDependencies: typescript: ^4.3.5 || ^5.0.0 @@ -13928,6 +14157,7 @@ packages: tsconfck@3.1.6: resolution: {integrity: sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==} engines: {node: ^18 || >=20} + deprecated: unmaintained hasBin: true peerDependencies: typescript: ^5.0.0 @@ -13966,6 +14196,11 @@ packages: engines: {node: '>=18.0.0'} hasBin: true + tsx@4.23.12: + resolution: {integrity: sha512-FDf4L4sYzKtzWYhU/Xm0AQFdTjdIxNo9ElTf2mxXM6k8YMHXzYUe4yODVaXP4V9uMFbVg8c0qyBccK2OOxb45Q==} + engines: {node: '>=18.0.0'} + hasBin: true + tuf-js@4.1.0: resolution: {integrity: sha512-50QV99kCKH5P/Vs4E2Gzp7BopNV+KzTXqWeaxrfu5IQJBOULRsTIS9seSsOVT8ZnGXzCyx55nYWAi4qJzpZKEQ==} engines: {node: ^20.17.0 || >=22.9.0} @@ -14050,8 +14285,8 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - undici-types@7.10.0: - resolution: {integrity: sha512-t5Fy/nfn+14LuOc2KNYg75vZqClpAiqscVvMygNnlsHBFpSXdJaYtXMcdNLpl/Qvc3P2cB3s6lOV51nqsFq4ag==} + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} undici@6.21.3: resolution: {integrity: sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==} @@ -14394,8 +14629,8 @@ packages: v8-compile-cache-lib@3.0.1: resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} - valibot@1.2.0: - resolution: {integrity: sha512-mm1rxUsmOxzrwnX5arGS+U4T25RdvpPjPN4yR0u9pUBov9+zGVtO84tif1eY4r6zWxVxu3KzIyknJy3rxfRZZg==} + valibot@1.4.2: + resolution: {integrity: sha512-gjdCvJ6d3RyHAneqxMYMW9QMCwYMb3jpOO0IyHZV1bnRHFBHrX3VkIILt5XYR0WhwHiH7Mty8ovuPZ/O3gamrg==} peerDependencies: typescript: '>=5' peerDependenciesMeta: @@ -15351,7 +15586,7 @@ snapshots: transitivePeerDependencies: - chokidar - '@angular/build@21.2.13(@angular/compiler-cli@21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3))(@angular/compiler@21.2.15)(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(@angular/platform-browser@21.2.15(@angular/common@21.2.15(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2)))(@types/node@24.3.0)(chokidar@5.0.0)(jiti@2.6.1)(postcss@8.5.6)(terser@5.43.1)(tslib@2.8.1)(tsx@4.21.0)(typescript@5.9.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(yaml@2.8.2)': + '@angular/build@21.2.13(@angular/compiler-cli@21.2.15(@angular/compiler@21.2.15)(typescript@5.9.3))(@angular/compiler@21.2.15)(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(@angular/platform-browser@21.2.15(@angular/common@21.2.15(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2)))(@types/node@25.9.5)(chokidar@5.0.0)(jiti@2.6.1)(postcss@8.5.6)(terser@5.43.1)(tslib@2.8.1)(tsx@4.23.12)(typescript@5.9.3)(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(yaml@2.8.2)': dependencies: '@ampproject/remapping': 2.3.0 '@angular-devkit/architect': 0.2102.13(chokidar@5.0.0) @@ -15360,8 +15595,8 @@ snapshots: '@babel/core': 7.29.0 '@babel/helper-annotate-as-pure': 7.27.3 '@babel/helper-split-export-declaration': 7.24.7 - '@inquirer/confirm': 5.1.21(@types/node@24.3.0) - '@vitejs/plugin-basic-ssl': 2.1.4(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@inquirer/confirm': 5.1.21(@types/node@25.9.5) + '@vitejs/plugin-basic-ssl': 2.1.4(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) beasties: 0.4.1 browserslist: 4.28.1 esbuild: 0.27.3 @@ -15382,14 +15617,14 @@ snapshots: tslib: 2.8.1 typescript: 5.9.3 undici: 7.24.4 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) watchpack: 2.5.1 optionalDependencies: '@angular/core': 21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2) '@angular/platform-browser': 21.2.15(@angular/common@21.2.15(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2))(rxjs@7.8.2))(@angular/core@21.2.15(@angular/compiler@21.2.15)(rxjs@7.8.2)) lmdb: 3.5.1 postcss: 8.5.6 - vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - chokidar @@ -15403,13 +15638,13 @@ snapshots: - tsx - yaml - '@angular/cli@21.2.13(@types/node@24.3.0)(chokidar@5.0.0)': + '@angular/cli@21.2.13(@types/node@25.9.5)(chokidar@5.0.0)': dependencies: '@angular-devkit/architect': 0.2102.13(chokidar@5.0.0) '@angular-devkit/core': 21.2.13(chokidar@5.0.0) '@angular-devkit/schematics': 21.2.13(chokidar@5.0.0) - '@inquirer/prompts': 7.10.1(@types/node@24.3.0) - '@listr2/prompt-adapter-inquirer': 3.0.5(@inquirer/prompts@7.10.1(@types/node@24.3.0))(@types/node@24.3.0)(listr2@9.0.5) + '@inquirer/prompts': 7.10.1(@types/node@25.9.5) + '@listr2/prompt-adapter-inquirer': 3.0.5(@inquirer/prompts@7.10.1(@types/node@25.9.5))(@types/node@25.9.5)(listr2@9.0.5) '@modelcontextprotocol/sdk': 1.26.0(zod@4.3.6) '@schematics/angular': 21.2.13(chokidar@5.0.0) '@yarnpkg/lockfile': 1.1.0 @@ -17939,10 +18174,10 @@ snapshots: '@esbuild/aix-ppc64@0.27.0': optional: true - '@esbuild/aix-ppc64@0.27.2': + '@esbuild/aix-ppc64@0.27.3': optional: true - '@esbuild/aix-ppc64@0.27.3': + '@esbuild/aix-ppc64@0.28.2': optional: true '@esbuild/android-arm64@0.17.6': @@ -17960,10 +18195,10 @@ snapshots: '@esbuild/android-arm64@0.27.0': optional: true - '@esbuild/android-arm64@0.27.2': + '@esbuild/android-arm64@0.27.3': optional: true - '@esbuild/android-arm64@0.27.3': + '@esbuild/android-arm64@0.28.2': optional: true '@esbuild/android-arm@0.17.6': @@ -17981,10 +18216,10 @@ snapshots: '@esbuild/android-arm@0.27.0': optional: true - '@esbuild/android-arm@0.27.2': + '@esbuild/android-arm@0.27.3': optional: true - '@esbuild/android-arm@0.27.3': + '@esbuild/android-arm@0.28.2': optional: true '@esbuild/android-x64@0.17.6': @@ -18002,10 +18237,10 @@ snapshots: '@esbuild/android-x64@0.27.0': optional: true - '@esbuild/android-x64@0.27.2': + '@esbuild/android-x64@0.27.3': optional: true - '@esbuild/android-x64@0.27.3': + '@esbuild/android-x64@0.28.2': optional: true '@esbuild/darwin-arm64@0.17.6': @@ -18023,10 +18258,10 @@ snapshots: '@esbuild/darwin-arm64@0.27.0': optional: true - '@esbuild/darwin-arm64@0.27.2': + '@esbuild/darwin-arm64@0.27.3': optional: true - '@esbuild/darwin-arm64@0.27.3': + '@esbuild/darwin-arm64@0.28.2': optional: true '@esbuild/darwin-x64@0.17.6': @@ -18044,10 +18279,10 @@ snapshots: '@esbuild/darwin-x64@0.27.0': optional: true - '@esbuild/darwin-x64@0.27.2': + '@esbuild/darwin-x64@0.27.3': optional: true - '@esbuild/darwin-x64@0.27.3': + '@esbuild/darwin-x64@0.28.2': optional: true '@esbuild/freebsd-arm64@0.17.6': @@ -18065,10 +18300,10 @@ snapshots: '@esbuild/freebsd-arm64@0.27.0': optional: true - '@esbuild/freebsd-arm64@0.27.2': + '@esbuild/freebsd-arm64@0.27.3': optional: true - '@esbuild/freebsd-arm64@0.27.3': + '@esbuild/freebsd-arm64@0.28.2': optional: true '@esbuild/freebsd-x64@0.17.6': @@ -18086,10 +18321,10 @@ snapshots: '@esbuild/freebsd-x64@0.27.0': optional: true - '@esbuild/freebsd-x64@0.27.2': + '@esbuild/freebsd-x64@0.27.3': optional: true - '@esbuild/freebsd-x64@0.27.3': + '@esbuild/freebsd-x64@0.28.2': optional: true '@esbuild/linux-arm64@0.17.6': @@ -18107,10 +18342,10 @@ snapshots: '@esbuild/linux-arm64@0.27.0': optional: true - '@esbuild/linux-arm64@0.27.2': + '@esbuild/linux-arm64@0.27.3': optional: true - '@esbuild/linux-arm64@0.27.3': + '@esbuild/linux-arm64@0.28.2': optional: true '@esbuild/linux-arm@0.17.6': @@ -18128,10 +18363,10 @@ snapshots: '@esbuild/linux-arm@0.27.0': optional: true - '@esbuild/linux-arm@0.27.2': + '@esbuild/linux-arm@0.27.3': optional: true - '@esbuild/linux-arm@0.27.3': + '@esbuild/linux-arm@0.28.2': optional: true '@esbuild/linux-ia32@0.17.6': @@ -18149,10 +18384,10 @@ snapshots: '@esbuild/linux-ia32@0.27.0': optional: true - '@esbuild/linux-ia32@0.27.2': + '@esbuild/linux-ia32@0.27.3': optional: true - '@esbuild/linux-ia32@0.27.3': + '@esbuild/linux-ia32@0.28.2': optional: true '@esbuild/linux-loong64@0.17.6': @@ -18170,10 +18405,10 @@ snapshots: '@esbuild/linux-loong64@0.27.0': optional: true - '@esbuild/linux-loong64@0.27.2': + '@esbuild/linux-loong64@0.27.3': optional: true - '@esbuild/linux-loong64@0.27.3': + '@esbuild/linux-loong64@0.28.2': optional: true '@esbuild/linux-mips64el@0.17.6': @@ -18191,10 +18426,10 @@ snapshots: '@esbuild/linux-mips64el@0.27.0': optional: true - '@esbuild/linux-mips64el@0.27.2': + '@esbuild/linux-mips64el@0.27.3': optional: true - '@esbuild/linux-mips64el@0.27.3': + '@esbuild/linux-mips64el@0.28.2': optional: true '@esbuild/linux-ppc64@0.17.6': @@ -18212,10 +18447,10 @@ snapshots: '@esbuild/linux-ppc64@0.27.0': optional: true - '@esbuild/linux-ppc64@0.27.2': + '@esbuild/linux-ppc64@0.27.3': optional: true - '@esbuild/linux-ppc64@0.27.3': + '@esbuild/linux-ppc64@0.28.2': optional: true '@esbuild/linux-riscv64@0.17.6': @@ -18233,10 +18468,10 @@ snapshots: '@esbuild/linux-riscv64@0.27.0': optional: true - '@esbuild/linux-riscv64@0.27.2': + '@esbuild/linux-riscv64@0.27.3': optional: true - '@esbuild/linux-riscv64@0.27.3': + '@esbuild/linux-riscv64@0.28.2': optional: true '@esbuild/linux-s390x@0.17.6': @@ -18254,10 +18489,10 @@ snapshots: '@esbuild/linux-s390x@0.27.0': optional: true - '@esbuild/linux-s390x@0.27.2': + '@esbuild/linux-s390x@0.27.3': optional: true - '@esbuild/linux-s390x@0.27.3': + '@esbuild/linux-s390x@0.28.2': optional: true '@esbuild/linux-x64@0.17.6': @@ -18275,10 +18510,10 @@ snapshots: '@esbuild/linux-x64@0.27.0': optional: true - '@esbuild/linux-x64@0.27.2': + '@esbuild/linux-x64@0.27.3': optional: true - '@esbuild/linux-x64@0.27.3': + '@esbuild/linux-x64@0.28.2': optional: true '@esbuild/netbsd-arm64@0.24.2': @@ -18290,10 +18525,10 @@ snapshots: '@esbuild/netbsd-arm64@0.27.0': optional: true - '@esbuild/netbsd-arm64@0.27.2': + '@esbuild/netbsd-arm64@0.27.3': optional: true - '@esbuild/netbsd-arm64@0.27.3': + '@esbuild/netbsd-arm64@0.28.2': optional: true '@esbuild/netbsd-x64@0.17.6': @@ -18311,10 +18546,10 @@ snapshots: '@esbuild/netbsd-x64@0.27.0': optional: true - '@esbuild/netbsd-x64@0.27.2': + '@esbuild/netbsd-x64@0.27.3': optional: true - '@esbuild/netbsd-x64@0.27.3': + '@esbuild/netbsd-x64@0.28.2': optional: true '@esbuild/openbsd-arm64@0.24.2': @@ -18326,10 +18561,10 @@ snapshots: '@esbuild/openbsd-arm64@0.27.0': optional: true - '@esbuild/openbsd-arm64@0.27.2': + '@esbuild/openbsd-arm64@0.27.3': optional: true - '@esbuild/openbsd-arm64@0.27.3': + '@esbuild/openbsd-arm64@0.28.2': optional: true '@esbuild/openbsd-x64@0.17.6': @@ -18347,10 +18582,10 @@ snapshots: '@esbuild/openbsd-x64@0.27.0': optional: true - '@esbuild/openbsd-x64@0.27.2': + '@esbuild/openbsd-x64@0.27.3': optional: true - '@esbuild/openbsd-x64@0.27.3': + '@esbuild/openbsd-x64@0.28.2': optional: true '@esbuild/openharmony-arm64@0.25.9': @@ -18359,10 +18594,10 @@ snapshots: '@esbuild/openharmony-arm64@0.27.0': optional: true - '@esbuild/openharmony-arm64@0.27.2': + '@esbuild/openharmony-arm64@0.27.3': optional: true - '@esbuild/openharmony-arm64@0.27.3': + '@esbuild/openharmony-arm64@0.28.2': optional: true '@esbuild/sunos-x64@0.17.6': @@ -18380,10 +18615,10 @@ snapshots: '@esbuild/sunos-x64@0.27.0': optional: true - '@esbuild/sunos-x64@0.27.2': + '@esbuild/sunos-x64@0.27.3': optional: true - '@esbuild/sunos-x64@0.27.3': + '@esbuild/sunos-x64@0.28.2': optional: true '@esbuild/win32-arm64@0.17.6': @@ -18401,10 +18636,10 @@ snapshots: '@esbuild/win32-arm64@0.27.0': optional: true - '@esbuild/win32-arm64@0.27.2': + '@esbuild/win32-arm64@0.27.3': optional: true - '@esbuild/win32-arm64@0.27.3': + '@esbuild/win32-arm64@0.28.2': optional: true '@esbuild/win32-ia32@0.17.6': @@ -18422,10 +18657,10 @@ snapshots: '@esbuild/win32-ia32@0.27.0': optional: true - '@esbuild/win32-ia32@0.27.2': + '@esbuild/win32-ia32@0.27.3': optional: true - '@esbuild/win32-ia32@0.27.3': + '@esbuild/win32-ia32@0.28.2': optional: true '@esbuild/win32-x64@0.17.6': @@ -18443,10 +18678,10 @@ snapshots: '@esbuild/win32-x64@0.27.0': optional: true - '@esbuild/win32-x64@0.27.2': + '@esbuild/win32-x64@0.27.3': optional: true - '@esbuild/win32-x64@0.27.3': + '@esbuild/win32-x64@0.28.2': optional: true '@eslint-community/eslint-utils@4.7.0(eslint@9.33.0(jiti@2.6.1))': @@ -18854,128 +19089,128 @@ snapshots: '@inquirer/ansi@1.0.2': {} - '@inquirer/checkbox@4.3.2(@types/node@24.3.0)': + '@inquirer/checkbox@4.3.2(@types/node@25.9.5)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@25.9.5) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/confirm@5.1.21(@types/node@24.3.0)': + '@inquirer/confirm@5.1.21(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/core@10.3.2(@types/node@24.3.0)': + '@inquirer/core@10.3.2(@types/node@25.9.5)': dependencies: '@inquirer/ansi': 1.0.2 '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@25.9.5) cli-width: 4.1.0 mute-stream: 2.0.0 signal-exit: 4.1.0 wrap-ansi: 6.2.0 yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/editor@4.2.23(@types/node@24.3.0)': + '@inquirer/editor@4.2.23(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/external-editor': 1.0.3(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/external-editor': 1.0.3(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/expand@4.0.23(@types/node@24.3.0)': + '@inquirer/expand@4.0.23(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/external-editor@1.0.3(@types/node@24.3.0)': + '@inquirer/external-editor@1.0.3(@types/node@25.9.5)': dependencies: chardet: 2.1.1 iconv-lite: 0.7.2 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 '@inquirer/figures@1.0.15': {} - '@inquirer/input@4.3.1(@types/node@24.3.0)': + '@inquirer/input@4.3.1(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/number@3.0.23(@types/node@24.3.0)': + '@inquirer/number@3.0.23(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/password@4.0.23(@types/node@24.3.0)': + '@inquirer/password@4.0.23(@types/node@25.9.5)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 - - '@inquirer/prompts@7.10.1(@types/node@24.3.0)': - dependencies: - '@inquirer/checkbox': 4.3.2(@types/node@24.3.0) - '@inquirer/confirm': 5.1.21(@types/node@24.3.0) - '@inquirer/editor': 4.2.23(@types/node@24.3.0) - '@inquirer/expand': 4.0.23(@types/node@24.3.0) - '@inquirer/input': 4.3.1(@types/node@24.3.0) - '@inquirer/number': 3.0.23(@types/node@24.3.0) - '@inquirer/password': 4.0.23(@types/node@24.3.0) - '@inquirer/rawlist': 4.1.11(@types/node@24.3.0) - '@inquirer/search': 3.2.2(@types/node@24.3.0) - '@inquirer/select': 4.4.2(@types/node@24.3.0) + '@types/node': 25.9.5 + + '@inquirer/prompts@7.10.1(@types/node@25.9.5)': + dependencies: + '@inquirer/checkbox': 4.3.2(@types/node@25.9.5) + '@inquirer/confirm': 5.1.21(@types/node@25.9.5) + '@inquirer/editor': 4.2.23(@types/node@25.9.5) + '@inquirer/expand': 4.0.23(@types/node@25.9.5) + '@inquirer/input': 4.3.1(@types/node@25.9.5) + '@inquirer/number': 3.0.23(@types/node@25.9.5) + '@inquirer/password': 4.0.23(@types/node@25.9.5) + '@inquirer/rawlist': 4.1.11(@types/node@25.9.5) + '@inquirer/search': 3.2.2(@types/node@25.9.5) + '@inquirer/select': 4.4.2(@types/node@25.9.5) optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/rawlist@4.1.11(@types/node@24.3.0)': + '@inquirer/rawlist@4.1.11(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/search@3.2.2(@types/node@24.3.0)': + '@inquirer/search@3.2.2(@types/node@25.9.5)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@25.9.5) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/select@4.4.2(@types/node@24.3.0)': + '@inquirer/select@4.4.2(@types/node@25.9.5)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.3.0) + '@inquirer/core': 10.3.2(@types/node@25.9.5) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/type': 3.0.10(@types/node@25.9.5) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 - '@inquirer/type@3.0.10(@types/node@24.3.0)': + '@inquirer/type@3.0.10(@types/node@25.9.5)': optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 '@internationalized/date@3.10.0': dependencies: @@ -19093,10 +19328,10 @@ snapshots: '@leichtgewicht/ip-codec@2.0.5': {} - '@listr2/prompt-adapter-inquirer@3.0.5(@inquirer/prompts@7.10.1(@types/node@24.3.0))(@types/node@24.3.0)(listr2@9.0.5)': + '@listr2/prompt-adapter-inquirer@3.0.5(@inquirer/prompts@7.10.1(@types/node@25.9.5))(@types/node@25.9.5)(listr2@9.0.5)': dependencies: - '@inquirer/prompts': 7.10.1(@types/node@24.3.0) - '@inquirer/type': 3.0.10(@types/node@24.3.0) + '@inquirer/prompts': 7.10.1(@types/node@25.9.5) + '@inquirer/type': 3.0.10(@types/node@25.9.5) listr2: 9.0.5 transitivePeerDependencies: - '@types/node' @@ -19319,6 +19554,8 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true + '@noble/hashes@2.3.0': {} + '@node-rs/jieba-android-arm-eabi@1.10.4': optional: true @@ -19524,11 +19761,11 @@ snapshots: '@nuxt/devalue@2.0.2': {} - '@nuxt/devtools-kit@2.7.0(magicast@0.3.5)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@nuxt/devtools-kit@2.7.0(magicast@0.3.5)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@nuxt/kit': 3.21.1(magicast@0.3.5) execa: 8.0.1 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - magicast @@ -19543,12 +19780,12 @@ snapshots: prompts: 2.4.2 semver: 7.7.4 - '@nuxt/devtools@2.7.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': + '@nuxt/devtools@2.7.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': dependencies: - '@nuxt/devtools-kit': 2.7.0(magicast@0.3.5)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@nuxt/devtools-kit': 2.7.0(magicast@0.3.5)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) '@nuxt/devtools-wizard': 2.7.0 '@nuxt/kit': 3.21.1(magicast@0.3.5) - '@vue/devtools-core': 7.7.9(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + '@vue/devtools-core': 7.7.9(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) '@vue/devtools-kit': 7.7.9 birpc: 2.9.0 consola: 3.4.2 @@ -19573,9 +19810,9 @@ snapshots: sirv: 3.0.2 structured-clone-es: 1.0.0 tinyglobby: 0.2.15 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-plugin-inspect: 11.3.3(@nuxt/kit@3.21.1(magicast@0.3.5))(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) - vite-plugin-vue-tracer: 1.2.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-plugin-inspect: 11.3.3(@nuxt/kit@3.21.1(magicast@0.3.5))(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) + vite-plugin-vue-tracer: 1.2.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) which: 5.0.0 ws: 8.18.3 transitivePeerDependencies: @@ -19653,12 +19890,12 @@ snapshots: rc9: 3.0.0 std-env: 3.10.0 - '@nuxt/vite-builder@3.16.2(@types/node@24.3.0)(eslint@9.33.0(jiti@2.6.1))(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(typescript@5.6.3)(vue-tsc@2.2.12(typescript@5.6.3))(vue@3.5.26(typescript@5.6.3))(yaml@2.8.2)': + '@nuxt/vite-builder@3.16.2(@types/node@25.9.5)(eslint@9.33.0(jiti@2.6.1))(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(typescript@5.6.3)(vue-tsc@2.2.12(typescript@5.6.3))(vue@3.5.26(typescript@5.6.3))(yaml@2.8.2)': dependencies: '@nuxt/kit': 3.16.2(magicast@0.3.5) '@rollup/plugin-replace': 6.0.3(rollup@4.56.0) - '@vitejs/plugin-vue': 5.2.4(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) - '@vitejs/plugin-vue-jsx': 4.2.0(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + '@vitejs/plugin-vue': 5.2.4(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + '@vitejs/plugin-vue-jsx': 4.2.0(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) autoprefixer: 10.4.21(postcss@8.5.6) consola: 3.4.2 cssnano: 7.1.2(postcss@8.5.6) @@ -19684,9 +19921,9 @@ snapshots: ufo: 1.6.3 unenv: 2.0.0-rc.24 unplugin: 2.3.11 - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-node: 3.2.4(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-plugin-checker: 0.9.3(eslint@9.33.0(jiti@2.6.1))(optionator@0.9.4)(typescript@5.6.3)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3)) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-plugin-checker: 0.9.3(eslint@9.33.0(jiti@2.6.1))(optionator@0.9.4)(typescript@5.6.3)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3)) vue: 3.5.26(typescript@5.6.3) vue-bundle-renderer: 2.2.0 transitivePeerDependencies: @@ -20636,7 +20873,7 @@ snapshots: '@radix-ui/rect@1.1.1': {} - '@remix-run/dev@2.17.4(@remix-run/react@2.17.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@5.6.3))(@remix-run/serve@2.17.4(typescript@5.6.3))(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3))(tsx@4.21.0)(typescript@5.6.3)(vite@5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1))(yaml@2.8.2)': + '@remix-run/dev@2.17.4(@remix-run/react@2.17.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(typescript@5.6.3))(@remix-run/serve@2.17.4(typescript@5.6.3))(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3))(tsx@4.23.12)(typescript@5.6.3)(vite@5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1))(yaml@2.8.2)': dependencies: '@babel/core': 7.28.6 '@babel/generator': 7.28.6 @@ -20653,7 +20890,7 @@ snapshots: '@remix-run/router': 1.23.2 '@remix-run/server-runtime': 2.17.4(typescript@5.6.3) '@types/mdx': 2.0.13 - '@vanilla-extract/integration': 6.5.0(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) + '@vanilla-extract/integration': 6.5.0(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) arg: 5.0.2 cacache: 17.1.4 chalk: 4.1.2 @@ -20681,7 +20918,7 @@ snapshots: pidtree: 0.6.0 postcss: 8.5.6 postcss-discard-duplicates: 5.1.0(postcss@8.5.6) - postcss-load-config: 4.0.2(postcss@8.5.6)(ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3)) + postcss-load-config: 4.0.2(postcss@8.5.6)(ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3)) postcss-modules: 6.0.1(postcss@8.5.6) prettier: 2.8.8 pretty-ms: 7.0.1 @@ -20692,13 +20929,13 @@ snapshots: set-cookie-parser: 2.7.2 tar-fs: 2.1.4 tsconfig-paths: 4.2.0 - valibot: 1.2.0(typescript@5.6.3) - vite-node: 3.2.4(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + valibot: 1.4.2(typescript@5.6.3) + vite-node: 3.2.4(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) ws: 7.5.10 optionalDependencies: '@remix-run/serve': 2.17.4(typescript@5.6.3) typescript: 5.6.3 - vite: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) + vite: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -21243,25 +21480,25 @@ snapshots: dependencies: acorn: 8.15.0 - '@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@sveltejs/vite-plugin-svelte-inspector@4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: - '@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@sveltejs/vite-plugin-svelte': 5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) debug: 4.4.3 svelte: 5.46.4 - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: - '@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(svelte@5.46.4)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@sveltejs/vite-plugin-svelte-inspector': 4.0.1(@sveltejs/vite-plugin-svelte@5.1.1(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(svelte@5.46.4)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) debug: 4.4.3 deepmerge: 4.3.1 kleur: 4.1.5 magic-string: 0.30.21 svelte: 5.46.4 - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vitefu: 1.1.1(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vitefu: 1.1.1(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) transitivePeerDependencies: - supports-color @@ -21449,19 +21686,19 @@ snapshots: transitivePeerDependencies: - crossws - '@tanstack/react-start@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0)': + '@tanstack/react-start@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4)(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0)': dependencies: '@tanstack/react-router': 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4) '@tanstack/react-start-client': 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4) '@tanstack/react-start-server': 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4) '@tanstack/router-utils': 1.161.4 '@tanstack/start-client-core': 1.162.6 - '@tanstack/start-plugin-core': 1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0) + '@tanstack/start-plugin-core': 1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0) '@tanstack/start-server-core': 1.162.6 pathe: 2.0.3 react: 19.2.4 react-dom: 19.2.4(react@19.2.4) - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - '@rsbuild/core' - crossws @@ -21503,12 +21740,12 @@ snapshots: prettier: 3.6.2 recast: 0.23.11 source-map: 0.7.6 - tsx: 4.21.0 + tsx: 4.23.12 zod: 3.25.76 transitivePeerDependencies: - supports-color - '@tanstack/router-plugin@1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0)': + '@tanstack/router-plugin@1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0)': dependencies: '@babel/core': 7.29.0 '@babel/plugin-syntax-jsx': 7.27.1(@babel/core@7.29.0) @@ -21525,8 +21762,8 @@ snapshots: zod: 3.25.76 optionalDependencies: '@tanstack/react-router': 1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4) - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-plugin-solid: 2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-plugin-solid: 2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) webpack: 5.102.0 transitivePeerDependencies: - supports-color @@ -21561,7 +21798,7 @@ snapshots: '@tanstack/start-fn-stubs@1.161.4': {} - '@tanstack/start-plugin-core@1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0)': + '@tanstack/start-plugin-core@1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0)': dependencies: '@babel/code-frame': 7.27.1 '@babel/core': 7.29.0 @@ -21569,7 +21806,7 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.40 '@tanstack/router-core': 1.162.6 '@tanstack/router-generator': 1.162.6 - '@tanstack/router-plugin': 1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(webpack@5.102.0) + '@tanstack/router-plugin': 1.162.8(@tanstack/react-router@1.162.8(react-dom@19.2.4(react@19.2.4))(react@19.2.4))(vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)))(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(webpack@5.102.0) '@tanstack/router-utils': 1.161.4 '@tanstack/start-client-core': 1.162.6 '@tanstack/start-server-core': 1.162.6 @@ -21581,8 +21818,8 @@ snapshots: srvx: 0.11.7 tinyglobby: 0.2.15 ufo: 1.6.3 - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vitefu: 1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vitefu: 1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) xmlbuilder2: 4.0.3 zod: 3.25.76 transitivePeerDependencies: @@ -21716,14 +21953,14 @@ snapshots: dependencies: '@types/node': 22.18.0 - '@types/bun@1.3.14': - dependencies: - bun-types: 1.3.14 - '@types/bun@1.3.9': dependencies: bun-types: 1.3.9 + '@types/bun@1.4.1': + dependencies: + bun-types: 1.4.1 + '@types/chai@5.2.2': dependencies: '@types/deep-eql': 4.0.2 @@ -21869,9 +22106,9 @@ snapshots: dependencies: undici-types: 6.21.0 - '@types/node@24.3.0': + '@types/node@25.9.5': dependencies: - undici-types: 7.10.0 + undici-types: 7.24.6 optional: true '@types/object-inspect@1.13.0': {} @@ -22188,7 +22425,7 @@ snapshots: transitivePeerDependencies: - babel-plugin-macros - '@vanilla-extract/integration@6.5.0(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1)': + '@vanilla-extract/integration@6.5.0(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1)': dependencies: '@babel/core': 7.28.6 '@babel/plugin-syntax-typescript': 7.27.1(@babel/core@7.28.6) @@ -22201,8 +22438,8 @@ snapshots: lodash: 4.17.21 mlly: 1.8.0 outdent: 0.8.0 - vite: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) - vite-node: 1.6.1(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) + vite: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) + vite-node: 1.6.1(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -22238,11 +22475,11 @@ snapshots: '@vercel/oidc@3.0.3': {} - '@vitejs/plugin-basic-ssl@2.1.4(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitejs/plugin-basic-ssl@2.1.4(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - '@vitejs/plugin-react@4.7.0(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitejs/plugin-react@4.7.0(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22250,11 +22487,11 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.27 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@4.7.0(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitejs/plugin-react@4.7.0(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22262,11 +22499,11 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.27 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 - vite: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@vitejs/plugin-react@5.0.2(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitejs/plugin-react@5.0.2(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@babel/core': 7.28.3 '@babel/plugin-transform-react-jsx-self': 7.27.1(@babel/core@7.28.3) @@ -22274,27 +22511,27 @@ snapshots: '@rolldown/pluginutils': 1.0.0-beta.34 '@types/babel__core': 7.20.5 react-refresh: 0.17.0 - vite: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color - '@vitejs/plugin-vue-jsx@4.2.0(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': + '@vitejs/plugin-vue-jsx@4.2.0(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': dependencies: '@babel/core': 7.29.0 '@babel/plugin-transform-typescript': 7.28.0(@babel/core@7.29.0) '@rolldown/pluginutils': 1.0.0-beta.34 '@vue/babel-plugin-jsx': 1.5.0(@babel/core@7.29.0) - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vue: 3.5.26(typescript@5.6.3) transitivePeerDependencies: - supports-color - '@vitejs/plugin-vue@5.2.4(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': + '@vitejs/plugin-vue@5.2.4(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': dependencies: - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vue: 3.5.26(typescript@5.6.3) - '@vitest/coverage-v8@3.2.4(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitest/coverage-v8@3.2.4(vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@ampproject/remapping': 2.3.0 '@bcoe/v8-coverage': 1.0.2 @@ -22309,7 +22546,7 @@ snapshots: std-env: 3.9.0 test-exclude: 7.0.1 tinyrainbow: 2.0.0 - vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vitest: 3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color @@ -22321,21 +22558,21 @@ snapshots: chai: 5.3.3 tinyrainbow: 2.0.0 - '@vitest/mocker@3.2.4(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitest/mocker@3.2.4(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.19 optionalDependencies: - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - '@vitest/mocker@3.2.4(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))': + '@vitest/mocker@3.2.4(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))': dependencies: '@vitest/spy': 3.2.4 estree-walker: 3.0.3 magic-string: 0.30.19 optionalDependencies: - vite: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) '@vitest/pretty-format@3.2.4': dependencies: @@ -22482,14 +22719,14 @@ snapshots: '@vue/devtools-api@6.6.4': {} - '@vue/devtools-core@7.7.9(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': + '@vue/devtools-core@7.7.9(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3))': dependencies: '@vue/devtools-kit': 7.7.9 '@vue/devtools-shared': 7.7.9 mitt: 3.0.1 nanoid: 5.1.6 pathe: 2.0.3 - vite-hot-client: 2.1.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite-hot-client: 2.1.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) vue: 3.5.26(typescript@5.6.3) transitivePeerDependencies: - vite @@ -24035,11 +24272,11 @@ snapshots: base64-js: 1.5.1 ieee754: 1.2.1 - bun-types@1.3.14: + bun-types@1.3.9: dependencies: '@types/node': 22.18.0 - bun-types@1.3.9: + bun-types@1.4.1: dependencies: '@types/node': 22.18.0 @@ -24549,6 +24786,10 @@ snapshots: create-require@1.1.1: {} + cron-parser@5.5.0: + dependencies: + luxon: 3.7.2 + croner@9.1.0: {} cross-spawn@7.0.6: @@ -24786,10 +25027,10 @@ snapshots: whatwg-mimetype: 4.0.0 whatwg-url: 14.2.0 - db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)): + db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)): optionalDependencies: better-sqlite3: 12.6.2 - drizzle-orm: 0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0) + drizzle-orm: 0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0) de-indent@1.0.2: {} @@ -24964,28 +25205,28 @@ snapshots: dotenv@17.2.3: {} - drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0): + drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.9)(pg@8.18.0)(sql.js@1.14.0): optionalDependencies: '@opentelemetry/api': 1.9.0 '@types/better-sqlite3': 7.6.13 '@types/pg': 8.16.0 '@types/sql.js': 1.4.9 better-sqlite3: 12.6.2 - bun-types: 1.3.14 + bun-types: 1.3.9 pg: 8.18.0 sql.js: 1.14.0 - optional: true - drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.9)(pg@8.18.0)(sql.js@1.14.0): + drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0): optionalDependencies: '@opentelemetry/api': 1.9.0 '@types/better-sqlite3': 7.6.13 '@types/pg': 8.16.0 '@types/sql.js': 1.4.9 better-sqlite3: 12.6.2 - bun-types: 1.3.9 + bun-types: 1.4.1 pg: 8.18.0 sql.js: 1.14.0 + optional: true dunder-proto@1.0.1: dependencies: @@ -25242,35 +25483,6 @@ snapshots: '@esbuild/win32-ia32': 0.27.0 '@esbuild/win32-x64': 0.27.0 - esbuild@0.27.2: - optionalDependencies: - '@esbuild/aix-ppc64': 0.27.2 - '@esbuild/android-arm': 0.27.2 - '@esbuild/android-arm64': 0.27.2 - '@esbuild/android-x64': 0.27.2 - '@esbuild/darwin-arm64': 0.27.2 - '@esbuild/darwin-x64': 0.27.2 - '@esbuild/freebsd-arm64': 0.27.2 - '@esbuild/freebsd-x64': 0.27.2 - '@esbuild/linux-arm': 0.27.2 - '@esbuild/linux-arm64': 0.27.2 - '@esbuild/linux-ia32': 0.27.2 - '@esbuild/linux-loong64': 0.27.2 - '@esbuild/linux-mips64el': 0.27.2 - '@esbuild/linux-ppc64': 0.27.2 - '@esbuild/linux-riscv64': 0.27.2 - '@esbuild/linux-s390x': 0.27.2 - '@esbuild/linux-x64': 0.27.2 - '@esbuild/netbsd-arm64': 0.27.2 - '@esbuild/netbsd-x64': 0.27.2 - '@esbuild/openbsd-arm64': 0.27.2 - '@esbuild/openbsd-x64': 0.27.2 - '@esbuild/openharmony-arm64': 0.27.2 - '@esbuild/sunos-x64': 0.27.2 - '@esbuild/win32-arm64': 0.27.2 - '@esbuild/win32-ia32': 0.27.2 - '@esbuild/win32-x64': 0.27.2 - esbuild@0.27.3: optionalDependencies: '@esbuild/aix-ppc64': 0.27.3 @@ -25300,6 +25512,35 @@ snapshots: '@esbuild/win32-ia32': 0.27.3 '@esbuild/win32-x64': 0.27.3 + esbuild@0.28.2: + optionalDependencies: + '@esbuild/aix-ppc64': 0.28.2 + '@esbuild/android-arm': 0.28.2 + '@esbuild/android-arm64': 0.28.2 + '@esbuild/android-x64': 0.28.2 + '@esbuild/darwin-arm64': 0.28.2 + '@esbuild/darwin-x64': 0.28.2 + '@esbuild/freebsd-arm64': 0.28.2 + '@esbuild/freebsd-x64': 0.28.2 + '@esbuild/linux-arm': 0.28.2 + '@esbuild/linux-arm64': 0.28.2 + '@esbuild/linux-ia32': 0.28.2 + '@esbuild/linux-loong64': 0.28.2 + '@esbuild/linux-mips64el': 0.28.2 + '@esbuild/linux-ppc64': 0.28.2 + '@esbuild/linux-riscv64': 0.28.2 + '@esbuild/linux-s390x': 0.28.2 + '@esbuild/linux-x64': 0.28.2 + '@esbuild/netbsd-arm64': 0.28.2 + '@esbuild/netbsd-x64': 0.28.2 + '@esbuild/openbsd-arm64': 0.28.2 + '@esbuild/openbsd-x64': 0.28.2 + '@esbuild/openharmony-arm64': 0.28.2 + '@esbuild/sunos-x64': 0.28.2 + '@esbuild/win32-arm64': 0.28.2 + '@esbuild/win32-ia32': 0.28.2 + '@esbuild/win32-x64': 0.28.2 + escalade@3.1.1: {} escalade@3.2.0: {} @@ -27227,6 +27468,8 @@ snapshots: lunr@2.3.9: {} + luxon@3.7.2: {} + lz-string@1.5.0: {} magic-string-ast@0.7.1: @@ -28335,7 +28578,7 @@ snapshots: neo-async@2.6.2: {} - nitropack@2.13.1(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13): + nitropack@2.13.1(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13): dependencies: '@cloudflare/kv-asset-handler': 0.4.2 '@rollup/plugin-alias': 6.0.0(rollup@4.56.0) @@ -28356,11 +28599,11 @@ snapshots: cookie-es: 2.0.0 croner: 9.1.0 crossws: 0.3.5 - db0: 0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)) + db0: 0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)) defu: 6.1.4 destr: 2.0.5 dot-prop: 10.1.0 - esbuild: 0.27.2 + esbuild: 0.27.3 escape-string-regexp: 5.0.0 etag: 1.8.1 exsolve: 1.0.8 @@ -28402,7 +28645,7 @@ snapshots: unenv: 2.0.0-rc.24 unimport: 5.6.0 unplugin-utils: 0.3.1 - unstorage: 1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2) + unstorage: 1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2) untyped: 2.0.0 unwasm: 0.5.3 youch: 4.1.0-beta.13 @@ -28608,15 +28851,15 @@ snapshots: schema-utils: 3.3.0 webpack: 5.102.0 - nuxt@3.16.2(@parcel/watcher@2.5.6)(@types/node@24.3.0)(better-sqlite3@12.6.2)(cac@6.7.14)(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)))(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13)(eslint@9.33.0(jiti@2.6.1))(ioredis@5.9.2)(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(typescript@5.6.3)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3))(yaml@2.8.2): + nuxt@3.16.2(@parcel/watcher@2.5.6)(@types/node@25.9.5)(better-sqlite3@12.6.2)(cac@6.7.14)(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)))(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13)(eslint@9.33.0(jiti@2.6.1))(ioredis@5.9.2)(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(typescript@5.6.3)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3))(yaml@2.8.2): dependencies: '@nuxt/cli': 3.33.1(@nuxt/schema@3.16.2)(cac@6.7.14)(magicast@0.3.5) '@nuxt/devalue': 2.0.2 - '@nuxt/devtools': 2.7.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) + '@nuxt/devtools': 2.7.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)) '@nuxt/kit': 3.16.2(magicast@0.3.5) '@nuxt/schema': 3.16.2 '@nuxt/telemetry': 2.7.0(@nuxt/kit@3.16.2(magicast@0.3.5)) - '@nuxt/vite-builder': 3.16.2(@types/node@24.3.0)(eslint@9.33.0(jiti@2.6.1))(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(typescript@5.6.3)(vue-tsc@2.2.12(typescript@5.6.3))(vue@3.5.26(typescript@5.6.3))(yaml@2.8.2) + '@nuxt/vite-builder': 3.16.2(@types/node@25.9.5)(eslint@9.33.0(jiti@2.6.1))(magicast@0.3.5)(optionator@0.9.4)(rollup@4.56.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(typescript@5.6.3)(vue-tsc@2.2.12(typescript@5.6.3))(vue@3.5.26(typescript@5.6.3))(yaml@2.8.2) '@oxc-parser/wasm': 0.60.0 '@unhead/vue': 2.1.4(vue@3.5.26(typescript@5.6.3)) '@vue/shared': 3.5.26 @@ -28645,7 +28888,7 @@ snapshots: mlly: 1.8.0 mocked-exports: 0.1.1 nanotar: 0.2.1 - nitropack: 2.13.1(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13) + nitropack: 2.13.1(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0))(encoding@0.1.13) nypm: 0.6.4 ofetch: 1.5.1 ohash: 2.0.11 @@ -28667,7 +28910,7 @@ snapshots: unimport: 4.2.0 unplugin: 2.3.11 unplugin-vue-router: 0.12.0(vue-router@4.6.4(vue@3.5.26(typescript@5.6.3)))(vue@3.5.26(typescript@5.6.3)) - unstorage: 1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2) + unstorage: 1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2) untyped: 2.0.0 vue: 3.5.26(typescript@5.6.3) vue-bundle-renderer: 2.2.0 @@ -28675,7 +28918,7 @@ snapshots: vue-router: 4.6.4(vue@3.5.26(typescript@5.6.3)) optionalDependencies: '@parcel/watcher': 2.5.6 - '@types/node': 24.3.0 + '@types/node': 25.9.5 transitivePeerDependencies: - '@azure/app-configuration' - '@azure/cosmos' @@ -29398,21 +29641,21 @@ snapshots: '@csstools/utilities': 2.0.0(postcss@8.5.6) postcss: 8.5.6 - postcss-load-config@4.0.2(postcss@8.5.6)(ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3)): + postcss-load-config@4.0.2(postcss@8.5.6)(ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3)): dependencies: lilconfig: 3.1.3 yaml: 2.8.2 optionalDependencies: postcss: 8.5.6 - ts-node: 10.9.2(@types/node@24.3.0)(typescript@5.6.3) + ts-node: 10.9.2(@types/node@25.9.5)(typescript@5.6.3) - postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2): + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(yaml@2.8.2): dependencies: lilconfig: 3.1.3 optionalDependencies: jiti: 2.6.1 postcss: 8.5.6 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 postcss-loader@7.3.4(postcss@8.5.6)(typescript@5.6.3)(webpack@5.102.0): @@ -31573,14 +31816,14 @@ snapshots: v8-compile-cache-lib: 3.0.1 yn: 3.1.1 - ts-node@10.9.2(@types/node@24.3.0)(typescript@5.6.3): + ts-node@10.9.2(@types/node@25.9.5)(typescript@5.6.3): dependencies: '@cspotcode/source-map-support': 0.8.1 '@tsconfig/node10': 1.0.11 '@tsconfig/node12': 1.0.11 '@tsconfig/node14': 1.0.3 '@tsconfig/node16': 1.0.4 - '@types/node': 24.3.0 + '@types/node': 25.9.5 acorn: 8.15.0 acorn-walk: 8.3.4 arg: 4.1.3 @@ -31610,7 +31853,7 @@ snapshots: tslib@2.8.1: {} - tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(typescript@5.9.3)(yaml@2.8.2): + tsup@8.5.0(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(typescript@5.9.3)(yaml@2.8.2): dependencies: bundle-require: 5.1.0(esbuild@0.25.9) cac: 6.7.14 @@ -31621,7 +31864,7 @@ snapshots: fix-dts-default-cjs-exports: 1.0.1 joycon: 3.1.1 picocolors: 1.1.1 - postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.21.0)(yaml@2.8.2) + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.6)(tsx@4.23.12)(yaml@2.8.2) resolve-from: 5.0.0 rollup: 4.50.2 source-map: 0.8.0-beta.0 @@ -31640,11 +31883,17 @@ snapshots: tsx@4.21.0: dependencies: - esbuild: 0.27.2 + esbuild: 0.27.3 get-tsconfig: 4.10.1 optionalDependencies: fsevents: 2.3.3 + tsx@4.23.12: + dependencies: + esbuild: 0.28.2 + optionalDependencies: + fsevents: 2.3.3 + tuf-js@4.1.0: dependencies: '@tufjs/models': 4.1.0 @@ -31735,7 +31984,7 @@ snapshots: undici-types@6.21.0: {} - undici-types@7.10.0: + undici-types@7.24.6: optional: true undici@6.21.3: {} @@ -31952,7 +32201,7 @@ snapshots: picomatch: 4.0.3 webpack-virtual-modules: 0.6.2 - unstorage@1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2): + unstorage@1.17.4(db0@0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)))(ioredis@5.9.2): dependencies: anymatch: 3.1.3 chokidar: 5.0.0 @@ -31963,7 +32212,7 @@ snapshots: ofetch: 1.5.1 ufo: 1.6.3 optionalDependencies: - db0: 0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.3.14)(pg@8.18.0)(sql.js@1.14.0)) + db0: 0.3.4(better-sqlite3@12.6.2)(drizzle-orm@0.44.7(@opentelemetry/api@1.9.0)(@types/better-sqlite3@7.6.13)(@types/pg@8.16.0)(@types/sql.js@1.4.9)(better-sqlite3@12.6.2)(bun-types@1.4.1)(pg@8.18.0)(sql.js@1.14.0)) ioredis: 5.9.2 untun@0.1.3: @@ -32102,7 +32351,7 @@ snapshots: v8-compile-cache-lib@3.0.1: {} - valibot@1.2.0(typescript@5.6.3): + valibot@1.4.2(typescript@5.6.3): optionalDependencies: typescript: 5.6.3 @@ -32151,23 +32400,23 @@ snapshots: '@types/unist': 3.0.3 vfile-message: 4.0.3 - vite-dev-rpc@1.1.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-dev-rpc@1.1.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: birpc: 2.9.0 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-hot-client: 2.1.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-hot-client: 2.1.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) - vite-hot-client@2.1.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-hot-client@2.1.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - vite-node@1.6.1(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1): + vite-node@1.6.1(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1): dependencies: cac: 6.7.14 debug: 4.4.3 pathe: 1.1.2 picocolors: 1.1.1 - vite: 5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1) + vite: 5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1) transitivePeerDependencies: - '@types/node' - less @@ -32179,13 +32428,13 @@ snapshots: - supports-color - terser - vite-node@3.2.4(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite-node@3.2.4(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.3.2(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - jiti @@ -32200,13 +32449,13 @@ snapshots: - tsx - yaml - vite-node@3.2.4(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite-node@3.2.4(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - jiti @@ -32221,7 +32470,7 @@ snapshots: - tsx - yaml - vite-plugin-checker@0.9.3(eslint@9.33.0(jiti@2.6.1))(optionator@0.9.4)(typescript@5.6.3)(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3)): + vite-plugin-checker@0.9.3(eslint@9.33.0(jiti@2.6.1))(optionator@0.9.4)(typescript@5.6.3)(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue-tsc@2.2.12(typescript@5.6.3)): dependencies: '@babel/code-frame': 7.28.6 chokidar: 4.0.3 @@ -32231,7 +32480,7 @@ snapshots: strip-ansi: 7.1.2 tiny-invariant: 1.3.3 tinyglobby: 0.2.15 - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vscode-uri: 3.1.0 optionalDependencies: eslint: 9.33.0(jiti@2.6.1) @@ -32239,7 +32488,7 @@ snapshots: typescript: 5.6.3 vue-tsc: 2.2.12(typescript@5.6.3) - vite-plugin-inspect@11.3.3(@nuxt/kit@3.21.1(magicast@0.3.5))(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-plugin-inspect@11.3.3(@nuxt/kit@3.21.1(magicast@0.3.5))(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: ansis: 4.2.0 debug: 4.4.3 @@ -32249,14 +32498,14 @@ snapshots: perfect-debounce: 2.1.0 sirv: 3.0.2 unplugin-utils: 0.3.1 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-dev-rpc: 1.1.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-dev-rpc: 1.1.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) optionalDependencies: '@nuxt/kit': 3.21.1(magicast@0.3.5) transitivePeerDependencies: - supports-color - vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: '@babel/core': 7.29.0 '@types/babel__core': 7.20.5 @@ -32264,15 +32513,15 @@ snapshots: merge-anything: 5.1.7 solid-js: 1.9.13 solid-refresh: 0.6.3(solid-js@1.9.13) - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vitefu: 1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vitefu: 1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) optionalDependencies: '@testing-library/jest-dom': 6.7.0 transitivePeerDependencies: - supports-color optional: true - vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-plugin-solid@2.11.12(@testing-library/jest-dom@6.7.0)(solid-js@1.9.13)(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: '@babel/core': 7.29.0 '@types/babel__core': 7.20.5 @@ -32280,46 +32529,46 @@ snapshots: merge-anything: 5.1.7 solid-js: 1.9.13 solid-refresh: 0.6.3(solid-js@1.9.13) - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vitefu: 1.1.1(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vitefu: 1.1.1(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) optionalDependencies: '@testing-library/jest-dom': 6.7.0 transitivePeerDependencies: - supports-color - vite-plugin-vue-tracer@1.2.0(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)): + vite-plugin-vue-tracer@1.2.0(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2))(vue@3.5.26(typescript@5.6.3)): dependencies: estree-walker: 3.0.3 exsolve: 1.0.8 magic-string: 0.30.21 pathe: 2.0.3 source-map-js: 1.2.1 - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) vue: 3.5.26(typescript@5.6.3) - vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): dependencies: debug: 4.4.3 globrex: 0.1.2 tsconfck: 3.1.6(typescript@5.9.3) optionalDependencies: - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) transitivePeerDependencies: - supports-color - typescript - vite@5.4.21(@types/node@24.3.0)(sass@1.97.3)(terser@5.43.1): + vite@5.4.21(@types/node@25.9.5)(sass@1.97.3)(terser@5.43.1): dependencies: esbuild: 0.21.5 postcss: 8.5.6 rollup: 4.56.0 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 fsevents: 2.3.3 sass: 1.97.3 terser: 5.43.1 - vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32328,15 +32577,15 @@ snapshots: rollup: 4.56.0 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 - vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32350,10 +32599,10 @@ snapshots: jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 - vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: esbuild: 0.25.9 fdir: 6.5.0(picomatch@4.0.3) @@ -32362,15 +32611,15 @@ snapshots: rollup: 4.50.2 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 - vite@7.3.2(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite@7.3.2(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: esbuild: 0.27.3 fdir: 6.5.0(picomatch@4.0.4) @@ -32384,10 +32633,10 @@ snapshots: jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 - vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: esbuild: 0.27.3 fdir: 6.5.0(picomatch@4.0.4) @@ -32396,31 +32645,31 @@ snapshots: rollup: 4.56.0 tinyglobby: 0.2.15 optionalDependencies: - '@types/node': 24.3.0 + '@types/node': 25.9.5 fsevents: 2.3.3 jiti: 2.6.1 sass: 1.97.3 terser: 5.43.1 - tsx: 4.21.0 + tsx: 4.23.12 yaml: 2.8.2 - vitefu@1.1.1(vite@6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vitefu@1.1.1(vite@6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): optionalDependencies: - vite: 6.4.1(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 6.4.1(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - vitefu@1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vitefu@1.1.1(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): optionalDependencies: - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - vitefu@1.1.1(vite@7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)): + vitefu@1.1.1(vite@7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)): optionalDependencies: - vite: 7.3.2(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.3.2(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) - vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@22.18.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@vitest/mocker': 3.2.4(vite@7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -32438,8 +32687,8 @@ snapshots: tinyglobby: 0.2.15 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-node: 3.2.4(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@22.18.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 @@ -32459,11 +32708,11 @@ snapshots: - tsx - yaml - vitest@3.2.4(@types/debug@4.1.12)(@types/node@24.3.0)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2): + vitest@3.2.4(@types/debug@4.1.12)(@types/node@25.9.5)(jiti@2.6.1)(jsdom@26.1.0)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2): dependencies: '@types/chai': 5.2.2 '@vitest/expect': 3.2.4 - '@vitest/mocker': 3.2.4(vite@7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2)) + '@vitest/mocker': 3.2.4(vite@7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2)) '@vitest/pretty-format': 3.2.4 '@vitest/runner': 3.2.4 '@vitest/snapshot': 3.2.4 @@ -32481,12 +32730,12 @@ snapshots: tinyglobby: 0.2.15 tinypool: 1.1.1 tinyrainbow: 2.0.0 - vite: 7.1.5(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) - vite-node: 3.2.4(@types/node@24.3.0)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.21.0)(yaml@2.8.2) + vite: 7.1.5(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@25.9.5)(jiti@2.6.1)(sass@1.97.3)(terser@5.43.1)(tsx@4.23.12)(yaml@2.8.2) why-is-node-running: 2.3.0 optionalDependencies: '@types/debug': 4.1.12 - '@types/node': 24.3.0 + '@types/node': 25.9.5 jsdom: 26.1.0 transitivePeerDependencies: - jiti diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 0ae08557f54..5ce55660405 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -29,4 +29,8 @@ packages: - 'modules/sdk-test-case-conversion-ts' - 'docs' - 'codex-plugin/scripts' + - 'spacetime-*-ts' + - 'spacetime-*-ts/example' + - 'spacetime-*-ts/spacetimedb' + - 'spacetime-*-ts/example/spacetimedb' minimumReleaseAge: 1440 diff --git a/spacetime-cron-ts/.npmrc b/spacetime-cron-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/LICENSE.txt b/spacetime-cron-ts/LICENSE.txt new file mode 100644 index 00000000000..4e61a2122e7 --- /dev/null +++ b/spacetime-cron-ts/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Clockwork Labs, Inc + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/spacetime-cron-ts/README.md b/spacetime-cron-ts/README.md new file mode 100644 index 00000000000..902ea7b0ee0 --- /dev/null +++ b/spacetime-cron-ts/README.md @@ -0,0 +1,389 @@ +# @spacetimedb/cron + +Calendar and interval scheduling for SpacetimeDB TypeScript modules. + +Each job has stable database state, one per-job schedule table, a statically +registered handler, typed arguments, and bounded run history. Calendar +schedules support IANA time zones and daylight-saving transitions. Reducer +failures use SpacetimeDB's temporary volatile recovery mechanism until nested +transactions are available. + +## Requirements + +- A SpacetimeDB CLI and server compatible with the host SDK +- The `spacetimedb` npm version required by this package's peer dependency +- Host support for the `spacetime:sys@2.0` volatile procedure used by failure + recovery +- Node.js 20 or later for package tooling + +## Install + +```bash +npm install @spacetimedb/cron spacetimedb +``` + +`spacetimedb` is a peer dependency. Use the same SDK version for the application module and this package. + +For the complete install, build, and publish workflow, see the repository's +[Getting started guide](https://spacetimedb.com/docs/). + +## Usage + +### Integrate into an application + +```ts +import { + SenderError, + schema, + table, + t, + toCamelCase, + type InferSchema, + type ProcedureCtx, + type ReducerCtx, +} from 'spacetimedb/server'; +import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { spacetimeCron } from '@spacetimedb/cron'; + +const { cronTable, createCron, schedule, unschedule } = spacetimeCron({ + table, + t, + toCamelCase, + ScheduleAt, + Timestamp, + SenderError, +}); + +const dailyReport = cronTable({ + name: 'daily_report', + args: t.object('DailyReportCronArgs', { + workspaceId: t.u64(), + format: t.string(), + }), +}); +const heartbeat = cronTable({ name: 'heartbeat' }); +const refreshCatalog = cronTable({ name: 'refresh_catalog' }); + +const cron = createCron([dailyReport, heartbeat, refreshCatalog], { + publicTables: true, + reconcileEverySeconds: 300, +}); + +const report = table( + { name: 'report', public: true }, + { + id: t.u64().primaryKey().autoInc(), + generatedAt: t.timestamp(), + } +); + +const spacetimedb = schema({ ...cron.tables, report }); +export default spacetimedb; + +type Schema = InferSchema; +type Tx = ReducerCtx; +type Proc = ProcedureCtx; + +export const generateReport = dailyReport.cronReducer( + spacetimedb, + (ctx: Tx, args, invocation) => { + ctx.db.report.insert({ + id: 0n, + generatedAt: invocation.scheduledFor, + }); + console.log( + `Generating ${args.format} report for workspace ${args.workspaceId}` + ); + } +); + +export const beat = heartbeat.cronReducer(spacetimedb, (_ctx: Tx) => { + // Perform deterministic database work here. +}); + +export const refresh = refreshCatalog.cronProcedure( + spacetimedb, + (ctx: Proc, invocation) => { + // Use invocation.id as the idempotency key for an external request. + ctx.http.fetch('https://example.com/catalog'); + } +); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + schedule(ctx, dailyReport, '0 9 * * 1-5', { + timezone: 'America/New_York', + maxFailures: 3, + args: { workspaceId: 42n, format: 'summary' }, + }); + schedule(ctx, heartbeat, { everySeconds: 30 }); + schedule(ctx, refreshCatalog, '0 */15 * * * *'); +}); +``` + +`init` seeds schedules for a fresh database. Runtime schedule changes remain database state across module publishes. + +## API + +### Registering jobs + +Create one handle for each statically known job: + +```ts +const cleanup = cronTable({ name: 'cleanup' }); +``` + +Declare a SpacetimeDB type when a job needs durable arguments: + +```ts +const archiveWorkspace = cronTable({ + name: 'archive_workspace', + args: t.object('ArchiveWorkspaceCronArgs', { + workspaceId: t.u64(), + retainDays: t.u32(), + }), +}); +``` + +The handle carries the inferred argument type through `schedule()`, +`cronReducer()`, and `cronProcedure()`. The argument builder may be any +SpacetimeDB type, although a named `t.object()` gives most jobs the clearest +call site and database schema. + +Job names use lowercase snake_case and may contain up to 48 characters. Pass +every handle to one `createCron()` call, register exactly one reducer or +procedure for each handle. `schedule()` rejects a configuration with a missing +handler. When `reconcileEverySeconds` is configured, export +`cron.reconcileReducer()`. Applications that expose cron status export the +`jobs` view returned by `cron.publicViews()`. + +Each reducer job handles its normal fires and its internal recovery calls. A +handler failure schedules the same job reducer with a private recovery payload. +The second invocation records the failure and restores calendar scheduling in a +fresh transaction. It does not call the application handler. Procedure jobs use +their separate transaction flow and do not use volatile recovery. + +Use `cronReducer` for deterministic database work. The handler receives the consumer module's typed reducer context and a `CronInvocation`: + +```ts +export const runCleanup = cleanup.cronReducer( + spacetimedb, + (ctx: Tx, invocation) => { + console.log(invocation.id); + // Database writes commit together when the handler succeeds. + } +); +``` + +Use `cronProcedure` for HTTP requests and other procedure capabilities: + +```ts +export const syncRemote = remoteSync.cronProcedure( + spacetimedb, + (ctx: Proc, invocation) => { + sendRequest({ idempotencyKey: invocation.id }); + } +); +``` + +Handlers complete synchronously. SpacetimeDB procedure APIs, including `ctx.http.fetch` and `ctx.withTx`, expose synchronous module calls. + +Argument-bearing handlers receive their typed payload before the invocation +metadata: + +```ts +export const runArchive = archiveWorkspace.cronReducer( + spacetimedb, + (ctx: Tx, args, invocation) => { + archiveRows(ctx, args.workspaceId, args.retainDays); + console.log(invocation.id); + } +); +``` + +### Scheduling and cancellation + +`schedule()` first repairs any enabled jobs with missing triggers. It then +creates or replaces the requested schedule, clears failure state, increments +the job generation, and enables the job. + +```ts +schedule(ctx, cleanup, '30 2 * * *', { timezone: 'UTC' }); +schedule(ctx, cleanup, { everySeconds: 300 }); + +schedule(ctx, archiveWorkspace, '0 3 * * *', { + timezone: 'UTC', + args: { workspaceId: 42n, retainDays: 90 }, +}); +``` + +Arguments are required when scheduling an argument-bearing job. Rescheduling +replaces the schedule, arguments, generation, and pending fire atomically. A +handler receives the argument value read at the start of its fire. + +Cron expressions accept five fields or six fields when seconds are included. Fixed intervals accept whole seconds from 1 through 31,536,000. + +`unschedule()` runs the same opportunistic repair before removing the target +fire, incrementing its generation, and leaving job and history rows available +for inspection. + +```ts +unschedule(ctx, cleanup); +``` + +These helpers perform scheduling operations. Application reducers remain responsible for authorization. + +### Database state + +The package adds these shared tables: + +| Table | Purpose | +| ---------- | ------------------------------------------------------------------- | +| `cron_job` | Private schedule, typed arguments, generation, health, and next run | +| `cron_run` | Completed invocation identity, outcome, and bounded history | + +When `reconcileEverySeconds` is set, the package also adds +`cron_reconcile_tick`. It contains one native interval row that periodically +repairs enabled jobs with missing triggers. + +Each job receives one `_fire` schedule table bound directly to its +`_cron` reducer or procedure. An enabled job owns exactly one row in +that table. Calendar jobs replace one-shot rows after each fire. Fixed-rate +jobs retain one native interval row. + +The package owns the shared names above, the public view name `cron_jobs`, every +`_fire` table, and every `_cron` scheduled function. +Enabling periodic reconciliation also reserves `cron_reconcile` and +`cron_reconcile_tick`. Consumer modules should keep those database function, +table, and view names available for cron. + +`cron_job` is always private. Registering `cron.publicViews()` exposes +`cron_jobs`, a subscribable projection of job state that omits typed arguments +and detailed failure text. Its optional `disabledReason` is one of +`disabled_by_operator`, `failure_threshold_reached`, +`lost_fire_threshold_reached`, `invalid_schedule_state`, or `disabled`. +`publicTables` defaults to `false`; enabling it exposes each per-job fire table +and `cron_run`, including run error details. The fire-table `recovery` column is +internal. Stored schedule rows leave it empty. + +For calendar jobs, `cron_jobs.nextRunAt` and the job's fire-table `targetAt` +identify the logical next occurrence. For native interval jobs, `nextRunAt` is +an estimate based on the most recent fire. The database owner and module +reducers can inspect the private `cron_job` table directly. + +### Execution model + +Each fire table is bound directly to one statically registered handler. + +For reducer jobs, the middleware rearms a calendar schedule before calling the +handler. On success, the successor, application writes, job health, and run +record commit in one transaction. On failure, the middleware serializes the +fire row with an internal recovery payload, schedules the same +`_cron` reducer through +`volatile_nonatomic_schedule_immediate`, and rethrows. The fire transaction +rolls back, including partial application writes. The recovery invocation runs +in a fresh transaction. It validates the database caller, generation, and +sequence before it records the failure. Calendar recovery replaces the pending +fire. Native interval rows persist, so interval recovery keeps that row and +updates job health. + +The explicit recovery payload distinguishes a recovery call from a normal fire. +The implementation does not infer the call type from schedule-row presence. +This gives calendar and interval jobs the same failure path and prevents the +application handler from running again during recovery. + +The volatile call is best effort and is not persisted. A process crash, +uncatchable trap, or lost message can temporarily leave an enabled calendar job +without a fire. The package detects that broken invariant during every +`schedule()` and `unschedule()` operation. Set `reconcileEverySeconds` to add a +low-frequency native interval sweep: + +```ts +const cron = createCron(jobs, { reconcileEverySeconds: 300 }); + +// Export after registering the job handlers. +export const cronReconcile = cron.reconcileReducer(spacetimedb); +``` + +Repair removes any stale trigger, inserts a valid current-generation trigger, +and records one `Failed` run with error `lost_fire`. The normal failure counter, +history cap, and automatic disable policy apply. Without the optional sweep, +repair occurs on the next management operation. With it, detection is bounded +by the configured interval and scheduler availability. + +This remains a temporary best-effort design until nested transactions are +available. Native interval job rows remain scheduled independently. + +Procedure jobs secure the next calendar fire in a committed transaction, run +the procedure work, then record the outcome in another transaction. A process +failure during external work can lose the run record, but it does not remove +the next calendar fire. `CronInvocation.id` is stable and should be used as an +external idempotency key. + +`maxFailures` counts consecutive recorded failures. A positive threshold +disables the job and stores the reason. A successful invocation resets the +counter. + +### Argument schema changes + +Job names and argument builders are part of the module's database schema. +Adding a new job adds a new internal union variant. Changing the argument +builder for an existing job requires a SpacetimeDB schema migration. For an +incompatible payload change, a new job name provides a clean version boundary. + +### Scheduling behavior + +- The next calendar occurrence is computed strictly after the dispatch timestamp. +- An overdue one-shot trigger produces one catch-up invocation. Intermediate missed occurrences are skipped. +- Spring-forward and fall-back behavior follows `cron-parser` 5.x and is covered by tests. +- Sparse expressions use internal checkpoint triggers so valid occurrences beyond the host timer horizon remain scheduled. +- Fixed intervals use SpacetimeDB native `ScheduleAt.interval` rows. + +Scheduled functions execute through SpacetimeDB's scheduler. A long-running procedure delays other scheduled work in the same module, so procedure handlers should finish promptly. + +### Run history + +`historyCap` defaults to five completed records per job and accepts values from +0 through 1,000. + +Run statuses are: + +- `Ok`: work completed successfully +- `Failed`: the handler returned an error + +### Parser exports + +```ts +import { + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from '@spacetimedb/cron/parser'; +``` + +## Testing + +```bash +pnpm test +pnpm lint +pnpm typecheck +pnpm run test:recovery +pnpm run test:module:local +``` + +The local integration suite requires `spacetime start` and validates module +publication, calendar chains, native intervals, typed reducer and procedure +arguments, same-reducer volatile recovery, reducer rollback, +opportunistic and interval-sweep lost-fire repair, automatic disablement, +procedure outcomes, generations, cancellation, history bounds, authorization, +and the example module. The recovery suite verifies that a procedure commits +its next calendar fire before external work, survives a host stop, and performs +at most one catch-up invocation after downtime. + +See the [browser example](./example/) for a complete integration. + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-cron-ts/example/.env.example b/spacetime-cron-ts/example/.env.example new file mode 100644 index 00000000000..b43135687a0 --- /dev/null +++ b/spacetime-cron-ts/example/.env.example @@ -0,0 +1,9 @@ +# Copy to .env. The example server loads this on startup. + +# ---------------- Static server ---------------- +HOST=127.0.0.1 +PORT=8788 + +# ---------------- SpacetimeDB ---------------- +STDB_URI=ws://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-cron-example diff --git a/spacetime-cron-ts/example/.npmrc b/spacetime-cron-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/example/README.md b/spacetime-cron-ts/example/README.md new file mode 100644 index 00000000000..339e2d3d2fe --- /dev/null +++ b/spacetime-cron-ts/example/README.md @@ -0,0 +1,198 @@ +# Cron example + +This example is a small browser dashboard backed directly by SpacetimeDB. It shows two jobs: + +- `digest`, a weekday calendar job in `America/New_York` +- `cleanup`, a five-minute native interval job with a typed `keep` argument + +The dashboard subscribes to the sanitized `cron_jobs` view, exact calendar targets, interval estimates, run outcomes, and application activity. The private job rows retain typed arguments without exposing them to browser subscriptions. Controls can reschedule or disable either job. Selecting `cleanup` also supplies its typed row-retention argument when scheduling. + +This is a local development example. Its scheduling reducers accept any connected caller so the browser can exercise the submodule. Add application authorization before deploying equivalent controls. The example also enables `publicTables`, which exposes run history and trigger state for the dashboard. Review that visibility before using the same option in an application. + +## What this demonstrates + +- Declaring static calendar and interval jobs. +- Attaching a typed argument to the `cleanup` job. +- Registering one handler and one schedule table for each job. +- Scheduling defaults during a fresh database initialization. +- Rescheduling and disabling jobs through application reducers. +- Subscribing to sanitized job state, run history, and application activity. +- Repairing an enabled job that loses its pending fire. +- Keeping browser-visible job state separate from private typed arguments. + +## Prerequisites + +- Node.js 20 or later +- pnpm 10 +- A SpacetimeDB CLI and server built from this checkout, with the CLI available as `spacetime` +- A local SpacetimeDB server + +This example uses the workspace SDK. The CLI and server must support the same +host APIs as that SDK. + +## Quick start + +Start the server in a separate terminal: + +```bash +spacetime start +``` + +From this directory: + +```bash +pnpm install +pnpm --dir spacetimedb install +pnpm run build:module:fresh +pnpm run dev +``` + +Open . + +`build:module:fresh` performs four steps: + +1. Builds the TypeScript module. +2. Publishes `spacetime-cron-example` to the local server with fresh data. +3. Regenerates TypeScript client bindings. +4. Typechecks and bundles the browser application. + +After a module edit, preserve existing local data with: + +```bash +pnpm run build:module +``` + +## Use in your project + +This workspace tests the submodule source in this repository. Consumer +applications install the published release: + +```bash +npm install @spacetimedb/cron spacetimedb +``` + +The complete server integration is in [`spacetimedb/src/index.ts`](./spacetimedb/src/index.ts). The browser integration is in [`src/app.ts`](./src/app.ts). + +## Configuration + +The static server reads these optional variables from the process environment or `.env` files: + +| Variable | Default | Purpose | +| --------------------- | ------------------------ | ------------------------------------ | +| `PORT` | `8788` | Development web-server port. | +| `HOST` | `127.0.0.1` | Development web-server bind address. | +| `STDB_URI` | `ws://127.0.0.1:3000` | Browser WebSocket endpoint. | +| `SPACETIMEDB_DB_NAME` | `spacetime-cron-example` | Published database name. | + +The browser connects directly to SpacetimeDB. The Express process serves static files and `/api/config`. + +## Execution flow + +1. `cronTable()` declares `digest` and `cleanup` as static jobs. `cleanup` also + declares `{ keep: u32 }` as its durable argument. +2. `createCron()` creates the private shared job table, run history, one schedule + table for each job, and the optional five-minute reconciler. +3. `schema()` mounts the Cron tables with the example's `activity_log` table. +4. `cronReducer()` binds each job to its static handler. +5. `cron.reconcileReducer()` registers the low-frequency lost-fire repair sweep. +6. `init` schedules the weekday digest and five-minute cleanup defaults on a + fresh publish. +7. The browser subscribes to `cron_jobs`, `cron_run`, and `activity_log`. +8. The scheduling form calls application reducers. Those reducers validate the + selected job and typed cleanup argument before calling `schedule()`. + +The `digest` handler appends a summary row. The `cleanup` handler keeps the newest +configured number of activity rows and records how many older rows it removed. + +## Failure and recovery behavior + +Reducer jobs run in a transaction. A successful job commits its application +writes, run record, health update, and next calendar fire together. + +When a reducer handler throws, the fire transaction rolls back. Cron uses the +temporary SpacetimeDB volatile primitive to call the same job reducer with an +internal recovery payload, then rethrows the original error. The second +invocation restores the calendar schedule and records the failed run in a new +transaction. It does not run the application handler again. Native interval +rows remain present, and the same recovery path records their failure state. + +The volatile request is best effort. A host failure can leave an enabled job +without a pending fire. This example enables a five-minute reconciler. The +reconciler repairs that invariant and records a failed run with `lost_fire`. +Calls to `schedule()` and `unschedule()` also perform this repair +opportunistically. + +Typed arguments remain in the private `cron_job` row. The browser-visible +`cron_jobs` view omits them. This example exposes fire tables and detailed run +history through `publicTables` for demonstration. Applications should expose +only the status required by their users. + +## Authorization and deployment boundaries + +- `scheduleCron`, `scheduleEvery`, and `unscheduleJob` are open so a local browser + can exercise the submodule. Production modules must authorize these calls. +- Job names and argument types are part of the database schema. Changing an + existing argument type requires a schema migration or a new job name. +- Reducer handlers must remain deterministic. Use a Cron procedure for HTTP or + other procedure capabilities. +- Procedure handlers should use `CronInvocation.id` as an external idempotency + key. +- The included Express process is a local static server. Production needs TLS, + explicit origin policy, and process supervision. + +## Build and verification + +From `spacetime-cron-ts/example`: + +```powershell +pnpm --dir spacetimedb run build +pnpm run build +pnpm exec tsc -p tsconfig.json +``` + +From `spacetime-cron-ts`, run the package and local integration suites: + +```powershell +pnpm test +pnpm run test:module:local +pnpm run test:recovery +``` + +`test:module:local` requires a running local SpacetimeDB server and publishes a +temporary database. `test:recovery` starts and removes its own isolated server. +Together, they exercise reducer rollback, same-reducer volatile recovery, +calendar and interval failures, typed arguments, lost-fire reconciliation, +history limits, and host restart recovery. + +For a browser release check: + +1. Confirm both seeded jobs appear after a fresh publish. +2. Schedule `digest` as a short interval and confirm a run and activity row + appear. +3. Schedule `cleanup` with a new `keep` value and confirm the active schedule + remains after reload. +4. Unschedule a job and confirm it becomes disabled with no pending fire. +5. Reschedule the disabled job and confirm it fires again. +6. Confirm the browser console has no errors and every subscription applies. + +## Troubleshooting + +- **No jobs appear:** confirm `SPACETIMEDB_DB_NAME` matches + `spacetime-cron-example` and reload after the subscription applies. +- **The browser cannot connect:** confirm `STDB_URI` points to the server used by + `spacetime publish --server local`. +- **A local package edit is missing:** run + `pnpm --dir spacetimedb install --force`, then rebuild the module. +- **A schedule is rejected:** use a five-field or six-field Cron expression, a + valid IANA time zone, or an interval from 1 through 31,536,000 seconds. +- **A job disables itself:** inspect its recent failed runs and configured + failure threshold before rescheduling it. + +## Important files + +- `spacetimedb/src/index.ts` - job declarations, handlers, initialization, and + browser-facing management reducers. +- `src/app.ts` - typed connection, subscriptions, rendering, and controls. +- `public/index.html` - dashboard structure. +- `public/styles.css` - dashboard presentation. +- `server.ts` - static development server and browser-safe configuration. diff --git a/spacetime-cron-ts/example/package.json b/spacetime-cron-ts/example/package.json new file mode 100644 index 00000000000..46b087eebd9 --- /dev/null +++ b/spacetime-cron-ts/example/package.json @@ -0,0 +1,28 @@ +{ + "name": "spacetime-cron-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings/app --module-path ./spacetimedb -y", + "build:module": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local && pnpm run spacetime:generate && pnpm run build:app", + "build:module:fresh": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local:reset && pnpm run spacetime:generate && pnpm run build:app", + "check": "tsc --noEmit", + "build:app": "pnpm run check && esbuild src/app.ts --bundle --format=esm --outfile=public/app.js --target=es2022 --sourcemap", + "build": "pnpm run spacetime:generate && pnpm run build:app", + "dev": "pnpm run build && tsx server.ts" + }, + "dependencies": { + "@spacetimedb/submodule-shared": "workspace:*", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.10.2", + "esbuild": "^0.28.0", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/example/public/index.html b/spacetime-cron-ts/example/public/index.html new file mode 100644 index 00000000000..9326b444d62 --- /dev/null +++ b/spacetime-cron-ts/example/public/index.html @@ -0,0 +1,272 @@ + + + + + + + SpacetimeDB Cron + + + + +
+
+ + + SpacetimeDB + Cron + +
+ + + Connecting + + +
+
+ +
+
+ +
+ 0 + Configured jobs +
+
+
+ +
+ 0 + Healthy schedules +
+
+
+ +
+ 0 + Total dispatches +
+
+
+ +
+
+
+
+

Configured jobs

+

+ Schedules + 0 +

+
+ + + Live state + +
+
+
+ +

No jobs scheduled

+

Choose a preset or configure a schedule below.

+
+ +
+
+ +
+
+
+
+

Execution history

+

+ Recent runs + 0 +

+
+
+
+
+ +

Runs will appear after a job fires.

+
+ +
+
+ +
+
+
+

Application output

+

+ Activity + 0 +

+
+
+
+
+ +

Handler output will appear here.

+
+ +
+
+
+
+ +
+
+

Try the API

+

Schedule a job

+

+ Configure one of the example handlers with a calendar expression or + a fixed interval. Scheduling the same job again replaces its current + configuration. +

+
+ + + +
+
+ +
+
+ + + + + +
+
+

+ +
+
+
+ + +
+ + + diff --git a/spacetime-cron-ts/example/public/styles.css b/spacetime-cron-ts/example/public/styles.css new file mode 100644 index 00000000000..83580dfa79e --- /dev/null +++ b/spacetime-cron-ts/example/public/styles.css @@ -0,0 +1,982 @@ +:root { + color-scheme: dark; + --page: #070b0f; + --surface: #0d1419; + --surface-raised: #111b21; + --surface-soft: #152128; + --line: #22313b; + --line-strong: #324750; + --text: #f3f5f6; + --muted: #8a9aa5; + --muted-bright: #b9c4ca; + --accent: #49d4ba; + --accent-strong: #78ead4; + --blue: #52b8f4; + --violet: #a997ff; + --green: #4cf490; + --amber: #f4c95d; + --red: #ff8f8f; + --radius-lg: 18px; + --radius-md: 12px; + --radius-sm: 8px; + font-family: + Inter, + ui-sans-serif, + system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + sans-serif; +} + +* { + box-sizing: border-box; +} + +html { + min-width: 320px; + scroll-behavior: smooth; +} + +body { + min-height: 100vh; + margin: 0; + color: var(--text); + background: + radial-gradient( + circle at 15% -10%, + rgb(73 212 186 / 12%), + transparent 32rem + ), + radial-gradient(circle at 95% 8%, rgb(82 184 244 / 8%), transparent 28rem), + var(--page); +} + +button, +input, +select { + font: inherit; +} + +button, +a, +select { + -webkit-tap-highlight-color: transparent; +} + +button { + color: inherit; +} + +a { + color: inherit; +} + +[hidden] { + display: none !important; +} + +.shell { + width: min(1240px, calc(100% - 40px)); + margin: 0 auto; + padding: 20px 0 36px; +} + +.topbar { + position: relative; + z-index: 10; + display: flex; + align-items: center; + justify-content: space-between; + min-height: 68px; + padding: 14px 16px 14px 20px; + border: 1px solid rgb(255 255 255 / 7%); + border-radius: var(--radius-lg); + background: rgb(13 20 25 / 82%); + box-shadow: 0 18px 60px rgb(0 0 0 / 18%); + backdrop-filter: blur(18px); +} + +.brand { + display: inline-flex; + align-items: center; + gap: 11px; + text-decoration: none; +} + +.brand img { + width: 31px; + height: 28px; +} + +.brand-name { + font-size: 1.02rem; + font-weight: 680; + letter-spacing: -0.025em; +} + +.brand-product { + padding: 4px 8px; + border: 1px solid var(--line-strong); + border-radius: 6px; + color: var(--muted-bright); + background: var(--surface-soft); + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.08em; + line-height: 1; + text-transform: uppercase; +} + +.topbar-actions, +.form-actions { + display: flex; + align-items: center; + gap: 12px; +} + +.connection { + display: inline-flex; + align-items: center; + gap: 8px; + min-height: 36px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: 999px; + color: var(--muted-bright); + background: rgb(7 11 15 / 55%); + font-size: 0.78rem; + font-weight: 600; +} + +.connection-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--amber); + box-shadow: 0 0 0 4px rgb(244 201 93 / 10%); +} + +.connection[data-state='connected'] .connection-dot { + background: var(--green); + box-shadow: 0 0 0 4px rgb(76 244 144 / 10%); +} + +.connection[data-state='error'] .connection-dot, +.connection[data-state='disconnected'] .connection-dot { + background: var(--red); + box-shadow: 0 0 0 4px rgb(255 143 143 / 10%); +} + +.button { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + min-height: 40px; + padding: 0 15px; + border: 1px solid transparent; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.82rem; + font-weight: 700; + transition: + border-color 150ms ease, + background 150ms ease, + color 150ms ease, + transform 150ms ease; +} + +.button:not(:disabled):active { + transform: translateY(1px); +} + +.button:disabled { + cursor: not-allowed; + opacity: 0.45; +} + +.button-primary { + color: #04100d; + background: var(--accent); + box-shadow: 0 8px 28px rgb(73 212 186 / 13%); +} + +.button-primary:not(:disabled):hover { + background: var(--accent-strong); +} + +.button-secondary { + border-color: var(--line); + color: var(--muted-bright); + background: var(--surface-raised); +} + +.button-secondary:not(:disabled):hover { + border-color: var(--line-strong); + color: var(--text); + background: var(--surface-soft); +} + +.button-small { + min-height: 32px; + padding: 0 11px; + font-size: 0.74rem; +} + +.eyebrow, +.panel-kicker { + margin: 0 0 10px; + color: var(--accent); + font-size: 0.69rem; + font-weight: 800; + letter-spacing: 0.15em; + text-transform: uppercase; +} + +.summary { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + margin-top: 12px; +} + +.summary-card { + display: flex; + align-items: center; + gap: 14px; + min-height: 92px; + padding: 18px 20px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: rgb(13 20 25 / 75%); +} + +.summary-card strong { + display: block; +} + +.summary-card strong { + font-size: 1.55rem; + font-weight: 620; + letter-spacing: -0.04em; +} + +.summary-card div > span { + margin-top: 2px; + color: var(--muted); + font-size: 0.76rem; +} + +.summary-card .summary-icon { + display: grid; + width: 40px; + height: 40px; + flex: 0 0 auto; + border: 1px solid; + border-radius: 10px; + place-items: center; + line-height: 0; +} + +.summary-icon svg, +.empty-icon svg { + width: 18px; + height: 18px; + fill: none; + stroke: currentColor; + stroke-linecap: round; + stroke-linejoin: round; + stroke-width: 1.8; +} + +.summary-icon-blue { + border-color: rgb(82 184 244 / 22%); + color: var(--blue); + background: rgb(82 184 244 / 8%); +} + +.summary-icon-green { + border-color: rgb(76 244 144 / 22%); + color: var(--green); + background: rgb(76 244 144 / 8%); +} + +.summary-icon-violet { + border-color: rgb(169 151 255 / 22%); + color: var(--violet); + background: rgb(169 151 255 / 8%); +} + +.workspace { + display: grid; + grid-template-columns: minmax(0, 1.3fr) minmax(320px, 0.7fr); + gap: 12px; + margin-top: 12px; +} + +.workspace-side { + display: grid; + grid-template-rows: repeat(2, minmax(0, 1fr)); + gap: 12px; +} + +.panel { + min-width: 0; + overflow: hidden; + border: 1px solid var(--line); + border-radius: var(--radius-lg); + background: rgb(13 20 25 / 82%); +} + +.panel-header { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 84px; + padding: 20px 22px; + border-bottom: 1px solid var(--line); +} + +.panel-header-compact { + min-height: 76px; + padding: 17px 20px; +} + +.panel-kicker { + margin-bottom: 6px; + color: var(--muted); + font-size: 0.61rem; +} + +.panel h2 { + display: flex; + align-items: center; + gap: 9px; + margin: 0; + font-size: 1rem; + font-weight: 650; + letter-spacing: -0.02em; +} + +.count { + display: inline-grid; + min-width: 22px; + height: 22px; + padding: 0 6px; + border: 1px solid var(--line); + border-radius: 999px; + place-items: center; + color: var(--muted); + background: var(--page); + font-size: 0.65rem; +} + +.live-label { + display: inline-flex; + align-items: center; + gap: 7px; + color: var(--muted); + font-size: 0.69rem; + font-weight: 650; +} + +.live-label span { + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 9px rgb(73 212 186 / 60%); +} + +.panel-body { + min-height: 360px; + padding: 12px; +} + +.panel-body-compact { + min-height: 208px; +} + +.empty-state { + display: grid; + min-height: 335px; + padding: 36px 20px; + place-content: center; + place-items: center; + text-align: center; +} + +.empty-state-small { + min-height: 182px; +} + +.empty-icon { + display: grid; + width: 42px; + height: 42px; + margin-bottom: 13px; + border: 1px solid var(--line); + border-radius: 12px; + place-items: center; + color: var(--accent); + background: var(--surface-raised); + line-height: 0; +} + +.empty-state h3 { + margin: 0; + font-size: 0.91rem; + font-weight: 650; +} + +.empty-state p { + max-width: 280px; + margin: 7px 0 0; + color: var(--muted); + font-size: 0.76rem; + line-height: 1.55; +} + +.job-list, +.event-list { + margin: 0; + padding: 0; + list-style: none; +} + +.job-list { + display: grid; + gap: 9px; +} + +.job-card { + padding: 17px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: var(--surface-raised); +} + +.job-card[data-enabled='false'] { + opacity: 0.72; +} + +.job-card-top, +.event-item { + display: flex; + align-items: center; +} + +.job-card-top { + justify-content: space-between; + gap: 16px; +} + +.job-identity { + display: flex; + align-items: center; + min-width: 0; + gap: 11px; +} + +.job-icon { + display: grid; + width: 38px; + height: 38px; + flex: 0 0 auto; + border: 1px solid rgb(73 212 186 / 20%); + border-radius: 10px; + place-items: center; + color: var(--accent); + background: rgb(73 212 186 / 7%); + font-size: 0.76rem; + font-weight: 800; + line-height: 1; +} + +.job-identity strong, +.job-identity code { + display: block; +} + +.job-identity strong { + overflow: hidden; + font-size: 0.9rem; + font-weight: 650; + text-overflow: ellipsis; + white-space: nowrap; +} + +.job-identity code, +.job-schedule code, +.preset code { + color: var(--muted); + font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', monospace; + font-size: 0.67rem; +} + +.job-identity code { + margin-top: 3px; +} + +.status-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 5px 8px; + border: 1px solid; + border-radius: 999px; + font-size: 0.63rem; + font-weight: 750; + text-transform: capitalize; +} + +.status-badge::before { + width: 5px; + height: 5px; + border-radius: 50%; + background: currentColor; + content: ''; +} + +.status-badge.enabled { + border-color: rgb(76 244 144 / 20%); + color: var(--green); + background: rgb(76 244 144 / 7%); +} + +.status-badge.disabled { + border-color: rgb(255 143 143 / 20%); + color: var(--red); + background: rgb(255 143 143 / 7%); +} + +.job-schedule { + margin: 15px 0; + padding: 10px 12px; + overflow: hidden; + border: 1px solid rgb(255 255 255 / 5%); + border-radius: var(--radius-sm); + background: rgb(7 11 15 / 45%); + text-overflow: ellipsis; + white-space: nowrap; +} + +.job-schedule code { + color: var(--muted-bright); +} + +.job-footer { + display: flex; + align-items: end; + justify-content: space-between; + gap: 16px; +} + +.job-metrics { + display: flex; + min-width: 0; + gap: 22px; +} + +.metric span, +.metric strong { + display: block; +} + +.metric span { + margin-bottom: 3px; + color: var(--muted); + font-size: 0.59rem; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.metric strong { + max-width: 200px; + overflow: hidden; + color: var(--muted-bright); + font-size: 0.72rem; + font-weight: 570; + text-overflow: ellipsis; + white-space: nowrap; +} + +.metric strong.unhealthy { + color: var(--amber); +} + +.event-list { + max-height: 320px; + overflow-y: auto; +} + +.event-item { + align-items: flex-start; + gap: 11px; + padding: 12px 8px; + border-bottom: 1px solid rgb(34 49 59 / 70%); +} + +.event-item:last-child { + border-bottom: 0; +} + +.event-marker { + width: 8px; + height: 8px; + margin-top: 5px; + flex: 0 0 auto; + border: 2px solid var(--surface); + border-radius: 50%; + background: var(--accent); + box-shadow: 0 0 0 2px rgb(73 212 186 / 18%); +} + +.event-marker.ok { + background: var(--green); + box-shadow: 0 0 0 2px rgb(76 244 144 / 16%); +} + +.event-marker.failed { + background: var(--red); + box-shadow: 0 0 0 2px rgb(255 143 143 / 16%); +} + +.event-content { + min-width: 0; +} + +.event-title, +.event-copy, +.event-time { + display: block; +} + +.event-title { + overflow: hidden; + font-size: 0.76rem; + font-weight: 650; + text-overflow: ellipsis; + white-space: nowrap; +} + +.event-copy { + margin-top: 3px; + overflow-wrap: anywhere; + color: var(--muted-bright); + font-size: 0.7rem; + line-height: 1.45; +} + +.event-time { + margin-top: 4px; + color: var(--muted); + font-size: 0.62rem; +} + +.scheduler { + display: grid; + grid-template-columns: minmax(260px, 0.7fr) minmax(0, 1.3fr); + gap: 40px; + margin-top: 12px; + padding: 36px; + scroll-margin-top: 20px; + border: 1px solid var(--line); + border-radius: var(--radius-lg); + background: + linear-gradient(125deg, rgb(73 212 186 / 4%), transparent 36%), + var(--surface); +} + +.scheduler-intro h2 { + margin: 0; + font-size: 1.65rem; + font-weight: 590; + letter-spacing: -0.04em; +} + +.scheduler-intro > p:not(.eyebrow) { + margin: 13px 0 0; + color: var(--muted); + font-size: 0.79rem; + line-height: 1.6; +} + +.presets { + display: grid; + gap: 7px; + margin-top: 22px; +} + +.preset { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + width: 100%; + min-height: 43px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + cursor: pointer; + color: var(--muted-bright); + background: var(--surface-raised); + text-align: left; + transition: + border-color 150ms ease, + background 150ms ease; +} + +.preset:hover { + border-color: var(--line-strong); + background: var(--surface-soft); +} + +.preset span { + font-size: 0.7rem; + font-weight: 650; +} + +.schedule-form { + align-self: center; + padding: 22px; + border: 1px solid var(--line); + border-radius: var(--radius-md); + background: rgb(7 11 15 / 36%); +} + +.field-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.field { + display: grid; + min-width: 0; + gap: 7px; +} + +.field-wide { + grid-column: 1 / -1; +} + +.field > span { + color: var(--muted-bright); + font-size: 0.67rem; + font-weight: 700; +} + +.field input, +.field select { + width: 100%; + min-width: 0; + min-height: 42px; + padding: 0 12px; + border: 1px solid var(--line); + border-radius: var(--radius-sm); + outline: none; + color: var(--text); + background: var(--surface-raised); + font-size: 0.78rem; + transition: + border-color 150ms ease, + box-shadow 150ms ease; +} + +.field select { + cursor: pointer; +} + +.field input:focus, +.field select:focus { + border-color: rgb(73 212 186 / 70%); + box-shadow: 0 0 0 3px rgb(73 212 186 / 9%); +} + +.field small { + color: var(--muted); + font-size: 0.62rem; +} + +.form-actions { + min-height: 58px; + margin-top: 18px; + padding-top: 17px; + border-top: 1px solid var(--line); + justify-content: space-between; +} + +.form-status { + margin: 0; + color: var(--muted); + font-size: 0.7rem; + line-height: 1.45; +} + +.form-status[data-tone='success'] { + color: var(--green); +} + +.form-status[data-tone='error'] { + color: var(--red); +} + +.footer { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 28px 0 2px; + color: var(--muted); + font-size: 0.68rem; +} + +.footer img { + width: 18px; + height: 16px; +} + +.footer a { + color: var(--muted-bright); + font-weight: 650; + text-decoration: none; +} + +.footer a:hover { + color: var(--text); +} + +.footer-divider { + width: 1px; + height: 14px; + margin: 0 3px; + background: var(--line-strong); +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 3px; +} + +@media (max-width: 940px) { + .workspace, + .scheduler { + grid-template-columns: 1fr; + } + + .workspace-side { + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-template-rows: auto; + } + + .scheduler { + gap: 28px; + } + + .presets { + grid-template-columns: repeat(3, 1fr); + } + + .preset { + align-items: flex-start; + flex-direction: column; + gap: 5px; + padding: 11px; + } +} + +@media (max-width: 680px) { + .shell { + width: min(100% - 24px, 1240px); + padding-top: 12px; + } + + .topbar { + align-items: flex-start; + flex-direction: column; + gap: 14px; + padding: 16px; + } + + .topbar-actions { + width: 100%; + } + + .connection, + .topbar-actions .button { + flex: 1; + } + + .summary { + grid-template-columns: 1fr; + } + + .summary-card { + min-height: 76px; + } + + .workspace-side { + grid-template-columns: 1fr; + } + + .panel-header { + padding: 17px; + } + + .job-footer { + align-items: stretch; + flex-direction: column; + } + + .job-metrics { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 10px; + } + + .metric strong { + max-width: 100%; + } + + .scheduler { + padding: 24px 18px; + } + + .presets, + .field-grid { + grid-template-columns: 1fr; + } + + .field-wide { + grid-column: auto; + } + + .schedule-form { + padding: 17px; + } + + .form-actions { + align-items: stretch; + flex-direction: column; + } + + .form-actions .button { + width: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + + *, + *::before, + *::after { + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + } +} diff --git a/spacetime-cron-ts/example/server.ts b/spacetime-cron-ts/example/server.ts new file mode 100644 index 00000000000..ee49651af4a --- /dev/null +++ b/spacetime-cron-ts/example/server.ts @@ -0,0 +1,52 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { existsSync, readFileSync } from 'node:fs'; +import express, { type Request, type Response } from 'express'; +import dotenv from 'dotenv'; +import { exampleUiAssetsDir } from '@spacetimedb/submodule-shared/server'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); +const inheritedEnv = new Set(Object.keys(process.env)); + +function loadEnv(pathname: string, override: boolean): void { + if (!existsSync(pathname)) return; + + const parsed = dotenv.parse(readFileSync(pathname)); + for (const [key, value] of Object.entries(parsed)) { + if (value.trim() === '') continue; + if (inheritedEnv.has(key)) continue; + if (override || process.env[key] === undefined) { + process.env[key] = value; + } + } +} + +// Shared env supplies defaults; example-local env wins for app settings. +// Explicit process environment has highest priority. +loadEnv(path.resolve(__dirname, '..', '..', '.env'), false); +loadEnv(path.resolve(__dirname, '..', '.env'), false); +loadEnv(path.resolve(__dirname, '.env'), true); + +const PORT = Number.parseInt(process.env.PORT ?? '8788', 10); +const HOST = process.env.HOST?.trim() || '127.0.0.1'; +const STDB_URI = process.env.STDB_URI ?? 'ws://127.0.0.1:3000'; +const DB_NAME = process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-cron-example'; + +const app = express(); +app.use(express.json({ limit: '256kb' })); +app.use('/assets', express.static(exampleUiAssetsDir)); +app.use(express.static(path.join(__dirname, 'public'))); + +app.get('/api/health', (_req: Request, res: Response) => { + res.json({ ok: true, databaseName: DB_NAME }); +}); + +app.get('/api/config', (_req: Request, res: Response) => { + res.json({ spacetimeUri: STDB_URI, databaseName: DB_NAME }); +}); + +app.listen(PORT, HOST, () => { + console.log(`Cron example running at http://${HOST}:${PORT}`); + console.log(` SpacetimeDB: ${STDB_URI} (${DB_NAME})`); +}); diff --git a/spacetime-cron-ts/example/spacetimedb/.npmrc b/spacetime-cron-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/example/spacetimedb/package.json b/spacetime-cron-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..d8cb9efbd6e --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-cron-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-cron-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-cron-example" + }, + "dependencies": { + "@spacetimedb/cron": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/example/spacetimedb/src/index.ts b/spacetime-cron-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..574fd6ae53f --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,175 @@ +import { + schema, + table, + t, + SenderError, + toCamelCase, + type ReducerCtx, + type InferSchema, +} from 'spacetimedb/server'; +import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { spacetimeCron, type CronJobReference } from '@spacetimedb/cron'; + +// One injection point: hand the library this module's own SDK objects so the +// bundle contains exactly one copy of the spacetimedb SDK. +const { cronTable, createCron, schedule, unschedule } = spacetimeCron({ + table, + t, + toCamelCase, + ScheduleAt, + Timestamp, + SenderError, +}); + +// ── Jobs ───────────────────────────────────────────────────────────────────── + +const digest = cronTable({ name: 'digest' }); +const cleanup = cronTable({ + name: 'cleanup', + args: t.object('CleanupCronArgs', { keep: t.u32() }), +}); + +const cron = createCron([digest, cleanup], { + publicTables: true, + reconcileEverySeconds: 300, +}); + +// ── App tables ─────────────────────────────────────────────────────────────── + +const activityLog = table( + { name: 'activity_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + message: t.string(), + at: t.timestamp().index(), + } +); + +const spacetimedb = schema({ ...cron.tables, activityLog }); +export default spacetimedb; + +type Schema = InferSchema; +type Tx = ReducerCtx; + +// ── Cron wiring ────────────────────────────────────────────────────────────── + +export const runDigest = digest.cronReducer(spacetimedb, (ctx: Tx) => { + const entries = ctx.db.activityLog.count(); + ctx.db.activityLog.insert({ + id: 0n, + jobName: 'digest', + message: `digest generated over ${entries} log entries`, + at: ctx.timestamp, + }); +}); + +export const runCleanup = cleanup.cronReducer(spacetimedb, (ctx: Tx, args) => { + const total = Number(ctx.db.activityLog.count()); + if (total <= args.keep) return; + const excess = total - args.keep + 1; + const oldest = [...ctx.db.activityLog.iter()] + .sort((left, right) => { + const delta = + left.at.microsSinceUnixEpoch - right.at.microsSinceUnixEpoch; + return delta < 0n ? -1 : delta > 0n ? 1 : 0; + }) + .slice(0, excess); + for (const row of oldest) { + ctx.db.activityLog.delete(row); + } + ctx.db.activityLog.insert({ + id: 0n, + jobName: 'cleanup', + message: `pruned ${oldest.length} old entries`, + at: ctx.timestamp, + }); +}); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + // Code-declared defaults on first publish. Both are runtime state after + // this: reschedule or disable them from the UI without republishing. + schedule(ctx, digest, '0 9 * * 1-5', { timezone: 'America/New_York' }); + schedule(ctx, cleanup, { everySeconds: 300 }, { args: { keep: 50 } }); +}); + +// ── Client-facing management ───────────────────────────────────────────────── + +// These reducers are open so the local browser can exercise the submodule. +// Production applications must enforce their own admin policy. + +const jobs: Record = { digest, cleanup }; + +function jobByName(name: string): CronJobReference { + const job = jobs[name]; + if (!job) throw new SenderError(`cron.unknown_job:${name}`); + return job; +} + +function cleanupKeep(value: number): number { + if (!Number.isInteger(value) || value < 1 || value > 1_000) { + throw new SenderError('cleanup.invalid_keep:must be between 1 and 1000'); + } + return value; +} + +export const scheduleCron = spacetimedb.reducer( + { + name: t.string(), + expression: t.string(), + timezone: t.string(), + keep: t.u32(), + }, + (ctx, args) => { + try { + if (args.name === 'cleanup') { + schedule(ctx, cleanup, args.expression, { + timezone: args.timezone, + args: { keep: cleanupKeep(args.keep) }, + }); + } else if (args.name === 'digest') { + schedule(ctx, digest, args.expression, { timezone: args.timezone }); + } else { + throw new SenderError(`cron.unknown_job:${args.name}`); + } + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } + } +); + +export const scheduleEvery = spacetimedb.reducer( + { name: t.string(), seconds: t.u32(), keep: t.u32() }, + (ctx, args) => { + try { + if (args.name === 'cleanup') { + schedule( + ctx, + cleanup, + { everySeconds: args.seconds }, + { args: { keep: cleanupKeep(args.keep) } } + ); + } else if (args.name === 'digest') { + schedule(ctx, digest, { everySeconds: args.seconds }); + } else { + throw new SenderError(`cron.unknown_job:${args.name}`); + } + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } + } +); + +export const unscheduleJob = spacetimedb.reducer( + { name: t.string() }, + (ctx, { name }) => { + unschedule(ctx, jobByName(name)); + } +); diff --git a/spacetime-cron-ts/example/spacetimedb/tsconfig.json b/spacetime-cron-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..4b41d0f867b --- /dev/null +++ b/spacetime-cron-ts/example/spacetimedb/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-cron-ts/example/src/app.ts b/spacetime-cron-ts/example/src/app.ts new file mode 100644 index 00000000000..38b944d0dd6 --- /dev/null +++ b/spacetime-cron-ts/example/src/app.ts @@ -0,0 +1,449 @@ +import { DbConnection, tables, type ErrorContext } from './module_bindings/app'; +import type { CronSchedule } from './module_bindings/app/types'; + +interface ServerConfig { + spacetimeUri: string; + databaseName: string; +} + +type ConnectionState = 'connecting' | 'connected' | 'disconnected' | 'error'; +type StatusTone = 'neutral' | 'success' | 'error'; + +let connection: DbConnection | null = null; + +function element( + tag: T, + className?: string, + text?: string +): HTMLElementTagNameMap[T] { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined) node.textContent = text; + return node; +} + +function byId(id: string): T { + const node = document.getElementById(id); + if (!node) throw new Error(`Missing required element #${id}`); + return node as T; +} + +function setText(id: string, value: string | number | bigint): void { + byId(id).textContent = String(value); +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function formatTime(micros: bigint): string { + return new Date(Number(micros / 1_000n)).toLocaleString(undefined, { + dateStyle: 'medium', + timeStyle: 'medium', + }); +} + +function formatJobName(name: string): string { + return name + .split('_') + .map(part => `${part.charAt(0).toUpperCase()}${part.slice(1)}`) + .join(' '); +} + +function scheduleLabel(schedule: CronSchedule): string { + if (schedule.tag === 'Cron') { + return `${schedule.value.expression} · ${schedule.value.timezone}`; + } + return `Every ${schedule.value.seconds} seconds`; +} + +function nextRunLabel(nextRunAt?: { microsSinceUnixEpoch: bigint }): string { + return nextRunAt ? formatTime(nextRunAt.microsSinceUnixEpoch) : 'Not armed'; +} + +function setConnection(state: ConnectionState, label: string): void { + byId('connection').dataset.state = state; + setText('conn', label); + const enabled = state === 'connected'; + byId('open-scheduler').disabled = !enabled; + byId('btn-schedule').disabled = !enabled; +} + +function setFormStatus(text: string, tone: StatusTone = 'neutral'): void { + const status = byId('form-status'); + status.textContent = text; + status.dataset.tone = tone; +} + +function setCollectionVisibility( + listId: string, + emptyId: string, + hasItems: boolean +): void { + byId(listId).hidden = !hasItems; + byId(emptyId).hidden = hasItems; +} + +function metric(label: string, value: string, unhealthy = false): HTMLElement { + const node = element('div', 'metric'); + const valueNode = element( + 'strong', + unhealthy ? 'unhealthy' : undefined, + value + ); + node.append(element('span', undefined, label), valueNode); + return node; +} + +function renderJobs(): void { + if (!connection) return; + const jobs = [...connection.db.cronJobs.iter()].sort((left, right) => + left.name.localeCompare(right.name) + ); + const list = byId('jobs'); + list.replaceChildren(); + + let healthy = 0; + let dispatches = 0n; + + for (const job of jobs) { + if (job.enabled && job.consecutiveFailures === 0) healthy += 1; + dispatches += job.fireCount; + + const item = element('li', 'job-card'); + item.dataset.enabled = String(job.enabled); + + const heading = element('div', 'job-card-top'); + const identity = element('div', 'job-identity'); + const name = element('div'); + name.append( + element('strong', undefined, formatJobName(job.name)), + element('code', undefined, job.name) + ); + identity.append( + element('span', 'job-icon', job.name.charAt(0).toUpperCase()), + name + ); + + const statusText = job.enabled ? 'enabled' : 'disabled'; + const status = element('span', `status-badge ${statusText}`, statusText); + if (job.disabledReason) status.title = job.disabledReason; + heading.append(identity, status); + + const schedule = element('div', 'job-schedule'); + schedule.append(element('code', undefined, scheduleLabel(job.schedule))); + + const footer = element('div', 'job-footer'); + const metrics = element('div', 'job-metrics'); + metrics.append( + metric('Next run', nextRunLabel(job.nextRunAt)), + metric('Dispatches', String(job.fireCount)), + metric( + 'Failures', + String(job.consecutiveFailures), + job.consecutiveFailures > 0 + ) + ); + footer.append(metrics); + + if (job.enabled) { + const button = element( + 'button', + 'button button-secondary button-small', + 'Unschedule' + ); + button.type = 'button'; + button.onclick = async () => { + const current = connection; + if (!current) return; + button.disabled = true; + setFormStatus(`Unscheduling ${formatJobName(job.name)}...`); + try { + await current.reducers.unscheduleJob({ name: job.name }); + setFormStatus(`${formatJobName(job.name)} unscheduled.`, 'success'); + } catch (error) { + setFormStatus(errorMessage(error), 'error'); + button.disabled = false; + } + }; + footer.append(button); + } + + item.append(heading, schedule, footer); + list.append(item); + } + + setText('job-count', jobs.length); + setText('stat-jobs', jobs.length); + setText('stat-healthy', healthy); + setText('stat-fires', dispatches); + setCollectionVisibility('jobs', 'jobs-empty', jobs.length > 0); +} + +function renderRuns(): void { + if (!connection) return; + const runs = [...connection.db.cronRun.iter()] + .sort((left, right) => { + const leftTime = left.scheduledFor.microsSinceUnixEpoch; + const rightTime = right.scheduledFor.microsSinceUnixEpoch; + if (leftTime !== rightTime) return leftTime > rightTime ? -1 : 1; + const byName = left.jobName.localeCompare(right.jobName); + if (byName !== 0) return byName; + return left.sequence > right.sequence + ? -1 + : left.sequence < right.sequence + ? 1 + : 0; + }) + .slice(0, 20); + const list = byId('runs'); + list.replaceChildren(); + + for (const run of runs) { + const failed = run.status.tag === 'Failed'; + const item = element('li', 'event-item'); + const marker = element('span', `event-marker ${failed ? 'failed' : 'ok'}`); + marker.setAttribute('aria-hidden', 'true'); + const content = element('div', 'event-content'); + content.append( + element( + 'span', + 'event-title', + `${formatJobName(run.jobName)} · ${run.status.tag}` + ) + ); + if (run.error) { + content.append(element('span', 'event-copy', run.error)); + } + content.append( + element( + 'time', + 'event-time', + formatTime(run.scheduledFor.microsSinceUnixEpoch) + ) + ); + item.append(marker, content); + list.append(item); + } + + setText('run-count', runs.length); + setCollectionVisibility('runs', 'runs-empty', runs.length > 0); +} + +function renderActivity(): void { + if (!connection) return; + const entries = [...connection.db.activityLog.iter()] + .sort((left, right) => { + const leftTime = left.at.microsSinceUnixEpoch; + const rightTime = right.at.microsSinceUnixEpoch; + if (leftTime !== rightTime) return leftTime > rightTime ? -1 : 1; + return left.id > right.id ? -1 : left.id < right.id ? 1 : 0; + }) + .slice(0, 20); + const list = byId('activity'); + list.replaceChildren(); + + for (const entry of entries) { + const item = element('li', 'event-item'); + const marker = element('span', 'event-marker'); + marker.setAttribute('aria-hidden', 'true'); + const content = element('div', 'event-content'); + content.append( + element('span', 'event-title', formatJobName(entry.jobName)), + element('span', 'event-copy', entry.message), + element('time', 'event-time', formatTime(entry.at.microsSinceUnixEpoch)) + ); + item.append(marker, content); + list.append(item); + } + + setText('activity-count', entries.length); + setCollectionVisibility('activity', 'activity-empty', entries.length > 0); +} + +function renderAll(): void { + renderJobs(); + renderRuns(); + renderActivity(); +} + +function updateScheduleFields(): void { + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const isCron = kind.value === 'cron'; + setText('spec-expr-label', isCron ? 'Expression' : 'Seconds'); + setText( + 'spec-help', + isCron + ? 'Use five fields, or six fields to include seconds.' + : 'Enter a whole number of seconds.' + ); + expression.placeholder = isCron ? '*/10 * * * * *' : '10'; + byId('spec-tz-wrap').hidden = !isCron; +} + +function applyPreset(preset: string): void { + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const timezone = byId('spec-tz'); + + if (preset === 'weekday') { + kind.value = 'cron'; + expression.value = '0 9 * * 1-5'; + timezone.value = 'America/New_York'; + } else if (preset === 'five-minutes') { + kind.value = 'every'; + expression.value = '300'; + } else { + kind.value = 'cron'; + expression.value = '*/10 * * * * *'; + timezone.value = 'UTC'; + } + + updateScheduleFields(); + setFormStatus('Preset applied.'); + expression.focus(); +} + +function registerUiHandlers(): void { + const form = byId('schedule-form'); + const kind = byId('spec-kind'); + const expression = byId('spec-expr'); + const timezone = byId('spec-tz'); + const jobName = byId('job-name'); + const cleanupKeep = byId('cleanup-keep'); + const submit = byId('btn-schedule'); + + form.onsubmit = async event => { + event.preventDefault(); + const current = connection; + if (!current) { + setFormStatus('Connect to SpacetimeDB before scheduling a job.', 'error'); + return; + } + + const name = jobName.value; + const keep = Number(cleanupKeep.value); + submit.disabled = true; + setFormStatus(''); + try { + if ( + name === 'cleanup' && + (!Number.isInteger(keep) || keep < 1 || keep > 1_000) + ) { + throw new Error('Rows to keep must be an integer from 1 through 1000.'); + } + if (kind.value === 'cron') { + const value = expression.value.trim(); + if (!value) throw new Error('Enter a cron expression.'); + setFormStatus(`Scheduling ${formatJobName(name)}...`); + await current.reducers.scheduleCron({ + name, + expression: value, + timezone: timezone.value.trim() || 'UTC', + keep, + }); + } else { + const seconds = Number(expression.value); + if (!Number.isInteger(seconds) || seconds < 1) { + throw new Error('Interval seconds must be a positive integer.'); + } + setFormStatus(`Scheduling ${formatJobName(name)}...`); + await current.reducers.scheduleEvery({ name, seconds, keep }); + } + setFormStatus(`${formatJobName(name)} scheduled.`, 'success'); + } catch (error) { + setFormStatus(errorMessage(error), 'error'); + } finally { + submit.disabled = connection === null; + } + }; + + kind.onchange = () => { + const isCron = kind.value === 'cron'; + expression.value = isCron ? '*/10 * * * * *' : '10'; + updateScheduleFields(); + setFormStatus(''); + }; + + jobName.onchange = () => { + byId('cleanup-keep-wrap').hidden = jobName.value !== 'cleanup'; + setFormStatus(''); + }; + + for (const preset of document.querySelectorAll( + '[data-preset]' + )) { + preset.onclick = () => applyPreset(preset.dataset.preset ?? ''); + } + + byId('open-scheduler').onclick = () => { + byId('scheduler').scrollIntoView({ behavior: 'smooth', block: 'center' }); + window.setTimeout(() => jobName.focus(), 250); + }; + + updateScheduleFields(); +} + +function registerRowCallbacks(connection: DbConnection): void { + connection.db.cronJobs.onInsert(renderJobs); + connection.db.cronJobs.onUpdate(renderJobs); + connection.db.cronJobs.onDelete(renderJobs); + connection.db.cronRun.onInsert(renderRuns); + connection.db.cronRun.onUpdate(renderRuns); + connection.db.cronRun.onDelete(renderRuns); + connection.db.activityLog.onInsert(renderActivity); + connection.db.activityLog.onUpdate(renderActivity); + connection.db.activityLog.onDelete(renderActivity); +} + +function subscribeToTables(connection: DbConnection): void { + connection + .subscriptionBuilder() + .onApplied(renderAll) + .onError((ctx: ErrorContext) => + console.error('subscription error', ctx.event) + ) + .subscribe([tables.cronJobs, tables.cronRun, tables.activityLog]); +} + +async function loadServerConfig(): Promise { + const response = await fetch('/api/config'); + if (!response.ok) { + throw new Error(`Config request failed: ${response.status}`); + } + return (await response.json()) as ServerConfig; +} + +function connect(config: ServerConfig): void { + DbConnection.builder() + .withUri(config.spacetimeUri) + .withDatabaseName(config.databaseName) + .onConnect((current: DbConnection) => { + connection = current; + setConnection('connected', config.databaseName); + registerRowCallbacks(current); + subscribeToTables(current); + }) + .onConnectError((_ctx: ErrorContext, error: Error) => { + setConnection('error', 'Connection failed'); + setFormStatus(error.message, 'error'); + }) + .onDisconnect((_ctx, error) => { + connection = null; + setConnection('disconnected', 'Disconnected'); + if (error) setFormStatus(error.message, 'error'); + }) + .build(); +} + +async function main(): Promise { + registerUiHandlers(); + setConnection('connecting', 'Connecting'); + connect(await loadServerConfig()); +} + +void main().catch(error => { + setConnection('error', 'Configuration failed'); + setFormStatus(errorMessage(error), 'error'); +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts new file mode 100644 index 00000000000..e6c83267786 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/activity_log_table.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + jobName: __t.string().name("job_name"), + message: __t.string(), + at: __t.timestamp(), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts new file mode 100644 index 00000000000..107696eecfe --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cleanup_fire_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronFireRecovery, +} from "./types"; + + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()).name("target_at"), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts new file mode 100644 index 00000000000..a7f49c2639a --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_jobs_table.ts @@ -0,0 +1,30 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronSchedule, +} from "./types"; + + +export default __t.row({ + name: __t.string().primaryKey(), + get schedule() { + return CronSchedule; + }, + enabled: __t.bool(), + maxFailures: __t.u32().name("max_failures"), + consecutiveFailures: __t.u32().name("consecutive_failures"), + fireCount: __t.u64().name("fire_count"), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()).name("last_run_at"), + nextRunAt: __t.option(__t.timestamp()).name("next_run_at"), + disabledReason: __t.option(__t.string()).name("disabled_reason"), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts new file mode 100644 index 00000000000..e58ad71b8ca --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_reconcile_tick_table.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + key: __t.string(), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts new file mode 100644 index 00000000000..122a896817f --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/cron_run_table.ts @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronRunStatus, +} from "./types"; + + +export default __t.row({ + invocationId: __t.string().primaryKey().name("invocation_id"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + sequence: __t.u64(), + scheduledFor: __t.timestamp().name("scheduled_for"), + completedAt: __t.timestamp().name("completed_at"), + get status() { + return CronRunStatus; + }, + error: __t.option(__t.string()), +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts b/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts new file mode 100644 index 00000000000..107696eecfe --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/digest_fire_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; +import { + CronFireRecovery, +} from "./types"; + + +export default __t.row({ + scheduledId: __t.u64().primaryKey().name("scheduled_id"), + scheduledAt: __t.scheduleAt().name("scheduled_at"), + jobName: __t.string().name("job_name"), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()).name("target_at"), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); diff --git a/spacetime-cron-ts/example/src/module_bindings/app/index.ts b/spacetime-cron-ts/example/src/module_bindings/app/index.ts new file mode 100644 index 00000000000..628c885946b --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/index.ts @@ -0,0 +1,203 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.10.1 (commit 5418e2f229c57f503d4306ae9e5fb6df29533f7d). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from "spacetimedb"; + +// Import all reducer arg schemas +import ScheduleCronReducer from "./schedule_cron_reducer"; +import ScheduleEveryReducer from "./schedule_every_reducer"; +import UnscheduleJobReducer from "./unschedule_job_reducer"; + +// Import all procedure arg schemas + +// Import all table schema definitions +import ActivityLogRow from "./activity_log_table"; +import CleanupFireRow from "./cleanup_fire_table"; +import CronJobsRow from "./cron_jobs_table"; +import CronReconcileTickRow from "./cron_reconcile_tick_table"; +import CronRunRow from "./cron_run_table"; +import DigestFireRow from "./digest_fire_table"; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + activityLog: __table({ + name: 'activity_log', + indexes: [ + { accessor: 'at', name: 'activity_log_at_idx_btree', algorithm: 'btree', columns: [ + 'at', + ] }, + { accessor: 'id', name: 'activity_log_id_idx_btree', algorithm: 'btree', columns: [ + 'id', + ] }, + { accessor: 'jobName', name: 'activity_log_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + ], + constraints: [ + { name: 'activity_log_id_key', constraint: 'unique', columns: ['id'] }, + ], + }, ActivityLogRow), + cleanupFire: __table({ + name: 'cleanup_fire', + indexes: [ + { accessor: 'jobName', name: 'cleanup_fire_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + { accessor: 'scheduledId', name: 'cleanup_fire_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'cleanup_fire_job_name_key', constraint: 'unique', columns: ['jobName'] }, + { name: 'cleanup_fire_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, CleanupFireRow), + cronReconcileTick: __table({ + name: 'cron_reconcile_tick', + indexes: [ + { accessor: 'key', name: 'cron_reconcile_tick_key_idx_btree', algorithm: 'btree', columns: [ + 'key', + ] }, + { accessor: 'scheduledId', name: 'cron_reconcile_tick_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'cron_reconcile_tick_key_key', constraint: 'unique', columns: ['key'] }, + { name: 'cron_reconcile_tick_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, CronReconcileTickRow), + cronRun: __table({ + name: 'cron_run', + indexes: [ + { accessor: 'invocationId', name: 'cron_run_invocation_id_idx_btree', algorithm: 'btree', columns: [ + 'invocationId', + ] }, + { accessor: 'jobName', name: 'cron_run_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + ], + constraints: [ + { name: 'cron_run_invocation_id_key', constraint: 'unique', columns: ['invocationId'] }, + ], + }, CronRunRow), + digestFire: __table({ + name: 'digest_fire', + indexes: [ + { accessor: 'jobName', name: 'digest_fire_job_name_idx_btree', algorithm: 'btree', columns: [ + 'jobName', + ] }, + { accessor: 'scheduledId', name: 'digest_fire_scheduled_id_idx_btree', algorithm: 'btree', columns: [ + 'scheduledId', + ] }, + ], + constraints: [ + { name: 'digest_fire_job_name_key', constraint: 'unique', columns: ['jobName'] }, + { name: 'digest_fire_scheduled_id_key', constraint: 'unique', columns: ['scheduledId'] }, + ], + }, DigestFireRow), + cronJobs: __table({ + name: 'cron_jobs', + indexes: [ + ], + constraints: [ + ], + }, CronJobsRow), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema("schedule_cron", ScheduleCronReducer), + __reducerSchema("schedule_every", ScheduleEveryReducer), + __reducerSchema("unschedule_job", UnscheduleJobReducer), +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures( +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.10.1" as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +export const tables: __QueryBuilder = __makeQueryBuilder(tablesSchema.schemaType); + +/** The reducers available in this remote SpacetimeDB module. */ +export const reducers = __convertToAccessorMap(reducersSchema.reducersType.reducers); + +/** The procedures available in this remote SpacetimeDB module. */ +export const procedures = __convertToAccessorMap(proceduresSchema.procedures); + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config)); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts new file mode 100644 index 00000000000..708fe42e2e6 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/schedule_cron_reducer.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), + expression: __t.string(), + timezone: __t.string(), + keep: __t.u32(), +}; diff --git a/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts new file mode 100644 index 00000000000..e054dd57fa5 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/schedule_every_reducer.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), + seconds: __t.u32(), + keep: __t.u32(), +}; diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types.ts b/spacetime-cron-ts/example/src/module_bindings/app/types.ts new file mode 100644 index 00000000000..c538888e35f --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types.ts @@ -0,0 +1,153 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const ActivityLog = __t.object("ActivityLog", { + id: __t.u64(), + jobName: __t.string(), + message: __t.string(), + at: __t.timestamp(), +}); +export type ActivityLog = __Infer; + +export const CleanupCronArgs = __t.object("CleanupCronArgs", { + keep: __t.u32(), +}); +export type CleanupCronArgs = __Infer; + +export const CleanupFire = __t.object("CleanupFire", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + jobName: __t.string(), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); +export type CleanupFire = __Infer; + +export const CronFireRecovery = __t.object("CronFireRecovery", { + sequence: __t.u64(), + scheduledFor: __t.timestamp(), + error: __t.string(), +}); +export type CronFireRecovery = __Infer; + +export const CronJob = __t.object("CronJob", { + name: __t.string(), + get schedule() { + return CronSchedule; + }, + get args() { + return CronJobArgsValue; + }, + enabled: __t.bool(), + maxFailures: __t.u32(), + consecutiveFailures: __t.u32(), + fireCount: __t.u64(), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()), + nextRunAt: __t.option(__t.timestamp()), + disabledReason: __t.option(__t.string()), +}); +export type CronJob = __Infer; + +// The tagged union or sum type for the algebraic type `CronJobArgsValue`. +export const CronJobArgsValue = __t.enum("CronJobArgsValue", { + get Cleanup() { + return CleanupCronArgs; + }, + Digest: __t.unit(), +}); +export type CronJobArgsValue = __Infer; + +export const CronJobView = __t.object("CronJobView", { + name: __t.string(), + get schedule() { + return CronSchedule; + }, + enabled: __t.bool(), + maxFailures: __t.u32(), + consecutiveFailures: __t.u32(), + fireCount: __t.u64(), + generation: __t.u64(), + lastRunAt: __t.option(__t.timestamp()), + nextRunAt: __t.option(__t.timestamp()), + disabledReason: __t.option(__t.string()), +}); +export type CronJobView = __Infer; + +export const CronJobs = __t.object("CronJobs", {}); +export type CronJobs = __Infer; + +export const CronReconcileTick = __t.object("CronReconcileTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + key: __t.string(), +}); +export type CronReconcileTick = __Infer; + +export const CronRun = __t.object("CronRun", { + invocationId: __t.string(), + jobName: __t.string(), + generation: __t.u64(), + sequence: __t.u64(), + scheduledFor: __t.timestamp(), + completedAt: __t.timestamp(), + get status() { + return CronRunStatus; + }, + error: __t.option(__t.string()), +}); +export type CronRun = __Infer; + +// The tagged union or sum type for the algebraic type `CronRunStatus`. +export const CronRunStatus = __t.enum("CronRunStatus", { + Ok: __t.unit(), + Failed: __t.unit(), +}); +export type CronRunStatus = __Infer; + +// The tagged union or sum type for the algebraic type `CronSchedule`. +export const CronSchedule = __t.enum("CronSchedule", { + get Cron() { + return CronSpec; + }, + get Every() { + return EverySpec; + }, +}); +export type CronSchedule = __Infer; + +export const CronSpec = __t.object("CronSpec", { + expression: __t.string(), + timezone: __t.string(), +}); +export type CronSpec = __Infer; + +export const DigestFire = __t.object("DigestFire", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), + jobName: __t.string(), + generation: __t.u64(), + targetAt: __t.option(__t.timestamp()), + get recovery() { + return __t.option(CronFireRecovery); + }, +}); +export type DigestFire = __Infer; + +export const EverySpec = __t.object("EverySpec", { + seconds: __t.u32(), +}); +export type EverySpec = __Infer; + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts b/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts new file mode 100644 index 00000000000..d5ac825c9ab --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types/procedures.ts @@ -0,0 +1,10 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all procedure arg schemas + + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts b/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts new file mode 100644 index 00000000000..3f09c30fc78 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/types/reducers.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all reducer arg schemas +import ScheduleCronReducer from "../schedule_cron_reducer"; +import ScheduleEveryReducer from "../schedule_every_reducer"; +import UnscheduleJobReducer from "../unschedule_job_reducer"; + +export type ScheduleCronParams = __Infer; +export type ScheduleEveryParams = __Infer; +export type UnscheduleJobParams = __Infer; + diff --git a/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts b/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts new file mode 100644 index 00000000000..ce493ee8574 --- /dev/null +++ b/spacetime-cron-ts/example/src/module_bindings/app/unschedule_job_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + name: __t.string(), +}; diff --git a/spacetime-cron-ts/example/tsconfig.json b/spacetime-cron-ts/example/tsconfig.json new file mode 100644 index 00000000000..143c4fb996c --- /dev/null +++ b/spacetime-cron-ts/example/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "server.ts"], + "exclude": ["node_modules", "spacetimedb"] +} diff --git a/spacetime-cron-ts/package.json b/spacetime-cron-ts/package.json new file mode 100644 index 00000000000..808da1f0c00 --- /dev/null +++ b/spacetime-cron-ts/package.json @@ -0,0 +1,69 @@ +{ + "name": "@spacetimedb/cron", + "description": "Calendar and interval scheduling for SpacetimeDB TypeScript modules.", + "version": "0.3.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./parser": { + "types": "./src/parser.ts", + "default": "./src/parser.ts" + } + }, + "files": [ + "src", + "LICENSE.txt", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-cron-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-cron-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "cron", + "scheduler", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "pnpm run test:parser && pnpm run test:schedule && pnpm run test:validation && pnpm run test:registration", + "test:parser": "tsx scripts/test-cron-parser.ts", + "test:module:local": "node scripts/test-module-local.mjs", + "test:registration": "node --import tsx --import ./scripts/sys-abi-test-register.mjs scripts/test-registration.ts", + "test:recovery": "node scripts/test-recovery.mjs", + "test:schedule": "tsx scripts/test-schedule.ts", + "test:validation": "tsx scripts/test-validation.ts" + }, + "dependencies": { + "cron-parser": "5.5.0" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/scripts/sys-abi-test-register.mjs b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs new file mode 100644 index 00000000000..556603c3447 --- /dev/null +++ b/spacetime-cron-ts/scripts/sys-abi-test-register.mjs @@ -0,0 +1,19 @@ +import { register } from 'node:module'; + +const loaderSource = ` + const sysAbiUrl = 'data:text/javascript,' + encodeURIComponent( + 'export function volatile_nonatomic_schedule_immediate() {}' + ); + + export function resolve(specifier, context, nextResolve) { + if (specifier === 'spacetime:sys@2.0') { + return { shortCircuit: true, url: sysAbiUrl }; + } + return nextResolve(specifier, context); + } +`; + +register( + `data:text/javascript,${encodeURIComponent(loaderSource)}`, + import.meta.url +); diff --git a/spacetime-cron-ts/scripts/test-cron-parser.ts b/spacetime-cron-ts/scripts/test-cron-parser.ts new file mode 100644 index 00000000000..b0e4151fa9b --- /dev/null +++ b/spacetime-cron-ts/scripts/test-cron-parser.ts @@ -0,0 +1,210 @@ +// Pure-Node sanity test. No STDB needed. + +import { + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from '../src/parser'; + +function assert(cond: boolean, msg: string): void { + if (!cond) { + process.stderr.write(`FAIL: ${msg}\n`); + process.exit(1); + } +} + +function check( + expr: string, + fromIso: string, + expectIso: string, + timezone = 'UTC' +): void { + const parsed = parseCronExpression(expr); + const fromMicros = BigInt(new Date(fromIso).getTime()) * 1000n; + const next = nextFireAfter(parsed, fromMicros, timezone); + if (next === undefined) { + assert( + false, + `${expr} [${timezone}] from ${fromIso} → undefined (expected ${expectIso})` + ); + return; + } + const got = new Date(Number(next / 1000n)).toISOString(); + assert( + got === expectIso, + `${expr} [${timezone}] from ${fromIso} → ${got} (expected ${expectIso})` + ); + process.stdout.write( + ` ${expr.padEnd(15)} [${timezone.padEnd(20)}] from ${fromIso} → ${got} ✓\n` + ); +} + +process.stdout.write('cron parser tests\n'); + +// "every minute" +check('* * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:01:00.000Z'); +check('* * * * *', '2026-05-04T12:00:30.000Z', '2026-05-04T12:01:00.000Z'); + +// every 15 minutes +check('*/15 * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:15:00.000Z'); +check('*/15 * * * *', '2026-05-04T12:50:00.000Z', '2026-05-04T13:00:00.000Z'); + +// daily at 9:00 UTC +check('0 9 * * *', '2026-05-04T08:00:00.000Z', '2026-05-04T09:00:00.000Z'); +check('0 9 * * *', '2026-05-04T09:00:00.000Z', '2026-05-05T09:00:00.000Z'); + +// Mondays at 9:00 UTC (Mon = 1) +check('0 9 * * 1', '2026-05-04T08:00:00.000Z', '2026-05-04T09:00:00.000Z'); // Mon May 4 +check('0 9 * * MON', '2026-05-04T10:00:00.000Z', '2026-05-11T09:00:00.000Z'); // next Mon + +// First of the month at midnight +check('0 0 1 * *', '2026-05-04T00:00:00.000Z', '2026-06-01T00:00:00.000Z'); + +// Range + list: weekdays at quarter past 9 +check('15 9 * * 1-5', '2026-05-02T00:00:00.000Z', '2026-05-04T09:15:00.000Z'); // skip weekend + +// Step inside range: every 5 minutes between :00 and :30 +check('0-30/5 * * * *', '2026-05-04T12:00:00.000Z', '2026-05-04T12:05:00.000Z'); +check('0-30/5 * * * *', '2026-05-04T12:30:00.000Z', '2026-05-04T13:00:00.000Z'); + +// DOM + DOW union (Vixie cron); next Mon (May 11) wins over next 1st (Jun 1). +check('0 0 1 * 1', '2026-05-04T00:00:00.000Z', '2026-05-11T00:00:00.000Z'); + +// Named months +check('0 0 1 JAN *', '2026-05-04T00:00:00.000Z', '2027-01-01T00:00:00.000Z'); + +// Unsatisfiable (Feb 31): cron-parser rejects up-front in strict mode. +let unsatThrew = false; +try { + parseCronExpression('0 0 31 2 *'); +} catch { + unsatThrew = true; +} +assert(unsatThrew, '0 0 31 2 * should be rejected as unsatisfiable'); +process.stdout.write( + ' 0 0 31 2 * rejected as unsatisfiable ✓\n' +); + +// Validation +let threw = false; +try { + parseCronExpression('invalid'); +} catch { + threw = true; +} +assert(threw, 'invalid expression should throw'); + +assert( + parseCronExpression(' 0 9 * * * ').expression === '0 9 * * *', + 'expression should be normalized' +); +for (const invalid of ['', ' ', '*'.repeat(MAX_CRON_EXPRESSION_LENGTH + 1)]) { + let invalidThrew = false; + try { + parseCronExpression(invalid); + } catch { + invalidThrew = true; + } + assert( + invalidThrew, + `expression should be rejected: ${JSON.stringify(invalid.slice(0, 20))}` + ); +} + +const hashed = parseCronExpression('H * * * *'); +const hashedFrom = + BigInt(new Date('2026-05-04T12:00:00.000Z').getTime()) * 1000n; +assert( + nextFireAfter(hashed, hashedFrom, 'UTC') === + nextFireAfter(hashed, hashedFrom, 'UTC'), + 'hashed expressions should resolve deterministically' +); + +process.stdout.write('\ntimezone tests\n'); + +// 9am Pacific: 17:00 UTC in PST, 16:00 UTC in PDT. +check( + '0 9 * * *', + '2026-01-15T00:00:00.000Z', + '2026-01-15T17:00:00.000Z', + 'America/Los_Angeles' +); +check( + '0 9 * * *', + '2026-07-15T00:00:00.000Z', + '2026-07-15T16:00:00.000Z', + 'America/Los_Angeles' +); + +// 9am Tokyo = 00:00 UTC same day. +check( + '0 9 * * *', + '2026-05-03T23:59:00.000Z', + '2026-05-04T00:00:00.000Z', + 'Asia/Tokyo' +); +// 00:00 UTC IS 9am Tokyo today; strict-after means next is tomorrow. +check( + '0 9 * * *', + '2026-05-04T00:00:00.000Z', + '2026-05-05T00:00:00.000Z', + 'Asia/Tokyo' +); + +// "Every Monday 9am" in NY (EST/EDT) +check( + '0 9 * * MON', + '2026-01-04T00:00:00.000Z', + '2026-01-05T14:00:00.000Z', + 'America/New_York' +); // Mon Jan 5 9am EST = 14:00 UTC + +// During the New York DST spring-forward, 02:30 resolves to the next available local time. +check( + '30 2 * * *', + '2026-03-08T00:00:00.000Z', + '2026-03-08T07:30:00.000Z', + 'America/New_York' +); + +// DST fall-back: 01:30 NY happens twice, fires once at first occurrence. +check( + '30 1 * * *', + '2026-10-31T23:59:59.000Z', + '2026-11-01T05:30:00.000Z', + 'America/New_York' +); +check( + '30 1 * * *', + '2026-11-01T05:30:00.000Z', + '2026-11-02T06:30:00.000Z', + 'America/New_York' +); + +// IANA validation +assert(isValidTimezone('UTC'), 'UTC should be valid'); +assert( + isValidTimezone('America/Los_Angeles'), + 'America/Los_Angeles should be valid' +); +assert(!isValidTimezone('Not_A_Real/Timezone'), 'bogus tz should be invalid'); +assert( + !isValidTimezone(' UTC'), + 'timezone with surrounding whitespace should be invalid' +); +assert( + !isValidTimezone('x'.repeat(MAX_TIMEZONE_LENGTH + 1)), + 'oversized timezone should be invalid' +); +assert( + nextFireAfter(parseCronExpression('* * * * *'), 0n, 'Not_A_Real/Timezone') === + undefined, + 'nextFireAfter should reject an invalid timezone' +); +process.stdout.write( + ' isValidTimezone gate ✓\n' +); + +process.stdout.write('\nall parser tests passed.\n'); diff --git a/spacetime-cron-ts/scripts/test-module-local.mjs b/spacetime-cron-ts/scripts/test-module-local.mjs new file mode 100644 index 00000000000..90b1f627937 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-module-local.mjs @@ -0,0 +1,509 @@ +// Local integration suite for @spacetimedb/cron. Publishes the demo module +// (spacetimedb/) and the example module (example/spacetimedb/) against a +// running local SpacetimeDB and drives the full fire semantics: +// single-stage scheduled handlers, volatile failure recovery, lost-fire repair, +// payload rollback, auto-disable, procedures, generations, and cancellation. +// +// Requires: `spacetime start` running locally. +import * as assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; + +const database = `cron-release-${process.pid}-${Date.now()}`; +const exampleDatabase = `${database}-example`; +const serverArgs = ['--server', 'local']; +let published = false; +let examplePublished = false; + +function run(args, options = {}) { + const result = spawnSync('spacetime', args, { + cwd: new URL('..', import.meta.url), + encoding: 'utf8', + shell: false, + }); + if (options.expectFailure) { + assert.notEqual( + result.status, + 0, + `command unexpectedly succeeded: spacetime ${args.join(' ')}` + ); + return result; + } + assert.equal( + result.status, + 0, + `command failed: spacetime ${args.join(' ')}\n${result.stdout}\n${result.stderr}` + ); + return result; +} + +function call(name, ...args) { + return run(['call', ...serverArgs, database, name, ...args]); +} + +function callExpectFailure(name, ...args) { + return run(['call', ...serverArgs, database, name, ...args], { + expectFailure: true, + }); +} + +function sql(query, target = database) { + const result = run(['sql', ...serverArgs, '--format', 'json', target, query]); + return JSON.parse(result.stdout)[0].rows; +} + +function sqlExpectFailure(query, target = database) { + return run(['sql', ...serverArgs, '--format', 'json', target, query], { + expectFailure: true, + }); +} + +function count(table, where = '') { + return Number(sql(`SELECT COUNT(*) AS count FROM ${table} ${where}`)[0][0]); +} + +function jobRow(name) { + const rows = sql( + `SELECT enabled, fireCount, consecutiveFailures, disabledReason, generation FROM cron_job WHERE name = '${name}'` + ); + assert.equal(rows.length, 1, `expected one cron_job row for ${name}`); + const [enabled, fireCount, consecutiveFailures, disabledReason, generation] = + rows[0]; + return { + enabled, + fireCount, + consecutiveFailures, + disabledReason, + generation, + }; +} + +function publicDisabledReason(name) { + const rows = sql( + `SELECT disabledReason FROM cron_jobs WHERE name = '${name}'` + ); + assert.equal(rows.length, 1, `expected one cron_jobs row for ${name}`); + const option = rows[0][0]; + assert.deepEqual(option?.[0], 0, `expected a disabled reason for ${name}`); + return option[1]; +} + +function wait(milliseconds) { + return new Promise(resolve => setTimeout(resolve, milliseconds)); +} + +async function poll(description, check, timeoutMilliseconds = 15_000) { + const deadline = Date.now() + timeoutMilliseconds; + let lastError; + + while (Date.now() < deadline) { + try { + const result = check(); + if (result) return result; + lastError = undefined; + } catch (error) { + lastError = error; + } + await wait(200); + } + + const detail = lastError instanceof Error ? `: ${lastError.message}` : ''; + throw new Error(`timed out waiting for ${description}${detail}`); +} + +try { + run([ + 'publish', + ...serverArgs, + '--yes', + '--module-path', + 'spacetimedb', + database, + ]); + published = true; + + // init seeded the heartbeat job (every 30s) declaratively. + assert.equal(count('cron_job'), 1, 'init must seed exactly one job'); + assert.equal( + count('cron_jobs'), + 1, + 'public job view must expose seeded state' + ); + assert.equal( + sql("SELECT name, enabled FROM cron_jobs WHERE name = 'heartbeat'").length, + 1, + 'public job view must support filtered operational queries' + ); + sqlExpectFailure('SELECT args FROM cron_jobs'); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'seeded job must have exactly one pending fire' + ); + assert.equal( + count('cron_reconcile_tick'), + 1, + 'configured reconciliation must keep one native interval row' + ); + + // Management operations opportunistically repair an enabled job whose fire + // disappeared, record the loss, and preserve the one-row invariant. + call('drop_heartbeat_fire_for_test'); + assert.equal(count('heartbeat_fire'), 0); + assert.equal(jobRow('heartbeat').enabled, true); + call( + 'schedule_report', + JSON.stringify('0 0 1 1 *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('reconcile-probe'), + '1' + ); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'management scheduling must repair another enabled job' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'heartbeat'"), + 1, + 'opportunistic repair must record lost_fire' + ); + assert.deepEqual( + sql("SELECT error FROM cron_run WHERE jobName = 'heartbeat'")[0][0], + [0, 'lost_fire'], + 'repair history must preserve the lost_fire reason' + ); + + // The optional interval sweep repairs the same invariant without a + // management call. + call('schedule_every', JSON.stringify('heartbeat'), '30', '0'); + call('drop_heartbeat_fire_for_test'); + await poll('the reconciliation sweep to restore heartbeat', () => { + return ( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'") === 1 && + count('cron_run', "WHERE jobName = 'heartbeat'") >= 2 + ); + }); + assert.equal( + count('heartbeat_fire', "WHERE jobName = 'heartbeat'"), + 1, + 'reconciliation sweep must restore a missing fire' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'heartbeat'"), + 2, + 'sweep repair must record lost_fire' + ); + + // Lost fires participate in the normal consecutive-failure policy. + call('schedule_every', JSON.stringify('heartbeat'), '30', '1'); + call('drop_heartbeat_fire_for_test'); + await poll( + 'the lost-fire policy to disable heartbeat', + () => jobRow('heartbeat').enabled === false + ); + const lostFireDisabled = jobRow('heartbeat'); + assert.equal(lostFireDisabled.enabled, false); + assert.match( + String(lostFireDisabled.disabledReason), + /failed_1_consecutive_times:lost_fire/ + ); + assert.equal( + publicDisabledReason('heartbeat'), + 'lost_fire_threshold_reached', + 'public view must expose a safe lost-fire reason code' + ); + assert.equal(count('heartbeat_fire'), 0); + call('schedule_every', JSON.stringify('heartbeat'), '30', '0'); + + // Chain job fires on cadence and keeps the single-pending-fire invariant. + call( + 'schedule_report', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('primary'), + '25' + ); + await poll( + 'at least two report fires', + () => count('tick_log', "WHERE jobName = 'report'") >= 2 + ); + const reportTicks = count('tick_log', "WHERE jobName = 'report'"); + assert.ok( + reportTicks >= 2, + `expected at least two report fires, got ${reportTicks}` + ); + assert.equal( + count('report_fire', "WHERE jobName = 'report'"), + 1, + 'chain job must keep exactly one pending fire' + ); + const report = jobRow('report'); + assert.equal(report.enabled, true); + // Fires keep landing between queries, so bound rather than equate. + assert.ok( + Number(report.fireCount) >= reportTicks, + `fireCount ${report.fireCount} must cover observed ticks ${reportTicks}` + ); + const reportArgs = sql( + "SELECT value, count FROM argument_log WHERE jobName = 'report'" + ); + assert.ok(reportArgs.length >= 2, 'report arguments must reach every fire'); + assert.ok( + reportArgs.every( + ([value, batchSize]) => value === 'primary' && batchSize === 25 + ), + 'report fires must receive the scheduled typed arguments' + ); + + const reportGeneration = BigInt(report.generation); + call( + 'schedule_report', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('replacement'), + '7' + ); + assert.equal( + BigInt(jobRow('report').generation), + reportGeneration + 1n, + 'rescheduling typed work must start a new generation' + ); + await poll( + 'the replacement report arguments', + () => + count( + 'argument_log', + "WHERE jobName = 'report' AND value = 'replacement' AND count = 7" + ) >= 1 + ); + assert.ok( + count( + 'argument_log', + "WHERE jobName = 'report' AND value = 'replacement' AND count = 7" + ) >= 1, + 'rescheduling must replace the durable arguments' + ); + + // A failed payload rolls back its writes. Volatile recovery rearms the + // calendar chain, records the failure, and disables at the threshold. + call( + 'schedule_cron', + JSON.stringify('flaky'), + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '2' + ); + call('set_flaky_failing', 'true'); + await poll('the flaky job to reach its failure threshold', () => { + const state = jobRow('flaky'); + return !state.enabled && Number(state.consecutiveFailures) >= 2; + }); + assert.equal( + count('tick_log', "WHERE jobName = 'flaky'"), + 0, + 'failed payload writes must roll back' + ); + const flaky = jobRow('flaky'); + assert.equal(flaky.enabled, false, 'flaky must auto-disable'); + assert.equal(Number(flaky.consecutiveFailures), 2); + assert.match( + String(flaky.disabledReason), + /failed_2_consecutive_times:flaky\.failure/ + ); + assert.equal( + publicDisabledReason('flaky'), + 'failure_threshold_reached', + 'public view must not expose handler errors' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 0, + 'auto-disabled job must have no pending fire' + ); + assert.equal( + count('cron_run', "WHERE jobName = 'flaky'"), + 2, + 'each failed invocation must have one durable run record' + ); + + // Native interval rows persist after a failed transaction. The explicit + // recovery payload must still record the failure and apply maxFailures. + const failuresBeforeInterval = count('cron_run', "WHERE jobName = 'flaky'"); + call('schedule_every', JSON.stringify('flaky'), '1', '1'); + await poll('the failed interval job to disable itself', () => { + const state = jobRow('flaky'); + return !state.enabled && Number(state.consecutiveFailures) >= 1; + }); + assert.equal( + count('cron_run', "WHERE jobName = 'flaky'"), + failuresBeforeInterval + 1, + 'interval recovery must commit one failed run record' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 0, + 'an interval job disabled by maxFailures must remove its persistent fire' + ); + + // Recovery: fix the payload and reschedule; the chain resumes cleanly. + call('set_flaky_failing', 'false'); + call('schedule_every', JSON.stringify('flaky'), '1', '0'); + await poll( + 'the rescheduled flaky job to fire', + () => count('tick_log', "WHERE jobName = 'flaky'") >= 1 + ); + assert.ok( + count('tick_log', "WHERE jobName = 'flaky'") >= 1, + 'rescheduled job must fire again' + ); + assert.equal(jobRow('flaky').enabled, true); + + // Rescheduling creates a new generation so stale fire or recovery work cannot + // mutate the replacement schedule. + const recoveredGeneration = BigInt(jobRow('flaky').generation); + call('schedule_every', JSON.stringify('flaky'), '2', '0'); + assert.equal( + BigInt(jobRow('flaky').generation), + recoveredGeneration + 1n, + 'reschedule must increment the generation' + ); + assert.equal( + count('flaky_fire', "WHERE jobName = 'flaky'"), + 1, + 'reschedule must atomically replace the pending trigger' + ); + + // Procedure job: fires through the two-transaction middleware. + call( + 'schedule_probe', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0', + JSON.stringify('health-check') + ); + await poll('the procedure job to fire with its arguments', () => { + return ( + count('tick_log', "WHERE jobName = 'probe'") >= 1 && + count( + 'argument_log', + "WHERE jobName = 'probe' AND value = 'health-check'" + ) >= 1 + ); + }); + assert.ok( + count('tick_log', "WHERE jobName = 'probe'") >= 1, + 'procedure job must fire' + ); + assert.ok( + count( + 'argument_log', + "WHERE jobName = 'probe' AND value = 'health-check'" + ) >= 1, + 'procedure job must receive its typed arguments' + ); + assert.equal(count('probe_fire', "WHERE jobName = 'probe'"), 1); + + // Unschedule disarms and disables without deleting state. + call('unschedule_job', JSON.stringify('probe')); + assert.equal( + count('probe_fire', "WHERE jobName = 'probe'"), + 0, + 'unschedule must disarm' + ); + assert.equal(jobRow('probe').enabled, false); + + // Procedure failures are recorded in a committed follow-up transaction and + // participate in the same automatic disable policy. + call('unschedule_job', JSON.stringify('flaky')); + call('set_flaky_failing', 'true'); + const successfulProbeTicks = count('tick_log', "WHERE jobName = 'probe'"); + call( + 'schedule_probe', + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '1', + JSON.stringify('failure-check') + ); + await poll( + 'the failed procedure to disable itself', + () => jobRow('probe').enabled === false + ); + const failedProbe = jobRow('probe'); + assert.equal( + failedProbe.enabled, + false, + 'failed procedure must auto-disable' + ); + assert.equal(Number(failedProbe.consecutiveFailures), 1); + assert.match(String(failedProbe.disabledReason), /probe\.failure/); + assert.equal( + count('tick_log', "WHERE jobName = 'probe'"), + successfulProbeTicks, + 'failed procedure must not report successful application work' + ); + call('set_flaky_failing', 'false'); + + // History stays capped (default 5 per job) despite many report fires. + const reportFireCountBeforeHistoryCheck = Number(jobRow('report').fireCount); + await poll( + 'additional report fires for history pruning', + () => + Number(jobRow('report').fireCount) >= + reportFireCountBeforeHistoryCheck + 2 + ); + assert.ok( + count('cron_run', "WHERE jobName = 'report'") <= 5, + 'completed history must stay bounded' + ); + + // Validation rejections surface as failed calls before any row changes. + callExpectFailure( + 'schedule_cron', + JSON.stringify('report'), + JSON.stringify('not a cron'), + JSON.stringify('UTC'), + '0' + ); + callExpectFailure( + 'schedule_cron', + JSON.stringify('report'), + JSON.stringify('* * * * *'), + JSON.stringify('Mars/Olympus'), + '0' + ); + callExpectFailure('schedule_every', JSON.stringify('report'), '0', '0'); + callExpectFailure('schedule_every', JSON.stringify('nope'), '5', '0'); + + // Scheduled job reducers reject direct client calls. + callExpectFailure('forge_report_fire_for_test'); + + // The example module publishes and seeds its declared jobs. + run([ + 'publish', + ...serverArgs, + '--yes', + '--module-path', + 'example/spacetimedb', + exampleDatabase, + ]); + examplePublished = true; + assert.equal( + Number( + sql('SELECT COUNT(*) AS count FROM cron_job', exampleDatabase)[0][0] + ), + 2, + 'example init must seed digest and cleanup' + ); + + console.log('cron module local test passed'); +} finally { + if (published) { + run(['delete', ...serverArgs, '--yes', database]); + } + if (examplePublished) { + run(['delete', ...serverArgs, '--yes', exampleDatabase]); + } +} diff --git a/spacetime-cron-ts/scripts/test-recovery.mjs b/spacetime-cron-ts/scripts/test-recovery.mjs new file mode 100644 index 00000000000..eb5d28295d8 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-recovery.mjs @@ -0,0 +1,307 @@ +// Crash-recovery integration test for @spacetimedb/cron. Runs an isolated +// SpacetimeDB instance so force-stopping it cannot disturb another server. The +// probe procedure remains in flight while the host is killed. The procedure's +// first transaction must preserve the calendar chain before the interruption. +import * as assert from 'node:assert/strict'; +import { spawn, spawnSync } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, rm } from 'node:fs/promises'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = fileURLToPath(new URL('..', import.meta.url)); +const dataDir = await mkdtemp(path.join(os.tmpdir(), 'cron-recovery-')); +const port = await reservePort(); +const serverUrl = `http://127.0.0.1:${port}`; +const database = 'cron-recovery'; +const serverLogs = []; +let server; + +function wait(milliseconds) { + return new Promise(resolve => setTimeout(resolve, milliseconds)); +} + +async function reservePort() { + const listener = net.createServer(); + listener.unref(); + await new Promise((resolve, reject) => { + listener.once('error', reject); + listener.listen(0, '127.0.0.1', resolve); + }); + const address = listener.address(); + assert.ok(address && typeof address === 'object'); + const selected = address.port; + await new Promise((resolve, reject) => + listener.close(error => (error ? reject(error) : resolve())) + ); + return selected; +} + +function run(args) { + const result = spawnSync('spacetime', args, { + cwd: root, + encoding: 'utf8', + shell: false, + windowsHide: true, + }); + assert.ifError(result.error); + assert.equal( + result.status, + 0, + `command failed: spacetime ${args.join(' ')}\n${result.stdout}\n${result.stderr}` + ); + return result; +} + +function call(name, ...args) { + return run(['call', '--server', serverUrl, database, name, ...args]); +} + +function sql(query) { + const result = run([ + 'sql', + '--server', + serverUrl, + '--format', + 'json', + database, + query, + ]); + return JSON.parse(result.stdout)[0].rows; +} + +function statusTag(value) { + const tags = ['Ok', 'Failed']; + assert.ok(Array.isArray(value), `unexpected status encoding: ${value}`); + const tag = tags[value[0]]; + assert.ok(tag, `unknown status variant: ${value[0]}`); + return tag; +} + +function runs() { + return sql( + "SELECT invocationId, sequence, status FROM cron_run WHERE jobName = 'recovery_probe'" + ).map(([invocationId, sequence, status]) => ({ + invocationId, + sequence: BigInt(sequence), + status: statusTag(status), + })); +} + +function job() { + const rows = sql( + "SELECT enabled, fireCount, consecutiveFailures FROM cron_job WHERE name = 'recovery_probe'" + ); + assert.equal(rows.length, 1, 'expected the recovery probe job'); + const [enabled, fireCount, consecutiveFailures] = rows[0]; + return { + enabled, + fireCount: BigInt(fireCount), + consecutiveFailures: Number(consecutiveFailures), + }; +} + +function blockingInvocationId() { + const rows = sql( + 'SELECT invocationId FROM recovery_probe_state WHERE singleton = true' + ); + return rows[0]?.[0]; +} + +async function poll(description, check, timeoutMilliseconds = 30_000) { + const deadline = Date.now() + timeoutMilliseconds; + let lastError; + while (Date.now() < deadline) { + try { + const result = await check(); + if (result) return result; + lastError = undefined; + } catch (error) { + lastError = error; + } + await wait(200); + } + const detail = lastError instanceof Error ? `: ${lastError.message}` : ''; + throw new Error(`timed out waiting for ${description}${detail}`); +} + +function startServer() { + const child = spawn( + 'spacetime', + [ + 'start', + '--listen-addr', + `127.0.0.1:${port}`, + '--data-dir', + dataDir, + '--non-interactive', + ], + { + cwd: root, + shell: false, + windowsHide: true, + stdio: ['ignore', 'pipe', 'pipe'], + } + ); + let output = ''; + const capture = chunk => { + output = `${output}${chunk}`.slice(-20_000); + }; + child.stdout.on('data', capture); + child.stderr.on('data', capture); + serverLogs.push(() => output); + return child; +} + +async function waitForServer(child) { + await poll( + 'isolated SpacetimeDB server', + () => + new Promise(resolve => { + if (child.exitCode !== null) { + resolve(false); + return; + } + const socket = net.createConnection({ host: '127.0.0.1', port }); + socket.once('connect', () => { + socket.destroy(); + resolve(true); + }); + socket.once('error', () => resolve(false)); + socket.setTimeout(500, () => { + socket.destroy(); + resolve(false); + }); + }) + ); + if (child.exitCode !== null) { + throw new Error(`isolated server exited early\n${serverLogs.at(-1)?.()}`); + } +} + +async function stopServer(child) { + if (!child || child.exitCode !== null) return; + const exited = once(child, 'exit'); + if (process.platform === 'win32') { + spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { + encoding: 'utf8', + windowsHide: true, + }); + } else { + child.kill('SIGKILL'); + } + await Promise.race([exited, wait(5_000)]); + if (child.exitCode === null) { + throw new Error(`failed to stop isolated server process ${child.pid}`); + } +} + +try { + server = startServer(); + await waitForServer(server); + run([ + 'publish', + '--server', + serverUrl, + '--yes', + '--module-path', + 'spacetimedb', + database, + ]); + + call( + 'schedule_cron', + JSON.stringify('recovery_probe'), + JSON.stringify('*/1 * * * * *'), + JSON.stringify('UTC'), + '0' + ); + const blockedInvocation = await poll( + 'the recovery probe to enter its blocking section', + blockingInvocationId + ); + assert.match(blockedInvocation, /^recovery_probe:[0-9]+:1$/); + assert.equal( + job().fireCount, + 1n, + 'the first transaction must reserve exactly one invocation before blocking' + ); + assert.equal( + runs().some(run => run.sequence === 1n), + false, + 'the blocked invocation must not have a completed outcome' + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM tick_log WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 0, + 'the blocked handler must not record completed application work' + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM recovery_probe_fire WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 1, + 'the first transaction must persist the successor before blocking' + ); + + await stopServer(server); + server = undefined; + + // Leave several calendar occurrences behind us. Recovery should execute at + // most one overdue occurrence before resuming from the current time. + await wait(5_000); + + server = startServer(); + await waitForServer(server); + await poll('a successful post-restart recovery probe', () => { + const observed = runs(); + const recovered = observed.some( + run => run.sequence > 1n && run.status === 'Ok' + ); + const state = job(); + return ( + recovered && + state.enabled && + state.fireCount >= 2n && + state.consecutiveFailures === 0 + ); + }); + await wait(500); + assert.ok( + job().fireCount <= 3n, + 'calendar recovery must not replay every occurrence missed during downtime' + ); + assert.equal( + Number( + sql( + "SELECT COUNT(*) AS count FROM recovery_probe_fire WHERE jobName = 'recovery_probe'" + )[0][0] + ), + 1, + 'the recovered calendar job must retain one successor trigger' + ); + + console.log('cron crash-recovery test passed'); +} catch (error) { + const logs = serverLogs.map( + (read, index) => `server ${index + 1}:\n${read()}` + ); + if (logs.length > 0) console.error(logs.join('\n')); + throw error; +} finally { + await stopServer(server); + await rm(dataDir, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 200, + }); +} diff --git a/spacetime-cron-ts/scripts/test-registration.ts b/spacetime-cron-ts/scripts/test-registration.ts new file mode 100644 index 00000000000..8c2b182d8bc --- /dev/null +++ b/spacetime-cron-ts/scripts/test-registration.ts @@ -0,0 +1,218 @@ +import * as assert from 'node:assert/strict'; +import { spacetimeCron } from '../src/cron'; +import type { CronSchema, CronSdk } from '../src/types'; + +interface DynamicValue { + (...args: unknown[]): DynamicValue; + readonly [key: PropertyKey]: DynamicValue; +} + +function dynamicValue(): DynamicValue { + const callable = () => dynamicValue(); + return new Proxy(callable, { + apply: () => dynamicValue(), + get: () => dynamicValue(), + }) as DynamicValue; +} + +function toCamelCase(value: string): string { + const converted = value + .replace(/[-_]+/g, '_') + .replace(/_([a-zA-Z0-9])/g, (_match, character: string) => + character.toUpperCase() + ); + return converted.charAt(0).toLowerCase() + converted.slice(1); +} + +const registrationSchema = { + reducer: (..._args: unknown[]) => ({}), + procedure: (..._args: unknown[]) => ({}), + anonymousView: (..._args: unknown[]) => ({}), +} as unknown as CronSchema; + +function createApi() { + return spacetimeCron({ + table: dynamicValue(), + t: dynamicValue(), + toCamelCase, + ScheduleAt: dynamicValue(), + Timestamp: dynamicValue(), + SenderError: dynamicValue(), + } as unknown as CronSdk); +} + +{ + const owner = createApi(); + const foreign = createApi().cronTable({ name: 'foreign' }); + assert.throws(() => owner.createCron([foreign]), /cron\.foreign_job_handle/); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'duplicate' }); + assert.throws( + () => api.createCron([job, job]), + /cron\.duplicate_job:duplicate/ + ); +} + +{ + const api = createApi(); + const first = api.cronTable({ name: 'first' }); + const second = api.cronTable({ name: 'second' }); + api.createCron([first]); + assert.throws( + () => api.createCron([second]), + /cron\.multiple_cores_not_supported/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'not_wired' }); + assert.throws( + () => job.cronReducer(registrationSchema, () => {}), + /cron\.not_wired:not_wired/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'missing_handler' }); + const cron = api.createCron([job], { reconcileEverySeconds: 60 }); + assert.throws( + () => cron.reconcileReducer(registrationSchema), + /cron\.missing_handlers:missing_handler/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'unscheduled_handler' }); + api.createCron([job]); + assert.throws( + () => api.schedule({}, job, { everySeconds: 60 }), + /cron\.missing_handlers:unscheduled_handler/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'duplicate_handler' }); + api.createCron([job]); + job.cronReducer(registrationSchema, () => {}); + assert.throws( + () => job.cronProcedure(registrationSchema, () => {}), + /cron\.handler_already_registered:duplicate_handler:reducer/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'no_reconciler' }); + const cron = api.createCron([job]); + job.cronReducer(registrationSchema, () => {}); + assert.throws( + () => cron.reconcileReducer(registrationSchema), + /cron\.reconcile_not_configured/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'reconcile_once' }); + const cron = api.createCron([job], { reconcileEverySeconds: 60 }); + job.cronReducer(registrationSchema, () => {}); + cron.reconcileReducer(registrationSchema); + assert.throws( + () => cron.reconcileReducer(registrationSchema), + /cron\.reconcile_reducer_already_registered/ + ); +} + +{ + const api = createApi(); + const job = api.cronTable({ name: 'views_once' }); + const cron = api.createCron([job]); + cron.publicViews(registrationSchema); + assert.throws( + () => cron.publicViews(registrationSchema), + /cron\.public_views_already_registered/ + ); +} + +{ + const api = createApi(); + const firstJob = api.cronTable({ name: 'first_job' }); + const secondJob = api.cronTable({ name: 'second_job' }); + const cron = api.createCron([firstJob, secondJob], { + reconcileEverySeconds: 60, + }); + assert.deepEqual(Object.keys(cron.tables).sort(), [ + 'cronJob', + 'cronReconcileTick', + 'cronRun', + 'firstJobFire', + 'secondJobFire', + ]); +} + +{ + let viewBody: ((ctx: unknown) => unknown) | undefined; + const schemaWithInspectableView = { + ...registrationSchema, + anonymousView: (...args: unknown[]) => { + viewBody = args[2] as (ctx: unknown) => unknown; + return {}; + }, + } as unknown as CronSchema; + const api = createApi(); + const job = api.cronTable({ name: 'sanitized_view' }); + const cron = api.createCron([job]); + cron.publicViews(schemaWithInspectableView); + assert.ok(viewBody); + + const baseRow = { + name: 'sanitized_view', + schedule: { tag: 'every', value: { seconds: 60 } }, + args: { tag: 'sanitized_view', value: undefined }, + enabled: false, + maxFailures: 1, + consecutiveFailures: 1, + fireCount: 1n, + generation: 1n, + lastRunAt: undefined, + nextRunAt: undefined, + }; + const privateReasons = [ + 'failed_1_consecutive_times:secret application failure', + 'failed_1_consecutive_times:lost_fire', + 'cron.invalid_schedule_state:secret parser detail', + 'disabled_by_operator', + 'unrecognized private detail', + ]; + const publicRows = viewBody({ + db: { + cronJob: { + iter: () => + privateReasons.map(disabledReason => ({ + ...baseRow, + disabledReason, + })), + }, + }, + }) as Array<{ disabledReason: string }>; + + assert.deepEqual( + publicRows.map(row => row.disabledReason), + [ + 'failure_threshold_reached', + 'lost_fire_threshold_reached', + 'invalid_schedule_state', + 'disabled_by_operator', + 'disabled', + ] + ); +} + +console.log('cron registration tests passed'); diff --git a/spacetime-cron-ts/scripts/test-schedule.ts b/spacetime-cron-ts/scripts/test-schedule.ts new file mode 100644 index 00000000000..cbd4e4f0786 --- /dev/null +++ b/spacetime-cron-ts/scripts/test-schedule.ts @@ -0,0 +1,199 @@ +// Unit tests for calendar occurrence computation. +// Run: pnpm test:schedule +import { + parseCronExpression, + nextFireAfter, + isValidTimezone, +} from '../src/parser'; + +let failures = 0; +function check(name: string, cond: boolean, detail?: string) { + if (cond) { + console.log(`ok ${name}`); + } else { + failures++; + console.error(`FAIL ${name}${detail ? `: ${detail}` : ''}`); + } +} + +const MICROS = 1000n; +function utcMicros( + y: number, + mo: number, + d: number, + h = 0, + mi = 0, + s = 0 +): bigint { + return BigInt(Date.UTC(y, mo - 1, d, h, mi, s)) * MICROS; +} +function fmt(micros: bigint | undefined, tz = 'UTC'): string { + if (micros === undefined) return 'undefined'; + return new Date(Number(micros / MICROS)).toLocaleString('en-US', { + timeZone: tz, + hour12: false, + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }); +} + +// 1. Basic calendar step: next minute boundary, strictly after `now`. +{ + const parsed = parseCronExpression('* * * * *'); + const now = utcMicros(2026, 8, 12, 10, 0, 30); // 10:00:30 + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'next-minute boundary', + next === utcMicros(2026, 8, 12, 10, 1, 0), + fmt(next) + ); +} + +// 2. Strictly-after semantics: asking at an exact occurrence must return the NEXT one. +{ + const parsed = parseCronExpression('* * * * *'); + const now = utcMicros(2026, 8, 12, 10, 1, 0); // exactly on an occurrence + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'strictly-after at exact occurrence', + next === utcMicros(2026, 8, 12, 10, 2, 0), + fmt(next) + ); +} + +// 3. Seconds granularity (6-field cron, used by the integration test). +{ + const parsed = parseCronExpression('*/2 * * * * *'); + const now = utcMicros(2026, 8, 12, 10, 0, 1); + const next = nextFireAfter(parsed, now, 'UTC'); + check( + 'seconds-granularity */2', + next === utcMicros(2026, 8, 12, 10, 0, 2), + fmt(next) + ); +} + +// 4. Timezone correctness: 09:00 America/New_York in August = 13:00 UTC (EDT, UTC-4). +{ + const parsed = parseCronExpression('0 9 * * *'); + const now = utcMicros(2026, 8, 12, 0, 0, 0); + const next = nextFireAfter(parsed, now, 'America/New_York'); + check('tz offset EDT', next === utcMicros(2026, 8, 12, 13, 0, 0), fmt(next)); +} + +// 5. DST spring-forward: 2026-03-08 02:30 does not exist in America/New_York. +// The job must not be lost and must not fire twice; document what it does. +{ + const parsed = parseCronExpression('30 2 * * *'); + const start = utcMicros(2026, 3, 7, 12, 0, 0); + const a = nextFireAfter(parsed, start, 'America/New_York'); + const b = + a !== undefined ? nextFireAfter(parsed, a, 'America/New_York') : undefined; + const c = + b !== undefined ? nextFireAfter(parsed, b, 'America/New_York') : undefined; + // Starting after noon on March 7 makes the first result the March 8 slot. + check( + 'spring-forward: occurrence exists', + a !== undefined && b !== undefined && c !== undefined + ); + check( + 'spring-forward: monotonic chain', + a !== undefined && b !== undefined && c !== undefined && a < b && b < c, + `${fmt(a, 'America/New_York')} | ${fmt(b, 'America/New_York')} | ${fmt(c, 'America/New_York')}` + ); + console.log( + ` info: 02:30 chain around spring-forward fires at: ${fmt(a, 'America/New_York')}, ${fmt(b, 'America/New_York')}, ${fmt(c, 'America/New_York')} (local NY time)` + ); +} + +// 6. DST fall-back: 2026-11-01 01:30 occurs twice in America/New_York. +// The chain must fire exactly once per calendar day, not twice. +{ + const parsed = parseCronExpression('30 1 * * *'); + const start = utcMicros(2026, 10, 31, 12, 0, 0); + const fires: bigint[] = []; + let cursor: bigint | undefined = start; + for (let i = 0; i < 3 && cursor !== undefined; i++) { + cursor = nextFireAfter(parsed, cursor, 'America/New_York'); + if (cursor !== undefined) fires.push(cursor); + } + const days = fires.map(f => + new Date(Number(f / MICROS)).toLocaleDateString('en-US', { + timeZone: 'America/New_York', + }) + ); + check( + 'fall-back: one fire per day', + new Set(days).size === days.length, + fires.map(f => fmt(f, 'America/New_York')).join(' | ') + ); + console.log( + ` info: 01:30 chain around fall-back fires at: ${fires.map(f => fmt(f, 'America/New_York')).join(', ')} (local NY time)` + ); +} + +// 7a. Statically impossible expressions are rejected at PARSE time (finding: +// cron-parser refuses Feb 30 outright, so create_job's validateSchedule +// catches these as invalid_expression before any row exists). +{ + let threw = false; + try { + parseCronExpression('0 0 30 2 *'); + } catch { + threw = true; + } + check('impossible Feb 30 rejected at parse', threw); +} + +// 7b. nextFireAfter -> undefined is still reachable at JS date bounds, so the +// fire reducer's disable-loudly path has a real (if exotic) trigger. +{ + const parsed = parseCronExpression('0 0 1 1 *'); + const nearMax = 8_640_000_000_000_000n * 1000n - 1_000_000n; // ~max JS date, in micros + const next = nextFireAfter(parsed, nearMax, 'UTC'); + check('date-bound overflow -> undefined', next === undefined, fmt(next)); +} + +// 8. Chain-step simulation: late fire does not drift the schedule. +// Job '0 * * * *' (hourly). Fire lands 7 minutes late; next must still be the +// top of the NEXT hour, not lateFire+1h. +{ + const parsed = parseCronExpression('0 * * * *'); + const lateFire = utcMicros(2026, 8, 12, 9, 7, 0); // fired late at 09:07 + const next = nextFireAfter(parsed, lateFire, 'UTC'); + check( + 'late fire re-arms nominal slot', + next === utcMicros(2026, 8, 12, 10, 0, 0), + fmt(next) + ); +} + +// 9. Catch-up semantics: an armed fire far in the past re-arms to the next FUTURE +// occurrence, skipping intermediate ones. This is one catch-up run. +{ + const parsed = parseCronExpression('*/5 * * * *'); + const wokeUpAt = utcMicros(2026, 8, 12, 11, 3, 0); // was down for hours + const next = nextFireAfter(parsed, wokeUpAt, 'UTC'); + check( + 'catch-up skips missed occurrences', + next === utcMicros(2026, 8, 12, 11, 5, 0), + fmt(next) + ); +} + +// 10. Timezone validation. +{ + check('valid tz', isValidTimezone('America/New_York')); + check('invalid tz rejected', !isValidTimezone('Mars/Olympus_Mons')); +} + +console.log( + failures === 0 + ? '\nAll schedule tests passed.' + : `\n${failures} test(s) FAILED.` +); +process.exit(failures === 0 ? 0 : 1); diff --git a/spacetime-cron-ts/scripts/test-types.ts b/spacetime-cron-ts/scripts/test-types.ts new file mode 100644 index 00000000000..eab0bbebaee --- /dev/null +++ b/spacetime-cron-ts/scripts/test-types.ts @@ -0,0 +1,72 @@ +// Compile-time API coverage. This file is checked by `pnpm typecheck`. +import { t } from 'spacetimedb/server'; +import type { + CronApi, + CronInvocation, + CronJobReference, + CronSchema, +} from '../src/index'; + +declare const cron: CronApi; +declare const ctx: object; +declare const spacetimedb: CronSchema; + +const heartbeat = cron.cronTable({ name: 'heartbeat' }); +const reportDefinition = { + name: 'report', + args: t.object('TypeTestReportArgs', { + tenantId: t.u64(), + batchSize: t.u32(), + }), +} as const; +const report = cron.cronTable(reportDefinition); + +heartbeat.cronReducer(spacetimedb, (_ctx: object, invocation) => { + const checked: CronInvocation = invocation; + void checked; +}); + +report.cronReducer(spacetimedb, (_ctx: object, args, invocation) => { + const tenantId: bigint = args.tenantId; + const batchSize: number = args.batchSize; + const checked: CronInvocation = invocation; + void tenantId; + void batchSize; + void checked; +}); + +cron.schedule(ctx, heartbeat, { everySeconds: 30 }); +cron.schedule(ctx, heartbeat, '0 * * * *', { timezone: 'UTC' }); +cron.schedule(ctx, report, '0 9 * * *', { + timezone: 'UTC', + args: { tenantId: 42n, batchSize: 100 }, +}); + +// @ts-expect-error Argument-bearing jobs require scheduling options with args. +cron.schedule(ctx, report, '0 9 * * *'); +// @ts-expect-error Argument-bearing jobs require an args property. +cron.schedule(ctx, report, '0 9 * * *', { timezone: 'UTC' }); +cron.schedule(ctx, report, '0 9 * * *', { + // @ts-expect-error tenantId is a u64 and therefore a bigint. + args: { tenantId: 42, batchSize: 100 }, +}); +cron.schedule( + ctx, + heartbeat, + { everySeconds: 30 }, + { + // @ts-expect-error Argumentless jobs do not accept an args property. + args: {}, + } +); + +const reference: CronJobReference = report; +cron.unschedule(ctx, reference); + +const core = cron.createCron([heartbeat, report], { + reconcileEverySeconds: 300, +}); +const reconcile = core.reconcileReducer(spacetimedb); +const publicViews = core.publicViews(spacetimedb); +void reconcile; +void publicViews.jobs; diff --git a/spacetime-cron-ts/scripts/test-validation.ts b/spacetime-cron-ts/scripts/test-validation.ts new file mode 100644 index 00000000000..549497ea7fc --- /dev/null +++ b/spacetime-cron-ts/scripts/test-validation.ts @@ -0,0 +1,97 @@ +import * as assert from 'node:assert/strict'; +import { + boundedScheduleTime, + CHECKPOINT_DELAY_MICROS, + MAX_ERROR_LENGTH, + MAX_FAILURES, + MAX_HISTORY_CAP, + MAX_INTERVAL_SECONDS, + normalizeHistoryCap, + normalizeJobArgs, + normalizeJobName, + normalizeMaxFailures, + normalizeReconcileEverySeconds, + normalizeSchedule, + truncateError, +} from '../src/schedule'; + +const utcMicros = (iso: string) => BigInt(Date.parse(iso)) * 1_000n; + +assert.equal(normalizeJobName('daily_report'), 'daily_report'); +for (const invalid of [ + '', + 'DailyReport', + 'daily-report', + '_daily', + 'daily__report', +]) { + assert.throws(() => normalizeJobName(invalid), /cron\.invalid_job_name/); +} +assert.throws(() => normalizeJobName(`a${'b'.repeat(48)}`), /invalid_job_name/); + +const now = utcMicros('2028-03-01T00:00:00.000Z'); +for (const everySeconds of [0, -1, 1.5, MAX_INTERVAL_SECONDS + 1]) { + assert.throws( + () => normalizeSchedule({ everySeconds }, undefined, now), + /cron\.invalid_interval/ + ); +} +assert.equal( + normalizeSchedule({ everySeconds: 30 }, undefined, now).firstAt, + now + 30_000_000n +); + +for (const maxFailures of [-1, 1.5, MAX_FAILURES + 1]) { + assert.throws( + () => normalizeMaxFailures(maxFailures), + /invalid_max_failures/ + ); +} +assert.equal(normalizeMaxFailures(undefined), 0); +assert.equal(normalizeMaxFailures(MAX_FAILURES), MAX_FAILURES); + +assert.deepEqual(normalizeJobArgs('heartbeat', false, undefined), {}); +assert.deepEqual( + normalizeJobArgs('report', true, { args: { tenantId: 42n } }), + { tenantId: 42n } +); +assert.equal( + normalizeJobArgs('optional', true, { args: undefined }), + undefined +); +assert.throws( + () => normalizeJobArgs('report', true, undefined), + /cron\.missing_args:report/ +); +assert.throws( + () => normalizeJobArgs('heartbeat', false, { args: {} }), + /cron\.unexpected_args:heartbeat/ +); + +for (const historyCap of [-1, 1.5, MAX_HISTORY_CAP + 1]) { + assert.throws(() => normalizeHistoryCap(historyCap), /invalid_history_cap/); +} +assert.equal(normalizeHistoryCap(undefined), 5); + +for (const seconds of [0, -1, 1.5, MAX_INTERVAL_SECONDS + 1]) { + assert.throws( + () => normalizeReconcileEverySeconds(seconds), + /invalid_reconcile_interval/ + ); +} +assert.equal(normalizeReconcileEverySeconds(undefined), undefined); +assert.equal(normalizeReconcileEverySeconds(300), 300); + +const leapDay = normalizeSchedule('0 0 29 2 *', { timezone: 'UTC' }, now); +assert.ok(leapDay.firstAt !== undefined); +assert.ok(leapDay.firstAt - now > CHECKPOINT_DELAY_MICROS); +assert.equal( + boundedScheduleTime(now, leapDay.firstAt), + now + CHECKPOINT_DELAY_MICROS +); + +const longError = 'x'.repeat(MAX_ERROR_LENGTH + 100); +assert.equal(truncateError(longError).length, MAX_ERROR_LENGTH); +assert.match(truncateError(longError), /\.\.\.$/); + +console.log('cron validation tests passed'); diff --git a/spacetime-cron-ts/spacetimedb/.npmrc b/spacetime-cron-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-cron-ts/spacetimedb/package.json b/spacetime-cron-ts/spacetimedb/package.json new file mode 100644 index 00000000000..d7d8053aa05 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-cron-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-cron", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-cron" + }, + "dependencies": { + "@spacetimedb/cron": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-cron-ts/spacetimedb/src/index.ts b/spacetime-cron-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..397e76ea4e2 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/src/index.ts @@ -0,0 +1,336 @@ +import { + schema, + table, + t, + SenderError, + toCamelCase, + type ReducerCtx, + type InferSchema, + type ProcedureCtx, +} from 'spacetimedb/server'; +import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { + spacetimeCron, + type CronJobHandle, + type CronJobReference, +} from '@spacetimedb/cron'; + +// One injection point: hand the library this module's own SDK objects so the +// bundle contains exactly one copy of the spacetimedb SDK. +const { cronTable, createCron, schedule, unschedule } = spacetimeCron({ + table, + t, + toCamelCase, + ScheduleAt, + Timestamp, + SenderError, +}); + +// ── Jobs ───────────────────────────────────────────────────────────────────── + +const heartbeat = cronTable({ name: 'heartbeat' }); +const report = cronTable({ + name: 'report', + args: t.object('ReportCronArgs', { + label: t.string(), + batchSize: t.u32(), + }), +}); +const flaky = cronTable({ name: 'flaky' }); +const probe = cronTable({ + name: 'probe', + args: t.object('ProbeCronArgs', { source: t.string() }), +}); +const recoveryProbe = cronTable({ name: 'recovery_probe' }); + +const cron = createCron([heartbeat, report, flaky, probe, recoveryProbe], { + publicTables: true, + reconcileEverySeconds: 2, +}); + +// ── App tables ─────────────────────────────────────────────────────────────── + +const tickLog = table( + { name: 'tick_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + at: t.timestamp(), + } +); + +const flakyState = table( + { name: 'flaky_state', public: true }, + { + singleton: t.bool().primaryKey(), + failing: t.bool(), + } +); + +const argumentLog = table( + { name: 'argument_log', public: true }, + { + id: t.u64().primaryKey().autoInc(), + jobName: t.string().index(), + value: t.string(), + count: t.u32(), + invocationId: t.string(), + } +); + +const recoveryProbeState = table( + { name: 'recovery_probe_state' }, + { + singleton: t.bool().primaryKey(), + invocationId: t.string(), + } +); + +const spacetimedb = schema({ + ...cron.tables, + tickLog, + flakyState, + argumentLog, + recoveryProbeState, +}); +export default spacetimedb; + +type Schema = InferSchema; +type Tx = ReducerCtx; +type Proc = ProcedureCtx; + +// ── Cron wiring ────────────────────────────────────────────────────────────── + +export const runHeartbeat = heartbeat.cronReducer(spacetimedb, (ctx: Tx) => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'heartbeat', at: ctx.timestamp }); +}); + +export const runReport = report.cronReducer( + spacetimedb, + (ctx: Tx, args, invocation) => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'report', at: ctx.timestamp }); + ctx.db.argumentLog.insert({ + id: 0n, + jobName: 'report', + value: args.label, + count: args.batchSize, + invocationId: invocation.id, + }); + } +); + +// Integration-only authorization probe. Direct calls must not execute a +// reducer that is reserved for the scheduler. +export const forgeReportFireForTest = spacetimedb.reducer(ctx => { + const fireTable = ctx.db.reportFire as unknown as { + iter(): Iterable; + }; + const fire = [...fireTable.iter()][0]; + if (!fire) throw new SenderError('cron.test_missing_report_fire'); + const invoke = runReport as unknown as ( + ctx: Tx, + args: { arg: unknown } + ) => void; + invoke(ctx, { arg: fire }); +}); + +// Handler writes roll back on failure. Volatile recovery records the failure +// and restores calendar jobs after the scheduled transaction aborts. +export const runFlaky = flaky.cronReducer(spacetimedb, (ctx: Tx) => { + ctx.db.tickLog.insert({ id: 0n, jobName: 'flaky', at: ctx.timestamp }); + const state = ctx.db.flakyState.singleton.find(true); + if (state?.failing) throw new Error('flaky.failure'); +}); + +// Procedure job: the natural home for side-effecting work such as outbound +// HTTP. Here it writes through withTx so the local suite can observe it. +export const runProbe = probe.cronProcedure( + spacetimedb, + (ctx: Proc, args, invocation) => { + const failing = ctx.withTx( + (tx: Tx) => tx.db.flakyState.singleton.find(true)?.failing ?? false + ); + if (failing) throw new Error('probe.failure'); + ctx.withTx((tx: Tx) => { + tx.db.tickLog.insert({ id: 0n, jobName: 'probe', at: tx.timestamp }); + tx.db.argumentLog.insert({ + id: 0n, + jobName: 'probe', + value: args.source, + count: 0, + invocationId: invocation.id, + }); + }); + } +); + +function blockUntilHostStops(): never { + for (;;) { + // The recovery test terminates the isolated host after observing its + // durable entry marker. V8 2.8 does not time out this execution path. + } +} + +// The first run remains in flight until the recovery test kills its isolated +// host. Its separate transactions prove what survives the interruption. +export const runRecoveryProbe = recoveryProbe.cronProcedure( + spacetimedb, + (ctx: Proc, run) => { + if (run.sequence === 1n) { + ctx.withTx((tx: Tx) => { + tx.db.recoveryProbeState.insert({ + singleton: true, + invocationId: run.id, + }); + }); + blockUntilHostStops(); + } + ctx.withTx((tx: Tx) => { + tx.db.tickLog.insert({ + id: 0n, + jobName: 'recovery_probe', + at: tx.timestamp, + }); + }); + } +); + +export const cronReconcile = cron.reconcileReducer(spacetimedb); +export const { jobs: cronJobs } = cron.publicViews(spacetimedb); + +export const init = spacetimedb.init(ctx => { + ctx.db.flakyState.insert({ singleton: true, failing: false }); + // Code-declared default for a fresh database. + schedule(ctx, heartbeat, { everySeconds: 30 }); +}); + +// ── CLI-facing management (thin wrappers over the library helpers) ─────────── + +const argumentlessJobs: Record = { + heartbeat, + flaky, + recovery_probe: recoveryProbe, +}; + +const allJobs: Record = { + ...argumentlessJobs, + report, + probe, +}; + +function argumentlessJobByName(name: string): CronJobHandle { + const job = argumentlessJobs[name]; + if (!job) throw new SenderError(`cron.unknown_job:${name}`); + return job; +} + +function jobByName(name: string): CronJobReference { + const job = allJobs[name]; + if (!job) throw new SenderError(`cron.unknown_job:${name}`); + return job; +} + +function scheduleSafely(operation: () => void): void { + try { + operation(); + } catch (err) { + throw err instanceof SenderError + ? err + : new SenderError(err instanceof Error ? err.message : String(err)); + } +} + +export const scheduleCron = spacetimedb.reducer( + { + name: t.string(), + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + }, + (ctx, args) => { + scheduleSafely(() => { + schedule(ctx, argumentlessJobByName(args.name), args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + }); + }); + } +); + +export const scheduleEvery = spacetimedb.reducer( + { name: t.string(), seconds: t.u32(), maxFailures: t.u32() }, + (ctx, args) => { + scheduleSafely(() => { + schedule( + ctx, + argumentlessJobByName(args.name), + { everySeconds: args.seconds }, + { maxFailures: args.maxFailures } + ); + }); + } +); + +export const scheduleReport = spacetimedb.reducer( + { + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + label: t.string(), + batchSize: t.u32(), + }, + (ctx, args) => { + scheduleSafely(() => { + schedule(ctx, report, args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + args: { label: args.label, batchSize: args.batchSize }, + }); + }); + } +); + +export const scheduleProbe = spacetimedb.reducer( + { + expression: t.string(), + timezone: t.string(), + maxFailures: t.u32(), + source: t.string(), + }, + (ctx, args) => { + scheduleSafely(() => { + schedule(ctx, probe, args.expression, { + timezone: args.timezone, + maxFailures: args.maxFailures, + args: { source: args.source }, + }); + }); + } +); + +export const unscheduleJob = spacetimedb.reducer( + { name: t.string() }, + (ctx, { name }) => { + unschedule(ctx, jobByName(name)); + } +); + +export const setFlakyFailing = spacetimedb.reducer( + { failing: t.bool() }, + (ctx, { failing }) => { + const state = ctx.db.flakyState.singleton.find(true); + if (state) ctx.db.flakyState.singleton.update({ ...state, failing }); + } +); + +// Integration-only fault injection for the lost-fire reconciler. +export const dropHeartbeatFireForTest = spacetimedb.reducer(ctx => { + const fireTable = ctx.db.heartbeatFire as unknown as { + iter(): Iterable<{ jobName: string }>; + delete(row: { jobName: string }): void; + }; + const pending = [...fireTable.iter()].find( + row => row.jobName === 'heartbeat' + ); + if (pending) fireTable.delete(pending); +}); diff --git a/spacetime-cron-ts/spacetimedb/tsconfig.json b/spacetime-cron-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-cron-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-cron-ts/src/cron.ts b/spacetime-cron-ts/src/cron.ts new file mode 100644 index 00000000000..bd8dc087de5 --- /dev/null +++ b/spacetime-cron-ts/src/cron.ts @@ -0,0 +1,1137 @@ +// eslint-disable-next-line @typescript-eslint/triple-slash-reference +/// +import { volatile_nonatomic_schedule_immediate } from 'spacetime:sys@2.0'; +import { BinaryWriter } from 'spacetimedb'; +import type { Infer, ModuleExport } from 'spacetimedb/server'; +import { + boundedScheduleTime, + CronInputError, + MAX_FAILURES, + normalizeHistoryCap, + normalizeJobArgs, + normalizeJobName, + normalizeMaxFailures, + normalizeReconcileEverySeconds, + normalizeSchedule, + nextOccurrence, + ONE_SECOND_MICROS, + truncateError, +} from './schedule'; +import type { + CronApi, + CronArgsBuilder, + CronCore, + CronCorePublicViews, + CronInvocation, + CronJobHandle, + CronJobReference, + CronSchedule, + CronSchema, + CronSdk, + CronTableDefinition, + CronTableOpts, + CronTableWithArgsOpts, + CronTimestamp, + CreateCronOpts, + ScheduleSpec, +} from './types'; + +const RECONCILE_REDUCER_NAME = 'cron_reconcile'; +const RECONCILE_TICK_KEY = 'cron'; + +const PUBLIC_DISABLED_REASONS = { + disabled: 'disabled', + disabledByOperator: 'disabled_by_operator', + failureThresholdReached: 'failure_threshold_reached', + invalidScheduleState: 'invalid_schedule_state', + lostFireThresholdReached: 'lost_fire_threshold_reached', +} as const; + +type RunStatus = 'Ok' | 'Failed'; + +interface IdentityLike { + toHexString(): string; +} + +interface DynamicSdkValue { + readonly [key: string]: DynamicSdkValue; + (...args: unknown[]): DynamicSdkValue; +} + +function asTableDefinition(value: DynamicSdkValue): CronTableDefinition { + return value as unknown as CronTableDefinition; +} + +interface RegistrationSchema { + anonymousView(...args: unknown[]): ModuleExport; + reducer(...args: unknown[]): ModuleExport; + procedure(...args: unknown[]): ModuleExport; +} + +type InternalHandler = (...args: unknown[]) => unknown; + +interface RuntimeScheduleOpts { + timezone?: string; + maxFailures?: number; + args?: unknown; +} + +interface UniqueAccessor { + find(key: Key): Row | undefined; + update(row: Row): unknown; +} + +interface IndexAccessor { + filter(key: Key): Iterable; +} + +interface TableView { + insert(row: Row): Row; + delete(row: Row): unknown; + iter(): Iterable; +} + +interface CronArgsValue { + tag: string; + value: unknown; +} + +interface JobRow { + name: string; + schedule: CronSchedule; + args: CronArgsValue; + enabled: boolean; + maxFailures: number; + consecutiveFailures: number; + fireCount: bigint; + generation: bigint; + lastRunAt: CronTimestamp | undefined; + nextRunAt: CronTimestamp | undefined; + disabledReason: string | undefined; +} + +function publicDisabledReason(reason: string | undefined): string | undefined { + if (reason === undefined) return undefined; + if (reason === 'disabled_by_operator') { + return PUBLIC_DISABLED_REASONS.disabledByOperator; + } + if (reason.startsWith('cron.invalid_schedule_state:')) { + return PUBLIC_DISABLED_REASONS.invalidScheduleState; + } + if (/^failed_[1-9][0-9]*_consecutive_times:lost_fire$/.test(reason)) { + return PUBLIC_DISABLED_REASONS.lostFireThresholdReached; + } + if (/^failed_[1-9][0-9]*_consecutive_times:/.test(reason)) { + return PUBLIC_DISABLED_REASONS.failureThresholdReached; + } + return PUBLIC_DISABLED_REASONS.disabled; +} + +interface FireRow { + scheduledId: bigint; + scheduledAt: unknown; + jobName: string; + generation: bigint; + targetAt: CronTimestamp | undefined; + recovery: FireRecovery | undefined; +} + +interface FireRecovery { + sequence: bigint; + scheduledFor: CronTimestamp; + error: string; +} + +interface RunRow { + invocationId: string; + jobName: string; + generation: bigint; + sequence: bigint; + scheduledFor: CronTimestamp; + completedAt: CronTimestamp; + status: { tag: RunStatus }; + error: string | undefined; +} + +interface ReconcileTickRow { + scheduledId: bigint; + scheduledAt: unknown; + key: string; +} + +type JobTable = TableView & { + name: UniqueAccessor; +}; + +type FireTable = TableView & { + jobName: UniqueAccessor; + scheduledId: UniqueAccessor; +}; + +type RunTable = TableView & { + invocationId: UniqueAccessor; + jobName: IndexAccessor; +}; + +type ReconcileTickTable = TableView & { + key: UniqueAccessor; +}; + +interface CronDatabase extends Record { + cronJob: JobTable; + cronRun: RunTable; + cronReconcileTick?: ReconcileTickTable; +} + +interface TransactionContext { + readonly db: CronDatabase; + readonly timestamp: CronTimestamp; + readonly sender: IdentityLike; + readonly databaseIdentity: IdentityLike; +} + +interface ProcedureContext { + readonly timestamp: CronTimestamp; + readonly sender: IdentityLike; + readonly databaseIdentity: IdentityLike; + withTx(body: (ctx: TransactionContext) => T): T; +} + +interface JobMetadata { + readonly handle: CronJobReference; + readonly argsType: DynamicSdkValue; + readonly hasArgs: boolean; + readonly fireTableName: string; + readonly fireAccessor: string; + readonly reducerName: string; + fire: DynamicSdkValue | undefined; + core: InternalCore | undefined; + registration: 'reducer' | 'procedure' | undefined; +} + +interface InternalCore extends CronCore { + readonly jobs: Map; + readonly historyCap: number; + readonly reconcileEverySeconds: number | undefined; + readonly reconcileTick: DynamicSdkValue | undefined; + reconcileRegistered: boolean; + publicViewsRegistered: boolean; +} + +interface PreparedFire { + readonly invocation: CronInvocation; + readonly args: unknown; +} + +function isThenable(value: unknown): value is PromiseLike { + return ( + (typeof value === 'object' || typeof value === 'function') && + value !== null && + 'then' in value && + typeof (value as { then?: unknown }).then === 'function' + ); +} + +function invocationId( + jobName: string, + generation: bigint, + sequence: bigint +): string { + return `${jobName}:${generation}:${sequence}`; +} + +/** Create a cron factory bound to the consumer module's SDK instance. */ +export function spacetimeCron(sdk: CronSdk): CronApi { + const { ScheduleAt, Timestamp, SenderError, toCamelCase } = sdk; + const table = sdk.table as unknown as DynamicSdkValue; + const t = sdk.t as unknown as DynamicSdkValue; + const metadata = new WeakMap(); + let coreCreated = false; + + const cronScheduleType = t.enum('CronSchedule', { + cron: t.object('CronSpec', { + expression: t.string(), + timezone: t.string(), + }), + every: t.object('EverySpec', { + seconds: t.u32(), + }), + }); + const runStatusType = t.enum('CronRunStatus', ['Ok', 'Failed']); + const fireRecoveryType = t.object('CronFireRecovery', { + sequence: t.u64(), + scheduledFor: t.timestamp(), + error: t.string(), + }); + + function requireMetadata(job: CronJobReference): JobMetadata { + const value = metadata.get(job); + if (!value) throw new Error('cron.foreign_job_handle'); + return value; + } + + function requireCore(job: CronJobReference): InternalCore { + const value = requireMetadata(job).core; + if (!value) { + throw new Error( + `cron.not_wired:${job.jobName}:pass the job to createCron() first` + ); + } + return value; + } + + function requireRegisteredHandlers(core: InternalCore): void { + const missing = [...core.jobs.values()] + .filter(job => !job.registration) + .map(job => job.handle.jobName); + if (missing.length > 0) { + throw new Error(`cron.missing_handlers:${missing.join(',')}`); + } + } + + function requireFire(job: JobMetadata): DynamicSdkValue { + if (!job.fire) { + throw new Error( + `cron.not_wired:${job.handle.jobName}:pass the job to createCron() first` + ); + } + return job.fire; + } + + function asTransactionContext(ctx: unknown): TransactionContext { + return ctx as TransactionContext; + } + + function requireDatabaseCaller( + ctx: Pick + ): void { + if (ctx.sender.toHexString() !== ctx.databaseIdentity.toHexString()) { + throw new SenderError('cron.not_authorized'); + } + } + + function fireTable(ctx: TransactionContext, job: JobMetadata): FireTable { + const value = ctx.db[job.fireAccessor]; + if (!value) { + throw new Error( + `cron.missing_table:${job.fireTableName}:spread cron.tables into schema()` + ); + } + return value as FireTable; + } + + function throwInputError(error: unknown): never { + if (error instanceof CronInputError) { + throw new SenderError(error.message); + } + throw error; + } + + function pruneHistory( + ctx: TransactionContext, + core: InternalCore, + jobName: string + ): void { + const rows = [...ctx.db.cronRun.jobName.filter(jobName)].sort( + (left, right) => + left.sequence < right.sequence + ? -1 + : left.sequence > right.sequence + ? 1 + : 0 + ); + const removeCount = Math.max(0, rows.length - core.historyCap); + for (const row of rows.slice(0, removeCount)) { + ctx.db.cronRun.delete(row); + } + } + + function recordRun( + ctx: TransactionContext, + core: InternalCore, + invocation: CronInvocation, + status: RunStatus, + error: string | undefined + ): void { + if (core.historyCap === 0) return; + if (ctx.db.cronRun.invocationId.find(invocation.id)) return; + ctx.db.cronRun.insert({ + invocationId: invocation.id, + jobName: invocation.jobName, + generation: invocation.generation, + sequence: invocation.sequence, + scheduledFor: invocation.scheduledFor, + completedAt: ctx.timestamp, + status: { tag: status }, + error, + }); + pruneHistory(ctx, core, invocation.jobName); + } + + function disarmFire(ctx: TransactionContext, job: JobMetadata): void { + const tableView = fireTable(ctx, job); + const pending = tableView.jobName.find(job.handle.jobName); + if (pending) tableView.delete(pending); + } + + function insertFire( + ctx: TransactionContext, + job: JobMetadata, + row: JobRow, + targetMicros: bigint | undefined + ): CronTimestamp | undefined { + const tableView = fireTable(ctx, job); + if (row.schedule.tag === 'every') { + tableView.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval( + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ), + jobName: row.name, + generation: row.generation, + targetAt: undefined, + recovery: undefined, + }); + return new Timestamp( + ctx.timestamp.microsSinceUnixEpoch + + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + } + if (targetMicros === undefined) return undefined; + const targetAt = new Timestamp(targetMicros); + tableView.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.time( + boundedScheduleTime(ctx.timestamp.microsSinceUnixEpoch, targetMicros) + ), + jobName: row.name, + generation: row.generation, + targetAt, + recovery: undefined, + }); + return targetAt; + } + + function replaceFire( + ctx: TransactionContext, + job: JobMetadata, + row: JobRow + ): JobRow { + disarmFire(ctx, job); + + let targetMicros: bigint | undefined; + if (row.schedule.tag === 'cron') { + try { + targetMicros = nextOccurrence( + row.schedule, + ctx.timestamp.microsSinceUnixEpoch + ); + } catch (error) { + return disableJob( + ctx, + job, + row, + `cron.invalid_schedule_state:${truncateError(error)}` + ); + } + if (targetMicros === undefined) { + return disableJob(ctx, job, row, 'cron.no_future_occurrence'); + } + } + + const nextRunAt = insertFire(ctx, job, row, targetMicros); + const updated = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(updated); + return updated; + } + + function ensureReconcileTick( + ctx: TransactionContext, + core: InternalCore + ): void { + const everySeconds = core.reconcileEverySeconds; + if (everySeconds === undefined) return; + if (!core.reconcileRegistered) { + throw new Error( + 'cron.reconcile_reducer_not_registered:export cron.reconcileReducer()' + ); + } + const tick = ctx.db.cronReconcileTick; + if (!tick) { + throw new Error( + 'cron.missing_table:cron_reconcile_tick:spread cron.tables into schema()' + ); + } + if (tick.key.find(RECONCILE_TICK_KEY)) return; + tick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval( + BigInt(everySeconds) * ONE_SECOND_MICROS + ), + key: RECONCILE_TICK_KEY, + }); + } + + function reconcileLostFires( + ctx: TransactionContext, + core: InternalCore + ): void { + for (const job of core.jobs.values()) { + const row = ctx.db.cronJob.name.find(job.handle.jobName); + if (!row || !row.enabled) { + disarmFire(ctx, job); + continue; + } + if (row.args.tag !== job.handle.jobName) { + disableJob(ctx, job, row, 'cron.invalid_args_state'); + continue; + } + + const pending = fireTable(ctx, job).jobName.find(row.name); + const validPending = + pending?.generation === row.generation && + pending.recovery === undefined && + (row.schedule.tag === 'cron' + ? pending.targetAt !== undefined + : pending.targetAt === undefined); + if (validPending) continue; + + const sequence = row.fireCount + 1n; + const invocation: CronInvocation = { + id: invocationId(row.name, row.generation, sequence), + jobName: row.name, + generation: row.generation, + sequence, + scheduledFor: row.nextRunAt ?? ctx.timestamp, + }; + replaceFire(ctx, job, row); + applyOutcome(ctx, core, job, invocation, 'Failed', 'lost_fire', true); + } + } + + function disableJob( + ctx: TransactionContext, + job: JobMetadata, + row: JobRow, + reason: string + ): JobRow { + disarmFire(ctx, job); + const updated = { + ...row, + enabled: false, + nextRunAt: undefined, + disabledReason: truncateError(reason), + }; + ctx.db.cronJob.name.update(updated); + return updated; + } + + function applyOutcome( + ctx: TransactionContext, + core: InternalCore, + job: JobMetadata, + invocation: CronInvocation, + status: RunStatus, + error: string | undefined, + advanceFireCount: boolean + ): void { + if (ctx.db.cronRun.invocationId.find(invocation.id)) return; + + let row = ctx.db.cronJob.name.find(invocation.jobName); + if (row && row.generation === invocation.generation) { + if (advanceFireCount && invocation.sequence !== row.fireCount + 1n) { + return; + } + const consecutiveFailures = + status === 'Failed' + ? Math.min(row.consecutiveFailures + 1, MAX_FAILURES) + : 0; + row = { + ...row, + fireCount: + invocation.sequence > row.fireCount + ? invocation.sequence + : row.fireCount, + consecutiveFailures, + lastRunAt: ctx.timestamp, + }; + ctx.db.cronJob.name.update(row); + if ( + status === 'Failed' && + row.enabled && + row.maxFailures > 0 && + consecutiveFailures >= row.maxFailures + ) { + disableJob( + ctx, + job, + row, + `failed_${consecutiveFailures}_consecutive_times:${error ?? status}` + ); + } + } + + recordRun(ctx, core, invocation, status, error); + } + + function prepareFire( + ctx: TransactionContext, + job: JobMetadata, + arg: FireRow, + reserveSequence: boolean + ): PreparedFire | undefined { + let row = ctx.db.cronJob.name.find(job.handle.jobName); + if (!row || !row.enabled || row.generation !== arg.generation) return; + if (row.args.tag !== job.handle.jobName) { + disableJob(ctx, job, row, 'cron.invalid_args_state'); + return; + } + + const nowMicros = ctx.timestamp.microsSinceUnixEpoch; + let scheduledFor = ctx.timestamp; + if (row.schedule.tag === 'cron') { + if (!arg.targetAt) { + disableJob(ctx, job, row, 'cron.invalid_trigger:missing_target'); + return; + } + const tableView = fireTable(ctx, job); + const fired = tableView.scheduledId.find(arg.scheduledId); + if (fired) tableView.delete(fired); + + const targetMicros = arg.targetAt.microsSinceUnixEpoch; + if (targetMicros > nowMicros) { + const nextRunAt = insertFire(ctx, job, row, targetMicros); + ctx.db.cronJob.name.update({ ...row, nextRunAt }); + return; + } + + scheduledFor = arg.targetAt; + const nextAt = nextOccurrence(row.schedule, nowMicros); + if (nextAt === undefined) { + row = disableJob(ctx, job, row, 'cron.no_future_occurrence'); + } else { + const nextRunAt = insertFire(ctx, job, row, nextAt); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + } else { + const nextRunAt = new Timestamp( + nowMicros + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + const sequence = row.fireCount + 1n; + if (reserveSequence) { + row = { ...row, fireCount: sequence }; + ctx.db.cronJob.name.update(row); + } + return { + args: row.args.value, + invocation: { + id: invocationId(row.name, row.generation, sequence), + jobName: row.name, + generation: row.generation, + sequence, + scheduledFor, + }, + }; + } + + function invokeHandler( + handler: InternalHandler, + ctx: unknown, + job: JobMetadata, + prepared: PreparedFire + ): unknown { + return job.hasArgs + ? handler(ctx, prepared.args, prepared.invocation) + : handler(ctx, prepared.invocation); + } + + function encodeFireArgument(job: JobMetadata, arg: FireRow): Uint8Array { + const rowType = requireFire(job).rowType as unknown as { + serialize(writer: BinaryWriter, value: FireRow): void; + }; + const writer = new BinaryWriter(256); + // A reducer with one row parameter has the same BSATN field sequence as + // the row itself. The SDK serializer keeps this encoding tied to the + // generated fire-table schema. + rowType.serialize(writer, arg); + return writer.getBuffer(); + } + + function scheduleRecovery( + job: JobMetadata, + arg: FireRow, + invocation: CronInvocation, + error: string + ): void { + const recoveryArg: FireRow = { + ...arg, + recovery: { + sequence: invocation.sequence, + scheduledFor: invocation.scheduledFor, + error, + }, + }; + volatile_nonatomic_schedule_immediate( + job.reducerName, + encodeFireArgument(job, recoveryArg) + ); + } + + function executeReducer( + rawCtx: unknown, + core: InternalCore, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler + ): void { + const ctx = asTransactionContext(rawCtx); + requireDatabaseCaller(ctx); + if (arg.recovery) { + recoverFailure(ctx, core, job, arg); + return; + } + const prepared = prepareFire(ctx, job, arg, false); + if (!prepared) return; + + try { + const result = invokeHandler(handler, rawCtx as Ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + 'cron.async_reducer_handler:reducers must complete synchronously' + ); + } + } catch (error) { + const detail = truncateError(error); + try { + scheduleRecovery(job, arg, prepared.invocation, detail); + } catch { + // Volatile recovery is best effort. Reconciliation repairs a missing + // calendar fire if the host loses this request. + } + throw error; + } + + applyOutcome(ctx, core, job, prepared.invocation, 'Ok', undefined, true); + } + + function executeProcedure( + rawCtx: unknown, + core: InternalCore, + job: JobMetadata, + arg: FireRow, + handler: InternalHandler + ): void { + const ctx = rawCtx as ProcedureContext; + requireDatabaseCaller(ctx); + if (arg.recovery) { + throw new SenderError('cron.invalid_procedure_recovery'); + } + const prepared = ctx.withTx(tx => prepareFire(tx, job, arg, true)); + if (!prepared) return; + + let error: string | undefined; + try { + const result = invokeHandler(handler, rawCtx as Ctx, job, prepared); + if (isThenable(result)) { + throw new Error( + 'cron.async_procedure_handler:procedures must complete synchronously' + ); + } + } catch (caught) { + error = truncateError(caught); + } + + ctx.withTx(tx => { + applyOutcome( + tx, + core, + job, + prepared.invocation, + error === undefined ? 'Ok' : 'Failed', + error, + false + ); + }); + } + + function recoverFailure( + ctx: TransactionContext, + core: InternalCore, + job: JobMetadata, + arg: FireRow + ): void { + const recovery = arg.recovery; + if (!recovery || arg.jobName !== job.handle.jobName) return; + const jobName = job.handle.jobName; + let row = ctx.db.cronJob.name.find(jobName); + if ( + !row || + !row.enabled || + row.generation !== arg.generation || + recovery.sequence !== row.fireCount + 1n + ) { + return; + } + + if (row.schedule.tag === 'cron') { + // Replace the fire unconditionally so stale visible state cannot block + // recovery. + row = replaceFire(ctx, job, row); + } else { + const nextRunAt = new Timestamp( + ctx.timestamp.microsSinceUnixEpoch + + BigInt(row.schedule.value.seconds) * ONE_SECOND_MICROS + ); + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + const invocation: CronInvocation = { + id: invocationId(jobName, arg.generation, recovery.sequence), + jobName, + generation: arg.generation, + sequence: recovery.sequence, + scheduledFor: recovery.scheduledFor, + }; + applyOutcome( + ctx, + core, + job, + invocation, + 'Failed', + truncateError(recovery.error), + true + ); + } + + function registerJob( + job: JobMetadata, + kind: 'reducer' | 'procedure' + ): InternalCore { + const core = requireCore(job.handle); + if (job.registration) { + throw new Error( + `cron.handler_already_registered:${job.handle.jobName}:${job.registration}` + ); + } + job.registration = kind; + return core; + } + + function cronTable< + const Name extends string, + ArgsBuilder extends CronArgsBuilder, + >( + opts: CronTableWithArgsOpts + ): CronJobHandle>; + function cronTable( + opts: CronTableOpts + ): CronJobHandle; + function cronTable( + opts: CronTableOpts | CronTableWithArgsOpts + ): CronJobReference { + const jobName = normalizeJobName(opts.name); + const hasArgs = 'args' in opts; + const argsType = hasArgs + ? (opts.args as unknown as DynamicSdkValue) + : t.unit(); + const handle = { + jobName, + cronReducer(spacetimedb: CronSchema, handler: InternalHandler) { + const job = requireMetadata(handle); + const core = registerJob(job, 'reducer'); + const fire = requireFire(job); + return (spacetimedb as RegistrationSchema).reducer( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + (ctx: unknown, { arg }: { arg: FireRow }) => { + executeReducer(ctx, core, job, arg, handler); + } + ); + }, + cronProcedure(spacetimedb: CronSchema, handler: InternalHandler) { + const job = requireMetadata(handle); + const core = registerJob(job, 'procedure'); + const fire = requireFire(job); + return (spacetimedb as RegistrationSchema).procedure( + { name: job.reducerName, onSchedule: fire }, + { arg: fire.rowType }, + t.unit(), + (ctx: unknown, { arg }: { arg: FireRow }) => { + executeProcedure(ctx, core, job, arg, handler); + return {}; + } + ); + }, + }; + metadata.set(handle, { + handle, + argsType, + hasArgs, + fireTableName: `${jobName}_fire`, + fireAccessor: toCamelCase(`${jobName}_fire`), + reducerName: `${jobName}_cron`, + fire: undefined, + core: undefined, + registration: undefined, + }); + return handle; + } + + function createCron( + jobs: readonly CronJobReference[], + opts?: CreateCronOpts + ): CronCore { + if (coreCreated) throw new Error('cron.multiple_cores_not_supported'); + if (jobs.length === 0) throw new Error('cron.no_jobs'); + coreCreated = true; + const historyCap = normalizeHistoryCap(opts?.historyCap); + const isPublic = opts?.publicTables ?? false; + const reconcileEverySeconds = normalizeReconcileEverySeconds( + opts?.reconcileEverySeconds + ); + + const jobsByName = new Map(); + const argumentTypes: Record = {}; + const usedAccessors = new Set(['cronJob', 'cronRun', 'cronReconcileTick']); + const sortedJobs = [...jobs].sort((left, right) => + left.jobName < right.jobName ? -1 : left.jobName > right.jobName ? 1 : 0 + ); + for (const handle of sortedJobs) { + const job = requireMetadata(handle); + if (jobsByName.has(handle.jobName)) { + throw new Error(`cron.duplicate_job:${handle.jobName}`); + } + if (job.core) { + throw new Error(`cron.job_already_wired:${handle.jobName}`); + } + if (usedAccessors.has(job.fireAccessor)) { + throw new Error(`cron.table_key_collision:${job.fireAccessor}`); + } + usedAccessors.add(job.fireAccessor); + jobsByName.set(handle.jobName, job); + argumentTypes[handle.jobName] = job.argsType; + } + + const cronJobArgsType = t.enum('CronJobArgsValue', argumentTypes); + const cronJob = table( + { name: 'cron_job', public: false }, + { + name: t.string().primaryKey(), + schedule: cronScheduleType, + args: cronJobArgsType, + enabled: t.bool(), + maxFailures: t.u32(), + consecutiveFailures: t.u32(), + fireCount: t.u64(), + generation: t.u64(), + lastRunAt: t.option(t.timestamp()), + nextRunAt: t.option(t.timestamp()), + disabledReason: t.option(t.string()), + } + ); + const cronJobViewRow = t.row('CronJobView', { + name: t.string().primaryKey(), + schedule: cronScheduleType, + enabled: t.bool(), + maxFailures: t.u32(), + consecutiveFailures: t.u32(), + fireCount: t.u64(), + generation: t.u64(), + lastRunAt: t.option(t.timestamp()), + nextRunAt: t.option(t.timestamp()), + disabledReason: t.option(t.string()), + }); + const cronRun = table( + { name: 'cron_run', public: isPublic }, + { + invocationId: t.string().primaryKey(), + jobName: t.string().index(), + generation: t.u64(), + sequence: t.u64(), + scheduledFor: t.timestamp(), + completedAt: t.timestamp(), + status: runStatusType, + error: t.option(t.string()), + } + ); + + const tables: Record = { + cronJob: asTableDefinition(cronJob), + cronRun: asTableDefinition(cronRun), + }; + let reconcileTick: DynamicSdkValue | undefined; + if (reconcileEverySeconds !== undefined) { + reconcileTick = table( + { name: 'cron_reconcile_tick', public: isPublic }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + key: t.string().unique(), + } + ); + tables.cronReconcileTick = asTableDefinition(reconcileTick); + } + for (const job of jobsByName.values()) { + const fire = table( + { name: job.fireTableName, public: isPublic }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + jobName: t.string().unique(), + generation: t.u64(), + targetAt: t.option(t.timestamp()), + recovery: t.option(fireRecoveryType), + } + ); + job.fire = fire; + tables[job.fireAccessor] = asTableDefinition(fire); + } + + const core: InternalCore = { + tables, + jobs: jobsByName, + historyCap, + reconcileEverySeconds, + reconcileTick, + reconcileRegistered: false, + publicViewsRegistered: false, + reconcileReducer(spacetimedb: CronSchema) { + if (core.reconcileRegistered) { + throw new Error('cron.reconcile_reducer_already_registered'); + } + if ( + core.reconcileEverySeconds === undefined || + core.reconcileTick === undefined + ) { + throw new Error( + 'cron.reconcile_not_configured:set createCron({ reconcileEverySeconds })' + ); + } + requireRegisteredHandlers(core); + core.reconcileRegistered = true; + const tick = core.reconcileTick; + return (spacetimedb as RegistrationSchema).reducer( + { name: RECONCILE_REDUCER_NAME, onSchedule: tick }, + { arg: tick.rowType }, + (rawCtx: unknown) => { + const ctx = asTransactionContext(rawCtx); + requireDatabaseCaller(ctx); + reconcileLostFires(ctx, core); + } + ); + }, + publicViews(spacetimedb: CronSchema): CronCorePublicViews { + if (core.publicViewsRegistered) { + throw new Error('cron.public_views_already_registered'); + } + core.publicViewsRegistered = true; + const jobsView = (spacetimedb as RegistrationSchema).anonymousView( + { name: 'cron_jobs', public: true }, + t.array(cronJobViewRow), + (rawCtx: unknown) => { + const ctx = rawCtx as Pick; + return [...ctx.db.cronJob.iter()].map(row => ({ + name: row.name, + schedule: row.schedule, + enabled: row.enabled, + maxFailures: row.maxFailures, + consecutiveFailures: row.consecutiveFailures, + fireCount: row.fireCount, + generation: row.generation, + lastRunAt: row.lastRunAt, + nextRunAt: row.nextRunAt, + disabledReason: publicDisabledReason(row.disabledReason), + })); + } + ); + return { jobs: jobsView }; + }, + }; + for (const job of jobsByName.values()) job.core = core; + return core; + } + + function schedule( + rawCtx: Ctx, + handle: CronJobReference, + spec: ScheduleSpec, + opts?: RuntimeScheduleOpts + ): void { + const ctx = asTransactionContext(rawCtx); + const job = requireMetadata(handle); + const core = requireCore(handle); + requireRegisteredHandlers(core); + let normalized; + let maxFailures: number; + let args: unknown; + try { + normalized = normalizeSchedule( + spec, + opts, + ctx.timestamp.microsSinceUnixEpoch + ); + maxFailures = normalizeMaxFailures(opts?.maxFailures); + args = normalizeJobArgs(handle.jobName, job.hasArgs, opts); + } catch (error) { + throwInputError(error); + } + + ensureReconcileTick(ctx, core); + reconcileLostFires(ctx, core); + + const existing = ctx.db.cronJob.name.find(handle.jobName); + const generation = (existing?.generation ?? 0n) + 1n; + disarmFire(ctx, job); + + let row: JobRow = { + name: handle.jobName, + schedule: normalized.schedule, + args: { tag: handle.jobName, value: args }, + enabled: true, + maxFailures, + consecutiveFailures: 0, + fireCount: existing?.fireCount ?? 0n, + generation, + lastRunAt: existing?.lastRunAt, + nextRunAt: undefined, + disabledReason: undefined, + }; + if (existing) ctx.db.cronJob.name.update(row); + else ctx.db.cronJob.insert(row); + + const nextRunAt = insertFire(ctx, job, row, normalized.firstAt); + if (!nextRunAt) { + throw new SenderError('cron.unsatisfiable_expression'); + } + row = { ...row, nextRunAt }; + ctx.db.cronJob.name.update(row); + } + + function unschedule(rawCtx: Ctx, handle: CronJobReference): void { + const ctx = asTransactionContext(rawCtx); + const job = requireMetadata(handle); + const core = requireCore(handle); + requireRegisteredHandlers(core); + ensureReconcileTick(ctx, core); + reconcileLostFires(ctx, core); + const row = ctx.db.cronJob.name.find(handle.jobName); + if (!row) return; + disarmFire(ctx, job); + ctx.db.cronJob.name.update({ + ...row, + enabled: false, + generation: row.generation + 1n, + consecutiveFailures: 0, + nextRunAt: undefined, + disabledReason: 'disabled_by_operator', + }); + } + + return { cronTable, createCron, schedule, unschedule }; +} diff --git a/spacetime-cron-ts/src/index.ts b/spacetime-cron-ts/src/index.ts new file mode 100644 index 00000000000..2ad33bc32f1 --- /dev/null +++ b/spacetime-cron-ts/src/index.ts @@ -0,0 +1,29 @@ +export { spacetimeCron } from './cron'; +export type { + CreateCronOpts, + CronApi, + CronArgsBuilder, + CronCore, + CronCorePublicViews, + CronInvocation, + CronJobHandle, + CronJobReference, + CronProcedureHandler, + CronReducerHandler, + CronSchedule, + CronSchema, + CronSdk, + CronTableOpts, + CronTableWithArgsOpts, + CronTimestamp, + ScheduleOpts, + ScheduleSpec, +} from './types'; +export { + parseCronExpression, + nextFireAfter, + isValidTimezone, + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + type ParsedCron, +} from './parser'; diff --git a/spacetime-cron-ts/src/parser.ts b/spacetime-cron-ts/src/parser.ts new file mode 100644 index 00000000000..dc2e2f94a67 --- /dev/null +++ b/spacetime-cron-ts/src/parser.ts @@ -0,0 +1,58 @@ +import { CronExpressionParser } from 'cron-parser'; + +// Avoids cron-parser's Math.random fallback (blocked in STDB reducers). +const HASH_SEED = 'spacetimedb-cron-submodule'; +export const MAX_CRON_EXPRESSION_LENGTH = 256; +export const MAX_TIMEZONE_LENGTH = 128; + +export type ParsedCron = { expression: string }; + +export function parseCronExpression(expr: string): ParsedCron { + const expression = expr.trim(); + if (expression.length === 0) throw new Error('cron expression is empty'); + if (expression.length > MAX_CRON_EXPRESSION_LENGTH) { + throw new Error( + `cron expression exceeds ${MAX_CRON_EXPRESSION_LENGTH} characters` + ); + } + CronExpressionParser.parse(expression, { hashSeed: HASH_SEED }); + return { expression }; +} + +// JS Date max range. +const MAX_SAFE_DATE_MS = 8_640_000_000_000_000; + +export function nextFireAfter( + parsed: ParsedCron, + afterMicros: bigint, + timezone: string = 'UTC' +): bigint | undefined { + if (!isValidTimezone(timezone)) return undefined; + const afterMs = Number(afterMicros / 1000n); + if (!Number.isFinite(afterMs) || Math.abs(afterMs) > MAX_SAFE_DATE_MS) { + return undefined; + } + try { + const interval = CronExpressionParser.parse(parsed.expression, { + currentDate: new Date(afterMs), + tz: timezone, + hashSeed: HASH_SEED, + }); + return BigInt(interval.next().getTime()) * 1000n; + } catch { + return undefined; + } +} + +export function isValidTimezone(tz: string): boolean { + if (tz.length === 0 || tz.length > MAX_TIMEZONE_LENGTH || tz !== tz.trim()) { + return false; + } + if (tz === 'UTC') return true; + try { + new Intl.DateTimeFormat('en-US', { timeZone: tz }); + return true; + } catch { + return false; + } +} diff --git a/spacetime-cron-ts/src/schedule.ts b/spacetime-cron-ts/src/schedule.ts new file mode 100644 index 00000000000..c4ba7db575c --- /dev/null +++ b/spacetime-cron-ts/src/schedule.ts @@ -0,0 +1,184 @@ +import { + MAX_CRON_EXPRESSION_LENGTH, + MAX_TIMEZONE_LENGTH, + isValidTimezone, + nextFireAfter, + parseCronExpression, +} from './parser'; +import type { CronSchedule, ScheduleSpec } from './types'; + +export const ONE_SECOND_MICROS = 1_000_000n; +export const MAX_INTERVAL_SECONDS = 31_536_000; +export const MAX_HISTORY_CAP = 1_000; +export const MAX_FAILURES = 4_294_967_295; +export const MAX_ERROR_LENGTH = 1_024; + +// The host limit is roughly 795 days. Annual checkpoints leave ample room for +// execution delay and keep valid sparse schedules, such as February 29, armed. +export const CHECKPOINT_DELAY_MICROS = + 365n * 24n * 60n * 60n * ONE_SECOND_MICROS; + +const JOB_NAME_PATTERN = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/; +const MAX_JOB_NAME_LENGTH = 48; + +export class CronInputError extends Error {} + +export interface NormalizedSchedule { + schedule: CronSchedule; + firstAt: bigint | undefined; +} + +export function normalizeJobName(name: string): string { + const normalized = name.trim(); + if ( + normalized.length === 0 || + normalized.length > MAX_JOB_NAME_LENGTH || + !JOB_NAME_PATTERN.test(normalized) + ) { + throw new CronInputError( + 'cron.invalid_job_name:use 1-48 lowercase snake_case characters' + ); + } + return normalized; +} + +export function normalizeHistoryCap(value: number | undefined): number { + const cap = value ?? 5; + if (!Number.isSafeInteger(cap) || cap < 0 || cap > MAX_HISTORY_CAP) { + throw new CronInputError( + `cron.invalid_history_cap:must be an integer between 0 and ${MAX_HISTORY_CAP}` + ); + } + return cap; +} + +export function normalizeReconcileEverySeconds( + value: number | undefined +): number | undefined { + if (value === undefined) return undefined; + if ( + !Number.isSafeInteger(value) || + value < 1 || + value > MAX_INTERVAL_SECONDS + ) { + throw new CronInputError( + `cron.invalid_reconcile_interval:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + ); + } + return value; +} + +export function normalizeMaxFailures(value: number | undefined): number { + const failures = value ?? 0; + if ( + !Number.isSafeInteger(failures) || + failures < 0 || + failures > MAX_FAILURES + ) { + throw new CronInputError( + `cron.invalid_max_failures:must be an integer between 0 and ${MAX_FAILURES}` + ); + } + return failures; +} + +export function normalizeJobArgs( + jobName: string, + hasArgs: boolean, + opts: { args?: unknown } | undefined +): unknown { + const supplied = Object.prototype.hasOwnProperty.call(opts ?? {}, 'args'); + if (hasArgs && !supplied) { + throw new CronInputError(`cron.missing_args:${jobName}`); + } + if (!hasArgs && supplied) { + throw new CronInputError(`cron.unexpected_args:${jobName}`); + } + return hasArgs ? opts?.args : {}; +} + +export function normalizeSchedule( + spec: ScheduleSpec, + opts: { timezone?: string } | undefined, + nowMicros: bigint +): NormalizedSchedule { + if (typeof spec !== 'string') { + const seconds = spec.everySeconds; + if ( + !Number.isSafeInteger(seconds) || + seconds < 1 || + seconds > MAX_INTERVAL_SECONDS + ) { + throw new CronInputError( + `cron.invalid_interval:seconds must be an integer between 1 and ${MAX_INTERVAL_SECONDS}` + ); + } + return { + schedule: { tag: 'every', value: { seconds } }, + firstAt: nowMicros + BigInt(seconds) * ONE_SECOND_MICROS, + }; + } + + const expression = spec.trim(); + const timezone = (opts?.timezone ?? 'UTC').trim() || 'UTC'; + if (expression.length === 0) { + throw new CronInputError('cron.invalid_expression:empty'); + } + if (expression.length > MAX_CRON_EXPRESSION_LENGTH) { + throw new CronInputError('cron.invalid_expression:too_long'); + } + if (timezone.length > MAX_TIMEZONE_LENGTH) { + throw new CronInputError('cron.invalid_timezone:too_long'); + } + if (!isValidTimezone(timezone)) { + throw new CronInputError(`cron.invalid_timezone:${timezone}`); + } + + let firstAt: bigint | undefined; + try { + firstAt = nextFireAfter( + parseCronExpression(expression), + nowMicros, + timezone + ); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new CronInputError(`cron.invalid_expression:${detail}`); + } + if (firstAt === undefined) { + throw new CronInputError('cron.unsatisfiable_expression'); + } + return { + schedule: { tag: 'cron', value: { expression, timezone } }, + firstAt, + }; +} + +export function nextOccurrence( + schedule: CronSchedule, + afterMicros: bigint +): bigint | undefined { + if (schedule.tag === 'every') { + return afterMicros + BigInt(schedule.value.seconds) * ONE_SECOND_MICROS; + } + return nextFireAfter( + parseCronExpression(schedule.value.expression), + afterMicros, + schedule.value.timezone + ); +} + +export function boundedScheduleTime( + nowMicros: bigint, + targetMicros: bigint +): bigint { + const checkpoint = nowMicros + CHECKPOINT_DELAY_MICROS; + return targetMicros < checkpoint ? targetMicros : checkpoint; +} + +export function truncateError(error: unknown): string { + const message = error instanceof Error ? error.message : String(error); + return message.length <= MAX_ERROR_LENGTH + ? message + : `${message.slice(0, MAX_ERROR_LENGTH - 3)}...`; +} diff --git a/spacetime-cron-ts/src/sys-abi.d.ts b/spacetime-cron-ts/src/sys-abi.d.ts new file mode 100644 index 00000000000..1453a30d467 --- /dev/null +++ b/spacetime-cron-ts/src/sys-abi.d.ts @@ -0,0 +1,10 @@ +// Ambient declaration for the host syscall used by the failure-reporting +// bridge. The SDK keeps this module internal, while the module bundler +// resolves the direct import inside the host. Keep this dependency isolated +// here so it can be replaced without changing the public cron API. +declare module 'spacetime:sys@2.0' { + export function volatile_nonatomic_schedule_immediate( + reducerName: string, + args: Uint8Array + ): void; +} diff --git a/spacetime-cron-ts/src/types.ts b/spacetime-cron-ts/src/types.ts new file mode 100644 index 00000000000..09edb01812e --- /dev/null +++ b/spacetime-cron-ts/src/types.ts @@ -0,0 +1,164 @@ +import type { Timestamp } from 'spacetimedb'; +import type { + Infer, + ModuleExport, + ScheduleAt, + SenderError, + t, + table, + toCamelCase, + VariantsObj, +} from 'spacetimedb/server'; + +export type CronSchedule = + | { tag: 'cron'; value: { expression: string; timezone: string } } + | { tag: 'every'; value: { seconds: number } }; + +/** A cron expression or a fixed interval in seconds. */ +export type ScheduleSpec = string | { everySeconds: number }; + +interface SchedulePolicyOpts { + /** IANA timezone for cron expressions. Defaults to `UTC`. */ + timezone?: string; + /** Consecutive failures before automatic disablement. `0` disables this policy. */ + maxFailures?: number; +} + +/** Schedule policy plus the durable arguments required by an argument-bearing job. */ +export type ScheduleOpts = SchedulePolicyOpts & + ([Args] extends [undefined] ? { args?: never } : { args: Args }); + +/** Any SpacetimeDB type builder accepted as a cron argument payload. */ +export type CronArgsBuilder = VariantsObj[string]; + +export interface CronTableOpts { + /** Stable snake_case job name. */ + name: Name; +} + +export interface CronTableWithArgsOpts< + Name extends string = string, + ArgsBuilder extends CronArgsBuilder = CronArgsBuilder, +> extends CronTableOpts { + /** Typed payload persisted with the schedule and copied into each invocation. */ + args: ArgsBuilder; +} + +export interface CreateCronOpts { + /** Completed run records retained per job. Defaults to `5`. */ + historyCap?: number; + /** Expose trigger and run tables to subscriptions. Defaults to `false`. */ + publicTables?: boolean; + /** + * Optional native interval that repairs enabled jobs with missing triggers. + * Management operations always run the same repair opportunistically. + */ + reconcileEverySeconds?: number; +} + +/** Structural view of the SpacetimeDB timestamp supplied to handlers. */ +export interface CronTimestamp { + readonly microsSinceUnixEpoch: bigint; + toISOString(): string; + toDate(): Date; + toMillis(): bigint; +} + +/** Stable metadata supplied to every cron invocation. */ +export interface CronInvocation { + /** Unique across every generation of every job. */ + readonly id: string; + readonly jobName: string; + readonly generation: bigint; + readonly sequence: bigint; + /** Logical calendar occurrence or interval fire time. */ + readonly scheduledFor: CronTimestamp; +} + +export type CronReducerHandler = [Args] extends [ + undefined, +] + ? (ctx: Ctx, invocation: CronInvocation) => void + : (ctx: Ctx, args: Args, invocation: CronInvocation) => void; + +export type CronProcedureHandler = [Args] extends [ + undefined, +] + ? (ctx: Ctx, invocation: CronInvocation) => void + : (ctx: Ctx, args: Args, invocation: CronInvocation) => void; + +export type CronTableDefinition = ReturnType; +export interface CronSchema { + readonly anonymousView: (...args: never[]) => ModuleExport; + readonly reducer: (...args: never[]) => ModuleExport; + readonly procedure: (...args: never[]) => ModuleExport; +} + +export interface CronJobReference { + readonly jobName: Name; +} + +export interface CronJobHandle + extends CronJobReference { + cronReducer( + spacetimedb: CronSchema, + handler: CronReducerHandler + ): ModuleExport; + cronProcedure( + spacetimedb: CronSchema, + handler: CronProcedureHandler + ): ModuleExport; +} + +export interface CronCorePublicViews { + /** Sanitized job state. Typed application arguments remain private. */ + readonly jobs: ModuleExport; +} + +export interface CronCore { + /** Spread into the consumer's `schema()` call. */ + readonly tables: Record; + /** Register and export the optional lost-trigger reconciliation sweep. */ + reconcileReducer(spacetimedb: CronSchema): ModuleExport; + /** Register the optional public job-state view exactly once. */ + publicViews(spacetimedb: CronSchema): CronCorePublicViews; +} + +export interface CronSdk { + /** Consumer module's `table` value from `spacetimedb/server`. */ + table: typeof table; + /** Consumer module's `t` value from `spacetimedb/server`. */ + t: typeof t; + /** Consumer module's `toCamelCase` value from `spacetimedb/server`. */ + toCamelCase: typeof toCamelCase; + /** Consumer module's `ScheduleAt` value from `spacetimedb`. */ + ScheduleAt: typeof ScheduleAt; + /** Consumer module's `Timestamp` value from `spacetimedb`. */ + Timestamp: typeof Timestamp; + /** Consumer module's `SenderError` value from `spacetimedb/server`. */ + SenderError: typeof SenderError; +} + +export interface CronApi { + cronTable( + opts: CronTableWithArgsOpts + ): CronJobHandle>; + cronTable( + opts: CronTableOpts + ): CronJobHandle; + createCron( + jobs: readonly CronJobReference[], + opts?: CreateCronOpts + ): CronCore; + /** Create or replace a job schedule and arm its first trigger. */ + schedule( + ctx: Ctx, + job: CronJobHandle, + spec: ScheduleSpec, + ...options: [Args] extends [undefined] + ? [opts?: ScheduleOpts] + : [opts: ScheduleOpts>] + ): void; + /** Disable a job and remove its pending trigger. */ + unschedule(ctx: Ctx, job: CronJobReference): void; +} diff --git a/spacetime-cron-ts/tsconfig.json b/spacetime-cron-ts/tsconfig.json new file mode 100644 index 00000000000..b2b4ecdcdda --- /dev/null +++ b/spacetime-cron-ts/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-crypto-ts/.npmrc b/spacetime-crypto-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-crypto-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-crypto-ts/LICENSE.txt b/spacetime-crypto-ts/LICENSE.txt new file mode 100644 index 00000000000..4e61a2122e7 --- /dev/null +++ b/spacetime-crypto-ts/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Clockwork Labs, Inc + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/spacetime-crypto-ts/README.md b/spacetime-crypto-ts/README.md new file mode 100644 index 00000000000..64b2192ef28 --- /dev/null +++ b/spacetime-crypto-ts/README.md @@ -0,0 +1,71 @@ +# @spacetimedb/crypto + +SHA-256, HMAC-SHA256, encoding helpers, constant-time byte comparison, and +webhook-signature verification for SpacetimeDB TypeScript modules. Hashing is +implemented with `@noble/hashes`. + +## Install + +```bash +npm install @spacetimedb/crypto +``` + +For the surrounding SpacetimeDB module workflow, see +[Getting started](https://spacetimedb.com/docs/). + +## Usage + +### Integrate into an application + +This pure helper package supplies hashing, encoding, and signature verification +functions. Import the function needed by the host HTTP handler. Pass the exact +raw request bytes and deterministic module time, then parse the provider payload +after signature verification succeeds. + +Verify a Stripe webhook with the raw body and module time: + +```ts +import { verifyStripeSignature } from '@spacetimedb/crypto'; + +const valid = verifyStripeSignature({ + rawBody, + signatureHeader: request.headers.get('stripe-signature') ?? '', + secret: webhookSecret, + nowSeconds: Number(ctx.timestamp.microsSinceUnixEpoch / 1_000_000n), +}); +``` + +Verify the raw webhook body before parsing it. Store webhook secrets in private +tables and keep them out of public rows and procedure results. + +## API + +- `sha256(data)` and `hmacSha256(key, message)` return `Uint8Array` digests. +- `timingSafeEqual(a, b)` compares every byte in equal-length arrays. +- `hexToBytes`, `bytesToHex`, and `base64ToBytes` convert common encodings. + Base64 accepts canonical padded or unpadded standard encoding and rejects + whitespace, misplaced padding, invalid lengths, and non-canonical pad bits. +- `verifyStripeSignature(options)` verifies Stripe's `v1` signature format. +- `verifySvixSignature(options)` verifies Svix-compatible signatures, including + Resend webhooks. +- `verifyGithubSignature(options)` verifies GitHub's SHA-256 webhook signature. + +Package entrypoints: + +- `@spacetimedb/crypto` exports hashing, encoding, comparison, and vendor + verification helpers. +- `@spacetimedb/crypto/vendors` is the focused webhook-verification + entrypoint. + +## Testing + +```bash +pnpm test +pnpm run lint +``` + +Tests use published vendor vectors and local fixtures; no network is required. + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-crypto-ts/package.json b/spacetime-crypto-ts/package.json new file mode 100644 index 00000000000..e6b20c42870 --- /dev/null +++ b/spacetime-crypto-ts/package.json @@ -0,0 +1,59 @@ +{ + "name": "@spacetimedb/crypto", + "description": "Deterministic hashing, encoding, and webhook-signature helpers for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./vendors": { + "types": "./src/vendors.ts", + "default": "./src/vendors.ts" + } + }, + "files": [ + "src", + "LICENSE.txt", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-crypto-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-crypto-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "cryptography", + "webhooks", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test-vectors.ts" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + }, + "dependencies": { + "@noble/hashes": "^2.2.0" + } +} diff --git a/spacetime-crypto-ts/scripts/test-vectors.ts b/spacetime-crypto-ts/scripts/test-vectors.ts new file mode 100644 index 00000000000..4d38209cd96 --- /dev/null +++ b/spacetime-crypto-ts/scripts/test-vectors.ts @@ -0,0 +1,340 @@ +// Verify the @noble/hashes wrappers and signature helpers against test vectors. +// Run via: pnpm test +// +// Sources: +// SHA-256 vectors: NIST CAVS examples + RFC 6234 §8.5 +// HMAC-SHA256 vectors: RFC 4231 §4 + +import { sha256 } from '../src/sha256.ts'; +import { hmacSha256 } from '../src/hmac.ts'; +import { + bytesToHex, + hexToBytes, + timingSafeEqual, + base64ToBytes, +} from '../src/timing.ts'; +import { + verifyStripeSignature, + verifyGithubSignature, + verifySvixSignature, +} from '../src/vendors.ts'; + +const enc = new TextEncoder(); + +let pass = 0, + fail = 0; + +function assertEq(label: string, got: string, expected: string): void { + if (got === expected) { + process.stdout.write(` OK ${label}\n`); + pass++; + } else { + process.stdout.write( + ` FAIL ${label}\n got: ${got}\n expected: ${expected}\n` + ); + fail++; + } +} + +function assert(label: string, cond: boolean): void { + if (cond) { + process.stdout.write(` OK ${label}\n`); + pass++; + } else { + process.stdout.write(` FAIL ${label}\n`); + fail++; + } +} + +// SHA-256 +process.stdout.write('SHA-256\n'); +assertEq( + 'empty string', + bytesToHex(sha256(enc.encode(''))), + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' +); +assertEq( + '"abc"', + bytesToHex(sha256(enc.encode('abc'))), + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad' +); +assertEq( + 'NIST 448-bit message', + bytesToHex( + sha256( + enc.encode('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq') + ) + ), + '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1' +); +// One million "a" characters exercises message-length packing in the padding. +const millionA = new Uint8Array(1_000_000); +millionA.fill(0x61); +assertEq( + '1,000,000 × "a"', + bytesToHex(sha256(millionA)), + 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0' +); + +// HMAC-SHA256 (RFC 4231 test cases) +process.stdout.write('\nHMAC-SHA256 (RFC 4231)\n'); + +assertEq( + 'TC1: 20 × 0x0b key, "Hi There"', + bytesToHex( + hmacSha256( + hexToBytes('0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b'), + enc.encode('Hi There') + ) + ), + 'b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7' +); + +assertEq( + 'TC2: "Jefe" key, "what do ya want for nothing?"', + bytesToHex( + hmacSha256(enc.encode('Jefe'), enc.encode('what do ya want for nothing?')) + ), + '5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843' +); + +assertEq( + 'TC3: 20 × 0xaa key, 50 × 0xdd data', + bytesToHex( + hmacSha256( + hexToBytes('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'), + hexToBytes('dd'.repeat(50)) + ) + ), + '773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe' +); + +assertEq( + 'TC4: 25-byte key, 50 × 0xcd', + bytesToHex( + hmacSha256( + hexToBytes('0102030405060708090a0b0c0d0e0f10111213141516171819'), + hexToBytes('cd'.repeat(50)) + ) + ), + '82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b' +); + +assertEq( + 'TC6: 131-byte key (forces hash-down), short data', + bytesToHex( + hmacSha256( + hexToBytes('aa'.repeat(131)), + enc.encode('Test Using Larger Than Block-Size Key - Hash Key First') + ) + ), + '60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54' +); + +assertEq( + 'TC7: 131-byte key, long data', + bytesToHex( + hmacSha256( + hexToBytes('aa'.repeat(131)), + enc.encode( + 'This is a test using a larger than block-size key and a larger than block-size data. ' + + 'The key needs to be hashed before being used by the HMAC algorithm.' + ) + ) + ), + '9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2' +); + +// timingSafeEqual +process.stdout.write('\ntimingSafeEqual\n'); +assert( + 'equal returns true', + timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])) +); +assert( + 'differing byte returns false', + !timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 4])) +); +assert( + 'different length returns false', + !timingSafeEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3, 4])) +); +assert( + 'two empty returns true', + timingSafeEqual(new Uint8Array([]), new Uint8Array([])) +); + +// Base64 round-trip +process.stdout.write('\nbase64\n'); +const b64Cases: Array<[string, string]> = [ + ['', ''], + ['f', 'Zg=='], + ['fo', 'Zm8='], + ['foo', 'Zm9v'], + ['foob', 'Zm9vYg=='], + ['fooba', 'Zm9vYmE='], + ['foobar', 'Zm9vYmFy'], +]; +for (const [plain, b64] of b64Cases) { + const decoded = new TextDecoder().decode(base64ToBytes(b64)); + assertEq(`decode("${b64}")`, decoded, plain); +} +assertEq( + 'decode unpadded Zg', + new TextDecoder().decode(base64ToBytes('Zg')), + 'f' +); +for (const malformed of [ + 'A', + '=AAA', + 'A=AA', + 'AA=A', + 'AAAA=', + 'AA===', + 'Zh==', + 'Zm9=', + 'Zg==\n', +]) { + let threw = false; + try { + base64ToBytes(malformed); + } catch { + threw = true; + } + assert(`reject malformed base64 ${JSON.stringify(malformed)}`, threw); +} + +// Stripe signature round-trip +// Construct a header the way Stripe does, then verify it round-trips. +process.stdout.write('\nStripe webhook signature\n'); +const stripeSecret = 'whsec_test_secret_1234567890'; +const stripeBody = '{"id":"evt_test","type":"customer.created"}'; +const stripeTs = '1700000000'; +const stripeMac = hmacSha256( + enc.encode(stripeSecret), + enc.encode(`${stripeTs}.${stripeBody}`) +); +const stripeHeader = `t=${stripeTs},v1=${bytesToHex(stripeMac)}`; +assert( + 'valid signature passes (tolerance bypass)', + verifyStripeSignature({ + rawBody: stripeBody, + signatureHeader: stripeHeader, + secret: stripeSecret, + toleranceSeconds: Infinity, + }) +); +assert( + 'mutated body fails', + !verifyStripeSignature({ + rawBody: stripeBody + 'x', + signatureHeader: stripeHeader, + secret: stripeSecret, + toleranceSeconds: Infinity, + }) +); +assert( + 'wrong secret fails', + !verifyStripeSignature({ + rawBody: stripeBody, + signatureHeader: stripeHeader, + secret: 'whsec_wrong', + toleranceSeconds: Infinity, + }) +); +assert( + 'old timestamp rejected when tolerance enforced', + !verifyStripeSignature({ + rawBody: stripeBody, + signatureHeader: stripeHeader, + secret: stripeSecret, + toleranceSeconds: 300, + nowSeconds: Number(stripeTs) + 1000, + }) +); +assert( + 'multiple v1 entries: any match wins', + verifyStripeSignature({ + rawBody: stripeBody, + signatureHeader: `t=${stripeTs},v1=deadbeef,v1=${bytesToHex(stripeMac)}`, + secret: stripeSecret, + toleranceSeconds: Infinity, + }) +); + +// GitHub signature round-trip +process.stdout.write('\nGitHub webhook signature\n'); +const ghSecret = "It's a Secret to Everybody"; +const ghBody = 'Hello, World!'; +const ghMac = hmacSha256(enc.encode(ghSecret), enc.encode(ghBody)); +assert( + 'roundtrip passes', + verifyGithubSignature({ + rawBody: ghBody, + signatureHeader: `sha256=${bytesToHex(ghMac)}`, + secret: ghSecret, + }) +); +// Known vector from GitHub docs. +assertEq( + 'docs example body→hex', + bytesToHex(hmacSha256(enc.encode(ghSecret), enc.encode(ghBody))), + '757107ea0eb2509fc211221cce984b8a37570b6d7586c22c46f4379c8b043e17' +); + +// Svix (Resend) signature round-trip +process.stdout.write('\nsvix (Resend) signature\n'); +// Construct as svix would. +const svixSecretRaw = new Uint8Array(32); +svixSecretRaw.fill(0x42); +// Helper to base64-encode (mirror of base64ToBytes). +function bytesToBase64(b: Uint8Array): string { + const ALPHABET = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + let s = ''; + for (let i = 0; i < b.length; i += 3) { + const b0 = b[i]; + const b1 = i + 1 < b.length ? b[i + 1] : 0; + const b2 = i + 2 < b.length ? b[i + 2] : 0; + s += ALPHABET[b0 >> 2]; + s += ALPHABET[((b0 & 3) << 4) | (b1 >> 4)]; + s += i + 1 < b.length ? ALPHABET[((b1 & 0xf) << 2) | (b2 >> 6)] : '='; + s += i + 2 < b.length ? ALPHABET[b2 & 0x3f] : '='; + } + return s; +} +const svixSecret = 'whsec_' + bytesToBase64(svixSecretRaw); +const svixId = 'msg_test_123'; +const svixTs = '1700000000'; +const svixBody = '{"event":"email.delivered"}'; +const svixMac = hmacSha256( + svixSecretRaw, + enc.encode(`${svixId}.${svixTs}.${svixBody}`) +); +const svixSig = 'v1,' + bytesToBase64(svixMac); +assert( + 'valid svix signature passes', + verifySvixSignature({ + rawBody: svixBody, + svixId, + svixTimestamp: svixTs, + svixSignature: svixSig, + secret: svixSecret, + toleranceSeconds: Infinity, + }) +); +assert( + 'mutated svix body fails', + !verifySvixSignature({ + rawBody: svixBody + 'x', + svixId, + svixTimestamp: svixTs, + svixSignature: svixSig, + secret: svixSecret, + toleranceSeconds: Infinity, + }) +); + +// Summary +process.stdout.write(`\n${pass} pass, ${fail} fail\n`); +if (fail > 0) process.exit(1); diff --git a/spacetime-crypto-ts/src/hmac.ts b/spacetime-crypto-ts/src/hmac.ts new file mode 100644 index 00000000000..f37d752e0ec --- /dev/null +++ b/spacetime-crypto-ts/src/hmac.ts @@ -0,0 +1,6 @@ +import { hmac } from '@noble/hashes/hmac.js'; +import { sha256 } from '@noble/hashes/sha2.js'; + +export function hmacSha256(key: Uint8Array, message: Uint8Array): Uint8Array { + return hmac(sha256, key, message); +} diff --git a/spacetime-crypto-ts/src/index.ts b/spacetime-crypto-ts/src/index.ts new file mode 100644 index 00000000000..bbd42c96545 --- /dev/null +++ b/spacetime-crypto-ts/src/index.ts @@ -0,0 +1,17 @@ +export { sha256, SHA256_BYTES } from './sha256.ts'; +export { hmacSha256 } from './hmac.ts'; +export { + timingSafeEqual, + hexToBytes, + bytesToHex, + base64ToBytes, +} from './timing.ts'; + +export { + verifyStripeSignature, + verifySvixSignature, + verifyGithubSignature, + type StripeVerifyOpts, + type SvixVerifyOpts, + type GithubVerifyOpts, +} from './vendors.ts'; diff --git a/spacetime-crypto-ts/src/sha256.ts b/spacetime-crypto-ts/src/sha256.ts new file mode 100644 index 00000000000..6c248908d44 --- /dev/null +++ b/spacetime-crypto-ts/src/sha256.ts @@ -0,0 +1,8 @@ +import { sha256 as nobleSha256 } from '@noble/hashes/sha2.js'; + +export function sha256(data: Uint8Array): Uint8Array { + return nobleSha256(data); +} + +export const SHA256_BYTES = 32; +export const SHA256_INTERNAL_BLOCK_SIZE = 64; diff --git a/spacetime-crypto-ts/src/timing.ts b/spacetime-crypto-ts/src/timing.ts new file mode 100644 index 00000000000..bbc530fa7fd --- /dev/null +++ b/spacetime-crypto-ts/src/timing.ts @@ -0,0 +1,85 @@ +/** + * Compare two byte arrays in time independent of their content. Returns true + * iff both have the same length AND identical bytes. + * + * IMPORTANT: this is only constant-time when arrays are equal length. The + * length check is up front and leaks length info, which is fine for fixed-size + * tags (HMAC outputs, JWT signatures). For variable-length comparisons you'd + * need to also pad to a max length. + * + * Note: the JIT can sometimes shortcut bitwise OR chains. The accumulator + * pattern below is the standard timing-safe construction; it's about as + * practical in pure JS without going to WASM. + */ +export function timingSafeEqual(a: Uint8Array, b: Uint8Array): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) { + diff |= a[i] ^ b[i]; + } + return diff === 0; +} + +export { hexToBytes, bytesToHex } from '@noble/hashes/utils.js'; + +/** Decode standard base64 (with or without padding). Throws on invalid input. */ +export function base64ToBytes(b64: string): Uint8Array { + if (/\s/.test(b64)) throw new Error('base64: whitespace is not allowed'); + if (b64.length % 4 === 1) throw new Error('base64: invalid length'); + const firstPad = b64.indexOf('='); + if (firstPad >= 0) { + const padding = b64.length - firstPad; + if ( + padding > 2 || + b64.length % 4 !== 0 || + !/^=+$/.test(b64.slice(firstPad)) + ) { + throw new Error('base64: invalid padding'); + } + } + + let s = b64; + while (s.length % 4 !== 0) s += '='; + const ALPHABET = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + const lookup = new Int8Array(256).fill(-1); + for (let i = 0; i < ALPHABET.length; i++) lookup[ALPHABET.charCodeAt(i)] = i; + lookup[0x3d /* '=' */] = 0; // Padding is removed after decoding. + + // Count pad to compute output length. + let pad = 0; + if (s.endsWith('==')) pad = 2; + else if (s.endsWith('=')) pad = 1; + + const out = new Uint8Array((s.length / 4) * 3 - pad); + let oi = 0; + for (let i = 0; i < s.length; i += 4) { + const c0 = lookup[s.charCodeAt(i)]; + const c1 = lookup[s.charCodeAt(i + 1)]; + const c2 = lookup[s.charCodeAt(i + 2)]; + const c3 = lookup[s.charCodeAt(i + 3)]; + if (c0 < 0 || c1 < 0 || c2 < 0 || c3 < 0) { + throw new Error('base64: invalid char'); + } + const finalQuartet = i + 4 === s.length; + if ( + s[i] === '=' || + s[i + 1] === '=' || + (!finalQuartet && (s[i + 2] === '=' || s[i + 3] === '=')) + ) { + throw new Error('base64: invalid padding'); + } + if (s[i + 2] === '=' && s[i + 3] !== '=') + throw new Error('base64: invalid padding'); + if (s[i + 2] === '=' && (c1 & 0x0f) !== 0) + throw new Error('base64: non-canonical padding'); + if (s[i + 3] === '=' && s[i + 2] !== '=' && (c2 & 0x03) !== 0) { + throw new Error('base64: non-canonical padding'); + } + const v = (c0 << 18) | (c1 << 12) | (c2 << 6) | c3; + if (oi < out.length) out[oi++] = (v >> 16) & 0xff; + if (oi < out.length) out[oi++] = (v >> 8) & 0xff; + if (oi < out.length) out[oi++] = v & 0xff; + } + return out; +} diff --git a/spacetime-crypto-ts/src/vendors.ts b/spacetime-crypto-ts/src/vendors.ts new file mode 100644 index 00000000000..f1299f88fbe --- /dev/null +++ b/spacetime-crypto-ts/src/vendors.ts @@ -0,0 +1,160 @@ +// Reference docs: +// Stripe: https://docs.stripe.com/webhooks/signatures +// Resend (svix): https://docs.svix.com/receiving/verifying-payloads/how-manual +// GitHub: https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries + +import { hmacSha256 } from './hmac.ts'; +import { timingSafeEqual, hexToBytes, base64ToBytes } from './timing.ts'; + +const enc = new TextEncoder(); + +// Stripe + +export interface StripeVerifyOpts { + /** The raw request body, exactly as received (do NOT re-stringify JSON). */ + rawBody: string; + /** Value of the `stripe-signature` request header. */ + signatureHeader: string; + /** The webhook signing secret, e.g. `whsec_...`. */ + secret: string; + /** + * Maximum age of the signed timestamp, in seconds. Stripe recommends 300 + * (5 minutes) to protect against replay. Pass `Infinity` to skip the check + * (only for tests). + */ + toleranceSeconds?: number; + /** Current Unix time in seconds. Defaults to `Date.now()/1000` but the + * STDB module runtime should pass `ctx.timestamp` converted to seconds. */ + nowSeconds?: number; +} + +/** + * Verify a Stripe webhook signature. Returns true iff the signature header + * contains at least one valid v1 signature AND the timestamp is within + * tolerance. + */ +export function verifyStripeSignature(opts: StripeVerifyOpts): boolean { + const tolerance = opts.toleranceSeconds ?? 300; + const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000); + + // Parse "t=1709836800,v1=abcdef,v1=12345..." into a map. + // Multiple v1 entries are possible after key rotation; any match wins. + const fields: Record = {}; + for (const part of opts.signatureHeader.split(',')) { + const eq = part.indexOf('='); + if (eq < 0) continue; + const k = part.slice(0, eq).trim(); + const v = part.slice(eq + 1).trim(); + (fields[k] ??= []).push(v); + } + + const tStr = fields.t?.[0]; + const v1List = fields.v1; + if (!tStr || !v1List || v1List.length === 0) return false; + + const t = Number.parseInt(tStr, 10); + if (!Number.isFinite(t)) return false; + if (tolerance !== Infinity && Math.abs(now - t) > tolerance) return false; + + const signed = enc.encode(`${tStr}.${opts.rawBody}`); + const expected = hmacSha256(enc.encode(opts.secret), signed); + + for (const v1Hex of v1List) { + let candidate: Uint8Array; + try { + candidate = hexToBytes(v1Hex); + } catch { + continue; + } + if (timingSafeEqual(expected, candidate)) return true; + } + return false; +} + +// Resend webhooks use Svix signatures. + +export interface SvixVerifyOpts { + rawBody: string; + /** `svix-id` header. */ + svixId: string; + /** `svix-timestamp` header (Unix seconds as string). */ + svixTimestamp: string; + /** `svix-signature` header, space-separated list like `v1,base64sig`. */ + svixSignature: string; + /** Endpoint secret, in the form `whsec_`. */ + secret: string; + toleranceSeconds?: number; + nowSeconds?: number; +} + +/** + * Verify a svix-style webhook signature (Resend, Clerk, FormBricks, …). + */ +export function verifySvixSignature(opts: SvixVerifyOpts): boolean { + const tolerance = opts.toleranceSeconds ?? 5 * 60; + const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000); + + const ts = Number.parseInt(opts.svixTimestamp, 10); + if (!Number.isFinite(ts)) return false; + if (tolerance !== Infinity && Math.abs(now - ts) > tolerance) return false; + + // Strip the `whsec_` prefix, base64-decode the rest. + const secretBody = opts.secret.startsWith('whsec_') + ? opts.secret.slice('whsec_'.length) + : opts.secret; + let secretBytes: Uint8Array; + try { + secretBytes = base64ToBytes(secretBody); + } catch { + return false; + } + + const signed = enc.encode( + `${opts.svixId}.${opts.svixTimestamp}.${opts.rawBody}` + ); + const expected = hmacSha256(secretBytes, signed); + + // Header is `v1, v1, ...`. Any match wins. + for (const part of opts.svixSignature.split(' ')) { + const comma = part.indexOf(','); + if (comma < 0) continue; + const version = part.slice(0, comma); + if (version !== 'v1') continue; + const sigB64 = part.slice(comma + 1); + let candidate: Uint8Array; + try { + candidate = base64ToBytes(sigB64); + } catch { + continue; + } + if (timingSafeEqual(expected, candidate)) return true; + } + return false; +} + +// GitHub + +export interface GithubVerifyOpts { + rawBody: string; + /** `x-hub-signature-256` header, of form `sha256=`. */ + signatureHeader: string; + /** Webhook secret as configured in the GitHub repo/org webhook settings. */ + secret: string; +} + +/** Verify a GitHub webhook signature (HMAC-SHA256 of body, hex-encoded). */ +export function verifyGithubSignature(opts: GithubVerifyOpts): boolean { + const prefix = 'sha256='; + if (!opts.signatureHeader.startsWith(prefix)) return false; + let candidate: Uint8Array; + try { + candidate = hexToBytes(opts.signatureHeader.slice(prefix.length)); + } catch { + return false; + } + const expected = hmacSha256( + enc.encode(opts.secret), + enc.encode(opts.rawBody) + ); + return timingSafeEqual(expected, candidate); +} diff --git a/spacetime-crypto-ts/tsconfig.json b/spacetime-crypto-ts/tsconfig.json new file mode 100644 index 00000000000..e6a8236bbab --- /dev/null +++ b/spacetime-crypto-ts/tsconfig.json @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "allowImportingTsExtensions": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"] +} diff --git a/spacetime-rate-limit-ts/.npmrc b/spacetime-rate-limit-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/LICENSE.txt b/spacetime-rate-limit-ts/LICENSE.txt new file mode 100644 index 00000000000..4e61a2122e7 --- /dev/null +++ b/spacetime-rate-limit-ts/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Clockwork Labs, Inc + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/spacetime-rate-limit-ts/README.md b/spacetime-rate-limit-ts/README.md new file mode 100644 index 00000000000..17bbd500788 --- /dev/null +++ b/spacetime-rate-limit-ts/README.md @@ -0,0 +1,152 @@ +# @spacetimedb/rate-limit + +Fixed-window rate limiter submodule for SpacetimeDB TypeScript modules. + +## Install + +```bash +npm install @spacetimedb/rate-limit spacetimedb +``` + +Requires SpacetimeDB 2.8.3 or later for submodule mounting. + +For the install-to-publish workflow, see +[Getting started](https://spacetimedb.com/docs/). + +This package gives you: + +- a `./submodule` namespace with submodule-owned bucket/config/admin tables +- standalone helper functions for direct host integration +- bounded sweep helpers for expired buckets +- admin-gated procedures for diagnostics and maintenance + +## Usage + +### Integrate into an application + +Register the namespace, install its scheduled cleanup and admin state, then call +`consume` from the host operation before performing the protected action: + +```ts +import { schema, SenderError, t, table } from 'spacetimedb/server'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; + +const post = table( + { name: 'post', public: true }, + { + id: t.u64().primaryKey().autoInc(), + author: t.identity(), + body: t.string(), + createdAt: t.timestamp(), + } +); + +const spacetimedb = schema({ + rateLimit, + post, +}); + +export const init = spacetimedb.init(ctx => { + rateLimit.installRateLimit(ctx.as.rateLimit); +}); + +export default spacetimedb; +``` + +Host procedures should call the standalone policy helper inside the same +transaction as the protected write. Derive the actor key from trusted request +or session state: + +```ts +export const create_post = spacetimedb.procedure( + { body: t.string() }, + t.unit(), + (ctx, args) => { + ctx.withTx(tx => { + const scope = 'post.create'; + const actor = ctx.sender.toHexString(); + const result = rateLimit.consumeRateLimit(tx.as.rateLimit, { + key: rateLimit.buildRateLimitKey(scope, actor), + scope, + limit: 10, + windowSeconds: 60, + }); + if (!result.allowed) throw new SenderError('rate_limit.blocked'); + const body = args.body.trim(); + if (!body) throw new SenderError('post.empty'); + tx.db.post.insert({ + id: 0n, + author: ctx.sender, + body, + createdAt: ctx.timestamp, + }); + }); + return {}; + } +); +``` + +The generated client calls the product-facing operation: + +```ts +await conn.procedures.createPost({ body: 'Hello' }); +``` + +The submodule owns these tables under its namespace: + +- `rateLimit.rate_limit_bucket` +- `rateLimit.rate_limit_admin_identity` +- `rateLimit.rate_limit_config` +- `rateLimit.rate_limit_sweep_tick` + +It also exposes the public admin view `rateLimit.admin_rate_limit_buckets`. +The view returns at most 1,000 rows and returns an empty set to non-admins. + +## API + +The root package exports lower-level helpers for custom standalone +implementations: + +- `consumeRateLimit` +- `buildRateLimitKey` +- `installRateLimitState` +- `runRateLimitSweep` +- `sweepRateLimits` +- `resolveRateLimitSweepBatch` + +The submodule `consume`, `runSweep`, and `reset_buckets` operations are admin-only. +Application-facing operations should enforce a fixed policy in host code and use +`consumeRateLimit` as shown above. `reset_buckets({ maxRows })` removes +1,000 rows by default and accepts a maximum of 10,000 per call, so destructive +maintenance remains bounded. + +Those helpers expect the same submodule table shape. Namespace-aware modules +use `@spacetimedb/rate-limit/submodule`. + +Package entrypoints: + +- `@spacetimedb/rate-limit/submodule` supplies the submodule namespace, + maintenance operations, and host helpers. +- `@spacetimedb/rate-limit/limit` exports standalone policy functions. +- `@spacetimedb/rate-limit` re-exports the supported helper surface. + +See the +[Powerhouse host module](./example/spacetimedb/) +for per-action policies, caller-visible status, and admin controls. + +## Exported defaults + +- `DEFAULT_SWEEP_BATCH = 500` +- `MAX_SWEEP_BATCH = 10_000` +- `DEFAULT_SWEEP_INTERVAL_SECONDS = 30n` + +## Testing + +```bash +pnpm test +pnpm run typecheck +``` + +## License + +[Apache-2.0](./LICENSE.txt). diff --git a/spacetime-rate-limit-ts/example/.env.example b/spacetime-rate-limit-ts/example/.env.example new file mode 100644 index 00000000000..e911ba7a27d --- /dev/null +++ b/spacetime-rate-limit-ts/example/.env.example @@ -0,0 +1,4 @@ +HOST=127.0.0.1 +PORT=8792 +STDB_URI=ws://127.0.0.1:3000 +SPACETIMEDB_DB_NAME=spacetime-rate-limit-example diff --git a/spacetime-rate-limit-ts/example/.npmrc b/spacetime-rate-limit-ts/example/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/example/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/example/README.md b/spacetime-rate-limit-ts/example/README.md new file mode 100644 index 00000000000..7f06ad0eb22 --- /dev/null +++ b/spacetime-rate-limit-ts/example/README.md @@ -0,0 +1,176 @@ +# Powerhouse rate-limit example + +Powerhouse is an arcade-style reactor game built with +[`@spacetimedb/rate-limit`](../). The browser requests actions; SpacetimeDB +owns energy, heat, upgrades, events, and the fixed-window limiter buckets registered +under the `rateLimit` namespace. + +## What this demonstrates + +- Mounting the Rate Limit submodule in an application module. +- Deriving server-owned actor keys and fixed gameplay scopes. +- Enforcing limits from procedures with typed allow/deny results. +- Using independent buckets for taps, overcharge, upgrades, and repair. +- Showing caller-specific cooldown status through scoped views. +- Bounded scheduled cleanup and administrator-only maintenance controls. + +## Prerequisites + +- Node.js 20 or later and pnpm 10. +- A SpacetimeDB CLI and server built from this checkout, with the CLI available as `spacetime`. +- A local SpacetimeDB server registered as `local`. +- A logged-in CLI identity for publishing and optional admin grants. + +This example uses the workspace SDK. Keep the matching local server running in +a separate terminal: + +```powershell +spacetime start +``` + +```powershell +spacetime server ping local +spacetime login show +``` + +## Quick start + +From `spacetime-rate-limit-ts/example`: + +```powershell +pnpm install +pnpm --dir spacetimedb install +node -e "require('node:fs').copyFileSync('.env.example', '.env')" +pnpm run build:module:fresh +pnpm run dev +``` + +Open , start the reactor, and tap rapidly enough to fill +the tap bucket and heat meter. + +`build:module:fresh` deletes and recreates only the local +`spacetime-rate-limit-example` database. Use `pnpm run build:module` to preserve current +players, upgrades, and limiter state. + +## Use in your project + +This workspace tests the submodule source in this repository. Consumer +applications install the published release: + +```bash +npm install @spacetimedb/rate-limit spacetimedb +``` + +Follow the package's +[integration guide](../README.md#integrate-into-an-application). Copy the +per-action policy and caller-status patterns; the reactor game, upgrades, and +heat model are application code. + +## Configuration + +| Variable | Default | Purpose | +| --------------------- | ------------------------------ | ------------------------------------ | +| `HOST` | `127.0.0.1` | Development web-server bind address. | +| `PORT` | `8792` | Development web-server port. | +| `STDB_URI` | `ws://127.0.0.1:3000` | Browser WebSocket endpoint. | +| `SPACETIMEDB_DB_NAME` | `spacetime-rate-limit-example` | Published database name. | + +The Node process serves static files, `GET /api/health`, and browser-safe +`GET /api/config`. Gameplay calls go directly from the browser to SpacetimeDB. + +## Limiting model + +Each protected action calls +`rateLimit.consumeRateLimit(ctx.as.rateLimit, ...)` with a server-selected scope, +an actor key derived from `ctx.sender`, a limit, a window, and an optional cost. +The returned result includes remaining capacity, reset time, and retry delay. +The submodule `consume` procedure is reserved for administrators; normal gameplay +uses the lower-level helper inside the host procedure's transaction. + +The submodule implements fixed-window limiting. Application heat and cooldown +mechanics are separate game rules layered over the rate limit, so a request may +be rejected by either system. + +The primary UI subscribes to application-owned views such as `reactor_state`, +`reactor_limit_status`, and `reactor_shop`. Raw bucket and limiter event data is +reserved for administrators. + +## Gameplay + +- Reactor taps generate energy while consuming the `reactor.tap` limit. +- Heat cools according to server time; an overheated reactor rejects more taps + until it recovers. +- Overcharge, repair, and shop installation use separate scopes and windows. +- Installed upgrades change server-owned capabilities and expose matching buttons. +- Recent events explain successful and rejected actions. + +The browser interpolates timers for presentation, but procedure responses and +subscribed server timestamps are authoritative. + +## Administration + +A fresh publish seeds the publisher as the initial Rate Limit submodule +administrator. The debug drawer remains empty and maintenance calls fail for an +ordinary browser identity. To exercise those controls locally, grant the browser +identity from the logged-in owner identity: + +```powershell +spacetime call --server local spacetime-rate-limit-example rateLimit.add_rate_limit_admin 0x +``` + +Admin resets and sweeps are bounded. Do not turn an unbounded delete into an +operator convenience endpoint. + +## Security and deployment boundaries + +- Actor keys are derived from trusted module context, not accepted from the + browser. A client-selected actor key would allow trivial limit evasion. +- A limit must guard the authoritative operation in the same server-side flow; + disabling a browser button is only presentation. +- Combine rate limiting with authentication, authorization, quotas, billing + controls, and network-level defenses. +- Stored browser tokens are development credentials and must not be logged or + committed. +- The admin event view returns at most 1,000 raw limiter events. +- The included Express process is a local static server. Production needs TLS, + explicit binding, origin policy, and supervision. + +## Build and verification + +```powershell +pnpm --dir spacetimedb run build +pnpm run build +pnpm exec tsc -p tsconfig.json +``` + +For a release smoke test: + +1. Confirm normal taps consume capacity and expose decreasing remaining counts. +2. Exceed each action limit and verify the denied operation makes no game-state + change. +3. Wait through a reset boundary and confirm the next action is accepted. +4. Verify two browser identities have independent player and bucket state. +5. Confirm a non-admin cannot view raw events, reset demo state, change config, or + trigger privileged maintenance. +6. Grant an admin identity and verify bounded sweep/reset behavior. + +## Troubleshooting + +- **Actions fail immediately:** inspect both limiter status and reactor heat; they + are independent rejection paths. +- **Debug data is empty:** grant the connected browser identity Rate Limit submodule + administrator access. +- **State is stale:** confirm `STDB_URI` targets the database published by + the `local` server registration. +- **An identity fails after reset:** reload once so the client can replace a + rejected development token. + +## Important files + +- `spacetimedb/src/index.ts` - submodule registration, reactor rules, scoped views, and + bounded maintenance operations. +- `src/app.ts` - connection, procedures, subscriptions, and UI bridge. +- `server.ts` - static development server and browser-safe configuration. +- `public/index.html` - Powerhouse interface. +- `public/ui.js` - reactor rendering and interaction handling. +- `public/styles.css` - Powerhouse presentation. diff --git a/spacetime-rate-limit-ts/example/package.json b/spacetime-rate-limit-ts/example/package.json new file mode 100644 index 00000000000..d9fd9da62b8 --- /dev/null +++ b/spacetime-rate-limit-ts/example/package.json @@ -0,0 +1,29 @@ +{ + "name": "spacetime-rate-limit-example", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "spacetime:generate": "spacetime generate --lang typescript --out-dir src/module_bindings/app --module-path ./spacetimedb -y", + "build:module": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local && pnpm run spacetime:generate && pnpm run build:app", + "build:module:fresh": "pnpm --dir spacetimedb run build && pnpm --dir spacetimedb run publish:local:reset && pnpm run spacetime:generate && pnpm run build:app", + "check": "tsc --noEmit", + "test": "tsx scripts/test-reactor-rules.ts", + "build:app": "pnpm run check && esbuild src/app.ts --bundle --format=esm --outfile=public/app.js --target=es2022 --sourcemap", + "build": "pnpm run spacetime:generate && pnpm run build:app", + "dev": "pnpm run build && tsx server.ts" + }, + "dependencies": { + "@spacetimedb/submodule-shared": "workspace:*", + "dotenv": "^16.4.7", + "express": "^4.21.2", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/express": "^4.17.21", + "@types/node": "^22.10.2", + "esbuild": "^0.28.0", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/example/public/index.html b/spacetime-rate-limit-ts/example/public/index.html new file mode 100644 index 00000000000..17da917c786 --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/index.html @@ -0,0 +1,174 @@ + + + + + + + + + Powerhouse + + + +
+
+
+ SpacetimeDB +
+

Powerhouse

+ Tap the core for energy, buy upgrades, and outproduce the crew. + Don't let it overheat. +
+
+
+ +
+
+
+ + + + 0 +
+ +
+ +
+
+
+ +
+
+
+ Core Heat + 0% · + stable +
+
+
+
+
+ Tap Charges + 8 / 8 · 6s window +
+
+
+
+
+ + +
+ +
+ Built on + SpacetimeDB +
+
+ + + + + diff --git a/spacetime-rate-limit-ts/example/public/styles.css b/spacetime-rate-limit-ts/example/public/styles.css new file mode 100644 index 00000000000..778fdee22cb --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/styles.css @@ -0,0 +1,1310 @@ +:root { + color-scheme: dark; + --demo-panel-height: auto; + --bg: #061013; + --panel: #0b181d; + --panel-2: #0e2028; + --line: #173846; + --line-strong: #24586d; + --text: #f1f7fb; + --muted: #8da8b8; + --accent: #22c7b8; + --accent-2: #ffce5c; + --danger: #ff6a66; + --ok: #52df8f; + --button: #b9c5d4; + font-family: + Inter, + ui-sans-serif, + system-ui, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + sans-serif; +} + +* { + box-sizing: border-box; +} + +html, +body { + min-height: 100%; +} + +body { + margin: 0; + min-height: 100dvh; + background: + radial-gradient( + circle at 55% 20%, + rgba(34, 199, 184, 0.09), + transparent 32rem + ), + radial-gradient( + circle at 20% 88%, + rgba(255, 206, 92, 0.07), + transparent 30rem + ), + var(--bg); + color: var(--text); +} + +button, +input { + font: inherit; +} + +button { + border: 1px solid var(--line-strong); + background: #0b1c23; + color: var(--text); + border-radius: 8px; + min-height: 38px; + padding: 0 14px; + font-weight: 800; + cursor: pointer; +} + +button.primary { + background: var(--button); + border-color: var(--button); + color: #020609; +} + +button:disabled { + cursor: not-allowed; + opacity: 0.5; +} + +.shell { + width: min(1180px, calc(100vw - 32px)); + margin: 0 auto; + padding: 16px 0 18px; + display: grid; + grid-template-rows: auto auto auto; + gap: 14px; + align-content: start; +} + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 12px 14px; + border: 1px solid var(--line); + border-radius: 8px; + background: rgba(11, 24, 29, 0.92); + box-shadow: 0 18px 55px rgba(0, 0, 0, 0.24); +} + +.app-title { + display: flex; + align-items: center; + gap: 10px; + font-weight: 900; +} + +.app-title h1 { + margin: 0; + font-size: 18px; + line-height: 1.1; +} + +.app-title-text { + display: flex; + flex-direction: column; + gap: 3px; + min-width: 0; +} + +.app-sub { + color: var(--muted); + font-weight: 600; + font-size: 12px; + line-height: 1.3; +} + +.app-mark { + height: 24px; + width: auto; + display: block; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + font-weight: 800; +} + +.brand img { + width: 28px; + height: 28px; +} + +.page-foot { + display: flex; + align-items: center; + justify-content: center; + gap: 11px; + margin-top: 0; + padding-top: 12px; + border-top: 1px solid rgba(23, 56, 70, 0.4); +} + +.page-foot .by { + color: #7e9cad; + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.page-foot img { + height: 28px; + width: auto; + opacity: 0.9; +} + +.layout { + display: grid; + grid-template-columns: minmax(420px, 0.95fr) minmax(360px, 1fr); + gap: 14px; + min-height: 0; + margin-top: 0; + align-items: start; +} + +.panel { + border: 1px solid var(--line); + border-radius: 8px; + background: rgba(11, 24, 29, 0.94); +} + +.arena { + height: 640px; + min-height: 0; + padding: 16px; + display: grid; + grid-template-rows: auto minmax(360px, 1fr) auto; + gap: 12px; +} + +.energy-banner { + border: 1px solid rgba(34, 199, 184, 0.26); + border-radius: 8px; + padding: 10px 14px; + background: + linear-gradient(135deg, rgba(34, 199, 184, 0.11), rgba(255, 206, 92, 0.05)), + #08141a; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + align-items: center; + gap: 16px; + animation: reactor-hum 3.4s ease-in-out infinite; +} + +@keyframes reactor-hum { + 0%, + 100% { + box-shadow: 0 0 0 0 rgba(34, 199, 184, 0); + } + 50% { + box-shadow: 0 0 20px 0 rgba(34, 199, 184, 0.1); + } +} + +.energy-banner.gain strong { + animation: energy-pop 0.34s ease; +} + +@keyframes energy-pop { + 0% { + transform: scale(1); + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); + } + 35% { + transform: scale(1.045); + text-shadow: 0 0 16px rgba(255, 206, 92, 0.34); + } + 100% { + transform: scale(1); + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); + } +} + +.energy-banner.gain .energy-icon { + animation: bolt-flicker 0.34s ease; +} + +@keyframes bolt-flicker { + 0% { + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); + } + 35% { + filter: drop-shadow(0 0 15px rgba(255, 206, 92, 0.45)) brightness(1.18); + } + 100% { + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); + } +} + +.energy-icon { + width: 40px; + height: 40px; + color: var(--accent-2); + filter: drop-shadow(0 0 12px rgba(255, 206, 92, 0.28)); +} + +.energy-icon .icon-bolt { + fill: currentColor; +} + +.color-dot { + width: 22px; + height: 22px; + min-height: 0; + padding: 0; + border-radius: 999px; + border: 2px solid rgba(241, 247, 251, 0.72); + background: var(--player-color, var(--accent)); + box-shadow: + 0 0 0 3px rgba(6, 16, 19, 0.95), + 0 0 18px var(--player-color, var(--accent)); +} + +.color-palette { + position: absolute; + left: 0; + top: calc(100% + 8px); + z-index: 5; + display: none; + grid-template-columns: repeat(4, 22px); + gap: 8px; + padding: 9px; + border: 1px solid var(--line); + border-radius: 8px; + background: #071318; + box-shadow: 0 18px 42px rgba(0, 0, 0, 0.34); +} + +.color-palette.open { + display: grid; +} + +.color-swatch { + width: 22px; + height: 22px; + min-height: 0; + padding: 0; + border-radius: 999px; + border: 1px solid rgba(241, 247, 251, 0.28); + background: var(--swatch); +} + +.energy-banner strong { + display: block; + font-size: clamp(28px, 4vw, 42px); + line-height: 0.95; + letter-spacing: 0; + text-align: right; + transform-origin: right center; + text-shadow: 0 0 15px rgba(255, 206, 92, 0.14); +} + +.reactor-wrap { + position: relative; + display: grid; + place-items: center; + text-align: center; + min-height: 0; + padding: 0; + isolation: isolate; +} + +.reactor-wrap::before, +.reactor-wrap::after { + content: ''; + position: absolute; + border-radius: 999px; + pointer-events: none; + transition: + opacity 220ms ease, + transform 220ms ease, + border-color 220ms ease, + box-shadow 220ms ease; + z-index: 0; +} + +.reactor-wrap::before { + width: min(400px, 72%); + aspect-ratio: 1; + background: radial-gradient( + circle, + rgba(34, 199, 184, 0.18), + rgba(34, 199, 184, 0.06) 38%, + transparent 68% + ); + filter: blur(22px); + opacity: 0.58; + transform: scale(0.94); +} + +.reactor-wrap::after { + width: min(330px, 60%); + aspect-ratio: 1; + border: 1px solid rgba(34, 199, 184, 0.28); + box-shadow: + 0 0 38px rgba(34, 199, 184, 0.12), + inset 0 0 46px rgba(34, 199, 184, 0.08); + opacity: 0.72; +} + +.reactor-wrap.warm::before { + background: radial-gradient( + circle, + rgba(255, 206, 92, 0.2), + rgba(34, 199, 184, 0.08) 38%, + transparent 70% + ); + opacity: 0.72; + transform: scale(1); +} + +.reactor-wrap.warm::after { + border-color: rgba(255, 206, 92, 0.32); + box-shadow: + 0 0 44px rgba(255, 206, 92, 0.16), + inset 0 0 48px rgba(34, 199, 184, 0.08); +} + +.reactor-wrap.critical::before { + background: radial-gradient( + circle, + rgba(255, 106, 102, 0.24), + rgba(255, 206, 92, 0.12) 36%, + transparent 70% + ); + opacity: 0.86; + transform: scale(1.06); +} + +.reactor-wrap.critical::after { + border-color: rgba(255, 106, 102, 0.42); + box-shadow: + 0 0 54px rgba(255, 106, 102, 0.22), + inset 0 0 54px rgba(255, 106, 102, 0.08); +} + +.pop-layer { + position: absolute; + inset: 0; + pointer-events: none; + overflow: visible; + z-index: 3; +} + +.energy-pop { + position: absolute; + left: 50%; + top: 36%; + color: var(--pop-color, var(--accent-2)); + font-weight: 900; + font-size: 24px; + line-height: 1; + padding: 6px 11px; + border: 1px solid + color-mix(in srgb, var(--pop-color, var(--accent-2)) 58%, white 6%); + border-radius: 999px; + background: rgba(4, 13, 17, 0.76); + box-shadow: + 0 0 0 3px rgba(4, 13, 17, 0.56), + 0 0 28px + color-mix(in srgb, var(--pop-color, var(--accent-2)) 58%, transparent); + text-shadow: 0 2px 16px + color-mix(in srgb, var(--pop-color, var(--accent-2)) 65%, transparent); + transform: translate(-50%, -50%); + animation: energyPop 900ms ease-out forwards; + will-change: transform, opacity; +} + +.energy-pop.cooling { + color: var(--pop-color, var(--ok)); + text-shadow: 0 2px 16px rgba(82, 223, 143, 0.45); +} + +.energy-pop.blocked { + color: var(--danger); + border-color: rgba(255, 106, 102, 0.55); + text-shadow: 0 2px 16px rgba(255, 106, 102, 0.45); +} + +.energy-pop.surge-pop { + color: var(--pop-color, var(--accent-2)); + font-size: 22px; + text-shadow: + 0 2px 18px rgba(255, 206, 92, 0.6), + 0 0 34px rgba(255, 106, 102, 0.32); +} + +@keyframes energyPop { + 0% { + opacity: 0; + transform: translate(-50%, -20%) scale(0.82); + } + 18% { + opacity: 1; + transform: translate(calc(-50% + var(--pop-x)), -58%) scale(1.08); + } + 100% { + opacity: 0; + transform: translate(calc(-50% + var(--pop-x)), -150%) scale(0.92); + } +} + +.reactor-button { + width: min(250px, 52vw); + aspect-ratio: 1; + border-radius: 999px; + border: 1px solid rgba(34, 199, 184, 0.45); + background: + radial-gradient( + circle at 50% 48%, + rgba(255, 255, 255, 0.95) 0 3%, + transparent 4% + ), + radial-gradient( + circle at 50% 50%, + #22c7b8 0 13%, + #116d73 14% 34%, + #0b2630 35% 58%, + #071218 59% 100% + ); + box-shadow: + 0 0 0 14px rgba(34, 199, 184, 0.05), + 0 0 80px rgba(34, 199, 184, 0.2), + inset 0 0 50px rgba(255, 255, 255, 0.08); + color: var(--text); + display: grid; + place-items: center; + padding: 0; + transition: + transform 120ms ease, + box-shadow 160ms ease, + filter 160ms ease; + z-index: 1; +} + +.reactor-button:not(:disabled):active { + transform: scale(0.985); +} + +.reactor-button.hot { + border-color: rgba(255, 106, 102, 0.75); + background: + radial-gradient( + circle at 50% 48%, + rgba(255, 255, 255, 0.95) 0 3%, + transparent 4% + ), + radial-gradient( + circle at 50% 50%, + #ffce5c 0 13%, + #b44538 14% 34%, + #311217 35% 58%, + #071218 59% 100% + ); + box-shadow: + 0 0 0 14px rgba(255, 106, 102, 0.06), + 0 0 90px rgba(255, 106, 102, 0.22), + inset 0 0 50px rgba(255, 255, 255, 0.08); +} + +.reactor-copy { + display: grid; + gap: 6px; + padding: 0; +} + +.reactor-copy b { + font-size: clamp(24px, 5vw, 42px); + line-height: 1; + text-shadow: + 0 1px 3px rgba(0, 0, 0, 0.65), + 0 0 26px rgba(2, 10, 14, 0.88); +} + +.reactor-copy span { + color: #d8f5fb; + font: + 800 12px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.08em; + text-transform: uppercase; + text-shadow: + 0 1px 3px rgba(0, 0, 0, 0.7), + 0 0 16px rgba(2, 10, 14, 0.82); +} + +.meter { + display: grid; + gap: 6px; + margin: 0 auto; + max-width: 520px; +} + +.meter + .meter { + margin-top: 10px; +} + +.meter-head { + display: flex; + justify-content: space-between; + color: var(--muted); + font-size: 13px; +} + +.track { + height: 14px; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 999px; + background: #061014; +} + +.fill { + height: 100%; + width: 0%; + background: linear-gradient( + 90deg, + var(--accent), + var(--accent-2), + var(--danger) + ); + transition: width 80ms linear; +} + +.charge-segments { + display: grid; + grid-template-columns: repeat(var(--charge-limit, 8), minmax(0, 1fr)); + gap: 4px; + padding: 3px; + border: 1px solid var(--line); + border-radius: 8px; + background: #061014; +} + +.charge-segment { + height: 12px; + border-radius: 4px; + background: #0b1c23; + border: 1px solid rgba(174, 232, 255, 0.1); +} + +.charge-segment.active { + border-color: rgba(174, 232, 255, 0.35); + background: linear-gradient(180deg, #5ed7ff, #168fc2); + box-shadow: 0 0 10px rgba(94, 215, 255, 0.2); +} + +.systems-dock { + position: absolute; + inset: 0; + pointer-events: none; + z-index: 2; +} + +.system-control { + position: absolute; + width: 128px; + aspect-ratio: 1; + pointer-events: auto; +} + +.system-control:nth-child(1) { + left: calc(50% + 150px); + top: calc(50% - 92px); + transform: translate(-50%, -50%); +} + +.system-control:nth-child(2) { + left: calc(50% - 150px); + top: calc(50% + 92px); + transform: translate(-50%, -50%); +} + +.system-control button { + width: 100%; + height: 100%; + border-radius: 999px; + display: grid; + gap: 4px; + place-items: center; + line-height: 1.15; + padding: 13px; + background: + radial-gradient( + circle at 50% 43%, + rgba(241, 247, 251, 0.1) 0 19%, + transparent 20% + ), + radial-gradient(circle at 50% 50%, #102c35 0 48%, #071419 49% 100%); + color: rgba(241, 247, 251, 0.92); + box-shadow: + inset 0 0 0 1px rgba(205, 245, 255, 0.08), + 0 16px 34px rgba(0, 0, 0, 0.34); + transition: + transform 120ms ease, + filter 160ms ease, + box-shadow 180ms ease; +} + +.system-control button:not(:disabled):active { + transform: scale(0.96); + filter: brightness(1.18); +} + +.system-control button > span { + color: var(--text); + text-shadow: 0 2px 12px rgba(0, 0, 0, 0.74); +} + +.system-control button > span:first-child { + font-size: 15px; + align-self: end; +} + +.system-control button > .button-sub { + align-self: start; + max-width: 102px; + text-align: center; +} + +.system-control button.coolant { + color: #74f0ac; + border-color: rgba(82, 223, 143, 0.62); + box-shadow: + inset 0 0 0 1px rgba(82, 223, 143, 0.13), + 0 16px 34px rgba(0, 0, 0, 0.34), + 0 0 24px rgba(82, 223, 143, 0.1); +} + +.system-control button.surge { + color: #ffdc72; + border-color: rgba(255, 206, 92, 0.68); + box-shadow: + inset 0 0 0 1px rgba(255, 206, 92, 0.14), + 0 16px 34px rgba(0, 0, 0, 0.34), + 0 0 24px rgba(255, 206, 92, 0.12); +} + +.system-control button:disabled { + opacity: 0.52; + filter: saturate(0.45); +} + +.system-control button.fired { + animation: systemFire 520ms ease-out; +} + +@keyframes systemFire { + 0% { + transform: scale(1); + filter: brightness(1); + } + 28% { + transform: scale(1.12); + filter: brightness(1.48); + } + 100% { + transform: scale(1); + filter: brightness(1); + } +} + +.button-sub { + color: rgba(2, 6, 9, 0.68); + font: + 800 10px/1.2 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +button:not(.primary) .button-sub { + color: var(--muted); +} + +.cooldown { + min-height: 18px; + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.cooldown.blocked { + color: var(--danger); +} + +.side { + height: 640px; + min-height: 0; +} + +.box { + padding: 16px; +} + +.box h2 { + margin: 0; + font-size: 18px; +} + +.sub { + color: var(--muted); + margin-top: 4px; + font-size: 13px; +} + +.console-panel { + height: 100%; + min-height: 0; + display: grid; + grid-template-rows: auto minmax(0, 1fr); + gap: 14px; +} + +.tabs { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 0; + padding: 16px 16px 0; + border-bottom: 1px solid var(--line); +} + +.tab { + min-height: 36px; + padding: 0 4px 10px; + border: 0; + border-radius: 0; + background: transparent; + color: var(--muted); + position: relative; + display: flex; + align-items: center; + justify-content: center; + gap: 7px; + box-shadow: none; +} + +.tab[aria-selected='true'] { + background: transparent; + color: var(--text); +} + +.tab[aria-selected='true']::after { + content: ''; + position: absolute; + left: 18px; + right: 18px; + bottom: -1px; + height: 2px; + border-radius: 999px 999px 0 0; + background: var(--accent); + box-shadow: 0 0 14px rgba(34, 199, 184, 0.35); +} + +.tab:not([aria-selected='true']):hover { + color: #c7dbe4; +} + +.tab-count { + color: var(--muted); + font: + 800 11px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.tab[aria-selected='true'] .tab-count { + color: var(--accent-2); +} + +.tab-content { + min-height: 0; + padding: 0 16px 16px; + overflow: hidden; + display: grid; +} + +.tab-pane { + display: none; + height: 100%; + min-height: 0; +} + +.tab-pane.active { + display: grid; + align-content: start; + overflow: auto; +} + +.pane-empty { + align-self: center; + display: grid; + justify-items: center; + align-content: center; + gap: 5px; + min-height: 160px; + padding: 24px 16px; + text-align: center; +} + +.pane-empty b { + color: #c7dbe4; + font-size: 14px; +} + +.pane-empty span { + color: var(--muted); + font-size: 12px; + max-width: 240px; +} + +.pane-spinner { + width: 22px; + height: 22px; + margin-bottom: 6px; + border-radius: 999px; + border: 2px solid var(--line); + border-top-color: var(--accent); + animation: pane-spin 0.8s linear infinite; +} + +@keyframes pane-spin { + to { + transform: rotate(360deg); + } +} + +.shop-list { + display: grid; + gap: 8px; +} + +.shop-item { + border: 1px solid var(--line); + border-radius: 8px; + padding: 11px 12px; + background: #08141a; + display: grid; + grid-template-columns: 38px minmax(0, 1fr) auto; + gap: 12px; + align-items: center; +} + +.shop-item.locked { + opacity: 0.55; +} + +.shop-icon { + width: 38px; + height: 38px; + display: grid; + place-items: center; + border-radius: 8px; + border: 1px solid + color-mix(in srgb, var(--lane, var(--line-strong)) 36%, var(--line)); + background: color-mix(in srgb, var(--lane, var(--accent)) 9%, #071318); + color: var(--lane, var(--accent)); +} + +.shop-icon svg { + width: 20px; + height: 20px; +} + +.shop-head { + min-width: 0; +} + +.shop-title { + display: flex; + align-items: baseline; + gap: 8px; + min-width: 0; +} + +.shop-title b { + font-size: 15px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.shop-level { + flex: none; + color: var(--lane, var(--accent)); + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.06em; + text-transform: uppercase; + padding: 2px 6px; + border-radius: 999px; + border: 1px solid + color-mix(in srgb, var(--lane, var(--accent)) 38%, transparent); + background: color-mix(in srgb, var(--lane, var(--accent)) 11%, transparent); +} + +.shop-effect { + display: block; + margin-top: 3px; + color: color-mix(in srgb, var(--lane, var(--accent)) 74%, var(--text)); + font: + 700 12px/1.3 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.shop-desc { + margin: 3px 0 0; + color: var(--muted); + font-size: 12px; + line-height: 1.35; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.shop-cost { + margin-top: 8px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 9px; + align-items: center; +} + +.shop-cost-track { + height: 5px; + overflow: hidden; + border: 1px solid var(--line); + border-radius: 999px; + background: #061014; +} + +.shop-cost-fill { + height: 100%; + width: 0%; + background: color-mix(in srgb, var(--lane, var(--accent)) 52%, #0a1620); + transition: + width 120ms linear, + background 200ms ease, + box-shadow 200ms ease; +} + +.shop-item.affordable .shop-cost-fill { + background: var(--lane, var(--accent)); + box-shadow: 0 0 9px + color-mix(in srgb, var(--lane, var(--accent)) 70%, transparent); +} + +.shop-cost-text { + color: var(--muted); + font: + 700 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.03em; + white-space: nowrap; +} + +.shop-item.affordable .shop-cost-text { + color: color-mix(in srgb, var(--lane, var(--accent)) 60%, var(--text)); +} + +.shop-buy-row { + display: grid; + justify-items: end; + align-items: center; +} + +.shop-buy-row button { + min-height: 32px; + width: 96px; + padding: 0 12px; + white-space: nowrap; + transition: transform 110ms ease; +} + +.shop-buy-row button:not(:disabled):hover { + transform: translateY(-1px); +} + +.shop-buy-row button:not(:disabled):active { + transform: translateY(0); +} + +.player-list, +.activity-list { + display: grid; + gap: 8px; + align-content: start; +} + +.player-row { + border: 1px solid var(--line); + border-radius: 8px; + background: #08141a; + padding: 10px 12px; +} + +.activity-row { + min-height: 30px; + display: grid; + grid-template-columns: 54px minmax(0, 1fr) auto; + gap: 10px; + align-items: center; + padding: 5px 0; + border-bottom: 1px solid rgba(23, 56, 70, 0.72); + border-left: 2px solid var(--player-color, transparent); + padding-left: 8px; +} + +.activity-row:last-child { + border-bottom: 0; +} + +.player-row { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + gap: 10px; + align-items: center; + position: relative; +} + +.player-row.current { + border-color: rgba(34, 199, 184, 0.34); +} + +.player-color { + width: 10px; + height: 10px; + border-radius: 999px; + background: var(--player-color, var(--accent)); + box-shadow: 0 0 14px var(--player-color, var(--accent)); +} + +.player-color-wrap { + position: relative; + display: grid; + place-items: center; +} + +.player-color-wrap .color-dot { + width: 10px; + height: 10px; + min-height: 10px; + border-width: 1px; + position: relative; + box-shadow: 0 0 14px var(--player-color, var(--accent)); +} + +.player-color-wrap .color-dot::after { + content: ''; + position: absolute; + inset: -8px; + border-radius: 999px; +} + +.player-palette { + left: -8px; + top: calc(100% + 10px); +} + +.player-meta { + display: flex; + align-items: baseline; + gap: 7px; + min-width: 0; +} + +.self-pill { + color: var(--accent-2); + font: + 800 9px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.player-row b, +.activity-row b { + display: block; + font-size: 13px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.player-row span, +.activity-row span { + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +.activity-row time { + color: var(--muted); + font: + 700 11px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + white-space: nowrap; +} + +.event-chip { + display: block; + width: 48px; + min-width: 48px; + max-width: 48px; + padding: 4px 0; + border: 1px solid var(--line); + border-radius: 7px; + text-align: center; + color: var(--muted); + background: #071318; + font: + 800 10px/1 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; + letter-spacing: 0.03em; + text-transform: uppercase; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.event-chip.tap { + border-color: rgba(34, 199, 184, 0.42); + color: #9ef4ea; + background: rgba(34, 199, 184, 0.08); +} + +.event-chip.surge { + border-color: rgba(255, 206, 92, 0.46); + color: #ffdf86; + background: rgba(255, 206, 92, 0.08); +} + +.event-chip.repair { + border-color: rgba(82, 223, 143, 0.44); + color: #a9f5c8; + background: rgba(82, 223, 143, 0.08); +} + +.event-chip.upgrade { + border-color: rgba(174, 232, 255, 0.4); + color: #c9efff; + background: rgba(174, 232, 255, 0.07); +} + +.event-chip.blocked { + border-color: rgba(255, 106, 102, 0.52); + color: #ffaaa7; + background: rgba(255, 106, 102, 0.08); +} + +.player-score { + color: var(--accent-2); + white-space: nowrap; + font: + 800 12px/1.4 ui-monospace, + SFMono-Regular, + Menlo, + Consolas, + monospace; +} + +@media (max-width: 900px) { + .layout { + grid-template-columns: 1fr; + } + .arena, + .side { + height: auto; + } +} + +@media (max-width: 560px) { + .shell { + width: min(100vw - 16px, 1320px); + } + .topbar { + align-items: flex-start; + flex-direction: column; + } + .reactor-wrap { + min-height: 420px; + } + .console-panel { + min-height: 0; + } + .tabs { + grid-template-columns: 1fr; + } + .system-control:nth-child(1), + .system-control:nth-child(2) { + position: absolute; + left: 50%; + right: auto; + top: auto; + bottom: auto; + transform: translateX(-50%); + } + .system-control:nth-child(1) { + top: 0; + } + .system-control:nth-child(2) { + bottom: 0; + } +} diff --git a/spacetime-rate-limit-ts/example/public/ui.js b/spacetime-rate-limit-ts/example/public/ui.js new file mode 100644 index 00000000000..16e5aa8d461 --- /dev/null +++ b/spacetime-rate-limit-ts/example/public/ui.js @@ -0,0 +1,763 @@ +const state = { + conn: 'connecting', + reactor: null, + events: [], + players: [], + statuses: [], + shop: [], + activeTab: 'shop', + currentIdentityHex: null, + colorPaletteOpen: false, +}; + +const $ = id => document.getElementById(id); +const fmt = new Intl.NumberFormat(); +const COOLANT_UNLOCK_LEVEL = 2; +const SURGE_UNLOCK_LEVEL = 2; +const PLAYER_COLORS = [ + '#22c7b8', + '#ffce5c', + '#52df8f', + '#ff6a66', + '#aee8ff', + '#d28cff', + '#ff9f6e', + '#8ddf65', +]; + +// Upgrade lanes reuse the colors the reactor already assigns to each system: +// amber = power/surge, green = cooling/coolant, cyan = tap charges. +const UPGRADE_LANES = { + power: { + color: 'var(--accent-2)', + count: 'powerUpgradeCount', + icon: '', + }, + cooling: { + color: 'var(--ok)', + count: 'coolingUpgradeCount', + icon: '', + }, + capacity: { + color: '#aee8ff', + count: 'capacityUpgradeCount', + icon: '', + }, + charges: { + color: '#5ed7ff', + count: 'chargeUpgradeCount', + icon: '', + }, + bay: { + color: 'var(--muted)', + count: 'bayUpgradeCount', + icon: '', + }, +}; + +function upgradeLaneColor(id) { + return UPGRADE_LANES[id]?.color ?? 'var(--accent)'; +} + +function upgradeLevel(id) { + const lane = UPGRADE_LANES[id]; + if (!lane) return 0; + return Number(state.reactor?.[lane.count] ?? 0); +} + +function costPercent(energy, cost) { + if (cost <= 0n) return 100; + if (energy >= cost) return 100; + return Number((energy * 100n) / cost); +} + +function microsToMs(ts) { + if (!ts || ts.microsSinceUnixEpoch == null) return 0; + return Number(ts.microsSinceUnixEpoch / 1000n); +} + +function eventTime(ts) { + const ms = microsToMs(ts); + return ms + ? new Date(ms).toLocaleTimeString([], { + hour: 'numeric', + minute: '2-digit', + second: '2-digit', + }) + : ''; +} + +function identityHex(identity) { + if (!identity) return ''; + if (typeof identity.toHexString === 'function') return identity.toHexString(); + return String(identity); +} + +function secondsUntil(ts) { + const ms = microsToMs(ts); + if (!ms) return 0; + return Math.max(0, Math.ceil((ms - Date.now()) / 1000)); +} + +function secondsUntilPrecise(ts) { + const ms = microsToMs(ts); + if (!ms) return 0; + return Math.max(0, (ms - Date.now()) / 1000); +} + +function formatSeconds(seconds) { + if (seconds <= 0) return 'ready'; + return `${seconds.toFixed(1)}s`; +} + +function effectiveReactor(reactor) { + if (!reactor) return null; + const elapsed = Math.max( + 0, + (Date.now() - microsToMs(reactor.updatedAt)) / 1000 + ); + const cooling = Number(reactor.coolingPerSecond ?? 4); + const capacity = Number(reactor.heatCapacity ?? 100); + const heat = Math.max(0, Number(reactor.heat ?? 0) - elapsed * cooling); + return { + ...reactor, + heat, + heatCapacity: capacity, + coolingPerSecond: cooling, + overheated: Boolean(reactor.overheated) && heat > capacity * 0.45, + }; +} + +function coolingText(reactor) { + if (!reactor || reactor.heat <= 0) return 'stable'; + if (reactor.overheated) { + const recoverAt = reactor.heatCapacity * 0.45; + const seconds = + Math.max(0, reactor.heat - recoverAt) / reactor.coolingPerSecond; + return seconds > 0 ? `Cooling ${formatSeconds(seconds)}` : 'safe'; + } + return `cooling ${formatSeconds(reactor.heat / reactor.coolingPerSecond)}`; +} + +function statusByScope(scope) { + return state.statuses.find(row => row.scope === scope); +} + +function effectiveStatus(scope) { + const row = statusByScope(scope); + if (!row) return null; + const seconds = secondsUntilPrecise(row.resetAt); + if (seconds <= 0) { + return { + ...row, + used: 0, + remaining: row.limit, + }; + } + return row; +} + +function isCooling(scope) { + const row = effectiveStatus(scope); + if (!row || row.remaining > 0) return false; + return secondsUntil(row.resetAt) > 0; +} + +function cooldownText(scope) { + const row = effectiveStatus(scope); + if (!row) return ''; + const seconds = secondsUntilPrecise(row.resetAt); + if (row.remaining <= 0 && seconds > 0) { + return scope === 'reactor.tap' + ? `Resets in ${formatSeconds(seconds)}` + : `Ready in ${formatSeconds(seconds)}`; + } + return `${row.remaining}/${row.limit} ready`; +} + +function cooldownButtonText(scope) { + const row = effectiveStatus(scope); + const seconds = secondsUntilPrecise(row?.resetAt); + return seconds > 0 ? formatSeconds(seconds) : 'Wait'; +} + +function tapChargeInfo(scope) { + const row = effectiveStatus(scope); + if (!row) return 'waiting'; + const seconds = secondsUntilPrecise(row.resetAt); + const reset = + seconds > 0 + ? `resets in ${formatSeconds(seconds)}` + : `${row.windowSeconds}s window`; + return `${row.remaining} / ${row.limit} · ${reset}`; +} + +function renderChargeSegments(scope) { + const row = effectiveStatus(scope); + const node = $('tapChargeSegments'); + if (!node) return; + const limit = row?.limit ?? 8; + const remaining = row?.remaining ?? 0; + node.style.setProperty('--charge-limit', String(Math.max(1, limit))); + node.innerHTML = Array.from( + { length: limit }, + (_value, index) => + `` + ).join(''); +} + +function hasCoolantFlush(reactor) { + return Number(reactor?.coolingUpgradeCount ?? 0) >= COOLANT_UNLOCK_LEVEL; +} + +function hasSurgeBurst(reactor) { + return Number(reactor?.powerUpgradeCount ?? 0) >= SURGE_UNLOCK_LEVEL; +} + +function romanLevel(value) { + const numerals = [ + [10, 'X'], + [9, 'IX'], + [5, 'V'], + [4, 'IV'], + [1, 'I'], + ]; + let n = Math.max(1, Math.min(20, Math.trunc(Number(value) || 1))); + let out = ''; + for (const [amount, label] of numerals) { + while (n >= amount) { + out += label; + n -= amount; + } + } + return out; +} + +function surgeLevel(reactor) { + return romanLevel(reactor?.reactorLevel ?? 1); +} + +function coolantLevel(reactor) { + return romanLevel(Math.max(1, Number(reactor?.coolingUpgradeCount ?? 0))); +} + +function surgePreview(reactor) { + const level = reactor?.reactorLevel ?? 1; + const heat = Math.max(28, Math.floor((reactor?.heatCapacity ?? 100) * 0.25)); + return `+${fmt.format(level * 10)} energy
+${heat} heat`; +} + +function coolantAmount(reactor) { + return Math.max(65, Math.floor((reactor?.heatCapacity ?? 100) * 0.55)); +} + +function coolantPreview(reactor) { + return `Vent -${coolantAmount(reactor)} heat`; +} + +function spawnReactorPop(text, kind = '', color = '') { + const layer = $('popLayer'); + const pop = document.createElement('div'); + pop.className = `energy-pop ${kind}`; + pop.textContent = text; + pop.style.setProperty( + '--pop-x', + `${Math.round((Math.random() - 0.5) * 90)}px` + ); + if (color) pop.style.setProperty('--pop-color', color); + layer.appendChild(pop); + window.setTimeout(() => pop.remove(), 850); +} + +function spawnEventPop(event) { + if (!event.allowed) { + if (event.scope === 'reactor.tap') + spawnReactorPop('WAIT', 'blocked', event.actorColor); + return; + } + if (event.energyDelta > 0n) { + const prefix = + event.kind === 'overcharge' || event.kind === 'overcharge_overheated' + ? 'SURGE +' + : '+'; + const kind = + event.kind === 'overcharge' || event.kind === 'overcharge_overheated' + ? 'surge-pop' + : ''; + spawnReactorPop( + `${prefix}${fmt.format(event.energyDelta)}`, + kind, + event.actorColor + ); + return; + } + if (event.kind === 'repair') { + spawnReactorPop('VENT', 'cooling', event.actorColor); + } +} + +function setBusy(button, busy) { + button.dataset.busy = busy ? 'true' : 'false'; +} + +function flashButton(button, allowed) { + button.classList.remove('fired'); + void button.offsetWidth; + if (allowed) button.classList.add('fired'); + window.setTimeout(() => button.classList.remove('fired'), 460); +} + +async function callAction(button, fn) { + if (button.dataset.busy === 'true') return; + if (!window.reactor) throw new Error('reactor.not_ready'); + setBusy(button, true); + try { + const result = await fn(); + flashButton(button, result.allowed); + render(); + } catch (err) { + console.error('reactor action failed', err); + render(); + } finally { + setBusy(button, false); + } +} + +let energyShown = 0; +let energyTarget = 0; +let energyReady = false; +let energyTween = null; +let energyGainTimer = null; + +function pulseEnergyGain() { + const banner = document.querySelector('.energy-banner'); + if (!banner) return; + banner.classList.remove('gain'); + void banner.offsetWidth; + banner.classList.add('gain'); + window.clearTimeout(energyGainTimer); + energyGainTimer = window.setTimeout( + () => banner.classList.remove('gain'), + 460 + ); +} + +function writeEnergy() { + $('energy').textContent = fmt.format(Math.round(energyShown)); +} + +function startEnergyTween() { + if (energyTween != null) return; + energyTween = window.setInterval(() => { + const diff = energyTarget - energyShown; + if (Math.abs(diff) < 0.5) { + energyShown = energyTarget; + writeEnergy(); + window.clearInterval(energyTween); + energyTween = null; + return; + } + energyShown += diff * 0.25; + writeEnergy(); + }, 16); +} + +function setEnergy(value) { + const next = Number(value); + if (!energyReady) { + energyReady = true; + energyShown = next; + energyTarget = next; + writeEnergy(); + return; + } + if (next > energyTarget) pulseEnergyGain(); + energyTarget = next; + if (energyShown !== energyTarget) startEnergyTween(); +} + +function renderStats() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const level = reactor?.reactorLevel ?? 1; + const capacity = reactor?.heatCapacity ?? 100; + const heat = reactor?.heat ?? 0; + const heatPct = capacity <= 0 ? 0 : (heat / capacity) * 100; + const overheated = Boolean(reactor?.overheated); + const tapCooling = isCooling('reactor.tap'); + + if (reactor) setEnergy(energy); + $('heatText').textContent = `${heat.toFixed(1)} / ${capacity}`; + $('coolText').textContent = coolingText(reactor); + $('heatFill').style.width = `${Math.max(0, Math.min(100, heatPct))}%`; + $('tapChargeInfo').textContent = tapChargeInfo('reactor.tap'); + renderChargeSegments('reactor.tap'); + + $('reactorWrap').classList.toggle('warm', heatPct >= 35 && heatPct < 70); + $('reactorWrap').classList.toggle('critical', overheated || heatPct >= 70); + $('tapBtn').classList.toggle( + 'hot', + overheated || heatPct >= 75 || tapCooling + ); + $('tapBtn').disabled = state.conn !== 'connected' || overheated || tapCooling; + $('reactorLabel').textContent = overheated + ? 'Overheated' + : tapCooling + ? 'No Charges' + : 'Tap'; + $('reactorHint').textContent = overheated + ? coolingText(reactor) + : tapCooling + ? cooldownText('reactor.tap') + : `+${level} energy · +${reactor?.tapHeatGain ?? 13} heat`; +} + +function paneEmpty(title, sub) { + if (state.conn !== 'connected') { + const connecting = + state.conn === 'error' + ? ['Reconnecting', 'Lost the link to SpacetimeDB.'] + : ['Connecting', 'Linking up with SpacetimeDB.']; + return `
${connecting[0]}${connecting[1]}
`; + } + return `
${title}${sub}
`; +} + +function renderShop() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const upgradeCooling = isCooling('reactor.upgrade'); + const rows = state.shop.filter(item => item.available); + $('shopList').innerHTML = + rows.length === 0 + ? paneEmpty('Loading upgrades', 'Fetching the reactor shop.') + : rows + .map(item => { + const affordable = energy >= item.cost; + const disabled = + state.conn !== 'connected' || upgradeCooling || !affordable; + const buttonText = upgradeCooling + ? cooldownButtonText('reactor.upgrade') + : 'Install'; + const lane = UPGRADE_LANES[item.id]; + const level = upgradeLevel(item.id); + return ` +
+ +
+
${item.name}${level > 0 ? `Lv ${level}` : ''}
+ ${item.effect} +

${item.description}

+
+
+ ${fmt.format(energy)} / ${fmt.format(item.cost)} +
+
+
+ +
+
+ `; + }) + .join(''); +} + +function renderPlayers() { + const rows = state.players ?? []; + $('playerCount').textContent = rows.length.toString(); + $('playerList').innerHTML = + rows.length === 0 + ? paneEmpty('No crew yet', 'Open another tab to bring a pilot online.') + : rows + .map(player => { + const isCurrent = + identityHex(player.identity) === state.currentIdentityHex; + const colorControl = isCurrent + ? `
+ +
+ ${PLAYER_COLORS.map( + swatch => + `` + ).join('')} +
+
` + : ''; + return ` +
+ ${colorControl} +
+
${player.displayName}${isCurrent ? 'You' : ''}
+ ${player.taps} taps · ${player.surges} surges · ${player.coolantUses} vents +
+
${fmt.format(player.contributedEnergy)}
+
+ `; + }) + .join(''); +} + +function activityChip(event) { + if (!event.allowed) return { className: 'blocked', label: 'Wait' }; + if (event.kind === 'tap' || event.kind === 'tap_overheated') + return { className: 'tap', label: 'Tap' }; + if (event.kind === 'overcharge' || event.kind === 'overcharge_overheated') + return { className: 'surge', label: 'Surge' }; + if (event.kind === 'repair') return { className: 'repair', label: 'Vent' }; + if (event.kind === 'upgrade') return { className: 'upgrade', label: 'Shop' }; + return { className: '', label: 'Room' }; +} + +function renderActivity() { + const rows = (state.events ?? []).slice(0, 18); + $('activityCount').textContent = rows.length.toString(); + $('activityList').innerHTML = + rows.length === 0 + ? paneEmpty('No activity yet', 'Tap the core to start the feed.') + : rows + .map(event => { + const delta = + event.energyDelta === 0n + ? '' + : ` ${event.energyDelta > 0n ? '+' : ''}${event.energyDelta.toString()} energy`; + const chip = activityChip(event); + return ` +
+ ${chip.label} + ${event.actorName}${delta} + +
+ `; + }) + .join(''); +} + +function renderTabs() { + $('shopCount').textContent = state.shop.length.toString(); + for (const tab of document.querySelectorAll('[data-tab]')) { + const active = tab.dataset.tab === state.activeTab; + tab.setAttribute('aria-selected', active ? 'true' : 'false'); + } + for (const pane of document.querySelectorAll('[data-pane]')) { + pane.classList.toggle('active', pane.dataset.pane === state.activeTab); + } +} + +function renderSystems() { + const reactor = effectiveReactor(state.reactor); + const heat = reactor?.heat ?? 0; + const overheated = Boolean(reactor?.overheated); + const systems = []; + const coolantUnlocked = hasCoolantFlush(reactor); + const surgeUnlocked = hasSurgeBurst(reactor); + + const repairCooling = isCooling('reactor.repair'); + const useful = overheated || heat >= 35; + if (coolantUnlocked) { + systems.push(` +
+ +
${repairCooling ? cooldownText('reactor.repair') : ''}
+
+ `); + } + + const surgeCooling = isCooling('reactor.overcharge'); + if (surgeUnlocked) { + systems.push(` +
+ +
${surgeCooling ? cooldownText('reactor.overcharge') : ''}
+
+ `); + } + + $('systemDock').innerHTML = systems.join(''); +} + +function updateShopTimers() { + const reactor = effectiveReactor(state.reactor); + const energy = reactor?.energy ?? 0n; + const upgradeCooling = isCooling('reactor.upgrade'); + + for (const item of state.shop.filter(row => row.available)) { + const button = document.querySelector( + `.upgrade-btn[data-upgrade-id="${item.id}"]` + ); + if (button instanceof HTMLButtonElement) { + const affordable = energy >= item.cost; + button.disabled = + state.conn !== 'connected' || upgradeCooling || !affordable; + button.textContent = upgradeCooling + ? cooldownButtonText('reactor.upgrade') + : 'Install'; + + const row = button.closest('.shop-item'); + if (row instanceof HTMLElement) { + row.classList.toggle('affordable', affordable); + const fill = row.querySelector('.shop-cost-fill'); + if (fill instanceof HTMLElement) + fill.style.width = `${costPercent(energy, item.cost)}%`; + const costText = row.querySelector('.shop-cost-text'); + if (costText) + costText.textContent = `${fmt.format(energy)} / ${fmt.format(item.cost)}`; + } + } + } +} + +function updateSystemTimers() { + const reactor = effectiveReactor(state.reactor); + const heat = reactor?.heat ?? 0; + const overheated = Boolean(reactor?.overheated); + + const repairBtn = $('repairBtn'); + if (repairBtn) { + const cooling = isCooling('reactor.repair'); + const useful = overheated || heat >= 35; + repairBtn.disabled = state.conn !== 'connected' || cooling || !useful; + const hint = $('repairHint'); + if (hint) + hint.textContent = cooling + ? cooldownText('reactor.repair') + : coolantPreview(reactor); + const cooldown = $('repairCooldown'); + if (cooldown) { + cooldown.textContent = cooling ? cooldownText('reactor.repair') : ''; + cooldown.classList.toggle('blocked', cooling); + } + } + + const surgeBtn = $('overchargeBtn'); + if (surgeBtn) { + const cooling = isCooling('reactor.overcharge'); + surgeBtn.disabled = state.conn !== 'connected' || overheated || cooling; + const hint = $('overchargeHint'); + if (hint) + hint.innerHTML = overheated + ? 'Core cooling' + : cooling + ? cooldownText('reactor.overcharge') + : surgePreview(reactor); + const cooldown = $('overchargeCooldown'); + if (cooldown) { + cooldown.textContent = cooling ? cooldownText('reactor.overcharge') : ''; + cooldown.classList.toggle('blocked', cooling); + } + } +} + +function render() { + renderStats(); + renderTabs(); + renderShop(); + renderSystems(); + renderPlayers(); + renderActivity(); +} + +function renderLive() { + renderStats(); + updateShopTimers(); + updateSystemTimers(); +} + +function animationLoop() { + renderLive(); + requestAnimationFrame(animationLoop); +} + +window.addEventListener('reactor:connState', ev => { + state.conn = ev.detail.state; + if (ev.detail.detail) { + console.warn('reactor connection state', ev.detail); + } + render(); +}); + +window.addEventListener('reactor:data', ev => { + state.reactor = ev.detail.state; + state.events = ev.detail.events ?? []; + state.players = ev.detail.players ?? []; + state.statuses = ev.detail.statuses ?? []; + state.shop = ev.detail.shop ?? []; + state.currentIdentityHex = ev.detail.currentIdentityHex ?? null; + render(); +}); + +window.addEventListener('reactor:eventInserted', ev => { + spawnEventPop(ev.detail.event); +}); + +window.addEventListener('reactor:ready', () => { + render(); +}); + +$('tapBtn').addEventListener('click', () => + callAction($('tapBtn'), () => window.reactor.tap()) +); +$('playerList').addEventListener('click', ev => { + const target = ev.target instanceof Element ? ev.target : null; + if (!target) return; + + if (target.closest('#crewColorDot')) { + state.colorPaletteOpen = !state.colorPaletteOpen; + renderPlayers(); + return; + } + + const button = target.closest('[data-color]'); + if (!(button instanceof HTMLButtonElement)) return; + const color = button.dataset.color; + if (!color || !window.reactor) return; + state.colorPaletteOpen = false; + window.reactor + .setPlayerColor(color) + .catch(err => console.error('setPlayerColor failed', err)); + renderPlayers(); +}); +document.addEventListener('pointerdown', ev => { + if (!state.colorPaletteOpen) return; + const target = ev.target instanceof Element ? ev.target : null; + if (target?.closest('#crewColorDot, #crewColorPalette')) return; + state.colorPaletteOpen = false; + renderPlayers(); +}); +document.addEventListener('keydown', ev => { + if (ev.key !== 'Escape' || !state.colorPaletteOpen) return; + state.colorPaletteOpen = false; + renderPlayers(); +}); +$('shopList').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('.upgrade-btn') : null; + if (button instanceof HTMLButtonElement) { + const upgradeId = button.dataset.upgradeId; + if (upgradeId) + callAction(button, () => window.reactor.buyUpgrade(upgradeId)); + } +}); +document.querySelector('.tabs').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('[data-tab]') : null; + if (!(button instanceof HTMLButtonElement)) return; + state.activeTab = button.dataset.tab; + renderTabs(); +}); +$('systemDock').addEventListener('click', ev => { + const button = + ev.target instanceof Element ? ev.target.closest('button') : null; + if (!(button instanceof HTMLButtonElement)) return; + if (button.id === 'repairBtn') + callAction(button, () => window.reactor.repair()); + if (button.id === 'overchargeBtn') + callAction(button, () => window.reactor.overcharge()); +}); +render(); +requestAnimationFrame(animationLoop); diff --git a/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts new file mode 100644 index 00000000000..5da0ad814e9 --- /dev/null +++ b/spacetime-rate-limit-ts/example/scripts/test-reactor-rules.ts @@ -0,0 +1,44 @@ +import * as assert from 'node:assert/strict'; +import { + COOLANT_UNLOCK_LEVEL, + SURGE_UNLOCK_LEVEL, + hasCoolantFlush, + hasSurgeBurst, + roomTuning, + tapLimitForState, + upgradeOffer, + upgradeWindowForState, + type UpgradeState, +} from '../spacetimedb/src/reactor-rules'; + +const state: UpgradeState = { + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, +}; + +assert.deepEqual(roomTuning(state, 1), { + heatCapacity: 100, + coolingPerSecond: 4, + tapHeatGain: 12, +}); +assert.deepEqual(roomTuning(state, 3), { + heatCapacity: 250, + coolingPerSecond: 12, + tapHeatGain: 12, +}); +assert.equal(upgradeOffer(state, 'power').cost, 12n); +assert.equal(tapLimitForState({ chargeUpgradeCount: 2 }), 12); +assert.equal(upgradeWindowForState({ bayUpgradeCount: 99 }), 5); +assert.equal( + hasCoolantFlush({ coolingUpgradeCount: COOLANT_UNLOCK_LEVEL }), + true +); +assert.equal( + hasSurgeBurst({ powerUpgradeCount: SURGE_UNLOCK_LEVEL - 1 }), + false +); + +console.log('reactor rules tests passed'); diff --git a/spacetime-rate-limit-ts/example/server.ts b/spacetime-rate-limit-ts/example/server.ts new file mode 100644 index 00000000000..5429fba7566 --- /dev/null +++ b/spacetime-rate-limit-ts/example/server.ts @@ -0,0 +1,42 @@ +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import express, { type Request, type Response } from 'express'; +import dotenv from 'dotenv'; +import { exampleUiAssetsDir } from '@spacetimedb/submodule-shared/server'; + +dotenv.config(); + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const PORT = Number.parseInt(process.env.PORT ?? '8792', 10); +const HOST = process.env.HOST?.trim() || '127.0.0.1'; +const STDB_URI = process.env.STDB_URI ?? 'ws://127.0.0.1:3000'; +const DB_NAME = + process.env.SPACETIMEDB_DB_NAME ?? 'spacetime-rate-limit-example'; + +const app = express(); +app.use(express.json({ limit: '256kb' })); +app.use('/assets', express.static(exampleUiAssetsDir)); +app.use( + express.static(path.join(__dirname, 'public'), { + etag: false, + lastModified: false, + setHeaders(res) { + res.setHeader('Cache-Control', 'no-store'); + }, + }) +); + +app.get('/api/health', (_req: Request, res: Response) => { + res.json({ ok: true, databaseName: DB_NAME }); +}); + +app.get('/api/config', (_req: Request, res: Response) => { + res.json({ spacetimeUri: STDB_URI, databaseName: DB_NAME }); +}); + +app.listen(PORT, HOST, () => { + console.log(`Rate-limit example running at http://${HOST}:${PORT}`); + console.log(` STDB -> ${STDB_URI} (${DB_NAME})`); +}); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/.npmrc b/spacetime-rate-limit-ts/example/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/example/spacetimedb/package.json b/spacetime-rate-limit-ts/example/spacetimedb/package.json new file mode 100644 index 00000000000..a3962a12a79 --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-rate-limit-example-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-rate-limit-example", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-rate-limit-example" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts new file mode 100644 index 00000000000..5817b1b1baa --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/index.ts @@ -0,0 +1,1130 @@ +import { t, Range, SenderError, type ViewCtx } from 'spacetimedb/server'; +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { ScheduleAt, Timestamp } from 'spacetimedb'; +import { + COOLANT_UNLOCK_LEVEL, + PLAYER_COLORS, + POWER_PER_UPGRADE, + SURGE_UNLOCK_LEVEL, + TAP_LIMIT, + hasCoolantFlush, + hasSurgeBurst, + overheatRecoverAt, + playerColor, + playerName, + roomTuning, + tapLimitForState, + upgradeOffer, + upgradeWindowForState, + type UpgradeLane, +} from './reactor-rules'; + +const ONE_SECOND_MICROS = 1_000_000n; + +const TAP_SCOPE = 'reactor.tap'; +const OVERCHARGE_SCOPE = 'reactor.overcharge'; +const UPGRADE_SCOPE = 'reactor.upgrade'; +const REPAIR_SCOPE = 'reactor.repair'; +const SHARED_REACTOR_KEY = 'room'; + +const TAP_WINDOW_SECONDS = 6; +const OVERCHARGE_LIMIT = 3; +const OVERCHARGE_WINDOW_SECONDS = 25; +const UPGRADE_LIMIT = 2; +const REPAIR_LIMIT = 1; +const REPAIR_WINDOW_SECONDS = 18; + +const DEFAULT_RETAIN_EVENTS = 2000; +const DEFAULT_EVENT_PRUNE_BATCH = 500; +const DEFAULT_RETAIN_REACTOR_EVENTS = 80; +const ACTIVE_CREW_WINDOW_SECONDS = 60; +const MAX_CREW_SCALING = 6; +const ADMIN_EVENT_VIEW_LIMIT = 1000; + +import { + rateLimitEvent, + reactorEvent, + reactorRoomState, + rateLimitDemoSweepTick, + spacetimedb, + type Schema, + type Tx, +} from './schema'; +export default spacetimedb; + +type ReactorStateRow = NonNullable< + ReturnType +>; +type ReactorPlayerRow = NonNullable< + ReturnType +>; + +function takeRows(rows: Iterable, limit: number): T[] { + const result: T[] = []; + for (const row of rows) { + if (result.length >= limit) break; + result.push(row); + } + return result; +} + +const reactorLimitStatusRow = t.object('ReactorLimitStatusRow', { + scope: t.string(), + label: t.string(), + limit: t.u32(), + windowSeconds: t.u32(), + used: t.u32(), + remaining: t.u32(), + resetAt: t.option(t.timestamp()), +}); + +const reactorShopItem = t.object('ReactorShopItemRow', { + slot: t.u32(), + id: t.string(), + name: t.string(), + description: t.string(), + effect: t.string(), + cost: t.u64(), + available: t.bool(), +}); + +const reactorPlayer = t.object('ReactorPlayerRow', { + identity: t.identity(), + displayName: t.string(), + color: t.string(), + contributedEnergy: t.u64(), + taps: t.u32(), + surges: t.u32(), + coolantUses: t.u32(), + upgradesBought: t.u32(), + joinedAt: t.timestamp(), + updatedAt: t.timestamp(), +}); + +const reactorActionResult = t.object('ReactorActionResult', { + allowed: t.bool(), + action: t.string(), + message: t.string(), + energy: t.u64(), + energyDelta: t.i64(), + retryAfterSeconds: t.u32(), + resetAt: t.timestamp(), +}); + +function isAdmin(ctx: ViewCtx): boolean { + return ( + ctx.db.rateLimit.rateLimitAdminIdentity.identity.find(ctx.sender) != null + ); +} + +function requireAdmin(ctx: Tx): void { + if ( + ctx.as.rateLimit.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null + ) { + throw new SenderError('rate_limit.not_authorized'); + } +} + +function actorKey(ctx: { sender: { toHexString(): string } }): string { + return ctx.sender.toHexString(); +} + +function limitKeyForScope( + scope: string, + ctx: { sender: { toHexString(): string } } +): string { + return scope === UPGRADE_SCOPE ? SHARED_REACTOR_KEY : actorKey(ctx); +} + +function bucketKey(scope: string, key: string): string { + return rateLimit.buildRateLimitKey(scope, key); +} + +function clampU32(value: number, min = 0, max = 0xffff_ffff): number { + return Math.max(min, Math.min(max, Math.trunc(value))); +} + +function requireUpgradeLane(value: string): UpgradeLane { + if ( + value === 'power' || + value === 'cooling' || + value === 'capacity' || + value === 'charges' || + value === 'bay' + ) + return value; + throw new SenderError('reactor.invalid_upgrade'); +} + +function activeCrewCount(tx: Tx): number { + const activeAfter = + tx.timestamp.microsSinceUnixEpoch - + BigInt(ACTIVE_CREW_WINDOW_SECONDS) * ONE_SECOND_MICROS; + let count = 0; + for (const _row of tx.db.reactorPlayerState.updatedAt.filter( + new Range({ tag: 'included', value: new Timestamp(activeAfter) }) + )) + count++; + return clampU32(Math.max(1, count), 1, MAX_CREW_SCALING); +} + +function tunedState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const tuning = roomTuning(state, activeCrewCount(tx)); + const heat = clampU32(state.heat, 0, tuning.heatCapacity); + return { + ...state, + ...tuning, + heat, + overheated: + state.overheated && heat > Math.floor(tuning.heatCapacity * 0.45), + }; +} + +function requirePlayerColor(color: string): string { + if (PLAYER_COLORS.includes(color)) return color; + throw new SenderError('reactor.invalid_player_color'); +} + +function ensurePlayer(tx: Tx): ReactorPlayerRow { + const existing = tx.db.reactorPlayerState.identity.find(tx.sender); + if (existing) return putPlayer(tx, existing); + const created = { + identity: tx.sender, + displayName: playerName(tx.sender), + color: playerColor(tx.sender), + contributedEnergy: 0n, + taps: 0, + surges: 0, + coolantUses: 0, + upgradesBought: 0, + joinedAt: tx.timestamp, + updatedAt: tx.timestamp, + }; + tx.db.reactorPlayerState.insert(created); + return created; +} + +function putPlayer(tx: Tx, player: ReactorPlayerRow): ReactorPlayerRow { + const next = { ...player, updatedAt: tx.timestamp }; + tx.db.reactorPlayerState.identity.update(next); + return next; +} + +function ensureState(tx: Tx): ReactorStateRow { + ensurePlayer(tx); + const existing = tx.db.reactorRoomState.singleton.find(true); + if (existing) return existing; + const tuningBase = { + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + }; + const tuning = roomTuning(tuningBase, activeCrewCount(tx)); + const created = { + singleton: true, + energy: 0n, + reactorLevel: 1, + upgradeCount: 0, + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, + combo: 0, + bestCombo: 0, + heat: 0, + heatCapacity: tuning.heatCapacity, + coolingPerSecond: tuning.coolingPerSecond, + tapHeatGain: tuning.tapHeatGain, + overheated: false, + updatedAt: tx.timestamp, + }; + tx.db.reactorRoomState.insert(created); + return created; +} + +function putState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const next = { ...state, updatedAt: tx.timestamp }; + tx.db.reactorRoomState.singleton.update(next); + return next; +} + +function cooledState(tx: Tx, state: ReactorStateRow): ReactorStateRow { + const tuned = tunedState(tx, state); + const elapsedSeconds = Number( + (tx.timestamp.microsSinceUnixEpoch - tuned.updatedAt.microsSinceUnixEpoch) / + ONE_SECOND_MICROS + ); + if ( + elapsedSeconds <= 0 && + tuned.heat === state.heat && + tuned.heatCapacity === state.heatCapacity && + tuned.coolingPerSecond === state.coolingPerSecond && + tuned.tapHeatGain === state.tapHeatGain && + tuned.overheated === state.overheated + ) + return state; + + const heat = Math.max( + 0, + tuned.heat - Math.max(0, elapsedSeconds) * tuned.coolingPerSecond + ); + const overheated = tuned.overheated && heat > overheatRecoverAt(tuned); + if ( + heat === state.heat && + overheated === state.overheated && + tuned.heatCapacity === state.heatCapacity && + tuned.coolingPerSecond === state.coolingPerSecond && + tuned.tapHeatGain === state.tapHeatGain + ) + return state; + + return putState(tx, { + ...tuned, + heat, + overheated, + }); +} + +function currentState(tx: Tx): ReactorStateRow { + return cooledState(tx, ensureState(tx)); +} + +function pruneRateLimitEvents( + tx: Tx, + retainEvents: number, + pruneBatch: number +): number { + const total = Number(tx.db.rateLimitEvent.count()); + if (total <= retainEvents) return 0; + + const toDelete = Math.min(pruneBatch, total - retainEvents); + let deleted = 0; + for (const row of tx.db.rateLimitEvent.createdAt.filter(new Range())) { + if (deleted >= toDelete) break; + tx.db.rateLimitEvent.delete(row); + deleted++; + } + return deleted; +} + +function pruneReactorEvents(tx: Tx): void { + const rows = [...tx.db.reactorEvent.iter()].sort((a, b) => + a.id < b.id ? -1 : a.id > b.id ? 1 : 0 + ); + const extra = rows.length - DEFAULT_RETAIN_REACTOR_EVENTS; + if (extra <= 0) return; + for (let i = 0; i < extra; i++) tx.db.reactorEvent.delete(rows[i]); +} + +function toU32(name: string, value: number): number { + if (!Number.isInteger(value) || value <= 0 || value > 0xffff_ffff) { + throw new Error(`rate_limit.invalid_${name}`); + } + return value; +} + +function recordLimitHit( + tx: Tx, + args: { + scope: string; + key: string; + limit: number; + windowSeconds: number; + cost: number; + allowed: boolean; + used: number; + remaining: number; + retryAfterSeconds: number; + resetAt: Tx['timestamp']; + } +) { + tx.db.rateLimitEvent.insert({ + id: 0n, + scope: args.scope, + key: args.key, + allowed: args.allowed, + limit: args.limit, + used: args.used, + remaining: args.remaining, + retryAfterSeconds: args.retryAfterSeconds, + windowSeconds: args.windowSeconds, + cost: args.cost, + resetAt: args.resetAt, + createdAt: tx.timestamp, + }); +} + +function recordReactorEvent( + tx: Tx, + args: { + kind: string; + scope: string; + message: string; + allowed: boolean; + energyDelta?: bigint; + retryAfterSeconds?: number; + } +) { + const player = ensurePlayer(tx); + tx.db.reactorEvent.insert({ + id: 0n, + identity: tx.sender, + actorName: player.displayName, + actorColor: player.color, + kind: args.kind, + scope: args.scope, + message: args.message, + allowed: args.allowed, + energyDelta: args.energyDelta ?? 0n, + retryAfterSeconds: args.retryAfterSeconds ?? 0, + createdAt: tx.timestamp, + }); + pruneReactorEvents(tx); +} + +function consumeAction( + tx: Tx, + scope: string, + actorKey: string, + limit: number, + windowSeconds: number, + cost = 1 +) { + return rateLimit.consumeRateLimit(tx.as.rateLimit, { + key: rateLimit.buildRateLimitKey(scope, actorKey), + scope, + limit, + windowSeconds, + cost, + }); +} + +function emptyActionResult(tx: Tx, action: string, message: string) { + const state = currentState(tx); + return { + allowed: true, + action, + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; +} + +export const init = spacetimedb.init(ctx => { + rateLimit.installRateLimit(ctx.as.rateLimit); + if (ctx.db.rateLimitDemoConfig.singleton.find(true) == null) { + ctx.db.rateLimitDemoConfig.insert({ + singleton: true, + retainEvents: DEFAULT_RETAIN_EVENTS, + eventPruneBatch: DEFAULT_EVENT_PRUNE_BATCH, + updatedAt: ctx.timestamp, + }); + } + if (ctx.db.rateLimitDemoSweepTick.count() === 0n) { + ctx.db.rateLimitDemoSweepTick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(30n * ONE_SECOND_MICROS), + }); + } +}); + +export const reactorState = spacetimedb.view( + { name: 'reactor_state', public: true }, + t.array(reactorRoomState.rowType), + ctx => { + const row = ctx.db.reactorRoomState.singleton.find(true); + return row ? [row] : []; + } +); + +export const reactorEvents = spacetimedb.view( + { name: 'reactor_events', public: true }, + t.array(reactorEvent.rowType), + ctx => + [...ctx.db.reactorEvent.iter()] + .sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0)) + .slice(0, DEFAULT_RETAIN_REACTOR_EVENTS) +); + +export const reactorPlayers = spacetimedb.view( + { name: 'reactor_players', public: true }, + t.array(reactorPlayer), + ctx => + [...ctx.db.reactorPlayerState.iter()] + .sort((a, b) => { + if (a.contributedEnergy === b.contributedEnergy) + return a.displayName.localeCompare(b.displayName); + return a.contributedEnergy < b.contributedEnergy ? 1 : -1; + }) + .slice(0, 16) +); + +export const reactorLimitStatus = spacetimedb.view( + { name: 'reactor_limit_status', public: true }, + t.array(reactorLimitStatusRow), + ctx => { + const state = ctx.db.reactorRoomState.singleton.find(true); + const tapLimit = state ? tapLimitForState(state) : TAP_LIMIT; + const upgradeWindowSeconds = upgradeWindowForState(state); + const specs = [ + { + scope: TAP_SCOPE, + label: 'Tap Coils', + limit: tapLimit, + windowSeconds: TAP_WINDOW_SECONDS, + }, + { + scope: OVERCHARGE_SCOPE, + label: 'Overcharger', + limit: OVERCHARGE_LIMIT, + windowSeconds: OVERCHARGE_WINDOW_SECONDS, + }, + { + scope: UPGRADE_SCOPE, + label: 'Upgrade Bay', + limit: UPGRADE_LIMIT, + windowSeconds: upgradeWindowSeconds, + }, + { + scope: REPAIR_SCOPE, + label: 'Repair Drones', + limit: REPAIR_LIMIT, + windowSeconds: REPAIR_WINDOW_SECONDS, + }, + ]; + return specs.map(spec => { + const key = limitKeyForScope(spec.scope, ctx); + const bucket = ctx.db.rateLimit.rateLimitBucket.key.find( + bucketKey(spec.scope, key) + ); + const used = Number(bucket?.count ?? 0); + return { + ...spec, + used, + remaining: clampU32(spec.limit - used), + resetAt: bucket?.expiresAt, + }; + }); + } +); + +export const reactorShop = spacetimedb.view( + { name: 'reactor_shop', public: true }, + t.array(reactorShopItem), + ctx => { + const state = ctx.db.reactorRoomState.singleton.find(true); + const base = state ?? { + powerUpgradeCount: 0, + coolingUpgradeCount: 0, + capacityUpgradeCount: 0, + chargeUpgradeCount: 0, + bayUpgradeCount: 0, + }; + return (['power', 'cooling', 'capacity', 'charges', 'bay'] as const).map( + lane => { + const offer = upgradeOffer(base, lane); + return { + slot: offer.slot, + id: offer.id, + name: offer.name, + description: offer.description, + effect: offer.effect, + cost: offer.cost, + available: true, + }; + } + ); + } +); + +export const rateLimitEventsAdmin = spacetimedb.view( + { name: 'rate_limit_events_admin', public: true }, + t.array(rateLimitEvent.rowType), + ctx => + isAdmin(ctx) + ? takeRows(ctx.db.rateLimitEvent.iter(), ADMIN_EVENT_VIEW_LIMIT) + : [] +); + +export const startReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let out: ReturnType | null = null; + ctx.withTx(tx => { + ensurePlayer(tx); + out = emptyActionResult(tx, 'start', 'Reactor online.'); + }); + if (!out) throw new Error('reactor.start_tx_failed'); + return out; + } +); + +export const tapReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const tapLimit = tapLimitForState(currentState(tx)); + const result = consumeAction( + tx, + TAP_SCOPE, + key, + tapLimit, + TAP_WINDOW_SECONDS + ); + recordLimitHit(tx, { + ...result, + limit: tapLimit, + windowSeconds: TAP_WINDOW_SECONDS, + cost: 1, + }); + const state = currentState(tx); + if (!result.allowed) { + const next = putState(tx, { + ...state, + combo: 0, + }); + const message = `Tap coils cooling for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'tap_rate_limited', + scope: TAP_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'tap', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + if (state.overheated) { + const message = 'Core is overheated.'; + recordReactorEvent(tx, { + kind: 'tap_heat_blocked', + scope: TAP_SCOPE, + message, + allowed: false, + }); + out = { + allowed: false, + action: 'tap', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + return; + } + + const gain = BigInt(state.reactorLevel); + const player = ensurePlayer(tx); + const combo = clampU32(state.combo + 1); + const heat = clampU32( + state.heat + state.tapHeatGain, + 0, + state.heatCapacity + ); + const next = putState(tx, { + ...state, + energy: state.energy + gain, + combo, + bestCombo: Math.max(state.bestCombo, combo), + heat, + overheated: heat >= state.heatCapacity, + }); + putPlayer(tx, { + ...player, + contributedEnergy: player.contributedEnergy + gain, + taps: clampU32(player.taps + 1), + }); + const message = + heat >= state.heatCapacity + ? 'Energy gained, but the core overheated.' + : `+${gain.toString()} energy.`; + recordReactorEvent(tx, { + kind: heat >= state.heatCapacity ? 'tap_overheated' : 'tap', + scope: TAP_SCOPE, + message, + allowed: true, + energyDelta: gain, + }); + out = { + allowed: true, + action: 'tap', + message, + energy: next.energy, + energyDelta: gain, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.tap_tx_failed'); + return out; + } +); + +export const overcharge = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let locked: { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: Tx['timestamp']; + } | null = null; + ctx.withTx(tx => { + const state = currentState(tx); + if (hasSurgeBurst(state)) return; + const message = `Install Plasma Coils level ${SURGE_UNLOCK_LEVEL} to unlock Surge Burst.`; + recordReactorEvent(tx, { + kind: 'system_locked', + scope: OVERCHARGE_SCOPE, + message, + allowed: false, + }); + locked = { + allowed: false, + action: 'overcharge', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; + }); + if (locked) return locked; + + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const result = consumeAction( + tx, + OVERCHARGE_SCOPE, + key, + OVERCHARGE_LIMIT, + OVERCHARGE_WINDOW_SECONDS + ); + recordLimitHit(tx, { + ...result, + windowSeconds: OVERCHARGE_WINDOW_SECONDS, + cost: 1, + }); + const state = currentState(tx); + if (!result.allowed || state.overheated) { + const message = result.allowed + ? 'Core is still cooling from the last overheat.' + : `Surge vents cooling down for ${result.retryAfterSeconds}s.`; + const next = putState(tx, { + ...state, + combo: 0, + overheated: state.overheated, + }); + recordReactorEvent(tx, { + kind: 'overcharge_blocked', + scope: OVERCHARGE_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'overcharge', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + + const gain = BigInt(state.reactorLevel * 10); + const player = ensurePlayer(tx); + const surgeHeat = Math.max(28, Math.floor(state.heatCapacity * 0.25)); + const heat = clampU32(state.heat + surgeHeat, 0, state.heatCapacity); + const combo = clampU32(state.combo + 3); + const next = putState(tx, { + ...state, + energy: state.energy + gain, + combo, + bestCombo: Math.max(state.bestCombo, combo), + heat, + overheated: heat >= state.heatCapacity, + }); + putPlayer(tx, { + ...player, + contributedEnergy: player.contributedEnergy + gain, + surges: clampU32(player.surges + 1), + }); + const message = + heat >= state.heatCapacity + ? `Surge Burst yielded +${gain.toString()} and blew the safeties.` + : `Surge Burst yielded +${gain.toString()} energy.`; + recordReactorEvent(tx, { + kind: + heat >= state.heatCapacity ? 'overcharge_overheated' : 'overcharge', + scope: OVERCHARGE_SCOPE, + message, + allowed: true, + energyDelta: gain, + }); + out = { + allowed: true, + action: 'overcharge', + message, + energy: next.energy, + energyDelta: gain, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.overcharge_tx_failed'); + return out; + } +); + +export const buyUpgrade = spacetimedb.procedure( + { upgradeId: t.string() }, + reactorActionResult, + (ctx, args) => { + const lane = requireUpgradeLane(args.upgradeId); + const key = limitKeyForScope(UPGRADE_SCOPE, ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const upgradeWindowSeconds = upgradeWindowForState( + tx.db.reactorRoomState.singleton.find(true) + ); + const result = consumeAction( + tx, + UPGRADE_SCOPE, + key, + UPGRADE_LIMIT, + upgradeWindowSeconds + ); + recordLimitHit(tx, { + ...result, + windowSeconds: upgradeWindowSeconds, + cost: 1, + }); + const state = currentState(tx); + const offer = upgradeOffer(state, lane); + const cost = offer.cost; + if (!result.allowed) { + const message = `Upgrade bay cooling down for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'upgrade_blocked', + scope: UPGRADE_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'upgrade', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + if (state.energy < cost) { + const message = `Need ${cost.toString()} energy for ${offer.name}.`; + recordReactorEvent(tx, { + kind: 'upgrade_insufficient_energy', + scope: UPGRADE_SCOPE, + message, + allowed: false, + }); + out = { + allowed: false, + action: 'upgrade', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + return; + } + + const player = ensurePlayer(tx); + const upgradeCount = clampU32(state.upgradeCount + 1); + const powerUpgradeCount = + lane === 'power' + ? clampU32(state.powerUpgradeCount + 1) + : state.powerUpgradeCount; + const coolingUpgradeCount = + lane === 'cooling' + ? clampU32(state.coolingUpgradeCount + 1) + : state.coolingUpgradeCount; + const capacityUpgradeCount = + lane === 'capacity' + ? clampU32(state.capacityUpgradeCount + 1) + : state.capacityUpgradeCount; + const chargeUpgradeCount = + lane === 'charges' + ? clampU32(state.chargeUpgradeCount + 1) + : state.chargeUpgradeCount; + const bayUpgradeCount = + lane === 'bay' + ? clampU32(state.bayUpgradeCount + 1) + : state.bayUpgradeCount; + const tuned = tunedState(tx, { + ...state, + upgradeCount, + powerUpgradeCount, + coolingUpgradeCount, + capacityUpgradeCount, + chargeUpgradeCount, + bayUpgradeCount, + reactorLevel: clampU32(1 + powerUpgradeCount * POWER_PER_UPGRADE), + }); + const next = putState(tx, { + ...tuned, + energy: state.energy - cost, + heat: Math.max(0, tuned.heat - 18), + overheated: false, + }); + putPlayer(tx, { + ...player, + upgradesBought: clampU32(player.upgradesBought + 1), + }); + const delta = -cost; + const message = `${offer.name} installed. ${offer.effect}.`; + recordReactorEvent(tx, { + kind: 'upgrade', + scope: UPGRADE_SCOPE, + message, + allowed: true, + energyDelta: delta, + }); + out = { + allowed: true, + action: 'upgrade', + message, + energy: next.energy, + energyDelta: delta, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.upgrade_tx_failed'); + return out; + } +); + +export const repairReactor = spacetimedb.procedure( + {}, + reactorActionResult, + ctx => { + let locked: { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: Tx['timestamp']; + } | null = null; + ctx.withTx(tx => { + const state = currentState(tx); + if (hasCoolantFlush(state)) return; + const message = `Install Thermal Vents level ${COOLANT_UNLOCK_LEVEL} to unlock Coolant Flush.`; + recordReactorEvent(tx, { + kind: 'system_locked', + scope: REPAIR_SCOPE, + message, + allowed: false, + }); + locked = { + allowed: false, + action: 'repair', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: tx.timestamp, + }; + }); + if (locked) return locked; + + const key = actorKey(ctx); + let out: ReturnType | null = null; + ctx.withTx(tx => { + const result = consumeAction( + tx, + REPAIR_SCOPE, + key, + REPAIR_LIMIT, + REPAIR_WINDOW_SECONDS + ); + recordLimitHit(tx, { + ...result, + windowSeconds: REPAIR_WINDOW_SECONDS, + cost: 1, + }); + const state = currentState(tx); + if (!result.allowed) { + const message = `Coolant system cooling down for ${result.retryAfterSeconds}s.`; + recordReactorEvent(tx, { + kind: 'repair_blocked', + scope: REPAIR_SCOPE, + message, + allowed: false, + retryAfterSeconds: result.retryAfterSeconds, + }); + out = { + allowed: false, + action: 'repair', + message, + energy: state.energy, + energyDelta: 0n, + retryAfterSeconds: result.retryAfterSeconds, + resetAt: result.resetAt, + }; + return; + } + + const next = putState(tx, { + ...state, + combo: 0, + heat: Math.max( + 0, + state.heat - Math.max(65, Math.floor(state.heatCapacity * 0.55)) + ), + overheated: false, + }); + const player = ensurePlayer(tx); + putPlayer(tx, { + ...player, + coolantUses: clampU32(player.coolantUses + 1), + }); + const message = 'Coolant flushed.'; + recordReactorEvent(tx, { + kind: 'repair', + scope: REPAIR_SCOPE, + message, + allowed: true, + }); + out = { + allowed: true, + action: 'repair', + message, + energy: next.energy, + energyDelta: 0n, + retryAfterSeconds: 0, + resetAt: result.resetAt, + }; + }); + if (!out) throw new Error('reactor.repair_tx_failed'); + return out; + } +); + +export const runSweep = spacetimedb.procedure( + { maxRows: t.option(t.u32()) }, + t.u32(), + (ctx, args) => { + const maxRows = + args.maxRows === undefined + ? undefined + : toU32('sweep_batch', Number(args.maxRows)); + const deleted = rateLimit.runSweep(ctx.as.rateLimit, { maxRows }); + ctx.withTx(tx => { + const demo = tx.db.rateLimitDemoConfig.singleton.find(true); + const retainEvents = Number(demo?.retainEvents ?? DEFAULT_RETAIN_EVENTS); + const pruneBatch = Number( + demo?.eventPruneBatch ?? DEFAULT_EVENT_PRUNE_BATCH + ); + pruneRateLimitEvents(tx, retainEvents, pruneBatch); + }); + return deleted; + } +); + +export const setPlayerColor = spacetimedb.reducer( + { color: t.string() }, + (ctx, args) => { + const color = requirePlayerColor(args.color); + const player = ensurePlayer(ctx); + putPlayer(ctx, { + ...player, + color, + }); + } +); + +export const resetDemo = spacetimedb.reducer({}, ctx => { + requireAdmin(ctx); + rateLimit.resetBuckets(ctx.as.rateLimit, {}); + for (const row of ctx.db.rateLimitEvent.iter()) + ctx.db.rateLimitEvent.delete(row); + for (const row of ctx.db.reactorEvent.iter()) ctx.db.reactorEvent.delete(row); + for (const row of ctx.db.reactorPlayerState.iter()) + ctx.db.reactorPlayerState.delete(row); + for (const row of ctx.db.reactorRoomState.iter()) + ctx.db.reactorRoomState.delete(row); +}); + +export const updateConfig = spacetimedb.reducer( + { + sweepBatch: t.option(t.u32()), + retainEvents: t.option(t.u32()), + eventPruneBatch: t.option(t.u32()), + }, + (ctx, args) => { + requireAdmin(ctx); + if (args.sweepBatch !== undefined) { + rateLimit.updateConfig(ctx.as.rateLimit, { + sweepBatch: toU32('sweep_batch', Number(args.sweepBatch)), + }); + } + if (args.retainEvents !== undefined || args.eventPruneBatch !== undefined) { + const demo = ctx.db.rateLimitDemoConfig.singleton.find(true); + if (!demo) throw new Error('rate_limit.demo_config_missing'); + ctx.db.rateLimitDemoConfig.singleton.update({ + ...demo, + retainEvents: + args.retainEvents === undefined + ? demo.retainEvents + : toU32('retain_events', Number(args.retainEvents)), + eventPruneBatch: + args.eventPruneBatch === undefined + ? demo.eventPruneBatch + : toU32('event_prune_batch', Number(args.eventPruneBatch)), + updatedAt: ctx.timestamp, + }); + } + } +); + +export const rateLimitDemoSweep = spacetimedb.reducer( + { onSchedule: rateLimitDemoSweepTick }, + { arg: rateLimitDemoSweepTick.rowType }, + (ctx, _args) => { + const demo = ctx.db.rateLimitDemoConfig.singleton.find(true); + const retainEvents = Number(demo?.retainEvents ?? DEFAULT_RETAIN_EVENTS); + const pruneBatch = Number( + demo?.eventPruneBatch ?? DEFAULT_EVENT_PRUNE_BATCH + ); + pruneRateLimitEvents(ctx, retainEvents, pruneBatch); + } +); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts new file mode 100644 index 00000000000..bf9e2bf316c --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/model.ts @@ -0,0 +1,74 @@ +import { table, t } from 'spacetimedb/server'; + +export const rateLimitEvent = table( + { name: 'rate_limit_event', public: false }, + { + id: t.u64().primaryKey().autoInc(), + scope: t.string().index(), + key: t.string(), + allowed: t.bool().index(), + limit: t.u32(), + used: t.u32(), + remaining: t.u32(), + retryAfterSeconds: t.u32(), + windowSeconds: t.u32(), + cost: t.u32(), + resetAt: t.timestamp(), + createdAt: t.timestamp().index(), + } +); +export const reactorRoomState = table( + { name: 'reactor_room_state', public: false }, + { + singleton: t.bool().primaryKey(), + energy: t.u64(), + reactorLevel: t.u32(), + upgradeCount: t.u32(), + powerUpgradeCount: t.u32(), + coolingUpgradeCount: t.u32(), + capacityUpgradeCount: t.u32(), + chargeUpgradeCount: t.u32(), + bayUpgradeCount: t.u32(), + combo: t.u32(), + bestCombo: t.u32(), + heat: t.u32(), + heatCapacity: t.u32(), + coolingPerSecond: t.u32(), + tapHeatGain: t.u32(), + overheated: t.bool(), + updatedAt: t.timestamp(), + } +); + +export const reactorPlayerState = table( + { name: 'reactor_player_state', public: false }, + { + identity: t.identity().primaryKey(), + displayName: t.string(), + color: t.string(), + contributedEnergy: t.u64(), + taps: t.u32(), + surges: t.u32(), + coolantUses: t.u32(), + upgradesBought: t.u32(), + joinedAt: t.timestamp(), + updatedAt: t.timestamp().index(), + } +); + +export const reactorEvent = table( + { name: 'reactor_event', public: false }, + { + id: t.u64().primaryKey().autoInc(), + identity: t.identity().index(), + actorName: t.string(), + actorColor: t.string(), + kind: t.string().index(), + scope: t.string(), + message: t.string(), + allowed: t.bool().index(), + energyDelta: t.i64(), + retryAfterSeconds: t.u32(), + createdAt: t.timestamp().index(), + } +); diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts new file mode 100644 index 00000000000..5288a4ae8bc --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/reactor-rules.ts @@ -0,0 +1,216 @@ +export const TAP_LIMIT = 8; +export const UPGRADE_WINDOW_SECONDS = 20; +export const COOLANT_UNLOCK_LEVEL = 2; +export const SURGE_UNLOCK_LEVEL = 2; + +const BASE_HEAT_CAPACITY = 100; +const BASE_HEAT_COOL_PER_SECOND = 4; +const BASE_TAP_HEAT_GAIN = 12; +const MAX_CREW_SCALING = 6; +const HEAT_CAPACITY_PER_EXTRA_CREW = 75; +const COOLING_PER_EXTRA_CREW = 4; +const POWER_UPGRADE_BASE_COST = 12; +const COOLING_UPGRADE_BASE_COST = 16; +const CAPACITY_UPGRADE_BASE_COST = 14; +const CHARGE_UPGRADE_BASE_COST = 18; +const BAY_UPGRADE_BASE_COST = 20; +const POWER_UPGRADE_COST_STEP = 18; +const COOLING_UPGRADE_COST_STEP = 18; +const CAPACITY_UPGRADE_COST_STEP = 20; +const CHARGE_UPGRADE_COST_STEP = 22; +const BAY_UPGRADE_COST_STEP = 24; +export const POWER_PER_UPGRADE = 1; +const COOLING_PER_UPGRADE = 2; +const CAPACITY_PER_UPGRADE = 30; +const CHARGES_PER_UPGRADE = 2; +const UPGRADE_WINDOW_REDUCTION_SECONDS = 3; +const MIN_UPGRADE_WINDOW_SECONDS = 5; + +export const PLAYER_COLORS = [ + '#22c7b8', + '#ffce5c', + '#52df8f', + '#ff6a66', + '#aee8ff', + '#d28cff', + '#ff9f6e', + '#8ddf65', +]; + +export type UpgradeLane = 'power' | 'cooling' | 'capacity' | 'charges' | 'bay'; + +export interface UpgradeState { + powerUpgradeCount: number; + coolingUpgradeCount: number; + capacityUpgradeCount: number; + chargeUpgradeCount: number; + bayUpgradeCount: number; +} + +export interface UpgradeOffer { + slot: number; + id: UpgradeLane; + name: string; + description: string; + effect: string; + cost: bigint; + level: number; +} + +function upgradeLevel(state: UpgradeState, lane: UpgradeLane): number { + if (lane === 'power') return Number(state.powerUpgradeCount); + if (lane === 'cooling') return Number(state.coolingUpgradeCount); + if (lane === 'charges') return Number(state.chargeUpgradeCount); + if (lane === 'bay') return Number(state.bayUpgradeCount); + return Number(state.capacityUpgradeCount); +} + +function upgradeCost(lane: UpgradeLane, level: number): bigint { + if (lane === 'power') + return BigInt(POWER_UPGRADE_BASE_COST + level * POWER_UPGRADE_COST_STEP); + if (lane === 'cooling') + return BigInt( + COOLING_UPGRADE_BASE_COST + level * COOLING_UPGRADE_COST_STEP + ); + if (lane === 'charges') + return BigInt(CHARGE_UPGRADE_BASE_COST + level * CHARGE_UPGRADE_COST_STEP); + if (lane === 'bay') + return BigInt(BAY_UPGRADE_BASE_COST + level * BAY_UPGRADE_COST_STEP); + return BigInt( + CAPACITY_UPGRADE_BASE_COST + level * CAPACITY_UPGRADE_COST_STEP + ); +} + +export function upgradeWindowForState( + state: Pick | null | undefined +): number { + const level = Number(state?.bayUpgradeCount ?? 0); + return Math.max( + MIN_UPGRADE_WINDOW_SECONDS, + UPGRADE_WINDOW_SECONDS - level * UPGRADE_WINDOW_REDUCTION_SECONDS + ); +} + +export function upgradeOffer( + state: UpgradeState, + lane: UpgradeLane +): UpgradeOffer { + const level = upgradeLevel(state, lane); + if (lane === 'power') { + return { + slot: 0, + id: lane, + name: 'Plasma Coils', + description: + level + 1 === SURGE_UNLOCK_LEVEL + ? 'More tap energy. Unlocks Surge Burst.' + : level >= SURGE_UNLOCK_LEVEL + ? 'More tap energy. Stronger surges.' + : 'More energy per tap.', + effect: `+${POWER_PER_UPGRADE} energy per tap${level + 1 === SURGE_UNLOCK_LEVEL ? ' + unlock Surge Burst' : ''}`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'cooling') { + return { + slot: 1, + id: lane, + name: 'Thermal Vents', + description: + level + 1 === COOLANT_UNLOCK_LEVEL + ? 'Faster cooling. Unlocks Coolant Flush.' + : level >= COOLANT_UNLOCK_LEVEL + ? 'Faster cooling. Quicker Coolant recharge.' + : 'Faster passive cooling.', + effect: `+${COOLING_PER_UPGRADE} cooling / sec${level + 1 === COOLANT_UNLOCK_LEVEL ? ' + unlock Coolant Flush' : ''}`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'charges') { + return { + slot: 3, + id: lane, + name: 'Tap Batteries', + description: 'More taps before a recharge.', + effect: `+${CHARGES_PER_UPGRADE} tap charges`, + cost: upgradeCost(lane, level), + level, + }; + } + if (lane === 'bay') { + return { + slot: 4, + id: lane, + name: 'Upgrade Bay', + description: 'Shorter cooldown between installs.', + effect: `-${UPGRADE_WINDOW_REDUCTION_SECONDS}s shop cooldown`, + cost: upgradeCost(lane, level), + level, + }; + } + return { + slot: 2, + id: lane, + name: 'Heat Sinks', + description: 'More heat before the core overheats.', + effect: `+${CAPACITY_PER_UPGRADE} heat capacity`, + cost: upgradeCost(lane, level), + level, + }; +} + +export function tapLimitForState( + state: Pick +): number { + return TAP_LIMIT + Number(state.chargeUpgradeCount) * CHARGES_PER_UPGRADE; +} + +export function hasCoolantFlush( + state: Pick +): boolean { + return state.coolingUpgradeCount >= COOLANT_UNLOCK_LEVEL; +} + +export function hasSurgeBurst( + state: Pick +): boolean { + return state.powerUpgradeCount >= SURGE_UNLOCK_LEVEL; +} + +export function overheatRecoverAt(state: { heatCapacity: number }): number { + return Math.floor(state.heatCapacity * 0.45); +} + +export function roomTuning( + state: Pick, + activeCrew: number +): { heatCapacity: number; coolingPerSecond: number; tapHeatGain: number } { + const crew = Math.max(1, Math.min(MAX_CREW_SCALING, Math.trunc(activeCrew))); + const clampU32 = (value: number) => + Math.max(0, Math.min(0xffff_ffff, Math.trunc(value))); + return { + heatCapacity: clampU32( + BASE_HEAT_CAPACITY + + Number(state.capacityUpgradeCount) * CAPACITY_PER_UPGRADE + + Math.max(0, crew - 1) * HEAT_CAPACITY_PER_EXTRA_CREW + ), + coolingPerSecond: clampU32( + BASE_HEAT_COOL_PER_SECOND + + Number(state.coolingUpgradeCount) * COOLING_PER_UPGRADE + + Math.max(0, crew - 1) * COOLING_PER_EXTRA_CREW + ), + tapHeatGain: BASE_TAP_HEAT_GAIN, + }; +} + +export function playerName(identity: { toHexString(): string }): string { + return `Crewmate ${identity.toHexString().slice(0, 6).toUpperCase()}`; +} + +export function playerColor(identity: { toHexString(): string }): string { + const hex = identity.toHexString().slice(-8); + const index = Number.parseInt(hex, 16) % PLAYER_COLORS.length; + return PLAYER_COLORS[index]!; +} diff --git a/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts b/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts new file mode 100644 index 00000000000..0e8d8e1e93a --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/src/schema.ts @@ -0,0 +1,52 @@ +import * as rateLimit from '@spacetimedb/rate-limit/submodule'; +import { + schema, + table, + t, + type InferSchema, + type ReducerCtx, +} from 'spacetimedb/server'; +import { + rateLimitEvent, + reactorEvent, + reactorPlayerState, + reactorRoomState, +} from './model'; + +export { + rateLimitEvent, + reactorEvent, + reactorPlayerState, + reactorRoomState, +} from './model'; + +export const rateLimitDemoConfig = table( + { name: 'rate_limit_demo_config', public: true }, + { + singleton: t.bool().primaryKey(), + retainEvents: t.u32(), + eventPruneBatch: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitDemoSweepTick = table( + { name: 'rate_limit_demo_sweep_tick' }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + } +); + +export const spacetimedb = schema({ + rateLimit, + rateLimitEvent, + reactorRoomState, + reactorPlayerState, + reactorEvent, + rateLimitDemoConfig, + rateLimitDemoSweepTick, +}); + +export type Schema = InferSchema; +export type Tx = ReducerCtx; diff --git a/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json b/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..48cc3989f52 --- /dev/null +++ b/spacetime-rate-limit-ts/example/spacetimedb/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/example/src/app.ts b/spacetime-rate-limit-ts/example/src/app.ts new file mode 100644 index 00000000000..817eccd57df --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/app.ts @@ -0,0 +1,436 @@ +import { + DbConnection, + tables, + type ErrorContext, + type EventContext, +} from './module_bindings/app/index.ts'; + +type TimestampLike = { microsSinceUnixEpoch: bigint }; + +type ReactorState = { + singleton: boolean; + energy: bigint; + reactorLevel: number; + upgradeCount: number; + powerUpgradeCount: number; + coolingUpgradeCount: number; + capacityUpgradeCount: number; + chargeUpgradeCount: number; + bayUpgradeCount: number; + combo: number; + bestCombo: number; + heat: number; + heatCapacity: number; + coolingPerSecond: number; + tapHeatGain: number; + overheated: boolean; + updatedAt: TimestampLike; +}; + +type ReactorEvent = { + id: bigint; + identity: unknown; + actorName: string; + actorColor: string; + kind: string; + scope: string; + message: string; + allowed: boolean; + energyDelta: bigint; + retryAfterSeconds: number; + createdAt: TimestampLike; +}; + +type ReactorPlayer = { + identity: unknown; + displayName: string; + color: string; + contributedEnergy: bigint; + taps: number; + surges: number; + coolantUses: number; + upgradesBought: number; + joinedAt: TimestampLike; + updatedAt: TimestampLike; +}; + +type ReactorLimitStatus = { + scope: string; + label: string; + limit: number; + windowSeconds: number; + used: number; + remaining: number; + resetAt?: TimestampLike; +}; + +type ReactorShopItem = { + slot: number; + id: string; + name: string; + description: string; + effect: string; + cost: bigint; + available: boolean; +}; + +type RateLimitDemoConfig = { + singleton: boolean; + retainEvents: number; + eventPruneBatch: number; + updatedAt: TimestampLike; +}; + +type ReactorActionResult = { + allowed: boolean; + action: string; + message: string; + energy: bigint; + energyDelta: bigint; + retryAfterSeconds: number; + resetAt: TimestampLike; +}; + +type ReactorActions = { + start: () => Promise; + tap: () => Promise; + overcharge: () => Promise; + buyUpgrade: (upgradeId: string) => Promise; + repair: () => Promise; + setPlayerColor: (color: string) => Promise; + runSweep: (maxRows?: number) => Promise; + resetDemo: () => Promise; + updateConfig: (args: { + sweepBatch?: number; + retainEvents?: number; + eventPruneBatch?: number; + }) => Promise; +}; + +declare global { + interface Window { + reactor?: ReactorActions; + } +} + +interface ServerConfig { + spacetimeUri: string; + databaseName: string; +} + +type TableEvents = { + iter(): Iterable; + onInsert(cb: (ctx: EventContext, row: T) => void): void; + onUpdate(cb: (ctx: EventContext, old: T, row: T) => void): void; + onDelete(cb: (ctx: EventContext, row: T) => void): void; +}; + +type SingletonTable = { + singleton: { find(key: boolean): T | null | undefined }; + onInsert(cb: (ctx: EventContext, row: T) => void): void; + onUpdate(cb: (ctx: EventContext, old: T, row: T) => void): void; + onDelete?(cb: (ctx: EventContext, row: T) => void): void; +}; + +type NamespacedDb = DbConnection['db'] & { + reactorState: TableEvents; + reactorEvents: TableEvents; + reactorLimitStatus: TableEvents; + reactorPlayers: TableEvents; + reactorShop: TableEvents; + rateLimitDemoConfig: SingletonTable; +}; + +let currentConn: DbConnection | null = null; +let reconnectTimer: ReturnType | null = null; +let reconnectAttempt = 0; +let serverConfig: ServerConfig | null = null; +let currentIdentityHex: string | null = null; + +const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 10000, 15000]; +const CONNECT_TIMEOUT_MS = 8000; +const TOKEN_STORAGE_PREFIX = 'reactor-clicker.stdb-token'; + +function emitConnectionState( + state: 'connecting' | 'connected' | 'error', + detail?: string +): void { + window.dispatchEvent( + new CustomEvent('reactor:connState', { detail: { state, detail } }) + ); +} + +function emitReactorState(): void { + if (!currentConn) { + window.dispatchEvent( + new CustomEvent('reactor:data', { + detail: { + state: null, + events: [], + players: [], + statuses: [], + shop: [], + demoConfig: null, + currentIdentityHex: null, + }, + }) + ); + return; + } + + const db = currentConn.db as NamespacedDb; + window.dispatchEvent( + new CustomEvent('reactor:data', { + detail: { + state: [...db.reactorState.iter()][0] ?? null, + events: [...db.reactorEvents.iter()].sort((a, b) => + a.id < b.id ? 1 : a.id > b.id ? -1 : 0 + ), + players: [...db.reactorPlayers.iter()].sort((a, b) => { + if (a.contributedEnergy === b.contributedEnergy) + return a.displayName.localeCompare(b.displayName); + return a.contributedEnergy < b.contributedEnergy ? 1 : -1; + }), + statuses: [...db.reactorLimitStatus.iter()].sort((a, b) => + a.label.localeCompare(b.label) + ), + shop: [...db.reactorShop.iter()].sort((a, b) => a.slot - b.slot), + demoConfig: db.rateLimitDemoConfig.singleton.find(true) ?? null, + currentIdentityHex, + }, + }) + ); +} + +function emitReactorEvent(row: ReactorEvent): void { + window.dispatchEvent( + new CustomEvent('reactor:eventInserted', { detail: { event: row } }) + ); +} + +async function loadServerConfig(): Promise { + const r = await fetch('/api/config'); + if (!r.ok) throw new Error(`/api/config returned ${r.status}`); + return (await r.json()) as ServerConfig; +} + +function isStoredTokenAuthError(err: unknown): boolean { + const message = err instanceof Error ? err.message : String(err); + return /unauthorized|verify token|websocket-token/i.test(message); +} + +function connectOnce( + cfg: ServerConfig, + tokenKey: string, + token?: string +): Promise { + return new Promise((resolve, reject) => { + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + reject(new Error('stdb.connect_timeout')); + }, CONNECT_TIMEOUT_MS); + const settle = (fn: () => void) => { + if (settled) return; + settled = true; + clearTimeout(timer); + fn(); + }; + + const builder = DbConnection.builder() + .withUri(cfg.spacetimeUri) + .withDatabaseName(cfg.databaseName) + .onConnect((conn, identity, nextToken) => + settle(() => { + currentIdentityHex = + typeof (identity as { toHexString?: () => string }).toHexString === + 'function' + ? (identity as { toHexString: () => string }).toHexString() + : String(identity); + window.localStorage.setItem(tokenKey, nextToken); + resolve(conn); + }) + ) + .onDisconnect((_ctx, err) => { + currentConn = null; + window.reactor = undefined; + emitConnectionState('error', err?.message ?? 'disconnected'); + scheduleReconnect(); + }) + .onConnectError((_ctx, err) => settle(() => reject(err))); + if (token) builder.withToken(token); + builder.build(); + }); +} + +async function connect(cfg: ServerConfig): Promise { + const tokenKey = `${TOKEN_STORAGE_PREFIX}.${cfg.spacetimeUri}.${cfg.databaseName}`; + const token = window.localStorage.getItem(tokenKey) ?? undefined; + try { + return await connectOnce(cfg, tokenKey, token); + } catch (err) { + if (token && isStoredTokenAuthError(err)) { + window.localStorage.removeItem(tokenKey); + return connectOnce(cfg, tokenKey); + } + throw err; + } +} + +function scheduleReconnect(): void { + if (reconnectTimer != null) return; + const delay = + RECONNECT_DELAYS_MS[ + Math.min(reconnectAttempt, RECONNECT_DELAYS_MS.length - 1) + ]; + reconnectTimer = setTimeout(() => { + reconnectTimer = null; + reconnectAttempt++; + main().catch(err => { + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + scheduleReconnect(); + }); + }, delay); +} + +type TableSyncState = { + subscriptionApplied: boolean; + seenEventIds: Set; +}; + +function subscribeToTables( + connection: DbConnection, + state: TableSyncState +): void { + const db = connection.db as NamespacedDb; + connection + .subscriptionBuilder() + .onApplied(() => { + for (const row of db.reactorEvents.iter()) { + state.seenEventIds.add(row.id.toString()); + } + state.subscriptionApplied = true; + emitReactorState(); + }) + .onError((ctx: ErrorContext) => + console.error('subscription error', ctx.event) + ) + .subscribe([ + tables.reactorState, + tables.reactorEvents, + tables.reactorLimitStatus, + tables.reactorPlayers, + tables.reactorShop, + tables.rateLimitDemoConfig, + ]); +} + +function registerRowCallbacks( + connection: DbConnection, + state: TableSyncState +): void { + const db = connection.db as NamespacedDb; + db.reactorState.onInsert(() => emitReactorState()); + db.reactorState.onUpdate(() => emitReactorState()); + db.reactorState.onDelete(() => emitReactorState()); + db.reactorEvents.onInsert((_ctx, row) => { + const id = row.id.toString(); + const isNewLiveEvent = + state.subscriptionApplied && !state.seenEventIds.has(id); + state.seenEventIds.add(id); + if (isNewLiveEvent) emitReactorEvent(row); + emitReactorState(); + }); + db.reactorEvents.onUpdate(() => emitReactorState()); + db.reactorEvents.onDelete(() => emitReactorState()); + db.reactorLimitStatus.onInsert(() => emitReactorState()); + db.reactorLimitStatus.onUpdate(() => emitReactorState()); + db.reactorLimitStatus.onDelete(() => emitReactorState()); + db.reactorPlayers.onInsert(() => emitReactorState()); + db.reactorPlayers.onUpdate(() => emitReactorState()); + db.reactorPlayers.onDelete(() => emitReactorState()); + db.reactorShop.onInsert(() => emitReactorState()); + db.reactorShop.onUpdate(() => emitReactorState()); + db.reactorShop.onDelete(() => emitReactorState()); + db.rateLimitDemoConfig.onInsert(() => emitReactorState()); + db.rateLimitDemoConfig.onUpdate(() => emitReactorState()); + db.rateLimitDemoConfig.onDelete?.(() => emitReactorState()); +} + +function requireConn(): DbConnection { + if (!currentConn) throw new Error('stdb.disconnected'); + return currentConn; +} + +function installReactorActions(): ReactorActions { + const actions: ReactorActions = { + start: async () => requireConn().procedures.startReactor({}), + tap: async () => requireConn().procedures.tapReactor({}), + overcharge: async () => requireConn().procedures.overcharge({}), + buyUpgrade: async (upgradeId: string) => + requireConn().procedures.buyUpgrade({ upgradeId }), + repair: async () => requireConn().procedures.repairReactor({}), + setPlayerColor: async (color: string) => { + requireConn().reducers.setPlayerColor({ color }); + }, + runSweep: async (maxRows?: number) => + requireConn().procedures.runSweep({ maxRows }), + resetDemo: async () => { + requireConn().reducers.resetDemo({}); + }, + updateConfig: async args => { + requireConn().reducers.updateConfig({ + sweepBatch: args.sweepBatch, + retainEvents: args.retainEvents, + eventPruneBatch: args.eventPruneBatch, + }); + }, + }; + window.reactor = actions; + return actions; +} + +async function main(): Promise { + window.reactor = undefined; + emitConnectionState('connecting'); + if (!serverConfig) { + serverConfig = await loadServerConfig(); + } + try { + const conn = await connect(serverConfig); + currentConn = conn; + reconnectAttempt = 0; + const tableSyncState: TableSyncState = { + subscriptionApplied: false, + seenEventIds: new Set(), + }; + registerRowCallbacks(conn, tableSyncState); + subscribeToTables(conn, tableSyncState); + const reactor = installReactorActions(); + window.dispatchEvent(new CustomEvent('reactor:ready')); + emitConnectionState('connected'); + reactor.start().catch((err: unknown) => { + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + }); + } catch (err) { + currentConn = null; + window.reactor = undefined; + throw err; + } +} + +main().catch(err => { + console.error('reactor connection failed', err); + emitConnectionState( + 'error', + err instanceof Error ? err.message : String(err) + ); + scheduleReconnect(); +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts new file mode 100644 index 00000000000..709e3a65208 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/buy_upgrade_procedure.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { + upgradeId: __t.string(), +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts new file mode 100644 index 00000000000..46da420fd5e --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/index.ts @@ -0,0 +1,257 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +// This was generated using spacetimedb cli version 2.10.1 (commit 5418e2f229c57f503d4306ae9e5fb6df29533f7d). + +/* eslint-disable */ +/* tslint:disable */ +import { + DbConnectionBuilder as __DbConnectionBuilder, + DbConnectionImpl as __DbConnectionImpl, + SubscriptionBuilderImpl as __SubscriptionBuilderImpl, + TypeBuilder as __TypeBuilder, + Uuid as __Uuid, + convertToAccessorMap as __convertToAccessorMap, + makeQueryBuilder as __makeQueryBuilder, + procedureSchema as __procedureSchema, + procedures as __procedures, + reducerSchema as __reducerSchema, + reducers as __reducers, + schema as __schema, + t as __t, + table as __table, + type AlgebraicTypeType as __AlgebraicTypeType, + type DbConnectionConfig as __DbConnectionConfig, + type ErrorContextInterface as __ErrorContextInterface, + type Event as __Event, + type EventContextInterface as __EventContextInterface, + type Infer as __Infer, + type QueryBuilder as __QueryBuilder, + type ReducerEventContextInterface as __ReducerEventContextInterface, + type RemoteModule as __RemoteModule, + type SubscriptionEventContextInterface as __SubscriptionEventContextInterface, + type SubscriptionHandleImpl as __SubscriptionHandleImpl, +} from "spacetimedb"; + +// Import all reducer arg schemas +import ResetDemoReducer from "./reset_demo_reducer"; +import SetPlayerColorReducer from "./set_player_color_reducer"; +import UpdateConfigReducer from "./update_config_reducer"; + +// Import all procedure arg schemas +import * as BuyUpgradeProcedure from "./buy_upgrade_procedure"; +import * as OverchargeProcedure from "./overcharge_procedure"; +import * as RepairReactorProcedure from "./repair_reactor_procedure"; +import * as RunSweepProcedure from "./run_sweep_procedure"; +import * as StartReactorProcedure from "./start_reactor_procedure"; +import * as TapReactorProcedure from "./tap_reactor_procedure"; + +// Import all table schema definitions +import RateLimitDemoConfigRow from "./rate_limit_demo_config_table"; +import RateLimitEventsAdminRow from "./rate_limit_events_admin_table"; +import ReactorEventsRow from "./reactor_events_table"; +import ReactorLimitStatusRow from "./reactor_limit_status_table"; +import ReactorPlayersRow from "./reactor_players_table"; +import ReactorShopRow from "./reactor_shop_table"; +import ReactorStateRow from "./reactor_state_table"; + +// Import namespace table schema definitions +import RateLimit_RateLimitConfigRow from "./rateLimit/rate_limit_config_table"; +import RateLimit_AdminRateLimitBucketsRow from "./rateLimit/admin_rate_limit_buckets_table"; + +// Import namespace reducer arg schemas +import RateLimit_AddRateLimitAdminReducer from "./rateLimit/add_rate_limit_admin_reducer"; +import RateLimit_ResetBucketsReducer from "./rateLimit/reset_buckets_reducer"; +import RateLimit_UpdateConfigReducer from "./rateLimit/update_config_reducer"; + +// Import namespace procedure arg schemas +import * as RateLimit_ConsumeProcedure from "./rateLimit/consume_procedure"; +import * as RateLimit_RunSweepProcedure from "./rateLimit/run_sweep_procedure"; + +/** Type-only namespace exports for generated type groups. */ + +/** The schema information for all tables in this module. This is defined the same was as the tables would have been defined in the server. */ +const tablesSchema = __schema({ + rateLimitDemoConfig: __table({ + name: 'rate_limit_demo_config', + indexes: [ + { accessor: 'singleton', name: 'rate_limit_demo_config_singleton_idx_btree', algorithm: 'btree', columns: [ + 'singleton', + ] }, + ], + constraints: [ + { name: 'rate_limit_demo_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, + ], + }, RateLimitDemoConfigRow), + rateLimitEventsAdmin: __table({ + name: 'rate_limit_events_admin', + indexes: [ + ], + constraints: [ + ], + }, RateLimitEventsAdminRow), + reactorEvents: __table({ + name: 'reactor_events', + indexes: [ + ], + constraints: [ + ], + }, ReactorEventsRow), + reactorLimitStatus: __table({ + name: 'reactor_limit_status', + indexes: [ + ], + constraints: [ + ], + }, ReactorLimitStatusRow), + reactorPlayers: __table({ + name: 'reactor_players', + indexes: [ + ], + constraints: [ + ], + }, ReactorPlayersRow), + reactorShop: __table({ + name: 'reactor_shop', + indexes: [ + ], + constraints: [ + ], + }, ReactorShopRow), + reactorState: __table({ + name: 'reactor_state', + indexes: [ + ], + constraints: [ + ], + }, ReactorStateRow), + "rateLimit.rate_limit_config": __table({ + name: 'rateLimit.rate_limit_config', + indexes: [ + { accessor: 'singleton', name: 'rate_limit_config_singleton_idx_btree', algorithm: 'btree', columns: [ + 'singleton', + ] }, + ], + constraints: [ + { name: 'rate_limit_config_singleton_key', constraint: 'unique', columns: ['singleton'] }, + ], + }, RateLimit_RateLimitConfigRow), + "rateLimit.admin_rate_limit_buckets": __table({ + name: 'rateLimit.admin_rate_limit_buckets', + indexes: [ + ], + constraints: [ + ], + }, RateLimit_AdminRateLimitBucketsRow), +}); + +/** The schema information for all reducers in this module. This is defined the same way as the reducers would have been defined in the server, except the body of the reducer is omitted in code generation. */ +const reducersSchema = __reducers( + __reducerSchema("reset_demo", ResetDemoReducer), + __reducerSchema("set_player_color", SetPlayerColorReducer), + __reducerSchema("update_config", UpdateConfigReducer), + __reducerSchema("rateLimit.add_rate_limit_admin", RateLimit_AddRateLimitAdminReducer), + __reducerSchema("rateLimit.reset_buckets", RateLimit_ResetBucketsReducer), + __reducerSchema("rateLimit.update_config", RateLimit_UpdateConfigReducer), +); + +/** The schema information for all procedures in this module. This is defined the same way as the procedures would have been defined in the server. */ +const proceduresSchema = __procedures( + __procedureSchema("buy_upgrade", BuyUpgradeProcedure.params, BuyUpgradeProcedure.returnType), + __procedureSchema("overcharge", OverchargeProcedure.params, OverchargeProcedure.returnType), + __procedureSchema("repair_reactor", RepairReactorProcedure.params, RepairReactorProcedure.returnType), + __procedureSchema("run_sweep", RunSweepProcedure.params, RunSweepProcedure.returnType), + __procedureSchema("start_reactor", StartReactorProcedure.params, StartReactorProcedure.returnType), + __procedureSchema("tap_reactor", TapReactorProcedure.params, TapReactorProcedure.returnType), + __procedureSchema("rateLimit.consume", RateLimit_ConsumeProcedure.params, RateLimit_ConsumeProcedure.returnType), + __procedureSchema("rateLimit.run_sweep", RateLimit_RunSweepProcedure.params, RateLimit_RunSweepProcedure.returnType), +); + +/** The remote SpacetimeDB module schema, both runtime and type information. */ +const REMOTE_MODULE = { + versionInfo: { + cliVersion: "2.10.1" as const, + }, + tables: tablesSchema.schemaType.tables, + reducers: reducersSchema.reducersType.reducers, + ...proceduresSchema, +} satisfies __RemoteModule< + typeof tablesSchema.schemaType, + typeof reducersSchema.reducersType, + typeof proceduresSchema +>; + +/** The tables available in this remote SpacetimeDB module. Each table reference doubles as a query builder. */ +const __qb = __makeQueryBuilder(tablesSchema.schemaType); +export const tables = { + rateLimitDemoConfig: __qb.rateLimitDemoConfig, + rateLimitEventsAdmin: __qb.rateLimitEventsAdmin, + reactorEvents: __qb.reactorEvents, + reactorLimitStatus: __qb.reactorLimitStatus, + reactorPlayers: __qb.reactorPlayers, + reactorShop: __qb.reactorShop, + reactorState: __qb.reactorState, + rateLimit: { + rateLimitConfig: __qb["rateLimit.rate_limit_config"], + adminRateLimitBuckets: __qb["rateLimit.admin_rate_limit_buckets"], + }, +} as const; + +/** The reducers available in this remote SpacetimeDB module. */ +const __reducerAccessors = __convertToAccessorMap(reducersSchema.reducersType.reducers); +export const reducers = { + resetDemo: __reducerAccessors.resetDemo, + setPlayerColor: __reducerAccessors.setPlayerColor, + updateConfig: __reducerAccessors.updateConfig, + rateLimit: { + addRateLimitAdmin: __reducerAccessors["rateLimit.addRateLimitAdmin"], + resetBuckets: __reducerAccessors["rateLimit.resetBuckets"], + updateConfig: __reducerAccessors["rateLimit.updateConfig"], + }, +} as const; + +/** The procedures available in this remote SpacetimeDB module. */ +const __procedureAccessors = __convertToAccessorMap(proceduresSchema.procedures); +export const procedures = { + buyUpgrade: __procedureAccessors.buyUpgrade, + overcharge: __procedureAccessors.overcharge, + repairReactor: __procedureAccessors.repairReactor, + runSweep: __procedureAccessors.runSweep, + startReactor: __procedureAccessors.startReactor, + tapReactor: __procedureAccessors.tapReactor, + rateLimit: { + consume: __procedureAccessors["rateLimit.consume"], + runSweep: __procedureAccessors["rateLimit.runSweep"], + }, +} as const; + +/** The context type returned in callbacks for all possible events. */ +export type EventContext = __EventContextInterface; +/** The context type returned in callbacks for reducer events. */ +export type ReducerEventContext = __ReducerEventContextInterface; +/** The context type returned in callbacks for subscription events. */ +export type SubscriptionEventContext = __SubscriptionEventContextInterface; +/** The context type returned in callbacks for error events. */ +export type ErrorContext = __ErrorContextInterface; +/** The subscription handle type to manage active subscriptions created from a {@link SubscriptionBuilder}. */ +export type SubscriptionHandle = __SubscriptionHandleImpl; + +/** Builder class to configure a new subscription to the remote SpacetimeDB instance. */ +export class SubscriptionBuilder extends __SubscriptionBuilderImpl {} + +/** Builder class to configure a new database connection to the remote SpacetimeDB instance. */ +export class DbConnectionBuilder extends __DbConnectionBuilder {} + +/** The typed database connection to manage connections to the remote SpacetimeDB instance. This class has type information specific to the generated module. */ +export class DbConnection extends __DbConnectionImpl { + /** Creates a new {@link DbConnectionBuilder} to configure and connect to the remote SpacetimeDB instance. */ + static builder = (): DbConnectionBuilder => { + return new DbConnectionBuilder(REMOTE_MODULE, (config: __DbConnectionConfig) => new DbConnection(config)); + }; + + /** Creates a new {@link SubscriptionBuilder} to configure a subscription to the remote SpacetimeDB instance. */ + override subscriptionBuilder = (): SubscriptionBuilder => { + return new SubscriptionBuilder(this); + }; +} + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/overcharge_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts new file mode 100644 index 00000000000..e39846ca8d9 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/add_rate_limit_admin_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + identity: __t.identity(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts new file mode 100644 index 00000000000..189f539a043 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/admin_rate_limit_buckets_table.ts @@ -0,0 +1,20 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + key: __t.string().primaryKey(), + scope: __t.string(), + windowStart: __t.timestamp().name("window_start"), + expiresAt: __t.timestamp().name("expires_at"), + count: __t.u32(), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts new file mode 100644 index 00000000000..a98b8588aad --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/consume_procedure.ts @@ -0,0 +1,24 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + RateLimitConsumeResult, +} from "./types"; + +export const params = { + scope: __t.string(), + actorKey: __t.string(), + limit: __t.u32(), + windowSeconds: __t.u32(), + cost: __t.option(__t.u32()), +}; +export const returnType = RateLimitConsumeResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts new file mode 100644 index 00000000000..66ffe86e399 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/rate_limit_config_table.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + sweepBatch: __t.u32().name("sweep_batch"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts new file mode 100644 index 00000000000..a7c5cc5274f --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/reset_buckets_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + maxRows: __t.option(__t.u32()), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/run_sweep_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + maxRows: __t.option(__t.u32()), +}; +export const returnType = __t.u32() \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts new file mode 100644 index 00000000000..151a90e827f --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/types.ts @@ -0,0 +1,56 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const AdminRateLimitBuckets = __t.object("AdminRateLimitBuckets", {}); +export type AdminRateLimitBuckets = __Infer; + +export const RateLimitAdminIdentity = __t.object("RateLimitAdminIdentity", { + identity: __t.identity(), + addedAtMicros: __t.i64(), +}); +export type RateLimitAdminIdentity = __Infer; + +export const RateLimitBucket = __t.object("RateLimitBucket", { + key: __t.string(), + scope: __t.string(), + windowStart: __t.timestamp(), + expiresAt: __t.timestamp(), + count: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitBucket = __Infer; + +export const RateLimitConfig = __t.object("RateLimitConfig", { + singleton: __t.bool(), + sweepBatch: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitConfig = __Infer; + +export const RateLimitConsumeResult = __t.object("RateLimitConsumeResult", { + allowed: __t.bool(), + scope: __t.string(), + key: __t.string(), + limit: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + retryAfterSeconds: __t.u32(), + resetAt: __t.timestamp(), +}); +export type RateLimitConsumeResult = __Infer; + +export const RateLimitSweepTick = __t.object("RateLimitSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitSweepTick = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts new file mode 100644 index 00000000000..54fcf361af1 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rateLimit/update_config_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + sweepBatch: __t.u32(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts new file mode 100644 index 00000000000..bcb7aa20309 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_demo_config_table.ts @@ -0,0 +1,18 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + retainEvents: __t.u32().name("retain_events"), + eventPruneBatch: __t.u32().name("event_prune_batch"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts new file mode 100644 index 00000000000..d6d861cbb6f --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/rate_limit_events_admin_table.ts @@ -0,0 +1,26 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + scope: __t.string(), + key: __t.string(), + allowed: __t.bool(), + limit: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + retryAfterSeconds: __t.u32().name("retry_after_seconds"), + windowSeconds: __t.u32().name("window_seconds"), + cost: __t.u32(), + resetAt: __t.timestamp().name("reset_at"), + createdAt: __t.timestamp().name("created_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts new file mode 100644 index 00000000000..207ec768f97 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_events_table.ts @@ -0,0 +1,25 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + id: __t.u64().primaryKey(), + identity: __t.identity(), + actorName: __t.string().name("actor_name"), + actorColor: __t.string().name("actor_color"), + kind: __t.string(), + scope: __t.string(), + message: __t.string(), + allowed: __t.bool(), + energyDelta: __t.i64().name("energy_delta"), + retryAfterSeconds: __t.u32().name("retry_after_seconds"), + createdAt: __t.timestamp().name("created_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts new file mode 100644 index 00000000000..fc9f0392d1e --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_limit_status_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + scope: __t.string(), + label: __t.string(), + limit: __t.u32(), + windowSeconds: __t.u32().name("window_seconds"), + used: __t.u32(), + remaining: __t.u32(), + resetAt: __t.option(__t.timestamp()).name("reset_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts new file mode 100644 index 00000000000..e9c658484b7 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_players_table.ts @@ -0,0 +1,24 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + identity: __t.identity(), + displayName: __t.string().name("display_name"), + color: __t.string(), + contributedEnergy: __t.u64().name("contributed_energy"), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32().name("coolant_uses"), + upgradesBought: __t.u32().name("upgrades_bought"), + joinedAt: __t.timestamp().name("joined_at"), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts new file mode 100644 index 00000000000..5a0217589e6 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_shop_table.ts @@ -0,0 +1,21 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + slot: __t.u32(), + id: __t.string(), + name: __t.string(), + description: __t.string(), + effect: __t.string(), + cost: __t.u64(), + available: __t.bool(), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts new file mode 100644 index 00000000000..422838dd710 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reactor_state_table.ts @@ -0,0 +1,31 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default __t.row({ + singleton: __t.bool().primaryKey(), + energy: __t.u64(), + reactorLevel: __t.u32().name("reactor_level"), + upgradeCount: __t.u32().name("upgrade_count"), + powerUpgradeCount: __t.u32().name("power_upgrade_count"), + coolingUpgradeCount: __t.u32().name("cooling_upgrade_count"), + capacityUpgradeCount: __t.u32().name("capacity_upgrade_count"), + chargeUpgradeCount: __t.u32().name("charge_upgrade_count"), + bayUpgradeCount: __t.u32().name("bay_upgrade_count"), + combo: __t.u32(), + bestCombo: __t.u32().name("best_combo"), + heat: __t.u32(), + heatCapacity: __t.u32().name("heat_capacity"), + coolingPerSecond: __t.u32().name("cooling_per_second"), + tapHeatGain: __t.u32().name("tap_heat_gain"), + overheated: __t.bool(), + updatedAt: __t.timestamp().name("updated_at"), +}); diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/repair_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts new file mode 100644 index 00000000000..e18fbc0a086 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/reset_demo_reducer.ts @@ -0,0 +1,13 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default {}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts new file mode 100644 index 00000000000..9815c99eb38 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/run_sweep_procedure.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const params = { + maxRows: __t.option(__t.u32()), +}; +export const returnType = __t.u32() \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts new file mode 100644 index 00000000000..42ec3238c75 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/set_player_color_reducer.ts @@ -0,0 +1,15 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + color: __t.string(), +}; diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/start_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts new file mode 100644 index 00000000000..d53ce96cf57 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/tap_reactor_procedure.ts @@ -0,0 +1,19 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +import { + ReactorActionResult, +} from "./types"; + +export const params = { +}; +export const returnType = ReactorActionResult \ No newline at end of file diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts new file mode 100644 index 00000000000..fd9c231c367 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types.ts @@ -0,0 +1,157 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export const RateLimitDemoConfig = __t.object("RateLimitDemoConfig", { + singleton: __t.bool(), + retainEvents: __t.u32(), + eventPruneBatch: __t.u32(), + updatedAt: __t.timestamp(), +}); +export type RateLimitDemoConfig = __Infer; + +export const RateLimitDemoSweepTick = __t.object("RateLimitDemoSweepTick", { + scheduledId: __t.u64(), + scheduledAt: __t.scheduleAt(), +}); +export type RateLimitDemoSweepTick = __Infer; + +export const RateLimitEvent = __t.object("RateLimitEvent", { + id: __t.u64(), + scope: __t.string(), + key: __t.string(), + allowed: __t.bool(), + limit: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + retryAfterSeconds: __t.u32(), + windowSeconds: __t.u32(), + cost: __t.u32(), + resetAt: __t.timestamp(), + createdAt: __t.timestamp(), +}); +export type RateLimitEvent = __Infer; + +export const RateLimitEventsAdmin = __t.object("RateLimitEventsAdmin", {}); +export type RateLimitEventsAdmin = __Infer; + +export const ReactorActionResult = __t.object("ReactorActionResult", { + allowed: __t.bool(), + action: __t.string(), + message: __t.string(), + energy: __t.u64(), + energyDelta: __t.i64(), + retryAfterSeconds: __t.u32(), + resetAt: __t.timestamp(), +}); +export type ReactorActionResult = __Infer; + +export const ReactorEvent = __t.object("ReactorEvent", { + id: __t.u64(), + identity: __t.identity(), + actorName: __t.string(), + actorColor: __t.string(), + kind: __t.string(), + scope: __t.string(), + message: __t.string(), + allowed: __t.bool(), + energyDelta: __t.i64(), + retryAfterSeconds: __t.u32(), + createdAt: __t.timestamp(), +}); +export type ReactorEvent = __Infer; + +export const ReactorEvents = __t.object("ReactorEvents", {}); +export type ReactorEvents = __Infer; + +export const ReactorLimitStatus = __t.object("ReactorLimitStatus", {}); +export type ReactorLimitStatus = __Infer; + +export const ReactorLimitStatusRow = __t.object("ReactorLimitStatusRow", { + scope: __t.string(), + label: __t.string(), + limit: __t.u32(), + windowSeconds: __t.u32(), + used: __t.u32(), + remaining: __t.u32(), + resetAt: __t.option(__t.timestamp()), +}); +export type ReactorLimitStatusRow = __Infer; + +export const ReactorPlayerRow = __t.object("ReactorPlayerRow", { + identity: __t.identity(), + displayName: __t.string(), + color: __t.string(), + contributedEnergy: __t.u64(), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32(), + upgradesBought: __t.u32(), + joinedAt: __t.timestamp(), + updatedAt: __t.timestamp(), +}); +export type ReactorPlayerRow = __Infer; + +export const ReactorPlayerState = __t.object("ReactorPlayerState", { + identity: __t.identity(), + displayName: __t.string(), + color: __t.string(), + contributedEnergy: __t.u64(), + taps: __t.u32(), + surges: __t.u32(), + coolantUses: __t.u32(), + upgradesBought: __t.u32(), + joinedAt: __t.timestamp(), + updatedAt: __t.timestamp(), +}); +export type ReactorPlayerState = __Infer; + +export const ReactorPlayers = __t.object("ReactorPlayers", {}); +export type ReactorPlayers = __Infer; + +export const ReactorRoomState = __t.object("ReactorRoomState", { + singleton: __t.bool(), + energy: __t.u64(), + reactorLevel: __t.u32(), + upgradeCount: __t.u32(), + powerUpgradeCount: __t.u32(), + coolingUpgradeCount: __t.u32(), + capacityUpgradeCount: __t.u32(), + chargeUpgradeCount: __t.u32(), + bayUpgradeCount: __t.u32(), + combo: __t.u32(), + bestCombo: __t.u32(), + heat: __t.u32(), + heatCapacity: __t.u32(), + coolingPerSecond: __t.u32(), + tapHeatGain: __t.u32(), + overheated: __t.bool(), + updatedAt: __t.timestamp(), +}); +export type ReactorRoomState = __Infer; + +export const ReactorShop = __t.object("ReactorShop", {}); +export type ReactorShop = __Infer; + +export const ReactorShopItemRow = __t.object("ReactorShopItemRow", { + slot: __t.u32(), + id: __t.string(), + name: __t.string(), + description: __t.string(), + effect: __t.string(), + cost: __t.u64(), + available: __t.bool(), +}); +export type ReactorShopItemRow = __Infer; + +export const ReactorState = __t.object("ReactorState", {}); +export type ReactorState = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts new file mode 100644 index 00000000000..44dde79c5fd --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/procedures.ts @@ -0,0 +1,28 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all procedure arg schemas +import * as BuyUpgradeProcedure from "../buy_upgrade_procedure"; +import * as OverchargeProcedure from "../overcharge_procedure"; +import * as RepairReactorProcedure from "../repair_reactor_procedure"; +import * as RunSweepProcedure from "../run_sweep_procedure"; +import * as StartReactorProcedure from "../start_reactor_procedure"; +import * as TapReactorProcedure from "../tap_reactor_procedure"; + +export type BuyUpgradeArgs = __Infer; +export type BuyUpgradeResult = __Infer; +export type OverchargeArgs = __Infer; +export type OverchargeResult = __Infer; +export type RepairReactorArgs = __Infer; +export type RepairReactorResult = __Infer; +export type RunSweepArgs = __Infer; +export type RunSweepResult = __Infer; +export type StartReactorArgs = __Infer; +export type StartReactorResult = __Infer; +export type TapReactorArgs = __Infer; +export type TapReactorResult = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts new file mode 100644 index 00000000000..3bed08e992d --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/types/reducers.ts @@ -0,0 +1,16 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { type Infer as __Infer } from "spacetimedb"; + +// Import all reducer arg schemas +import ResetDemoReducer from "../reset_demo_reducer"; +import SetPlayerColorReducer from "../set_player_color_reducer"; +import UpdateConfigReducer from "../update_config_reducer"; + +export type ResetDemoParams = __Infer; +export type SetPlayerColorParams = __Infer; +export type UpdateConfigParams = __Infer; + diff --git a/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts b/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts new file mode 100644 index 00000000000..d7ddcf900e6 --- /dev/null +++ b/spacetime-rate-limit-ts/example/src/module_bindings/app/update_config_reducer.ts @@ -0,0 +1,17 @@ +// THIS FILE IS AUTOMATICALLY GENERATED BY SPACETIMEDB. EDITS TO THIS FILE +// WILL NOT BE SAVED. MODIFY TABLES IN YOUR MODULE SOURCE CODE INSTEAD. + +/* eslint-disable */ +/* tslint:disable */ +import { + TypeBuilder as __TypeBuilder, + t as __t, + type AlgebraicTypeType as __AlgebraicTypeType, + type Infer as __Infer, +} from "spacetimedb"; + +export default { + sweepBatch: __t.option(__t.u32()), + retainEvents: __t.option(__t.u32()), + eventPruneBatch: __t.option(__t.u32()), +}; diff --git a/spacetime-rate-limit-ts/example/tsconfig.json b/spacetime-rate-limit-ts/example/tsconfig.json new file mode 100644 index 00000000000..ae0d0a4d3c3 --- /dev/null +++ b/spacetime-rate-limit-ts/example/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "types": ["node"], + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts", "server.ts"], + "exclude": ["node_modules", "spacetimedb"] +} diff --git a/spacetime-rate-limit-ts/package.json b/spacetime-rate-limit-ts/package.json new file mode 100644 index 00000000000..103fdd58762 --- /dev/null +++ b/spacetime-rate-limit-ts/package.json @@ -0,0 +1,64 @@ +{ + "name": "@spacetimedb/rate-limit", + "description": "Fixed-window rate limiting and bounded expiration sweeps for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./limit": { + "types": "./src/limit.ts", + "default": "./src/limit.ts" + }, + "./submodule": { + "types": "./src/submodule.ts", + "default": "./src/submodule.ts" + } + }, + "files": [ + "src", + "LICENSE.txt", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-rate-limit-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-rate-limit-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "rate-limit", + "security", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test.ts" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/scripts/test.ts b/spacetime-rate-limit-ts/scripts/test.ts new file mode 100644 index 00000000000..7f2df80b2d9 --- /dev/null +++ b/spacetime-rate-limit-ts/scripts/test.ts @@ -0,0 +1,182 @@ +import { Timestamp } from 'spacetimedb'; +import { + consumeRateLimit, + DEFAULT_SWEEP_BATCH, + MAX_SWEEP_BATCH, + resolveRateLimitSweepBatch, + sweepRateLimits, + type RateLimitBucketRow, +} from '../src/limit.ts'; +import { buildRateLimitKey } from '../src/key.ts'; + +let pass = 0; +let fail = 0; + +function assert(cond: boolean, name: string, detail = ''): void { + if (cond) { + pass++; + process.stdout.write(` ok ${name}\n`); + } else { + fail++; + process.stdout.write( + ` FAIL ${name}${detail ? `\n ${detail}` : ''}\n` + ); + } +} + +function assertThrows(fn: () => void, expected: string, name: string): void { + try { + fn(); + assert(false, name, `expected ${expected}`); + } catch (error) { + assert(error instanceof Error && error.message === expected, name); + } +} + +function makeTx(nowMicros = 0n) { + const rows = new Map(); + const tx = { + timestamp: new Timestamp(nowMicros), + db: { + rateLimitBucket: { + key: { + find: (key: string) => rows.get(key), + update: (row: RateLimitBucketRow) => rows.set(row.key, row), + }, + insert: (row: RateLimitBucketRow) => rows.set(row.key, row), + delete: (row: RateLimitBucketRow) => rows.delete(row.key), + expiresAt: { + filter: function* () { + yield* [...rows.values()].sort((a, b) => + a.expiresAt.microsSinceUnixEpoch < + b.expiresAt.microsSinceUnixEpoch + ? -1 + : 1 + ); + }, + }, + }, + }, + rows, + }; + return tx; +} + +{ + const tx = makeTx(); + consumeRateLimit(tx, { + key: 'fresh-a', + scope: 's', + limit: 1, + windowSeconds: 100, + }); + consumeRateLimit(tx, { + key: 'fresh-b', + scope: 's', + limit: 1, + windowSeconds: 100, + }); + consumeRateLimit(tx, { + key: 'expired', + scope: 's', + limit: 1, + windowSeconds: 1, + }); + tx.timestamp = new Timestamp(2_000_000n); + const deleted = sweepRateLimits( + tx, + tx.db.rateLimitBucket.expiresAt.filter(), + 2 + ); + assert(deleted === 1, 'sweep reaches expired buckets beyond fresh inserts'); + assert(!tx.rows.has('expired'), 'indexed sweep removes the expired bucket'); +} + +process.stdout.write('\nrate limiter\n'); + +{ + const tx = makeTx(); + assertThrows( + () => sweepRateLimits(tx, [], MAX_SWEEP_BATCH + 1), + 'rate_limit.invalid_sweep_batch', + 'sweep rejects an excessive batch size' + ); + const batch = resolveRateLimitSweepBatch({ + db: { + rateLimitConfig: { + singleton: { find: () => ({ sweepBatch: MAX_SWEEP_BATCH + 1 }) }, + }, + }, + }); + assert( + batch === DEFAULT_SWEEP_BATCH, + 'invalid stored sweep batch uses the default' + ); +} + +assert( + buildRateLimitKey('a:actor:b', 'c') !== buildRateLimitKey('a', 'b:actor:c'), + 'compound keys cannot collide through delimiters' +); + +{ + const tx = makeTx(); + const one = consumeRateLimit(tx, { + key: 'auth.login:ip:1', + scope: 'auth.login', + limit: 2, + windowSeconds: 60, + }); + const two = consumeRateLimit(tx, { + key: 'auth.login:ip:1', + scope: 'auth.login', + limit: 2, + windowSeconds: 60, + }); + const three = consumeRateLimit(tx, { + key: 'auth.login:ip:1', + scope: 'auth.login', + limit: 2, + windowSeconds: 60, + }); + assert(one.allowed && one.remaining === 1, 'first request allowed'); + assert(two.allowed && two.remaining === 0, 'second request allowed'); + assert( + !three.allowed && three.retryAfterSeconds === 60, + 'third request blocked' + ); +} + +{ + const tx = makeTx(); + consumeRateLimit(tx, { + key: 'k', + scope: 's', + limit: 1, + windowSeconds: 60, + }); + tx.timestamp = new Timestamp(61_000_000n); + const next = consumeRateLimit(tx, { + key: 'k', + scope: 's', + limit: 1, + windowSeconds: 60, + }); + assert(next.allowed && next.used === 1, 'expired window resets'); +} + +{ + const tx = makeTx(); + consumeRateLimit(tx, { + key: 'k', + scope: 's', + limit: 1, + windowSeconds: 1, + }); + tx.timestamp = new Timestamp(2_000_000n); + const deleted = sweepRateLimits(tx, tx.db.rateLimitBucket.expiresAt.filter()); + assert(deleted === 1 && tx.rows.size === 0, 'sweep removes expired buckets'); +} + +process.stdout.write(`\n${pass} passed, ${fail} failed\n`); +process.exit(fail === 0 ? 0 : 1); diff --git a/spacetime-rate-limit-ts/spacetimedb/.npmrc b/spacetime-rate-limit-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-rate-limit-ts/spacetimedb/package.json b/spacetime-rate-limit-ts/spacetimedb/package.json new file mode 100644 index 00000000000..e1bc09577f9 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-rate-limit-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-rate-limit", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-rate-limit" + }, + "dependencies": { + "@spacetimedb/rate-limit": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-rate-limit-ts/spacetimedb/src/index.ts b/spacetime-rate-limit-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..c057c30f4a0 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/src/index.ts @@ -0,0 +1,17 @@ +import spacetimedb from '../../src/submodule/schema'; +import { installRateLimit } from '../../src/submodule/install'; +export { + adminRateLimitBuckets, + addRateLimitAdmin, + consume, + rateLimitSweep, + resetBuckets, + runSweep, + updateConfig, +} from '../../src/submodule/operations'; + +export default spacetimedb; + +export const init = spacetimedb.init(ctx => { + installRateLimit(ctx); +}); diff --git a/spacetime-rate-limit-ts/spacetimedb/tsconfig.json b/spacetime-rate-limit-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-rate-limit-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-rate-limit-ts/src/index.ts b/spacetime-rate-limit-ts/src/index.ts new file mode 100644 index 00000000000..8b6eef65d6c --- /dev/null +++ b/spacetime-rate-limit-ts/src/index.ts @@ -0,0 +1,17 @@ +export { + DEFAULT_SWEEP_BATCH, + MAX_SWEEP_BATCH, + assertRateLimitSweepBatch, + DEFAULT_SWEEP_INTERVAL_SECONDS, + consumeRateLimit, + installRateLimitState, + resolveRateLimitSweepBatch, + runRateLimitSweep, + sweepRateLimits, + type ConsumeRateLimitOpts, + type RateLimitInitCtxLike, + type RateLimitResult, + type RateLimitSweepCtxLike, + type RateLimitTxLike, +} from './limit'; +export { buildRateLimitKey } from './key'; diff --git a/spacetime-rate-limit-ts/src/key.ts b/spacetime-rate-limit-ts/src/key.ts new file mode 100644 index 00000000000..7eb4c4b3cd4 --- /dev/null +++ b/spacetime-rate-limit-ts/src/key.ts @@ -0,0 +1,7 @@ +function encodePart(value: string): string { + return `${value.length}:${value}`; +} + +export function buildRateLimitKey(scope: string, actorKey: string): string { + return `${encodePart(scope)}${encodePart(actorKey)}`; +} diff --git a/spacetime-rate-limit-ts/src/limit.ts b/spacetime-rate-limit-ts/src/limit.ts new file mode 100644 index 00000000000..c3d5a1ec9ef --- /dev/null +++ b/spacetime-rate-limit-ts/src/limit.ts @@ -0,0 +1,297 @@ +import { ScheduleAt, Timestamp } from 'spacetimedb'; + +const ONE_SECOND_MICROS = 1_000_000n; +const U32_MAX = 0xffff_ffff; + +export const DEFAULT_SWEEP_BATCH = 500; +export const MAX_SWEEP_BATCH = 10_000; +export const DEFAULT_SWEEP_INTERVAL_SECONDS = 30n; + +export interface ConsumeRateLimitOpts { + key: string; + scope: string; + limit: number; + windowSeconds: number; + cost?: number; +} + +export type RateLimitResult = + | { + allowed: true; + key: string; + scope: string; + limit: number; + used: number; + remaining: number; + resetAt: Timestamp; + retryAfterSeconds: 0; + } + | { + allowed: false; + key: string; + scope: string; + limit: number; + used: number; + remaining: 0; + resetAt: Timestamp; + retryAfterSeconds: number; + }; + +function assertPositiveInt(name: string, value: number): void { + if (!Number.isInteger(value) || value <= 0 || value > U32_MAX) { + throw new Error(`rate_limit.invalid_${name}`); + } +} + +export function assertRateLimitSweepBatch(value: number): void { + assertPositiveInt('sweep_batch', value); + if (value > MAX_SWEEP_BATCH) { + throw new Error('rate_limit.invalid_sweep_batch'); + } +} + +function plusSeconds(timestamp: Timestamp, seconds: number): Timestamp { + return new Timestamp( + (timestamp.microsSinceUnixEpoch as bigint) + + BigInt(seconds) * ONE_SECOND_MICROS + ); +} + +function secondsUntil(now: Timestamp, future: Timestamp): number { + const delta = + (future.microsSinceUnixEpoch as bigint) - + (now.microsSinceUnixEpoch as bigint); + if (delta <= 0n) return 0; + return Number((delta + ONE_SECOND_MICROS - 1n) / ONE_SECOND_MICROS); +} + +export interface RateLimitBucketRow { + key: string; + scope: string; + windowStart: Timestamp; + expiresAt: Timestamp; + count: number; + updatedAt: Timestamp; +} + +export interface RateLimitTxLike { + timestamp: Timestamp; + db: { + rateLimitBucket: { + key: { + find(key: string): RateLimitBucketRow | null | undefined; + update(row: RateLimitBucketRow): void; + }; + insert(row: RateLimitBucketRow): void; + delete(row: RateLimitBucketRow): void; + }; + }; +} + +export interface RateLimitInitCtxLike { + timestamp: Timestamp; + db: { + rateLimitConfig: { + singleton: { + find( + key: boolean + ): + | { singleton: boolean; sweepBatch: number; updatedAt: Timestamp } + | null + | undefined; + update(row: { + singleton: boolean; + sweepBatch: number; + updatedAt: Timestamp; + }): void; + }; + insert(row: { + singleton: boolean; + sweepBatch: number; + updatedAt: Timestamp; + }): void; + }; + rateLimitSweepTick: { + insert(row: { scheduledId: bigint; scheduledAt: ScheduleAt }): void; + }; + }; +} + +export interface RateLimitInstallOpts { + sweepBatch?: number; + sweepIntervalSeconds?: bigint; +} + +export function installRateLimitState( + ctx: RateLimitInitCtxLike, + opts?: RateLimitInstallOpts +): void { + const sweepBatch = opts?.sweepBatch ?? DEFAULT_SWEEP_BATCH; + assertRateLimitSweepBatch(sweepBatch); + const sweepIntervalSeconds = + opts?.sweepIntervalSeconds ?? DEFAULT_SWEEP_INTERVAL_SECONDS; + if (sweepIntervalSeconds <= 0n) + throw new Error('rate_limit.invalid_sweep_interval_seconds'); + + const existing = ctx.db.rateLimitConfig.singleton.find(true); + if (!existing) { + ctx.db.rateLimitConfig.insert({ + singleton: true, + sweepBatch, + updatedAt: ctx.timestamp, + }); + } + + ctx.db.rateLimitSweepTick.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.interval(sweepIntervalSeconds * ONE_SECOND_MICROS), + }); +} + +export function resolveRateLimitSweepBatch(ctx: { + db: { + rateLimitConfig: { + singleton: { + find(key: boolean): { sweepBatch: number } | null | undefined; + }; + }; + }; +}): number { + const cfg = ctx.db.rateLimitConfig.singleton.find(true); + if (!cfg) return DEFAULT_SWEEP_BATCH; + const batch = Number(cfg.sweepBatch); + return Number.isInteger(batch) && batch > 0 && batch <= MAX_SWEEP_BATCH + ? batch + : DEFAULT_SWEEP_BATCH; +} + +export interface RateLimitSweepCtxLike extends RateLimitTxLike { + db: RateLimitTxLike['db'] & { + rateLimitConfig: { + singleton: { + find(key: boolean): { sweepBatch: number } | null | undefined; + }; + }; + }; +} + +export function runRateLimitSweep( + ctx: RateLimitSweepCtxLike, + expiredRows: Iterable +): number { + const batch = resolveRateLimitSweepBatch(ctx); + return sweepRateLimits(ctx, expiredRows, batch); +} + +export function consumeRateLimit( + tx: RateLimitTxLike, + opts: ConsumeRateLimitOpts +): RateLimitResult { + assertPositiveInt('limit', opts.limit); + assertPositiveInt('window', opts.windowSeconds); + const cost = opts.cost ?? 1; + assertPositiveInt('cost', cost); + + const now = tx.timestamp as Timestamp; + const resetAt = plusSeconds(now, opts.windowSeconds); + const existing = tx.db.rateLimitBucket.key.find(opts.key); + + if ( + !existing || + (existing.expiresAt.microsSinceUnixEpoch as bigint) <= + (now.microsSinceUnixEpoch as bigint) + ) { + if (cost > opts.limit) { + return { + allowed: false, + key: opts.key, + scope: opts.scope, + limit: opts.limit, + used: 0, + remaining: 0, + resetAt, + retryAfterSeconds: opts.windowSeconds, + }; + } + // Reuse an expired row until the sweeper deletes it. Update in place to + // avoid a key collision. + if (existing) { + tx.db.rateLimitBucket.key.update({ + ...existing, + scope: opts.scope, + windowStart: now, + expiresAt: resetAt, + count: cost, + updatedAt: now, + }); + } else { + tx.db.rateLimitBucket.insert({ + key: opts.key, + scope: opts.scope, + windowStart: now, + expiresAt: resetAt, + count: cost, + updatedAt: now, + }); + } + return { + allowed: true, + key: opts.key, + scope: opts.scope, + limit: opts.limit, + used: cost, + remaining: opts.limit - cost, + resetAt, + retryAfterSeconds: 0, + }; + } + + const used = existing.count as number; + if (used + cost > opts.limit) { + return { + allowed: false, + key: opts.key, + scope: opts.scope, + limit: opts.limit, + used, + remaining: 0, + resetAt: existing.expiresAt, + retryAfterSeconds: secondsUntil(now, existing.expiresAt), + }; + } + + const nextUsed = used + cost; + tx.db.rateLimitBucket.key.update({ + ...existing, + scope: opts.scope, + count: nextUsed, + updatedAt: now, + }); + return { + allowed: true, + key: opts.key, + scope: opts.scope, + limit: opts.limit, + used: nextUsed, + remaining: opts.limit - nextUsed, + resetAt: existing.expiresAt, + retryAfterSeconds: 0, + }; +} + +export function sweepRateLimits( + tx: RateLimitTxLike, + expiredRows: Iterable, + maxRows = DEFAULT_SWEEP_BATCH +): number { + assertRateLimitSweepBatch(maxRows); + const nowMicros = tx.timestamp.microsSinceUnixEpoch as bigint; + let deleted = 0; + for (const row of expiredRows) { + if (deleted >= maxRows) break; + if ((row.expiresAt.microsSinceUnixEpoch as bigint) > nowMicros) break; + tx.db.rateLimitBucket.delete(row); + deleted++; + } + return deleted; +} diff --git a/spacetime-rate-limit-ts/src/submodule.ts b/spacetime-rate-limit-ts/src/submodule.ts new file mode 100644 index 00000000000..ed5e49da5c2 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule.ts @@ -0,0 +1,28 @@ +export { default } from './submodule/schema'; +export { installRateLimit } from './submodule/install'; +export { + DEFAULT_SWEEP_BATCH, + MAX_SWEEP_BATCH, + assertRateLimitSweepBatch, + DEFAULT_SWEEP_INTERVAL_SECONDS, + consumeRateLimit, + installRateLimitState, + resolveRateLimitSweepBatch, + runRateLimitSweep, + sweepRateLimits, + type ConsumeRateLimitOpts, + type RateLimitInitCtxLike, + type RateLimitResult, + type RateLimitSweepCtxLike, + type RateLimitTxLike, +} from './limit'; +export { buildRateLimitKey } from './key'; +export { + adminRateLimitBuckets, + addRateLimitAdmin, + consume, + rateLimitSweep, + resetBuckets, + runSweep, + updateConfig, +} from './submodule/operations'; diff --git a/spacetime-rate-limit-ts/src/submodule/install.ts b/spacetime-rate-limit-ts/src/submodule/install.ts new file mode 100644 index 00000000000..0ad4b1ffcb3 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/install.ts @@ -0,0 +1,12 @@ +import { DEFAULT_SWEEP_BATCH, installRateLimitState } from '../index'; +import type { ReducerModuleCtx } from './schema'; + +export function installRateLimit(ctx: ReducerModuleCtx) { + if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { + ctx.db.rateLimitAdminIdentity.insert({ + identity: ctx.sender, + addedAtMicros: ctx.timestamp.microsSinceUnixEpoch, + }); + } + installRateLimitState(ctx, { sweepBatch: DEFAULT_SWEEP_BATCH }); +} diff --git a/spacetime-rate-limit-ts/src/submodule/operations.ts b/spacetime-rate-limit-ts/src/submodule/operations.ts new file mode 100644 index 00000000000..6a3c3d88d5b --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/operations.ts @@ -0,0 +1,193 @@ +import { Range, SenderError } from 'spacetimedb/server'; +import { + consumeRateLimit, + DEFAULT_SWEEP_BATCH, + MAX_SWEEP_BATCH, + runRateLimitSweep, + sweepRateLimits, +} from '../index'; +import { + rateLimitBucket, + rateLimitSweepTick, + spacetimedb, + t, + type ReducerModuleCtx, + type ViewModuleCtx, +} from './schema'; +import { buildRateLimitKey } from '../key'; + +const MAX_SCOPE_LENGTH = 128; +const MAX_ACTOR_KEY_LENGTH = 256; + +export const consumeResult = t.object('RateLimitConsumeResult', { + allowed: t.bool(), + scope: t.string(), + key: t.string(), + limit: t.u32(), + used: t.u32(), + remaining: t.u32(), + retryAfterSeconds: t.u32(), + resetAt: t.timestamp(), +}); + +function isAdmin(ctx: ViewModuleCtx): boolean { + return ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) != null; +} + +function requireAdmin(ctx: ReducerModuleCtx): void { + if (ctx.db.rateLimitAdminIdentity.identity.find(ctx.sender) == null) { + throw new SenderError('rate_limit.not_authorized'); + } +} + +function toU32(name: string, value: number, max = 0xffff_ffff): number { + if (!Number.isInteger(value) || value <= 0 || value > max) { + throw new SenderError(`rate_limit.invalid_${name}`); + } + return value; +} + +function sanitizePart(s: string): string { + return s.trim().replace(/\s+/g, ' '); +} + +export const consume = spacetimedb.procedure( + { + scope: t.string(), + actorKey: t.string(), + limit: t.u32(), + windowSeconds: t.u32(), + cost: t.option(t.u32()), + }, + consumeResult, + (ctx, args) => { + const scope = sanitizePart(args.scope); + const actorKey = sanitizePart(args.actorKey); + if (scope.length === 0 || scope.length > MAX_SCOPE_LENGTH) { + throw new SenderError('rate_limit.invalid_scope'); + } + if (actorKey.length === 0 || actorKey.length > MAX_ACTOR_KEY_LENGTH) { + throw new SenderError('rate_limit.invalid_actor_key'); + } + const limit = toU32('limit', Number(args.limit)); + const windowSeconds = toU32('window_seconds', Number(args.windowSeconds)); + const cost = toU32('cost', Number(args.cost ?? 1)); + const key = buildRateLimitKey(scope, actorKey); + + const out = ctx.withTx(tx => { + requireAdmin(tx); + const r = consumeRateLimit(tx, { + key, + scope, + limit, + windowSeconds, + cost, + }); + return { + allowed: r.allowed, + scope: r.scope, + key: r.key, + limit, + used: r.used, + remaining: r.remaining, + retryAfterSeconds: r.retryAfterSeconds, + resetAt: r.resetAt, + }; + }); + if (!out) throw new Error('rate_limit.consume_tx_failed'); + return out; + } +); + +export const runSweep = spacetimedb.procedure( + { maxRows: t.option(t.u32()) }, + t.u32(), + (ctx, args) => { + const maxRows = + args.maxRows === undefined + ? undefined + : toU32('sweep_batch', Number(args.maxRows), MAX_SWEEP_BATCH); + return ctx.withTx(tx => { + requireAdmin(tx); + return sweepRateLimits( + tx, + tx.db.rateLimitBucket.expiresAt.filter( + new Range(undefined, { tag: 'included', value: tx.timestamp }) + ), + maxRows ?? DEFAULT_SWEEP_BATCH + ); + }); + } +); + +export const addRateLimitAdmin = spacetimedb.reducer( + { identity: t.identity() }, + (ctx, args) => { + requireAdmin(ctx); + if (ctx.db.rateLimitAdminIdentity.identity.find(args.identity) == null) { + ctx.db.rateLimitAdminIdentity.insert({ + identity: args.identity, + addedAtMicros: ctx.timestamp.microsSinceUnixEpoch, + }); + } + } +); + +export const updateConfig = spacetimedb.reducer( + { sweepBatch: t.u32() }, + (ctx, args) => { + requireAdmin(ctx); + const cfg = ctx.db.rateLimitConfig.singleton.find(true); + if (!cfg) throw new Error('rate_limit.config_missing'); + ctx.db.rateLimitConfig.singleton.update({ + ...cfg, + sweepBatch: toU32( + 'sweep_batch', + Number(args.sweepBatch), + MAX_SWEEP_BATCH + ), + updatedAt: ctx.timestamp, + }); + } +); + +export const resetBuckets = spacetimedb.reducer( + { maxRows: t.option(t.u32()) }, + (ctx, args) => { + requireAdmin(ctx); + const maxRows = Math.min(Number(args.maxRows ?? 1000), 10_000); + let removed = 0; + for (const row of ctx.db.rateLimitBucket.iter()) { + if (removed >= maxRows) break; + ctx.db.rateLimitBucket.delete(row); + removed++; + } + } +); + +export const adminRateLimitBuckets = spacetimedb.view( + { name: 'admin_rate_limit_buckets', public: true }, + t.array(rateLimitBucket.rowType), + ctx => { + if (!isAdmin(ctx)) return []; + const rows = []; + for (const row of ctx.db.rateLimitBucket.iter()) { + if (rows.length >= 1000) break; + rows.push(row); + } + return rows; + } +); + +export const rateLimitSweep = spacetimedb.reducer( + { onSchedule: rateLimitSweepTick }, + { arg: rateLimitSweepTick.rowType }, + (ctx, _args) => { + runRateLimitSweep( + ctx, + ctx.db.rateLimitBucket.expiresAt.filter( + new Range(undefined, { tag: 'included', value: ctx.timestamp }) + ) + ); + } +); diff --git a/spacetime-rate-limit-ts/src/submodule/schema.ts b/spacetime-rate-limit-ts/src/submodule/schema.ts new file mode 100644 index 00000000000..3d546331a75 --- /dev/null +++ b/spacetime-rate-limit-ts/src/submodule/schema.ts @@ -0,0 +1,63 @@ +import { + schema, + table, + t, + type InferSchema, + type ProcedureCtx, + type ReducerCtx, + type TransactionCtx, + type ViewCtx, +} from 'spacetimedb/server'; + +export const rateLimitBucket = table( + { name: 'rate_limit_bucket', public: false }, + { + key: t.string().primaryKey(), + scope: t.string().index(), + windowStart: t.timestamp().index(), + expiresAt: t.timestamp().index(), + count: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitAdminIdentity = table( + { name: 'rate_limit_admin_identity', public: false }, + { + identity: t.identity().primaryKey(), + addedAtMicros: t.i64(), + } +); + +export const rateLimitConfig = table( + { name: 'rate_limit_config', public: true }, + { + singleton: t.bool().primaryKey(), + sweepBatch: t.u32(), + updatedAt: t.timestamp(), + } +); + +export const rateLimitSweepTick = table( + { name: 'rate_limit_sweep_tick' }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + } +); + +export const spacetimedb = schema({ + rateLimitBucket, + rateLimitAdminIdentity, + rateLimitConfig, + rateLimitSweepTick, +}); +export default spacetimedb; + +export type Schema = InferSchema; +export type ReducerModuleCtx = ReducerCtx; +export type ProcedureModuleCtx = ProcedureCtx; +export type TransactionModuleCtx = TransactionCtx; +export type ViewModuleCtx = ViewCtx; + +export { t }; diff --git a/spacetime-rate-limit-ts/tsconfig.json b/spacetime-rate-limit-ts/tsconfig.json new file mode 100644 index 00000000000..b2b4ecdcdda --- /dev/null +++ b/spacetime-rate-limit-ts/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-retry-ts/.npmrc b/spacetime-retry-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-retry-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-retry-ts/LICENSE.txt b/spacetime-retry-ts/LICENSE.txt new file mode 100644 index 00000000000..4e61a2122e7 --- /dev/null +++ b/spacetime-retry-ts/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 Clockwork Labs, Inc + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/spacetime-retry-ts/README.md b/spacetime-retry-ts/README.md new file mode 100644 index 00000000000..d14685c1f5e --- /dev/null +++ b/spacetime-retry-ts/README.md @@ -0,0 +1,127 @@ +# @spacetimedb/retry + +A typed retry factory for SpacetimeDB TypeScript modules. It creates a private +scheduled-task table, attempt history, admin controls, and exponential-backoff +dispatch around handlers defined by the host module. + +## Install + +```bash +npm install @spacetimedb/retry spacetimedb +``` + +The factory registers its tables and reducers in the host schema. It does not +mount a separate submodule schema. + +`spacetimedb` is a peer dependency. Keep its version aligned with the SDK used +to build the host module. + +For the install-to-publish workflow, see +[Getting started](https://spacetimedb.com/docs/). + +## Usage + +### Integrate into an application + +Retry is a factory because task variants and handlers belong to the host. The +example below is a module-definition skeleton: replace `sendReceipt` with an +idempotent application handler. + +Create the factory before the schema so its tables can be registered. Register the +scheduled reducer afterward to resolve the scheduled-table reference. + +```ts +import { SenderError, schema, t, table } from 'spacetimedb/server'; +import { ScheduleAt } from 'spacetimedb'; +import { + createRetrySubmodule, + retryFailed, + retryHandler, + retryOk, +} from '@spacetimedb/retry'; + +const retry = createRetrySubmodule( + { table, t, SenderError, ScheduleAt }, + { + sendReceipt: retryHandler( + t.object('SendReceiptArgs', { orderId: t.u64() }), + (ctx, { orderId }) => { + const result = sendReceipt(ctx, orderId); + return result.sent ? retryOk() : retryFailed(result.error); + } + ), + } +); + +const db = schema({ ...retry.tables }); +export const retryFire = db.reducer( + { onSchedule: retry.tables.retryTask }, + { arg: retry.tables.retryTask.rowType }, + retry.reducers.retryFire +); + +export const submitRetryTask = db.reducer( + retry.reducers.submitRetryTask.params, + retry.reducers.submitRetryTask.handler +); + +export const init = db.init(ctx => retry.installRetry(ctx)); +export default db; +``` + +Submit tagged arguments with an attempt cap and base backoff. The first attempt +is scheduled immediately; subsequent delays are `backoffSecs * 2^attempt`. + +Handlers must be idempotent. A returned failure or a thrown exception records a +failed attempt and schedules the next attempt, up to `maxAttempts`. Writes made +by the handler before a failure are committed with that attempt; Retry does not +provide a separate transaction for the handler. A host crash or transaction +abort can still prevent the retry from being scheduled. + +History retains the latest 1,000 attempts across all tasks. The admin history +view returns these attempts newest first. + +## API + +- `retryHandler(args, run)` associates a SpacetimeDB type builder with a task + handler. The handler returns `retryOk()` or `retryFailed(error)`. +- `makeRetryDispatch(handlers)` creates a typed tagged-union dispatcher. +- `createRetrySubmodule(deps, handlers, auth?)` returns tables, enum helpers, + reducers, admin views, and installation. +- `installRetry(ctx)` seeds the publishing identity as the initial admin. + +The generated client can submit a task when the host exports +`submitRetryTask`. The default factory authorization restricts this operation +to Retry administrators: + +```ts +await conn.reducers.submitRetryTask({ + name: `receipt:${orderId}`, + args: { tag: 'SendReceipt', value: { orderId } }, + maxAttempts: 5, + backoffSecs: 2, +}); +``` + +Product-facing applications usually expose a narrower reducer with fixed retry +limits and arguments derived from authorized application state. Operational +screens can subscribe to the factory's admin task and history views. + +Package entrypoints: + +- `@spacetimedb/retry/submodule` exports `createRetrySubmodule`. +- `@spacetimedb/retry` exports the factory, handler, dispatch, and result helpers. + +## Testing + +```bash +pnpm test +pnpm run lint +pnpm --dir spacetimedb run build +``` + +The build compiles the fixture module that registers the factory's tables and reducers. + +## License + +Apache-2.0. See [`LICENSE.txt`](./LICENSE.txt). diff --git a/spacetime-retry-ts/package.json b/spacetime-retry-ts/package.json new file mode 100644 index 00000000000..2e9b188485b --- /dev/null +++ b/spacetime-retry-ts/package.json @@ -0,0 +1,60 @@ +{ + "name": "@spacetimedb/retry", + "description": "Typed retry dispatch, exponential backoff, and attempt history for SpacetimeDB TypeScript modules.", + "version": "0.1.0", + "license": "Apache-2.0", + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./submodule": { + "types": "./src/submodule.ts", + "default": "./src/submodule.ts" + } + }, + "files": [ + "src", + "LICENSE.txt", + "README.md" + ], + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/clockworklabs/SpacetimeDB.git", + "directory": "spacetime-retry-ts" + }, + "homepage": "https://github.com/clockworklabs/SpacetimeDB/tree/master/spacetime-retry-ts#readme", + "bugs": { + "url": "https://github.com/clockworklabs/SpacetimeDB/issues" + }, + "keywords": [ + "spacetimedb", + "retry", + "backoff", + "typescript" + ], + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "tsx scripts/test.ts" + }, + "peerDependencies": { + "spacetimedb": "workspace:^" + }, + "devDependencies": { + "eslint": "^9.17.0", + "prettier": "^3.3.3", + "@types/node": "^22.10.2", + "spacetimedb": "workspace:*", + "tsx": "^4.21.0", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-retry-ts/scripts/test.ts b/spacetime-retry-ts/scripts/test.ts new file mode 100644 index 00000000000..adae425329d --- /dev/null +++ b/spacetime-retry-ts/scripts/test.ts @@ -0,0 +1,119 @@ +import * as assert from 'node:assert/strict'; +import { ScheduleAt, Timestamp, t, table } from 'spacetimedb'; +import { + makeRetryDispatch, + retryFailed, + retryHandler, + retryOk, +} from '../src/handler.ts'; +import { createRetrySubmodule } from '../src/submodule.ts'; + +const calls: string[] = []; +const handlers = { + noArgs: retryHandler(t.unit(), () => { + calls.push('noArgs'); + return retryOk(); + }), + withArgs: retryHandler( + t.object('TestArgs', { value: t.string() }), + (_ctx, args: { value: string }) => { + calls.push(args.value); + return retryFailed('try again'); + } + ), +}; + +assert.deepEqual(Object.keys(handlers), ['noArgs', 'withArgs']); +const dispatch = makeRetryDispatch(handlers); +assert.deepEqual(dispatch({}, { tag: 'noArgs' }), { ok: true }); +assert.deepEqual( + dispatch({}, { tag: 'withArgs', value: { value: 'payload' } }), + { + ok: false, + error: 'try again', + } +); +assert.deepEqual(calls, ['noArgs', 'payload']); +assert.throws( + () => dispatch({}, { tag: 'missing' as keyof typeof handlers }), + /unknown retry handler/ +); +assert.throws( + () => dispatch({}, { tag: 'toString' as keyof typeof handlers }), + /unknown retry handler/ +); + +const retry = createRetrySubmodule( + { table, t, ScheduleAt, SenderError: Error }, + { + throws: retryHandler(t.unit(), () => { + throw new Error('x'.repeat(3000)); + }), + fails: retryHandler(t.unit(), () => retryFailed('unavailable')), + succeeds: retryHandler(t.unit(), () => retryOk()), + }, + { isAdmin: () => true } +); +type Task = Parameters[1]['arg']; +type History = ReturnType[number]; +const history = new Map(); +const scheduled: Task[] = []; +let nextId = 0n; +const ctx = { + timestamp: new Timestamp(10_000_000n), + db: { + retryTask: { insert: (row: Task) => scheduled.push(row) }, + retryHistory: { + insert(row: History) { + const inserted = { ...row, id: ++nextId }; + history.set(inserted.id, inserted); + return inserted; + }, + id: { + update: (row: History) => history.set(row.id, row), + delete: (id: bigint) => history.delete(id), + }, + iter: () => history.values(), + }, + }, +}; +const task: Task = { + scheduledId: 1n, + scheduledAt: ScheduleAt.time(0n), + name: 'test', + args: { tag: 'throws' }, + attempt: 0, + maxAttempts: 3, + backoffSecs: 2, +}; +retry.reducers.retryFire(ctx, { arg: task }); +assert.equal(history.get(1n)?.status.tag, 'Failed'); +assert.equal(history.get(1n)?.error?.length, 2048); +assert.equal(scheduled[0].attempt, 1); +assert.deepEqual(scheduled[0].scheduledAt, ScheduleAt.time(12_000_000n)); +retry.reducers.retryFire(ctx, { arg: scheduled[0] }); +assert.equal(scheduled[1].attempt, 2); +assert.deepEqual(scheduled[1].scheduledAt, ScheduleAt.time(14_000_000n)); +retry.reducers.retryFire(ctx, { arg: scheduled[1] }); +assert.equal(history.get(3n)?.status.tag, 'GaveUp'); +assert.equal(scheduled.length, 2); +retry.reducers.retryFire(ctx, { + arg: { ...task, args: { tag: 'fails' } }, +}); +assert.equal(history.get(4n)?.error, 'unavailable'); +assert.equal(scheduled.length, 3); +for (let i = 0; i < 1001; i++) { + retry.reducers.retryFire(ctx, { + arg: { ...task, args: { tag: 'succeeds' } }, + }); +} +assert.equal(scheduled.length, 3); +assert.equal(history.size, 1000); +assert.equal(history.has(5n), false); +const recent = retry.views.retryHistoryAdmin(ctx); +assert.equal(recent.length, 1000); +assert.equal(recent[0].id, nextId); +assert.equal(recent[0].status.tag, 'Ok'); +assert.equal(recent.at(-1)?.id, nextId - 999n); + +console.log('retry tests passed'); diff --git a/spacetime-retry-ts/spacetimedb/.npmrc b/spacetime-retry-ts/spacetimedb/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-retry-ts/spacetimedb/package.json b/spacetime-retry-ts/spacetimedb/package.json new file mode 100644 index 00000000000..2538269257d --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/package.json @@ -0,0 +1,19 @@ +{ + "name": "spacetime-retry-module", + "version": "0.1.0", + "private": true, + "type": "module", + "scripts": { + "build": "spacetime build", + "publish:local": "spacetime publish --server local --yes spacetime-retry", + "publish:local:reset": "spacetime publish --server local --yes --delete-data=always spacetime-retry" + }, + "dependencies": { + "@spacetimedb/retry": "workspace:*", + "spacetimedb": "workspace:*" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "typescript": "^5.9.3" + } +} diff --git a/spacetime-retry-ts/spacetimedb/src/index.ts b/spacetime-retry-ts/spacetimedb/src/index.ts new file mode 100644 index 00000000000..2bb9da37e94 --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/src/index.ts @@ -0,0 +1,117 @@ +import { schema, table, t, SenderError } from 'spacetimedb/server'; +import { ScheduleAt } from 'spacetimedb'; +import { + createRetrySubmodule, + retryFailed, + retryHandler, + retryOk, + type RetryResult, +} from '@spacetimedb/retry'; + +interface FlakyTransaction { + timestamp: import('spacetimedb').Timestamp; + db: { + retryTask: { + name: { + filter(name: string): IterableIterator<{ attempt: number }>; + }; + }; + retryMetric: { + insert(row: { + id: bigint; + name: string; + value: number; + recordedAt: import('spacetimedb').Timestamp; + }): unknown; + }; + }; +} + +const flakyArgs = t.object('FlakyArgs', { + taskName: t.string(), + succeedAtAttempt: t.u8(), + throwOnFailure: t.bool(), +}); + +const flaky = retryHandler(flakyArgs, (ctx, args): RetryResult => { + const tx = ctx as FlakyTransaction; + const task = tx.db.retryTask.name.filter(args.taskName).next().value; + const attempt = Number(task?.attempt ?? 0); + if (attempt < args.succeedAtAttempt) { + const message = `simulated failure at attempt ${attempt}`; + if (args.throwOnFailure) throw new Error(message); + return retryFailed(message); + } + tx.db.retryMetric.insert({ + id: 0n, + name: `flaky-success-${args.taskName}`, + value: attempt, + recordedAt: tx.timestamp, + }); + return retryOk(); +}); + +const retryHandlers = { + flaky, +}; + +const retry = createRetrySubmodule( + { table, t, SenderError, ScheduleAt }, + retryHandlers +); +const { retryTask, retryHistory, retryAdminIdentity } = retry.tables; + +const retryMetric = table( + { name: 'retry_metric', public: true }, + { + id: t.u64().primaryKey().autoInc(), + name: t.string(), + value: t.f64(), + recordedAt: t.timestamp(), + } +); + +const spacetimedb = schema({ + retryTask, + retryHistory, + retryAdminIdentity, + retryMetric, +}); +export default spacetimedb; + +export const retryTasksAdmin = spacetimedb.view( + { name: 'retry_tasks_admin', public: true }, + t.array(retryTask.rowType), + retry.views.retryTasksAdmin +); + +export const retryHistoryAdmin = spacetimedb.view( + { name: 'retry_history_admin', public: true }, + t.array(retryHistory.rowType), + retry.views.retryHistoryAdmin +); + +export const init = spacetimedb.init(ctx => { + retry.installRetry(ctx); +}); + +export const retryFire = spacetimedb.reducer( + { onSchedule: retryTask }, + { arg: retryTask.rowType }, + retry.reducers.retryFire +); + +export const submitRetryTask = spacetimedb.reducer( + retry.reducers.submitRetryTask.params, + retry.reducers.submitRetryTask.handler +); + +export const addRetryAdminIdentity = spacetimedb.reducer( + retry.reducers.addRetryAdminIdentity.params, + retry.reducers.addRetryAdminIdentity.handler +); + +export const removeRetryAdminIdentity = spacetimedb.reducer( + retry.reducers.removeRetryAdminIdentity.params, + retry.reducers.removeRetryAdminIdentity.handler +); diff --git a/spacetime-retry-ts/spacetimedb/tsconfig.json b/spacetime-retry-ts/spacetimedb/tsconfig.json new file mode 100644 index 00000000000..8d8f9b03455 --- /dev/null +++ b/spacetime-retry-ts/spacetimedb/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node"] + }, + "include": ["src"] +} diff --git a/spacetime-retry-ts/src/handler.ts b/spacetime-retry-ts/src/handler.ts new file mode 100644 index 00000000000..1d149ec2ad5 --- /dev/null +++ b/spacetime-retry-ts/src/handler.ts @@ -0,0 +1,56 @@ +import type { ElementsObj, Infer as InferBuilder } from 'spacetimedb/server'; + +type TypeBuilderLike = ElementsObj[string]; +type IsUnit = [keyof T] extends [never] ? true : false; + +export type RetryResult = { ok: true } | { ok: false; error: string }; + +export const retryOk = (): RetryResult => ({ ok: true }); +export const retryFailed = (error: string): RetryResult => ({ + ok: false, + error, +}); + +type RunFn = + IsUnit> extends true + ? (ctx: unknown) => RetryResult + : (ctx: unknown, args: InferBuilder) => RetryResult; + +// A symbol key keeps this metadata outside t.enum's Object.keys traversal. +const RUN_KEY = Symbol.for('retry-ts/run'); + +export type RetryHandler = TB & { + [RUN_KEY]: RunFn; +}; + +export function retryHandler( + args: TB, + run: RunFn +): RetryHandler { + Object.defineProperty(args, RUN_KEY, { + value: run, + enumerable: false, + configurable: false, + writable: false, + }); + return args as RetryHandler; +} + +export function makeRetryDispatch>( + handlers: H +) { + return function dispatch( + ctx: Tx, + args: { tag: keyof H & string; value?: unknown } + ): RetryResult { + if (!Object.hasOwn(handlers, args.tag)) { + throw new Error(`unknown retry handler: ${args.tag}`); + } + const handler = handlers[args.tag]; + const run = handler[RUN_KEY]; + if ('value' in args) { + return (run as (c: Tx, v: unknown) => RetryResult)(ctx, args.value); + } + return (run as (c: Tx) => RetryResult)(ctx); + }; +} diff --git a/spacetime-retry-ts/src/index.ts b/spacetime-retry-ts/src/index.ts new file mode 100644 index 00000000000..f49751f7aee --- /dev/null +++ b/spacetime-retry-ts/src/index.ts @@ -0,0 +1,9 @@ +export { + makeRetryDispatch, + retryFailed, + retryHandler, + retryOk, + type RetryHandler, + type RetryResult, +} from './handler'; +export { createRetrySubmodule, type RetryHandlers } from './submodule'; diff --git a/spacetime-retry-ts/src/submodule.ts b/spacetime-retry-ts/src/submodule.ts new file mode 100644 index 00000000000..8f2bf95eca5 --- /dev/null +++ b/spacetime-retry-ts/src/submodule.ts @@ -0,0 +1,352 @@ +import { + makeRetryDispatch, + retryFailed, + type RetryHandler, + type RetryResult, +} from './handler'; +import type { Identity, ScheduleAt, Timestamp } from 'spacetimedb'; +import type { Infer, VariantsObj } from 'spacetimedb/server'; + +const ONE_SECOND_MICROS = 1_000_000n; +const MAX_ATTEMPTS = 10; +const MAX_BACKOFF_SECONDS = 3600; +const MAX_TASK_NAME_LENGTH = 128; +const MAX_ERROR_LENGTH = 2048; +const MAX_HISTORY_ROWS = 1000; + +export type RetryHandlers = Record; + +export type RetrySubmoduleDeps = { + table: (typeof import('spacetimedb/server'))['table']; + t: (typeof import('spacetimedb/server'))['t']; + SenderError: new (message: string) => Error; + ScheduleAt: { time(microsSinceUnixEpoch: bigint): ScheduleAt }; +}; + +export type RetryAuthorizationPolicy = { + isAdmin?: (ctx: unknown) => boolean; + requireAdmin?: (ctx: unknown) => void; +}; + +export function createRetrySubmodule( + deps: RetrySubmoduleDeps, + handlers: H, + auth: RetryAuthorizationPolicy = {} +) { + const { table, t, SenderError, ScheduleAt } = deps; + const retryArgs = t.enum('RetryArgs', handlers as unknown as VariantsObj); + + const retryTask = table( + { + name: 'retry_task', + public: false, + }, + { + scheduledId: t.u64().primaryKey().autoInc(), + scheduledAt: t.scheduleAt(), + name: t.string().index(), + args: retryArgs, + attempt: t.u8(), + maxAttempts: t.u8(), + backoffSecs: t.u32(), + } + ); + + const retryHistoryStatus = t.enum('RetryHistoryStatus', [ + 'Attempted', + 'Ok', + 'Failed', + 'GaveUp', + ]); + const RetryHistoryStatus = { + Attempted: { tag: 'Attempted' as const }, + Ok: { tag: 'Ok' as const }, + Failed: { tag: 'Failed' as const }, + GaveUp: { tag: 'GaveUp' as const }, + }; + + const retryHistory = table( + { name: 'retry_history', public: false }, + { + id: t.u64().primaryKey().autoInc(), + taskName: t.string().index(), + attempt: t.u8(), + status: retryHistoryStatus.index(), + error: t.option(t.string()), + ranAt: t.timestamp().index(), + } + ); + + const retryAdminIdentity = table( + { name: 'retry_admin_identity', public: false }, + { + identity: t.identity().primaryKey(), + addedAtMicros: t.i64(), + } + ); + + type RetryDispatchArg = { tag: string; value?: unknown }; + type RetryTaskRow = Infer; + type RetryHistoryRow = Infer; + type RetryAdminIdentityRow = Infer; + + interface RetryContext { + sender: Identity; + timestamp: Timestamp; + db: { + retryTask: { + name: { filter(name: string): IterableIterator }; + insert(row: RetryTaskRow): RetryTaskRow; + iter(): Iterable; + }; + retryHistory: { + id: { update(row: RetryHistoryRow): void; delete(id: bigint): boolean }; + insert(row: RetryHistoryRow): RetryHistoryRow; + iter(): Iterable; + }; + retryAdminIdentity: { + identity: { + find(identity: Identity): RetryAdminIdentityRow | null | undefined; + }; + insert(row: RetryAdminIdentityRow): RetryAdminIdentityRow; + delete(row: RetryAdminIdentityRow): void; + count(): bigint; + }; + }; + } + + function retryContext(ctx: unknown): RetryContext { + return ctx as RetryContext; + } + + const dispatchRetry = makeRetryDispatch(handlers); + + function installRetry(ctx: unknown): void { + const retryCtx = retryContext(ctx); + if (retryCtx.db.retryAdminIdentity.identity.find(retryCtx.sender) == null) { + retryCtx.db.retryAdminIdentity.insert({ + identity: retryCtx.sender, + addedAtMicros: retryCtx.timestamp.microsSinceUnixEpoch, + }); + } + } + + function requireAdmin(ctx: unknown): void { + if (auth.requireAdmin) { + auth.requireAdmin(ctx); + return; + } + const retryCtx = retryContext(ctx); + if (retryCtx.db.retryAdminIdentity.identity.find(retryCtx.sender) == null) { + throw new SenderError('retry.not_authorized'); + } + } + + function isAdmin(ctx: unknown): boolean { + if (auth.isAdmin) return auth.isAdmin(ctx); + const retryCtx = retryContext(ctx); + return ( + retryCtx.db.retryAdminIdentity.identity.find(retryCtx.sender) != null + ); + } + + function takeRows(rows: Iterable, limit = 1000): T[] { + const out: T[] = []; + for (const row of rows) { + if (out.length >= limit) break; + out.push(row); + } + return out; + } + + function retryTasksAdmin(ctx: unknown): RetryTaskRow[] { + const retryCtx = retryContext(ctx); + return isAdmin(ctx) ? takeRows(retryCtx.db.retryTask.iter()) : []; + } + + function retryHistoryAdmin(ctx: unknown): RetryHistoryRow[] { + const retryCtx = retryContext(ctx); + return isAdmin(ctx) + ? recentHistory(retryCtx).slice(0, MAX_HISTORY_ROWS) + : []; + } + + function recentHistory(ctx: RetryContext): RetryHistoryRow[] { + return [...ctx.db.retryHistory.iter()].sort((a, b) => + a.id > b.id ? -1 : a.id < b.id ? 1 : 0 + ); + } + + function retryFire(ctx: unknown, { arg }: { arg: RetryTaskRow }): void { + const retryCtx = retryContext(ctx); + const nowMicros = retryCtx.timestamp.microsSinceUnixEpoch as bigint; + + const inserted = retryCtx.db.retryHistory.insert({ + id: 0n, + taskName: arg.name, + attempt: arg.attempt, + status: RetryHistoryStatus.Attempted, + error: undefined, + ranAt: retryCtx.timestamp, + }); + for (const row of recentHistory(retryCtx).slice(MAX_HISTORY_ROWS)) { + retryCtx.db.retryHistory.id.delete(row.id); + } + + let result: RetryResult; + try { + result = dispatchRetry( + retryCtx, + arg.args as RetryDispatchArg & { tag: keyof H & string } + ); + } catch (error) { + // A caught exception does not roll back the handler's earlier writes. + result = retryFailed( + error instanceof Error ? error.message : String(error) + ); + } + + if (result.ok) { + retryCtx.db.retryHistory.id.update({ + ...inserted, + status: RetryHistoryStatus.Ok, + error: undefined, + }); + return; + } + + const errorMessage = result.error.slice(0, MAX_ERROR_LENGTH); + const isLast = arg.attempt + 1 >= arg.maxAttempts; + retryCtx.db.retryHistory.id.update({ + ...inserted, + status: isLast ? RetryHistoryStatus.GaveUp : RetryHistoryStatus.Failed, + error: errorMessage, + }); + + if (isLast) return; + + const factor = 1n << BigInt(arg.attempt); + const delay = BigInt(arg.backoffSecs) * factor * ONE_SECOND_MICROS; + retryCtx.db.retryTask.insert({ + ...arg, + scheduledId: 0n, + scheduledAt: ScheduleAt.time(nowMicros + delay), + attempt: arg.attempt + 1, + }); + } + + const submitRetryTaskParams = { + name: t.string(), + args: retryArgs, + maxAttempts: t.u8(), + backoffSecs: t.u32(), + }; + + function submitRetryTask( + ctx: unknown, + args: { + name: string; + args: RetryDispatchArg; + maxAttempts: number; + backoffSecs: number; + } + ): void { + const retryCtx = retryContext(ctx); + requireAdmin(ctx); + if ( + typeof args.name !== 'string' || + args.name.length === 0 || + args.name.length > MAX_TASK_NAME_LENGTH + ) { + throw new SenderError('retry.invalid_task_name'); + } + if ( + !Number.isInteger(args.maxAttempts) || + args.maxAttempts < 1 || + args.maxAttempts > MAX_ATTEMPTS + ) { + throw new SenderError('retry.invalid_max_attempts'); + } + if ( + !Number.isInteger(args.backoffSecs) || + args.backoffSecs < 1 || + args.backoffSecs > MAX_BACKOFF_SECONDS + ) { + throw new SenderError('retry.invalid_backoff_seconds'); + } + if (retryCtx.db.retryTask.name.filter(args.name).next().value != null) { + throw new SenderError(`retry.task_already_exists:${args.name}`); + } + retryCtx.db.retryTask.insert({ + scheduledId: 0n, + scheduledAt: ScheduleAt.time( + retryCtx.timestamp.microsSinceUnixEpoch as bigint + ), + name: args.name, + args: args.args, + attempt: 0, + maxAttempts: args.maxAttempts, + backoffSecs: args.backoffSecs, + }); + } + + function addRetryAdminIdentity( + ctx: unknown, + { identity }: { identity: Identity } + ): void { + const retryCtx = retryContext(ctx); + requireAdmin(ctx); + if (retryCtx.db.retryAdminIdentity.identity.find(identity) == null) { + retryCtx.db.retryAdminIdentity.insert({ + identity, + addedAtMicros: retryCtx.timestamp.microsSinceUnixEpoch, + }); + } + } + + function removeRetryAdminIdentity( + ctx: unknown, + { identity }: { identity: Identity } + ): void { + const retryCtx = retryContext(ctx); + requireAdmin(ctx); + const existing = retryCtx.db.retryAdminIdentity.identity.find(identity); + if (!existing) return; + if (retryCtx.db.retryAdminIdentity.count() <= 1n) { + throw new SenderError('retry.cannot_remove_last_admin'); + } + retryCtx.db.retryAdminIdentity.delete(existing); + } + + return { + tables: { + retryTask, + retryHistory, + retryAdminIdentity, + }, + retryArgs, + retryHistoryStatus, + RetryHistoryStatus, + installRetry, + requireAdmin, + views: { + retryTasksAdmin, + retryHistoryAdmin, + }, + reducers: { + retryFire, + submitRetryTask: { + params: submitRetryTaskParams, + handler: submitRetryTask, + }, + addRetryAdminIdentity: { + params: { identity: t.identity() }, + handler: addRetryAdminIdentity, + }, + removeRetryAdminIdentity: { + params: { identity: t.identity() }, + handler: removeRetryAdminIdentity, + }, + }, + } as const; +} diff --git a/spacetime-retry-ts/tsconfig.json b/spacetime-retry-ts/tsconfig.json new file mode 100644 index 00000000000..b2b4ecdcdda --- /dev/null +++ b/spacetime-retry-ts/tsconfig.json @@ -0,0 +1,15 @@ +{ + "compilerOptions": { + "target": "ESNext", + "module": "ESNext", + "strict": true, + "declaration": false, + "noEmit": true, + "skipLibCheck": true, + "moduleResolution": "Bundler", + "isolatedModules": true, + "allowImportingTsExtensions": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"], + "exclude": ["node_modules"] +} diff --git a/spacetime-submodule-shared-ts/.npmrc b/spacetime-submodule-shared-ts/.npmrc new file mode 100644 index 00000000000..44bdf80d1df --- /dev/null +++ b/spacetime-submodule-shared-ts/.npmrc @@ -0,0 +1 @@ +minimum-release-age=1440 diff --git a/spacetime-submodule-shared-ts/assets/brand.svg b/spacetime-submodule-shared-ts/assets/brand.svg new file mode 100644 index 00000000000..77cc436631a --- /dev/null +++ b/spacetime-submodule-shared-ts/assets/brand.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/spacetime-submodule-shared-ts/assets/logo.svg b/spacetime-submodule-shared-ts/assets/logo.svg new file mode 100644 index 00000000000..adaf36cbf9c --- /dev/null +++ b/spacetime-submodule-shared-ts/assets/logo.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/spacetime-submodule-shared-ts/package.json b/spacetime-submodule-shared-ts/package.json new file mode 100644 index 00000000000..83ee4fa12af --- /dev/null +++ b/spacetime-submodule-shared-ts/package.json @@ -0,0 +1,34 @@ +{ + "name": "@spacetimedb/submodule-shared", + "description": "Shared UI and server utilities for SpacetimeDB submodule examples.", + "version": "0.1.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./src/index.ts" + }, + "./server": { + "types": "./src/server.ts", + "default": "./src/server.ts" + }, + "./styles.css": "./src/styles/index.css" + }, + "scripts": { + "format": "prettier . --write --ignore-path ../.prettierignore", + "lint": "eslint . && prettier . --check --ignore-path ../.prettierignore", + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "devDependencies": { + "@types/node": "^22.10.2", + "eslint": "^9.17.0", + "jsdom": "^26.1.0", + "prettier": "^3.3.3", + "typescript": "~5.6.2", + "vitest": "^3.2.4" + } +} diff --git a/spacetime-submodule-shared-ts/scripts/auth.test.ts b/spacetime-submodule-shared-ts/scripts/auth.test.ts new file mode 100644 index 00000000000..baf33343274 --- /dev/null +++ b/spacetime-submodule-shared-ts/scripts/auth.test.ts @@ -0,0 +1,139 @@ +// @vitest-environment jsdom + +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { + authModeCopy, + authUrlState, + clearAuthResultParams, + mountAuthPanel, +} from '../src/auth-panel'; + +beforeEach(() => { + document.body.replaceChildren(); + vi.restoreAllMocks(); +}); + +describe('authModeCopy', () => { + it('returns login copy for the selected product', () => { + expect(authModeCopy('login', 'Grid')).toEqual({ + title: 'Welcome to Grid', + subtitle: 'Sign in to continue.', + submit: 'Sign in', + showEmail: true, + showName: false, + showPassword: true, + showForgot: true, + togglePrompt: "Don't have an account?", + toggleText: 'Sign up', + }); + }); +}); + +describe('authUrlState', () => { + it('reads a password reset token', () => { + expect( + authUrlState({ + pathname: '/auth/password/reset', + search: '?token=reset-123', + }) + ).toEqual({ + mode: 'reset', + resetToken: 'reset-123', + oauthError: undefined, + verified: false, + }); + }); + + it('reads OAuth and verification results', () => { + expect( + authUrlState({ pathname: '/', search: '?error=denied&verified=1' }) + ).toEqual({ + mode: 'login', + resetToken: undefined, + oauthError: 'denied', + verified: true, + }); + }); +}); + +describe('clearAuthResultParams', () => { + it('removes callback results and retains unrelated parameters', () => { + let nextUrl = ''; + clearAuthResultParams( + { pathname: '/notes', search: '?error=denied&verified=1&tab=active' }, + { + replaceState: (_data, _unused, url) => { + nextUrl = String(url); + }, + } + ); + expect(nextUrl).toBe('/notes?tab=active'); + }); +}); + +describe('mountAuthPanel', () => { + it('submits password login through the supplied action', async () => { + const login = vi.fn(async () => undefined); + const root = document.createElement('div'); + document.body.append(root); + mountAuthPanel(root, { + productName: 'Grid', + actions: { + login, + signup: vi.fn(async () => undefined), + forgotPassword: vi.fn(async () => undefined), + resetPassword: vi.fn(async () => undefined), + oauthStart: vi.fn(), + }, + }); + + const email = root.querySelector('input[type="email"]'); + const password = root.querySelector( + 'input[type="password"]' + ); + const form = root.querySelector('form'); + expect(email).not.toBeNull(); + expect(password).not.toBeNull(); + expect(form).not.toBeNull(); + email!.value = 'user@example.com'; + password!.value = 'password-123'; + form!.requestSubmit(); + + await vi.waitFor(() => { + expect(login).toHaveBeenCalledWith({ + email: 'user@example.com', + password: 'password-123', + }); + }); + }); + + it('changes modes and enables configured OAuth providers', () => { + const oauthStart = vi.fn(); + const root = document.createElement('div'); + document.body.append(root); + const panel = mountAuthPanel(root, { + productName: 'Chat', + actions: { + login: vi.fn(async () => undefined), + signup: vi.fn(async () => undefined), + forgotPassword: vi.fn(async () => undefined), + resetPassword: vi.fn(async () => undefined), + oauthStart, + }, + }); + + const google = root.querySelector( + '[data-provider="google"]' + ); + const modeToggle = + root.querySelectorAll('.auth-link')[1]; + expect(google?.disabled).toBe(true); + modeToggle.click(); + expect(root.querySelector('h1')?.textContent).toBe('Create account'); + + panel.setProviders({ google: true }); + expect(google?.disabled).toBe(false); + google?.click(); + expect(oauthStart).toHaveBeenCalledWith('google'); + }); +}); diff --git a/spacetime-submodule-shared-ts/scripts/server.test.ts b/spacetime-submodule-shared-ts/scripts/server.test.ts new file mode 100644 index 00000000000..3162aa88da1 --- /dev/null +++ b/spacetime-submodule-shared-ts/scripts/server.test.ts @@ -0,0 +1,65 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { + discardStoredServerToken, + exampleUiAssetsDir, + loadServerToken, + saveServerToken, +} from '../src/server'; + +const temporaryDirectories: string[] = []; + +function temporaryTokenPath(): string { + const directory = mkdtempSync(path.join(tmpdir(), 'stdb-submodule-shared-')); + temporaryDirectories.push(directory); + return path.join(directory, 'server-token'); +} + +afterEach(() => { + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { recursive: true, force: true }); + } +}); + +describe('example server support', () => { + it('resolves the shared SVG assets', () => { + for (const filename of ['brand.svg', 'logo.svg']) { + expect( + readFileSync(path.join(exampleUiAssetsDir, filename), 'utf8') + ).toMatch(/^ { + const tokenPath = temporaryTokenPath(); + writeFileSync(tokenPath, 'stored-token\n'); + + expect(loadServerToken(tokenPath, ' environment-token ')).toEqual({ + token: 'environment-token', + source: 'environment', + }); + }); + + it('saves, loads, and discards a server token', () => { + const tokenPath = temporaryTokenPath(); + + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: undefined, + source: 'none', + }); + + saveServerToken(tokenPath, ' generated-token '); + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: 'generated-token', + source: 'file', + }); + + discardStoredServerToken(tokenPath); + expect(loadServerToken(tokenPath, undefined)).toEqual({ + token: undefined, + source: 'none', + }); + }); +}); diff --git a/spacetime-submodule-shared-ts/src/auth-panel.ts b/spacetime-submodule-shared-ts/src/auth-panel.ts new file mode 100644 index 00000000000..7718ea23e15 --- /dev/null +++ b/spacetime-submodule-shared-ts/src/auth-panel.ts @@ -0,0 +1,448 @@ +import { githubIcon, googleIcon, spacetimeMark } from './icons'; + +export type AuthMode = 'login' | 'signup' | 'forgot' | 'reset'; + +export type AuthProviderAvailability = { + google: boolean; + github: boolean; +}; + +export type AuthPanelActions = { + login(args: { email: string; password: string }): Promise; + signup(args: { + email: string; + password: string; + name?: string; + }): Promise; + forgotPassword(email: string): Promise; + resetPassword(token: string, newPassword: string): Promise; + oauthStart(provider: 'google' | 'github'): void; +}; + +export type AuthPanelOptions = { + productName: string; + actions: AuthPanelActions; + logoSrc?: string; + initialMode?: AuthMode; + resetToken?: string; +}; + +export type AuthPanelController = { + destroy(): void; + focus(): void; + setMode(mode: AuthMode, resetToken?: string): void; + setProviders(providers: Partial): void; + showMessage(kind: 'error' | 'success', message: string): void; +}; + +type AuthModeCopy = { + title: string; + subtitle: string; + submit: string; + showEmail: boolean; + showName: boolean; + showPassword: boolean; + showForgot: boolean; + togglePrompt: string; + toggleText: string; +}; + +export function authModeCopy( + mode: AuthMode, + productName: string +): AuthModeCopy { + switch (mode) { + case 'signup': + return { + title: 'Create account', + subtitle: `Create an account to continue to ${productName}.`, + submit: 'Create account', + showEmail: true, + showName: true, + showPassword: true, + showForgot: false, + togglePrompt: 'Already have an account?', + toggleText: 'Sign in', + }; + case 'forgot': + return { + title: 'Reset your password', + subtitle: + 'Enter your email. A reset link will be sent if the account exists.', + submit: 'Send reset email', + showEmail: true, + showName: false, + showPassword: false, + showForgot: false, + togglePrompt: '', + toggleText: 'Back to sign in', + }; + case 'reset': + return { + title: 'Set a new password', + subtitle: 'Enter a new password with at least eight characters.', + submit: 'Reset password', + showEmail: false, + showName: false, + showPassword: true, + showForgot: false, + togglePrompt: '', + toggleText: 'Back to sign in', + }; + case 'login': + return { + title: `Welcome to ${productName}`, + subtitle: 'Sign in to continue.', + submit: 'Sign in', + showEmail: true, + showName: false, + showPassword: true, + showForgot: true, + togglePrompt: "Don't have an account?", + toggleText: 'Sign up', + }; + } +} + +export function authUrlState(location: Pick): { + mode: AuthMode; + resetToken?: string; + oauthError?: string; + verified: boolean; +} { + const params = new URLSearchParams(location.search); + const resetToken = + location.pathname === '/auth/password/reset' + ? (params.get('token') ?? undefined) + : undefined; + return { + mode: resetToken ? 'reset' : 'login', + resetToken, + oauthError: params.get('error') ?? undefined, + verified: params.get('verified') === '1', + }; +} + +export function clearAuthResultParams( + location: Pick, + history: Pick +): void { + const params = new URLSearchParams(location.search); + const hadResult = params.has('error') || params.has('verified'); + if (!hadResult) return; + params.delete('error'); + params.delete('verified'); + const search = params.toString(); + history.replaceState( + {}, + '', + `${location.pathname}${search ? `?${search}` : ''}` + ); +} + +function element( + tag: K, + className?: string +): HTMLElementTagNameMap[K] { + const node = document.createElement(tag); + if (className) node.className = className; + return node; +} + +function field( + id: string, + labelText: string, + type: HTMLInputElement['type'], + autocomplete: HTMLInputElement['autocomplete'], + placeholder: string +): { wrapper: HTMLDivElement; input: HTMLInputElement } { + const wrapper = element('div', 'auth-field'); + const label = element('label'); + label.htmlFor = id; + label.textContent = labelText; + const input = element('input'); + input.id = id; + input.type = type; + input.autocomplete = autocomplete; + input.placeholder = placeholder; + wrapper.append(label, input); + return { wrapper, input }; +} + +function oauthButton( + provider: 'google' | 'github', + label: string +): HTMLButtonElement { + const button = element('button', 'btn oauth block'); + button.type = 'button'; + button.dataset.provider = provider; + button.append(provider === 'google' ? googleIcon() : githubIcon(), label); + return button; +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +export function mountAuthPanel( + root: HTMLElement, + options: AuthPanelOptions +): AuthPanelController { + const abort = new AbortController(); + let mode = options.initialMode ?? 'login'; + let resetToken = options.resetToken; + let providers: AuthProviderAvailability = { google: false, github: false }; + root.classList.add('example-auth-panel'); + + const form = element('form', 'auth-card'); + + const logoLink = element('a'); + logoLink.href = 'https://spacetimedb.com'; + logoLink.target = '_blank'; + logoLink.rel = 'noopener noreferrer'; + logoLink.className = 'auth-logo-link'; + const logo = options.logoSrc + ? Object.assign(element('img', 'auth-logo'), { + src: options.logoSrc, + alt: 'SpacetimeDB', + }) + : spacetimeMark(); + logoLink.append(logo); + + const title = element('h1'); + const subtitle = element('p', 'auth-sub'); + const oauth = element('div', 'auth-oauth'); + const google = oauthButton('google', 'Continue with Google'); + const github = oauthButton('github', 'Continue with GitHub'); + oauth.append(google, github); + + const divider = element('div', 'auth-divider'); + const dividerText = element('span'); + dividerText.textContent = 'or'; + divider.append(dividerText); + + const email = field( + 'example-auth-email', + 'Email', + 'email', + 'email', + 'you@example.com' + ); + const name = field( + 'example-auth-name', + 'Name (optional)', + 'text', + 'name', + 'Display name' + ); + const password = field( + 'example-auth-password', + 'Password', + 'password', + 'current-password', + '' + ); + password.input.minLength = 8; + + const message = element('p', 'auth-message'); + message.setAttribute('role', 'status'); + message.setAttribute('aria-live', 'polite'); + message.hidden = true; + + const submit = element('button', 'btn primary block'); + submit.type = 'submit'; + + const forgotFoot = element('p', 'auth-foot'); + const forgot = element('button', 'auth-link'); + forgot.type = 'button'; + forgot.textContent = 'Forgot password?'; + forgotFoot.append(forgot); + + const toggleFoot = element('p', 'auth-foot'); + const togglePrompt = element('span'); + const toggle = element('button', 'auth-link'); + toggle.type = 'button'; + toggleFoot.append(togglePrompt, document.createTextNode(' '), toggle); + + form.append( + logoLink, + title, + subtitle, + oauth, + divider, + email.wrapper, + name.wrapper, + password.wrapper, + message, + submit, + forgotFoot, + toggleFoot + ); + root.replaceChildren(form); + + function showMessage(kind: 'error' | 'success', text: string): void { + message.className = `auth-message ${kind}`; + message.textContent = text; + message.hidden = false; + } + + function clearMessage(): void { + message.textContent = ''; + message.hidden = true; + } + + function applyMode(): void { + const copy = authModeCopy(mode, options.productName); + title.textContent = copy.title; + subtitle.textContent = copy.subtitle; + submit.textContent = copy.submit; + email.wrapper.hidden = !copy.showEmail; + email.input.required = copy.showEmail; + name.wrapper.hidden = !copy.showName; + password.wrapper.hidden = !copy.showPassword; + password.input.required = copy.showPassword; + password.input.autocomplete = + mode === 'login' ? 'current-password' : 'new-password'; + password.input.placeholder = mode === 'login' ? '' : 'Minimum 8 characters'; + forgotFoot.hidden = !copy.showForgot; + togglePrompt.textContent = copy.togglePrompt; + toggle.textContent = copy.toggleText; + clearMessage(); + } + + function applyProviders(): void { + for (const [button, enabled, envNames] of [ + [google, providers.google, 'GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET'], + [github, providers.github, 'GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET'], + ] as const) { + button.disabled = !enabled; + button.setAttribute('aria-disabled', String(!enabled)); + button.title = enabled ? '' : `Set ${envNames} in .env`; + } + } + + async function run(action: () => Promise): Promise { + clearMessage(); + submit.disabled = true; + form.setAttribute('aria-busy', 'true'); + try { + await action(); + } catch (error) { + showMessage('error', errorMessage(error)); + } finally { + submit.disabled = false; + form.removeAttribute('aria-busy'); + } + } + + form.addEventListener( + 'submit', + event => { + event.preventDefault(); + void run(async () => { + const emailValue = email.input.value.trim(); + const passwordValue = password.input.value; + if (mode === 'signup') { + await options.actions.signup({ + email: emailValue, + password: passwordValue, + name: name.input.value.trim() || undefined, + }); + return; + } + if (mode === 'forgot') { + await options.actions.forgotPassword(emailValue); + mode = 'login'; + applyMode(); + showMessage( + 'success', + 'If the account exists, a password reset link was sent.' + ); + return; + } + if (mode === 'reset') { + if (!resetToken) throw new Error('auth.missing_reset_token'); + await options.actions.resetPassword(resetToken, passwordValue); + resetToken = undefined; + mode = 'login'; + window.history.replaceState({}, '', '/'); + applyMode(); + showMessage( + 'success', + 'Password reset. Sign in with the new password.' + ); + return; + } + await options.actions.login({ + email: emailValue, + password: passwordValue, + }); + }); + }, + { signal: abort.signal } + ); + + forgot.addEventListener( + 'click', + () => { + mode = 'forgot'; + applyMode(); + email.input.focus(); + }, + { signal: abort.signal } + ); + + toggle.addEventListener( + 'click', + () => { + mode = + mode === 'forgot' || mode === 'reset' + ? 'login' + : mode === 'login' + ? 'signup' + : 'login'; + applyMode(); + email.input.focus(); + }, + { signal: abort.signal } + ); + + for (const button of [google, github]) { + button.addEventListener( + 'click', + () => { + const provider = button.dataset.provider as 'google' | 'github'; + if (!providers[provider]) { + showMessage('error', `${provider} OAuth is not configured.`); + return; + } + options.actions.oauthStart(provider); + }, + { signal: abort.signal } + ); + } + + applyMode(); + applyProviders(); + + return { + destroy() { + abort.abort(); + root.replaceChildren(); + root.classList.remove('example-auth-panel'); + }, + focus() { + (mode === 'reset' ? password.input : email.input).focus(); + }, + setMode(nextMode, nextResetToken) { + mode = nextMode; + resetToken = nextResetToken; + applyMode(); + }, + setProviders(nextProviders) { + providers = { ...providers, ...nextProviders }; + applyProviders(); + }, + showMessage, + }; +} diff --git a/spacetime-submodule-shared-ts/src/icons.ts b/spacetime-submodule-shared-ts/src/icons.ts new file mode 100644 index 00000000000..f04ada242fa --- /dev/null +++ b/spacetime-submodule-shared-ts/src/icons.ts @@ -0,0 +1,51 @@ +export function googleIcon(): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('aria-hidden', 'true'); + for (const [fill, d] of [ + [ + '#4285F4', + 'M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 0 1-2.2 3.32v2.76h3.56c2.08-1.92 3.28-4.74 3.28-8.09z', + ], + [ + '#34A853', + 'M12 23c2.97 0 5.46-.98 7.28-2.66l-3.56-2.76c-.98.66-2.24 1.06-3.72 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84A11 11 0 0 0 12 23z', + ], + [ + '#FBBC05', + 'M5.84 14.11A6.6 6.6 0 0 1 5.5 12c0-.73.13-1.44.34-2.11V7.05H2.18A11 11 0 0 0 1 12c0 1.78.43 3.46 1.18 4.95l3.66-2.84z', + ], + [ + '#EA4335', + 'M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1A11 11 0 0 0 2.18 7.05l3.66 2.84C6.71 7.3 9.14 5.38 12 5.38z', + ], + ]) { + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('fill', fill); + path.setAttribute('d', d); + svg.append(path); + } + return svg; +} + +export function githubIcon(): SVGSVGElement { + const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + svg.setAttribute('viewBox', '0 0 24 24'); + svg.setAttribute('fill', 'currentColor'); + svg.setAttribute('aria-hidden', 'true'); + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute( + 'd', + 'M12 .5C5.65.5.5 5.65.5 12c0 5.08 3.29 9.39 7.86 10.91.58.1.79-.25.79-.56v-2c-3.2.7-3.87-1.36-3.87-1.36-.53-1.34-1.3-1.7-1.3-1.7-1.06-.72.08-.7.08-.7 1.17.08 1.79 1.2 1.79 1.2 1.04 1.78 2.73 1.26 3.4.96.11-.75.41-1.26.74-1.55-2.55-.29-5.24-1.28-5.24-5.7 0-1.26.45-2.29 1.19-3.1-.12-.29-.52-1.47.11-3.06 0 0 .97-.31 3.18 1.18a11 11 0 0 1 5.78 0c2.2-1.49 3.18-1.18 3.18-1.18.63 1.59.23 2.77.11 3.06.74.81 1.19 1.84 1.19 3.1 0 4.43-2.7 5.41-5.27 5.69.42.36.79 1.08.79 2.18v3.23c0 .31.21.67.8.56A11.51 11.51 0 0 0 23.5 12C23.5 5.65 18.35.5 12 .5z' + ); + svg.append(path); + return svg; +} + +export function spacetimeMark(): HTMLImageElement { + const image = document.createElement('img'); + image.src = '/assets/logo.svg'; + image.alt = 'SpacetimeDB'; + image.classList.add('auth-logo'); + return image; +} diff --git a/spacetime-submodule-shared-ts/src/index.ts b/spacetime-submodule-shared-ts/src/index.ts new file mode 100644 index 00000000000..b23ec22f07d --- /dev/null +++ b/spacetime-submodule-shared-ts/src/index.ts @@ -0,0 +1,11 @@ +export { + authModeCopy, + authUrlState, + clearAuthResultParams, + mountAuthPanel, + type AuthMode, + type AuthPanelActions, + type AuthPanelController, + type AuthPanelOptions, + type AuthProviderAvailability, +} from './auth-panel'; diff --git a/spacetime-submodule-shared-ts/src/server.ts b/spacetime-submodule-shared-ts/src/server.ts new file mode 100644 index 00000000000..c81955b7853 --- /dev/null +++ b/spacetime-submodule-shared-ts/src/server.ts @@ -0,0 +1,73 @@ +import { spawnSync } from 'node:child_process'; +import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +export const exampleUiAssetsDir = fileURLToPath( + new URL('../assets/', import.meta.url) +); + +export type StoredServerToken = { + token: string | undefined; + source: 'environment' | 'file' | 'none'; +}; + +export function loadServerToken( + tokenPath: string, + environmentToken: string | undefined +): StoredServerToken { + const explicit = environmentToken?.trim(); + if (explicit) return { token: explicit, source: 'environment' }; + if (!existsSync(tokenPath)) return { token: undefined, source: 'none' }; + + const stored = readFileSync(tokenPath, 'utf8').trim(); + return stored + ? { token: stored, source: 'file' } + : { token: undefined, source: 'none' }; +} + +export function saveServerToken(tokenPath: string, token: string): void { + writeFileSync(tokenPath, `${token.trim()}\n`, { + encoding: 'utf8', + mode: 0o600, + }); +} + +export function discardStoredServerToken(tokenPath: string): void { + if (existsSync(tokenPath)) unlinkSync(tokenPath); +} + +export function grantServerIdentity(options: { + spacetimeBin?: string; + server: string; + database: string; + procedure: string; + identity: string; +}): void { + const spacetimeBin = options.spacetimeBin ?? 'spacetime'; + const result = spawnSync( + spacetimeBin, + [ + 'call', + '--server', + options.server, + options.database, + options.procedure, + JSON.stringify(options.identity), + ], + { encoding: 'utf8', shell: false } + ); + + if (result.error) { + throw new Error(`failed to run ${spacetimeBin}: ${result.error.message}`); + } + if (result.status !== 0) { + const detail = result.stderr.trim() || result.stdout.trim(); + throw new Error( + [ + `could not authorize the example server identity with ${options.procedure}`, + detail || `${spacetimeBin} exited ${result.status}`, + 'Publish the database with the currently logged-in CLI identity, then restart the example.', + ].join(': ') + ); + } +} diff --git a/spacetime-submodule-shared-ts/src/styles/index.css b/spacetime-submodule-shared-ts/src/styles/index.css new file mode 100644 index 00000000000..dd60f24604d --- /dev/null +++ b/spacetime-submodule-shared-ts/src/styles/index.css @@ -0,0 +1,253 @@ +:root { + --font-inter: 'Inter Variable', 'Inter', sans-serif; + --font-source: 'Source Code Pro Variable', 'Source Code Pro', monospace; + --font-ibm: 'IBM Plex Mono', monospace; + --color-green: #4cf490; + --color-green-10: #4cf4901a; + --color-green-20: #4cf49033; + --color-green-25: #4cf49040; + --color-green-50: #4cf49080; + --color-green-75: #4cf490bf; + --color-white: #d7d8d9; + --color-yellow: #fbdc8e; + --color-yellow-10: #fbdc8e1a; + --color-yellow-20: #fbdc8e33; + --color-purple: #a880ff; + --color-purple-2: #8a38f5; + --color-orange: #ff9e9e; + --color-blue: #02befa; + --color-blue-10: #02befa1a; + --color-blue-20: #02befa33; + --color-pink: #ff80fb; + --color-teal: #00ccb4; + --color-red: #ff4c4c; + --color-brown: #3b3b3b; + --color-n1: #e6e9f0; + --color-n2: #ced3e0; + --color-n3: #b6c0cf; + --color-n4: #6f7987; + --color-n5: #363840; + --color-n6: #202126; + --color-n7: #050505; + --color-n8: #060606; + --color-shade1: #162d38; + --color-shade2: #122530; + --color-shade3: #122129; + --color-shade4: #121e24; + --color-shade5: #0f191f; + --color-shade6: #0e161a; + --color-shade7: #0b1114; + --color-shade8: #0b0e12; + --color-border: var(--color-shade4); + --color-text: var(--color-n1); + --radius-sm: 6px; + --radius: 10px; + --radius-lg: 14px; +} + +.example-auth-panel { + width: min(380px, 100%); +} + +.auth-card { + box-sizing: border-box; + width: 100%; + padding: 28px; + display: flex; + flex-direction: column; + gap: 12px; + color: var(--color-n1); + background: linear-gradient(180deg, var(--color-shade5), var(--color-shade6)); + border: 1px solid var(--color-shade4); + border-radius: var(--radius-lg); +} + +.auth-logo-link { + display: inline-flex; + align-self: center; +} + +.auth-logo { + width: 56px; + height: 56px; + display: block; +} + +.auth-card h1 { + margin: 0; + color: var(--color-n1); + font-family: var(--font-inter); + font-size: 18px; + line-height: 24px; + text-align: center; +} + +.auth-sub, +.auth-foot, +.auth-message { + margin: 0; + font-family: var(--font-inter); + font-size: 12px; + line-height: 18px; + text-align: center; +} + +.auth-sub, +.auth-foot { + color: var(--color-n4); +} + +.auth-sub { + margin-bottom: 8px; + font-size: 13px; +} + +.auth-oauth, +.auth-field { + display: flex; + flex-direction: column; +} + +.auth-oauth { + gap: 8px; +} + +.auth-field { + gap: 4px; +} + +.auth-field label { + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + line-height: 14px; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.auth-field input, +.auth-card .btn { + box-sizing: border-box; + width: 100%; + height: 40px; + font-family: var(--font-inter); + font-size: 13px; + font-weight: 600; +} + +.auth-field input { + padding: 0 12px; + color: var(--color-n1); + background: var(--color-shade6); + border: 1px solid var(--color-shade4); + border-radius: var(--radius-sm); + outline: none; +} + +.auth-field input:focus { + border-color: var(--color-green); + box-shadow: 0 0 0 3px var(--color-green-20); +} + +.auth-card .btn { + display: flex; + align-items: center; + justify-content: center; + padding: 0 14px; + border-radius: var(--radius-sm); + cursor: pointer; +} + +.auth-card .btn.oauth { + gap: 10px; + color: var(--color-n1); + background: var(--color-shade7); + border: 1px solid var(--color-shade4); +} + +.auth-card .btn.oauth:hover:not(:disabled) { + background: var(--color-shade4); + border-color: var(--color-n4); +} + +.auth-card .btn.oauth svg { + width: 16px; + height: 16px; + flex-shrink: 0; +} + +.auth-card .btn.primary { + margin-top: 4px; + color: var(--color-n8); + background: var(--color-n3); + border: 2px solid var(--color-n3); +} + +.auth-card .btn.primary:hover:not(:disabled) { + color: var(--color-n8); + background: var(--color-white); + border-color: var(--color-white); +} + +.auth-card .btn:disabled { + cursor: not-allowed; + opacity: 0.45; +} + +.auth-divider { + display: flex; + align-items: center; + gap: 8px; + margin: 4px 0; + color: var(--color-n4); + font-family: var(--font-ibm); + font-size: 10px; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.auth-divider::before, +.auth-divider::after { + height: 1px; + flex: 1; + content: ''; + background: var(--color-shade4); +} + +.auth-link { + padding: 0; + color: var(--color-green); + font: inherit; + font-weight: 600; + background: none; + border: 0; + cursor: pointer; +} + +.auth-link:hover { + text-decoration: underline; +} + +.auth-message { + padding: 8px 10px; + border: 1px solid transparent; + border-radius: var(--radius-sm); +} + +.auth-message.error { + color: var(--color-orange); + background: #ff9e9e12; + border-color: #ff9e9e40; +} + +.auth-message.success { + color: var(--color-green); + background: var(--color-green-10); + border-color: var(--color-green-25); +} + +@media (max-width: 480px) { + .auth-card { + padding: 22px; + } +} diff --git a/spacetime-submodule-shared-ts/tsconfig.json b/spacetime-submodule-shared-ts/tsconfig.json new file mode 100644 index 00000000000..20fc11f9205 --- /dev/null +++ b/spacetime-submodule-shared-ts/tsconfig.json @@ -0,0 +1,13 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "strict": true, + "noEmit": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "isolatedModules": true + }, + "include": ["src/**/*.ts", "scripts/**/*.ts"] +}